-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmybeacons.py
executable file
·83 lines (60 loc) · 2.46 KB
/
mybeacons.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
import sys, re, json, asyncio
from argparse import ArgumentParser, Namespace
def mac_addr(x):
if not re.match("[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
raise ValueError()
return x
parser = ArgumentParser()
subparsers = parser.add_subparsers(help='action', dest='command', required=True)
sub = subparsers.add_parser('list', help = "List devices")
sub = subparsers.add_parser('add', help = "Add device")
sub.add_argument('-mac', type=mac_addr, required=True)
sub.add_argument('-name', default='no name')
sub = subparsers.add_parser('remove', help = "Remove device")
sub.add_argument('-mac', type=mac_addr, required=True)
sub = subparsers.add_parser('identify', help = "Identify a device")
sub.add_argument('-mac', type=mac_addr, required=True)
sub = subparsers.add_parser('config', help = 'Save configuration')
sub.add_argument('-s', '--save', action='store_true', help='Save configuration to file')
sub = subparsers.add_parser('discover', help = "Listen for device")
sub.add_argument('-name', required=True, metavar='Name', help='Device Name')
sub.add_argument('-t', type=int, choices=range(10,31), default=10, metavar='Timeout', help='Seconds to wait')
args = parser.parse_args()
config_cmd = json.JSONEncoder().encode(vars(args))
'''
'''
class ConfigClientProtocol:
def __init__(self, message, on_con_lost):
self.message = message
self.on_con_lost = on_con_lost
self.transport = None
def connection_made(self, transport):
self.transport = transport
self.transport.sendto(self.message.encode())
def datagram_received(self, data, addr):
print(data.decode())
self.transport.close()
def error_received(self, exc):
print('Error received:', exc)
def connection_lost(self, exc):
#print("Connection closed")
self.on_con_lost.set_result(True)
'''
'''
async def connect(msg):
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
on_con_lost = loop.create_future()
message = msg #"Hello World!"
transport, protocol = await loop.create_datagram_endpoint(
lambda: ConfigClientProtocol(message, on_con_lost),
remote_addr=('127.0.0.1', 9999))
# Wait until the protocol signals that the connection
# is lost and close the transport.
try:
await on_con_lost
finally:
transport.close()
asyncio.run(connect(config_cmd))