forked from beveradb/pysonofflan
/
client.py
447 lines (355 loc) · 13.6 KB
/
client.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import json
import logging
import time
from typing import Dict, Union, Callable, Awaitable
import asyncio
import traceback
import collections
import requests
from zeroconf import ServiceBrowser, Zeroconf
from pysonofflanr3 import sonoffcrypto
import socket
class SonoffLANModeClient:
"""
Implementation of the Sonoff LAN Mode Protocol R3
Uses protocol as was documented documented by Itead
This document has since been unpublished
"""
"""
Initialise class with connection parameters
:param str host: host name (is ip address)
:param device_id: the device name in the mDS servie name
:return:
"""
DEFAULT_TIMEOUT = 5
DEFAULT_PING_INTERVAL = 5
SERVICE_TYPE = "_ewelink._tcp.local."
# only a single zeroconf instance for all instances of this class
zeroconf = Zeroconf()
def __init__(
self,
host: str,
event_handler: Callable[[str], Awaitable[None]],
ping_interval: int = DEFAULT_PING_INTERVAL,
timeout: int = DEFAULT_TIMEOUT,
logger: logging.Logger = None,
loop=None,
device_id: str = "",
api_key: str = "",
outlet: int = None,
):
self.host = host
self.device_id = device_id
self.api_key = api_key
self.outlet = outlet
self.logger = logger
self.event_handler = event_handler
self.connected_event = asyncio.Event()
self.disconnected_event = asyncio.Event()
self.service_browser = None
self.loop = loop
self.http_session = None
self.my_service_name = None
self.last_request = None
self.encrypted = False
self.type = None
self._info_cache = None
self._last_params = {"switch": "off"}
self._times_added = 0
if self.logger is None:
self.logger = logging.getLogger(__name__)
def connect(self):
"""
Setup a mDNS listener
"""
# listen for any added SOnOff
self.service_browser = ServiceBrowser(
SonoffLANModeClient.zeroconf,
SonoffLANModeClient.SERVICE_TYPE,
listener=self,
)
def close_connection(self):
self.logger.debug("enter close_connection()")
self.service_browser = None
self.disconnected_event.set()
self.my_service_name = None
def remove_service(self, zeroconf, type, name):
if self.my_service_name == name:
self._info_cache = None
self.logger.debug("Service %s flagged for removal" % name)
self.loop.run_in_executor(None, self.retry_connection)
def add_service(self, zeroconf, type, name):
if self.my_service_name is not None:
if self.my_service_name == name:
self._times_added += 1
self.logger.info(
"Service %s added again (%s times)"
% (name, self._times_added)
)
self.my_service_name = None
asyncio.run_coroutine_threadsafe(
self.event_handler({}), self.loop
)
if self.my_service_name is None:
info = zeroconf.get_service_info(type, name)
found_ip = self.parseAddress(info.address)
if self.device_id is not None:
if (
name
== "eWeLink_"
+ self.device_id
+ "."
+ SonoffLANModeClient.SERVICE_TYPE
):
self.my_service_name = name
elif self.host is not None:
try:
if socket.gethostbyname(self.host) == found_ip:
self.my_service_name = name
except TypeError:
if self.host == found_ip:
self.my_service_name = name
if self.my_service_name is not None:
self.logger.info(
"Service type %s of name %s added", type, name
)
# listen for updates to the specific device
# (needed for zerconf 0.23.0, 0.24.0, fixed in later versions)
self.service_browser = ServiceBrowser(
zeroconf, name, listener=self
)
# create an http session so we can use http keep-alives
self.http_session = requests.Session()
# add the http headers
headers = collections.OrderedDict(
{
"Content-Type": "application/json;charset=UTF-8",
# "Connection": "keep-alive",
"Accept": "application/json",
"Accept-Language": "en-gb",
# "Content-Length": "0",
# "Accept-Encoding": "gzip, deflate",
# "Cache-Control": "no-store",
}
)
# self.http_session.headers.update(headers)
# needed to keep headers in same order
self.http_session.headers = headers
# find socket for end-point
socket_text = found_ip + ":" + str(info.port)
self.logger.debug("service is at %s", socket_text)
self.url = "http://" + socket_text
# setup retries
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# no retries at moment, control in sonoffdevice
retries = Retry(
total=0,
backoff_factor=0.5,
method_whitelist=["POST"],
status_forcelist=None,
)
self.http_session.mount(
"http://", HTTPAdapter(max_retries=retries)
)
# process the initial message
self.update_service(zeroconf, type, name)
def update_service(self, zeroconf, type, name):
# This is needed for zeroconfg 0.24.1
# onwards as updates come to the parent node
if self.my_service_name != name:
return
try:
info = zeroconf.get_service_info(type, name)
# This is useful optimsation for 0.24.1 onwards
# as multiple updates that are the same are received
if info.properties == self._info_cache:
self.logger.debug("same update received for device: %s", name)
return
else:
self._info_cache = info.properties
self.logger.debug("properties: %s", info.properties)
self.type = info.properties.get(b"type")
self.logger.debug("type: %s", self.type)
data1 = info.properties.get(b"data1")
data2 = info.properties.get(b"data2")
if data2 is not None:
data1 += data2
data3 = info.properties.get(b"data3")
if data3 is not None:
data1 += data3
data4 = info.properties.get(b"data4")
if data4 is not None:
data1 += data4
if info.properties.get(b"encrypt"):
self.encrypted = True
# decrypt the message
iv = info.properties.get(b"iv")
data = sonoffcrypto.decrypt(data1, iv, self.api_key)
self.logger.debug("decrypted data: %s", data)
else:
self.encrypted = False
data = data1
self.properties = info.properties
# process the events on an event loop
# this method is on a background thread called from zeroconf
asyncio.run_coroutine_threadsafe(
self.event_handler(data), self.loop
)
except ValueError as ex:
self.logger.error(
"Error updating service for device %s: %s"
" Probably wrong API key.",
self.device_id,
format(ex),
)
asyncio.run_coroutine_threadsafe(
self.event_handler(None), self.loop
)
except TypeError as ex:
self.logger.error(
"Error updating service for device %s: %s"
" Probably missing API key.",
self.device_id,
format(ex),
)
asyncio.run_coroutine_threadsafe(
self.event_handler(None), self.loop
)
except Exception as ex:
self.logger.error(
"Error updating service for device %s: %s, %s",
self.device_id,
format(ex),
traceback.format_exc(),
)
asyncio.run_coroutine_threadsafe(
self.event_handler(None), self.loop
)
def retry_connection(self):
while True:
try:
self.logger.debug(
"Sending retry message for %s" % self.device_id
)
self.send_signal_strength()
self.logger.info(
"Service %s flagged for removal, but is still active!"
% self.device_id
)
break
except OSError as ex:
self.logger.debug(
"Connection issue for device %s: %s",
self.device_id,
format(ex),
)
self.logger.info("Service %s removed" % self.device_id)
self.close_connection()
break
except Exception as ex:
self.logger.error(
"Retry_connection() Unexpected error for device %s: %s %s",
self.device_id,
format(ex),
traceback.format_exc(),
)
break
def send_switch(self, request: Union[str, Dict]):
if self.type == b"strip":
response = self.send(request, self.url + "/zeroconf/switches")
else:
response = self.send(request, self.url + "/zeroconf/switch")
try:
response_json = json.loads(response.content.decode("utf-8"))
error = response_json["error"]
if error != 0:
self.logger.warning(
"error received: %s, %s", self.device_id, response.content
)
# no need to process error, retry will resend message
else:
self.logger.debug("message sent to switch successfully")
# nothing to do, update is processed via the mDNS update
return response
except Exception as ex:
self.logger.error(
"error %s processing response: %s, %s",
format(ex),
response,
response.content,
)
def send_signal_strength(self):
response = self.send(
self.get_update_payload(self.device_id, {}),
self.url + "/zeroconf/signal_strength",
)
if response.status_code == 500:
self.logger.error("500 received")
raise OSError
else:
return response
def send(self, request: Union[str, Dict], url):
"""
Send message to an already-connected Sonoff LAN Mode Device
and return the response.
:param request: command to send to the device (can be dict or json)
:return:
"""
data = json.dumps(request, separators=(",", ":"))
self.logger.debug("Sending http message to %s: %s", url, data)
response = self.http_session.post(url, data=data)
self.logger.debug(
"response received: %s %s", response, response.content
)
return response
def get_update_payload(self, device_id: str, params: dict) -> Dict:
self._last_params = params
if self.type == b"strip" and params != {} and params is not None:
if self.outlet is None:
self.outlet = 0
switches = {"switches": [{"switch": "off", "outlet": 0}]}
switches["switches"][0]["switch"] = params["switch"]
switches["switches"][0]["outlet"] = int(self.outlet)
params = switches
payload = {
"sequence": str(
int(time.time() * 1000)
), # otherwise buffer overflow type issue caused in the device
"deviceid": device_id,
}
if self.encrypted:
self.logger.debug("params: %s", params)
if self.api_key != "" and self.api_key is not None:
sonoffcrypto.format_encryption_msg(
payload, self.api_key, params
)
self.logger.debug("encrypted: %s", payload)
else:
self.logger.error(
"missing api_key field for device: %s", self.device_id
)
else:
payload["encrypt"] = False
payload["data"] = params
self.logger.debug("message to send (plaintext): %s", payload)
return payload
def parseAddress(self, address):
"""
Resolve the IP address of the device
:param address:
:return: add_str
"""
add_list = []
for i in range(4):
add_list.append(int(address.hex()[(i * 2): (i + 1) * 2], 16))
add_str = (
str(add_list[0])
+ "."
+ str(add_list[1])
+ "."
+ str(add_list[2])
+ "."
+ str(add_list[3])
)
return add_str