-
Notifications
You must be signed in to change notification settings - Fork 15
/
sample.py
executable file
·135 lines (105 loc) · 3.67 KB
/
sample.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python
"""Example of using WyzeSense USB bridge.
**Usage:** ::
sample.py [options]
**Options:**
-d, --debug output debug log messages to stderr
-v, --verbose print and log more information
--device PATH USB device path [default: /dev/hidraw0]
**Examples:** ::
sample.py --device /dev/hidraw0 # Using WyzeSense USB bridge /dev/hidraw0
"""
from __future__ import print_function
from builtins import input
import re
import sys
import logging
import binascii
import wyzesense
def on_event(ws, e):
s = "[%s][%s]" % (e.Timestamp.strftime("%Y-%m-%d %H:%M:%S"), e.MAC)
if e.Type == 'state':
s += "StateEvent: sensor_type=%s, state=%s, battery=%d, signal=%d" % e.Data
else:
s += "RawEvent: type=%s, data=%r" % (e.Type, e.Data)
print(s)
def main(args):
if args['--debug']:
loglevel = logging.DEBUG - (1 if args['--verbose'] else 0)
logging.getLogger("wyzesense").setLevel(loglevel)
logging.getLogger().setLevel(loglevel)
device = args['--device']
print("Openning wyzesense gateway [%r]" % device)
try:
ws = wyzesense.Open(device, on_event)
if not ws:
print("Open wyzesense gateway failed")
return 1
print("Gateway info:")
print("\tMAC:%s" % ws.MAC)
print("\tVER:%s" % ws.Version)
print("\tENR:%s" % binascii.hexlify(ws.ENR))
except IOError:
print("No device found on path %r" % device)
return 2
def List(unused_args):
result = ws.List()
print("%d sensor paired:" % len(result))
logging.debug("%d sensor paired:", len(result))
for mac in result:
print("\tSensor: %s" % mac)
logging.debug("\tSensor: %s", mac)
def Pair(unused_args):
result = ws.Scan()
if result:
print("Sensor found: mac=%s, type=%d, version=%d" % result)
logging.debug("Sensor found: mac=%s, type=%d, version=%d", *result)
else:
print("No sensor found!")
logging.debug("No sensor found!")
def Unpair(mac_list):
for mac in mac_list:
if len(mac) != 8:
print("Invalid mac address, must be 8 characters: %s", mac)
logging.debug("Invalid mac address, must be 8 characters: %s", mac)
continue
print("Un-pairing sensor %s:" % mac)
logging.debug("Un-pairing sensor %s:", mac)
ws.Delete(mac)
print("Sensor %s removed" % mac)
logging.debug("Sensor %s removed", mac)
def HandleCmd():
cmd_handlers = {
'L': ('L to list', List),
'P': ('P to pair', Pair),
'U': ('U to unpair', Unpair),
'X': ('X to exit', None),
}
for v in list(cmd_handlers.values()):
print(v[0])
cmd_and_args = input("Action:").strip().upper().split()
if len(cmd_and_args) == 0:
return True
cmd = cmd_and_args[0]
if cmd not in cmd_handlers:
return True
handler = cmd_handlers[cmd]
if not handler[1]:
return False
handler[1](cmd_and_args[1:])
return True
try:
while HandleCmd():
pass
finally:
ws.Stop()
return 0
if __name__ == '__main__':
logging.basicConfig(format='%(levelname)s %(asctime)s %(message)s')
try:
from docopt import docopt
except ImportError:
sys.exit("the 'docopt' module is needed to execute this program")
# remove restructured text formatting before input to docopt
usage = re.sub(r'(?<=\n)\*\*(\w+:)\*\*.*\n', r'\1', __doc__)
sys.exit(main(docopt(usage)))