-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathYeelightDimmer.py
272 lines (203 loc) · 8.05 KB
/
YeelightDimmer.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
from Cryptodome.Cipher import AES
from bluepy.btle import UUID, Peripheral, DefaultDelegate, Scanner
import struct
import random
import time
class XiaomiEncryption(object):
@staticmethod
def _cipherInit(key):
perm = bytearray()
for i in range(0, 256):
perm.extend(bytes([i & 0xff]))
keyLen = len(key)
j = 0
for i in range(0, 256):
j += perm[i] + key[i % keyLen]
j = j & 0xff
perm[i], perm[j] = perm[j], perm[i]
return perm
@staticmethod
def mixA(mac, productID):
return bytes([mac[0], mac[2], mac[5], (productID & 0xff), (productID & 0xff), mac[4], mac[5], mac[1]])
@staticmethod
def mixB(mac, productID):
return bytes([mac[0], mac[2], mac[5], ((productID >> 8) & 0xff), mac[4], mac[0], mac[5], (productID & 0xff)])
@staticmethod
def _cipherCrypt(input, perm):
index1 = 0
index2 = 0
output = bytearray()
for i in range(0, len(input)):
index1 = index1 + 1
index1 = index1 & 0xff
index2 += perm[index1]
index2 = index2 & 0xff
perm[index1], perm[index2] = perm[index2], perm[index1]
idx = perm[index1] + perm[index2]
idx = idx & 0xff
outputByte = input[i] ^ perm[idx]
output.extend(bytes([outputByte & 0xff]))
return output
@staticmethod
def cipher(key, input):
perm = XiaomiEncryption._cipherInit(key)
return XiaomiEncryption._cipherCrypt(input, perm)
# AES
@staticmethod
def decryptMiBeaconV2(key, data):
# prepare aes key (12b -> 16b)
key_1 = key[0:6]
key_2 = bytes.fromhex("8d3d3c97")
key_3 = key[6:]
key = b"".join([key_1, key_2, key_3])
# extract packet fields
xiaomi_mac_reversed = data[7:13]
framectrl_data = data[2:4]
device_type = data[4:6]
encrypted_payload = data[13:]
packet_id = data[6:7]
payload_counter = b"".join([packet_id, encrypted_payload[-4:-1]])
# prepare nonce
nonce = b"".join([framectrl_data, device_type, payload_counter, xiaomi_mac_reversed[:-1]])
cipherpayload = encrypted_payload[:-4]
# AES decrypt
cipher = AES.new(key, AES.MODE_CCM, nonce=nonce, mac_len=4)
cipher.update(b"\x11")
return cipher.decrypt(cipherpayload)
class YeelightDimmer(object):
PRODUCT_ID = 950
UUID_PRIMARY_SERVICE = "fe95" # XIAOMI Inc.
XIAOMI_KEY1 = bytes([0x90, 0xCA, 0x85, 0xDE])
XIAOMI_KEY2 = bytes([0x92, 0xAB, 0x54, 0xFA])
HANDLE_AUTH_INIT = 19
HANDLE_AUTH = 3
HANDLE_BEACON_KEY = 25
HANDLE_READ_FIRMWARE_VERSION = 10
SUBSCRIBE_TRUE = bytes([0x01, 0x00])
def __init__(self, mac, beacon_key = None):
self.mac = mac.lower()
rmac = [x for x in bytes.fromhex(mac.replace(':',''))]
rmac.reverse()
self.reversed_mac = rmac
self.token = bytes([random.randint(0,255) for i in range(12)])
self.beacon_key = None
if not beacon_key is None:
self.beacon_key = bytes.fromhex(beacon_key)
self.prev_packet_id = None
self.auth_can_pass = False
def auth(self):
self.auth_can_pass = False
self.onConnectionStart()
if not self._connect():
self.onConnectionFail()
return
self.onConnectionDone()
self.onAuthStart()
descriptors = self.service.getDescriptors()
self.peripheral.writeCharacteristic(self.HANDLE_AUTH_INIT, self.XIAOMI_KEY1, True)
descriptors[1].write(self.SUBSCRIBE_TRUE, True)
self.peripheral.writeCharacteristic(self.HANDLE_AUTH, XiaomiEncryption.cipher(XiaomiEncryption.mixA(self.reversed_mac, self.PRODUCT_ID), self.token), "true")
self.peripheral.waitForNotifications(10.0) # 10 sec auth timeout
if not self.auth_can_pass: # this flag should be changed in handleNotification
self.onAuthFail()
return
self.peripheral.writeCharacteristic(self.HANDLE_AUTH, XiaomiEncryption.cipher(self.token, self.XIAOMI_KEY2), True)
# have to read firmware version to complete auth
self.firmware_version = XiaomiEncryption.cipher(self.token, self.peripheral.readCharacteristic(self.HANDLE_READ_FIRMWARE_VERSION)).decode()
self.beacon_key = bytes(XiaomiEncryption.cipher(self.token, self.peripheral.readCharacteristic(self.HANDLE_BEACON_KEY)))
self.onAuthDone(self.beacon_key)
return True
def subscribe(self):
self.scanner_run = True
scanner = Scanner().withDelegate(self)
self.scanner = scanner
scanner.start()
while self.scanner_run: # main loop
scanner.process(1) # 1 seconds timeout
scanner.stop()
def unsubscribe(self):
self.scanner_run = False
def _connect(self):
try:
self.peripheral = Peripheral(deviceAddr=self.mac)
self.peripheral.setDelegate(self)
self.service = self.peripheral.getServiceByUUID(self.UUID_PRIMARY_SERVICE)
except:
return False
return True
def handleNotification(self, cHandle, data):
if cHandle == self.HANDLE_AUTH:
decrypted_token = XiaomiEncryption.cipher(XiaomiEncryption.mixB(self.reversed_mac, self.PRODUCT_ID),
XiaomiEncryption.cipher(XiaomiEncryption.mixA(self.reversed_mac, self.PRODUCT_ID), data))
if (decrypted_token != self.token):
return # raise Exception("Authentication failed.")
self.auth_can_pass = True
def handleDiscovery(self, dev, isNewDev, isNewData):
if dev.addr != self.mac:
return
for (id, decsr, data) in dev.getScanData():
if id != 22:
continue
data = bytes.fromhex(data)
if len(data) < 23:
continue
packet_id = data[6]
if packet_id == self.prev_packet_id:
continue
self.prev_packet_id = packet_id
decrypted = XiaomiEncryption.decryptMiBeaconV2(self.beacon_key, data)
# The decrypted payload can be read as follows.
# 0110 = Button (= type of message according to the MiBeacon protocol)
# 03 = length of data
# 00 = value1
# ff = value2
# 04 = state
fields = struct.unpack(">HBbbB", decrypted[0:6])
if fields[0] != 0x0110: # unknown packet, skip
continue
if fields[1] != 3:
# never seen such packet, dont know how to handle
continue
self.onDataPacket(fields[2], fields[3], fields[4], decrypted)
def onDataPacket(self, value1, value2, button_state, raw):
if button_state == 4:
if value1 == 0:
return self.onRotate(value2, False)
if value2 == 0:
return self.onRotate(value1, True)
if value1 != 0 and value2 != 0:
# both rotated with button pressed and not.
# occures only near with button_pressed event
# print(value1, value2, button_state)
return
if button_state == 3:
if value1 == 0:
if value2 == 1:
return self.onClick()
else:
return self.onMultipleClicks(value2)
if value1 == 1:
return self.onLongPress(value2)
raise Exception("Unhandled dimmer packet: 0x%s" % raw.hex())
# methods to override
def onConnectionStart(self):
pass
def onConnectionDone(self):
pass
def onConnectionFail(self):
pass
def onAuthStart(self):
pass
def onAuthDone(self, beacon_key):
pass
def onAuthFail(self):
pass
# dimmer events
def onRotate(self, offset, button_down):
pass
def onClick(self):
pass
def onMultipleClicks(self, count):
pass
def onLongPress(self, duration):
pass