-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwitchyBot.py
161 lines (114 loc) · 4.4 KB
/
SwitchyBot.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# SwitchyBot API for switchbots using BLE
# Made by Forest for STIGHO Elektrotechniek
# https://github.com/TForest-UwU/Switchy
import config
import queue
import sys
import re
import os
sys.path.append(config.packagepath)
import pexpect
import pygatt
notification_queue = queue.Queue()
def handle_notification(handle: int, value: bytes):
notification_queue.put((handle, value))
class SysCmd():
"Class for system commands"
def restartblue():
os.system(config.terminalcmd + " " + config.resetcmd)
os.system(config.terminalcmd + " " + config.rfkillcmd)
def startblue():
os.system(config.terminalcmd + " " + config.startcmd)
os.system(config.terminalcmd + " " + config.agentcmd)
os.system(config.terminalcmd + " " + config.scancmd)
def stopblue():
os.system(config.terminalcmd + " " + config.stscancmd)
os.system(config.terminalcmd + " " + config.stagentcmd)
os.system(config.terminalcmd + " " + config.stopcmd)
class Bot(object):
"Switchbot class to control the bot"
def __init__(self, bot_id: int, mac: str, name: str):
if not re.match(r"[0-9A-F]{2}(?:[-:][0-9A-F]{2}){5}$", mac):
raise ValueError(f"Illegal Mac Address: ", mac)
self.bot_id = bot_id
self.mac = mac
self.name = name
self.adapter = pygatt.GATTToolBackend()
self.device = None
self.password = None
self.notification_activated = False
print(f"Succesfully created {self.name} at {self.mac} with id {self.bot_id}")
def connect(self, cmd_code: str):
connect = pexpect.spawn('hciconfig')
pnum = connect.expect(["hci0", pexpect.EOF, pexpect.TIMEOUT])
if pnum != 0:
print('No bluetooth hardware, exit now')
sys.exit()
connect = pexpect.spawn('hciconfig hci0 up')
con = pexpect.spawn('gatttool -b ' + self.mac + ' -t random -I')
con.expect('\[LE\]>')
print(f'Preparing to connect using {cmd_code}')
retry = config.tryconnect
index = 0
while retry > 0 and 0 == index:
con.sendline('connect')
index = con.expect(
['Error', '\[CON\]', 'Connection successful.*\[LE\]>'])
retry -= 1
if 0 == index:
print("Connection error")
return
print(f"Connected to {self.name} at {self.mac}")
con.sendline('char-desc')
con.expect(['\[CON\]', config.botuuid])
cmd_handle = con.before.decode('utf-8').split('\n')[-1].split()[2].strip(',')
con.sendline('char-write-cmd ' + cmd_handle + ' ' + cmd_code)
def press(self):
self.connect(config.presscode)
try:
self.adapter.start()
self._connect()
self._activate_notifications()
if self.password:
cmd = b'\x57\x11' + self.password
else:
cmd = b'\x57\x01'
self.write(handle=0x16, cmd=cmd)
finally:
self.adapter.stop()
def switch(self, state: str):
if "1" in state:
self.connect(config.oncode)
if "0" in state:
self.connect(config.offcode)
try:
self.adapter.start()
self._connect()
self._activate_notifications()
if self.password:
cmd = b'\x57\x11' + self.password
else:
cmd = b'\x57\x01'
if "1" in state:
cmd += b'\x01'
else:
cmd += b'\x02'
self.write(handle=0x16, cmd=cmd)
finally:
self.adapter.stop()
def _connect(self):
self.device = self.adapter.connect(self.mac, address_type=pygatt.BLEAddressType.random)
def _activate_notifications(self):
uuid = config.notifuuid
try:
self.device.subscribe(uuid, callback=handle_notification)
self.notification_activated = True
except pygatt.BLEError:
raise ConnectionError(message="Communication with BLE device failed")
def write(self, handle, cmd):
print(f"Succesfully sent {cmd} using {handle} to {self.name} at {self.mac}")
try:
self.device.char_write_handle(handle = handle, value = cmd)
except pygatt.BLEError:
print(f"Failed to send {cmd} to {self.name} at {self.mac}")
return