forked from jziolkowski/tdm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
611 lines (547 loc) · 15.9 KB
/
__init__.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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import logging
import re
from json import JSONDecodeError, loads
from PyQt5.QtCore import QObject, pyqtSignal
from Util.commands import commands as commands_json # noqa: F401
from Util.setoptions import setoptions # noqa: F401
commands = [
"Backlog",
"BlinkCount",
"BlinkTime",
"ButtonDebounce",
"FanSpeed",
"Interlock",
"LedMask",
"LedPower",
"LedPower",
"LedState",
"Power",
"PowerOnState",
"PulseTime",
"SwitchDebounce",
"SwitchMode",
"Delay",
"Emulation",
"Event",
"FriendlyName",
"Gpios",
"Gpio",
"I2Cscan",
"LogHost",
"LogPort",
"Modules",
"Module",
"OtaUrl",
"Pwm",
"PwmFrequency",
"PwmRange",
"Reset",
"Restart",
"Template",
"SaveData",
"SerialLog",
"Sleep",
"State",
"Status",
"SysLog",
"Timezone",
"TimeSTD",
"TimeDST",
"Upgrade",
"Upload",
"WebLog",
"AP",
"Hostname",
"IPAddress1",
"IPAddress2",
"IPAddress3",
"IPAddress4",
"NtpServer",
"Password",
"Ssid",
"WebPassword",
"WebSend",
"WebServer",
"WebRefresh",
"WebColor",
"WifiConfig",
"ButtonRetain",
"ButtonTopic",
"FullTopic",
"GroupTopic",
"MqttClient",
"MqttFingerprint",
"MqttHost",
"MqttPassword",
"MqttPort",
"MqttRetry",
"MqttUser",
"PowerRetain",
"Prefix1",
"Prefix2",
"Prefix3",
"Publish",
"Publish2",
"SensorRetain",
"StateText1",
"StateText2",
"StateText3",
"StateText4",
"SwitchRetain",
"SwitchTopic",
"TelePeriod",
"Topic",
"Rule",
"RuleTimer",
"Mem",
"Var",
"Add",
"Sub",
"Mult",
"Scale",
"CalcRes",
"Latitude",
"Longitude",
"Timers",
"Timer",
"AdcParam",
"Altitude",
"AmpRes",
"Counter",
"CounterDebounce",
"CounterType",
"EnergyRes",
"HumRes",
"PressRes",
"Sensor13",
"Sensor15",
"Sensor20",
"Sensor27",
"Sensor34",
"TempRes",
"VoltRes",
"WattRes",
"WeightRes",
"AmpRes",
"CurrentHigh",
"CurrentLow",
"CurrentSet",
"EnergyRes",
"EnergyReset",
"EnergyReset1",
"EnergyReset2",
"EnergyReset3",
"FreqRes",
"FrequencySet",
"MaxPower",
"MaxPowerHold",
"MaxPowerWindow",
"PowerDelta",
"PowerHigh",
"PowerLow",
"PowerSet",
"Status",
"VoltageHigh",
"VoltageLow",
"VoltageSet",
"VoltRes",
"WattRes",
"Channel",
"Color",
"Color2",
"Color3",
"Color4",
"Color5",
"Color6",
"CT",
"Dimmer",
"Fade",
"HsbColor",
"HsbColor1",
"HsbColor2",
"HsbColor3",
"Led",
"LedTable",
"Pixels",
"Rotation",
"Scheme",
"Speed",
"Wakeup",
"WakeupDuration",
"White",
"Width1",
"Width2",
"Width3",
"Width4",
"RfCode",
"RfHigh",
"RfHost",
"RfKey",
"RfLow",
"RfRaw",
"RfSync",
"IRsend",
"IRhvac",
"SetOption0",
"SetOption1",
"SetOption2",
"SetOption3",
"SetOption4",
"SetOption8",
"SetOption10",
"SetOption11",
"SetOption12",
"SetOption13",
"SetOption15",
"SetOption16",
"SetOption17",
"SetOption18",
"SetOption19",
"SetOption20",
"SetOption21",
"SetOption24",
"SetOption26",
"SetOption28",
"SetOption29",
"SetOption30",
"SetOption31",
"SetOption32",
"SetOption33",
"SetOption34",
"SetOption36",
"SetOption37",
"SetOption38",
"SetOption51",
"SetOption52",
"SetOption53",
"SetOption54",
"SetOption55",
"SetOption56",
"SetOption57",
"SetOption58",
"SetOption59",
"SetOption60",
"SetOption61",
"SetOption62",
"SetOption63",
"SetOption64",
"Baudrate",
"SBaudrate",
"SerialDelimiter",
"SerialDelimiter",
"SerialSend",
"SerialSend2",
"SerialSend3",
"SerialSend4",
"SerialSend5",
"SSerialSend",
"SSerialSend2",
"SSerialSend3",
"SSerialSend4",
"SSerialSend5",
"MP3DAC",
"MP3Device",
"MP3EQ",
"MP3Pause",
"MP3Play",
"MP3Reset",
"MP3Stop",
"MP3Track",
"MP3Volume",
"DomoticzIdx",
"DomoticzKeyIdx",
"DomoticzSensorIdx",
"DomoticzSwitchIdx",
"DomoticzUpdateTimer",
"KnxTx_Cmnd",
"KnxTx_Val",
"KNX_ENABLED",
"KNX_ENHANCED",
"KNX_PA",
"KNX_GA",
"KNX_GA",
"KNX_CB",
"KNX_CB",
"Display",
"DisplayAddress",
"DisplayDimmer",
"DisplayMode",
"DisplayModel",
"DisplayRefresh",
"DisplaySize",
"DisplayRotate",
"DisplayText",
"DisplayCols",
"DisplayRows",
"DisplayFont",
]
prefixes = ["tele", "stat", "cmnd"]
default_patterns = [
"%prefix%/%topic%/", # = %prefix%/%topic% (Tasmota default)
"%topic%/%prefix%/", # = %topic%/%prefix% (Tasmota with SetOption19 enabled for HomeAssistant AutoDiscovery)
]
custom_patterns = []
resets = [
"1: reset device settings to firmware defaults",
"2: erase flash, reset device settings to firmware defaults",
"3: erase flash SDK parameters",
"4: reset device settings to firmware defaults, keep Wi-Fi credentials",
"5: erase flash, reset parameters to firmware defaults, keep Wi-Fi settings",
"6: erase flash, reset parameters to firmware defaults, keep Wi-Fi and MQTT settings",
"99: reset device bootcount to zero",
]
template_adc = {
"0": "None",
"15": "User",
"1": "Analog",
"2": "Temperature",
"3": "Light",
"4": "Button",
"5": "Buttoni",
}
def initial_commands():
commands = [
["status", 0],
["template", ""],
["modules", ""],
["gpio", ""],
["gpios", "255"],
["buttondebounce", ""],
["switchdebounce", ""],
["interlock", ""],
["blinktime", ""],
["blinkcount", ""],
["mqttlog", ""], # will be removed after MqttLog will be added to Status 3
]
for pt in range(8):
commands.append(["pulsetime{}".format(pt + 1), ""])
return commands
def parse_topic(full_topic, topic):
"""
:param full_topic: FullTopic to match against
:param topic: MQTT topic from which the reply arrived
:return: If match is found, returns dictionary including device Topic, prefix (cmnd/tele/stat) and reply endpoint
"""
full_topic = (
"{}(?P<reply>.*)".format(full_topic).replace("%topic%", "(?P<topic>.*?)").replace("%prefix%", "(?P<prefix>.*?)")
)
match = re.fullmatch(full_topic, topic)
if match:
return match.groupdict()
return {}
def parse_payload(payload):
match = re.match(r"(\d+) \((.*)\)", payload)
if match:
return dict([match.groups()])
return {}
def expand_fulltopic(fulltopic):
fulltopics = []
for prefix in prefixes:
topic = fulltopic.replace("%prefix%", prefix).replace("%topic%", "+") + "#" # expand prefix and topic
topic = topic.replace("+/#", "#") # simplify wildcards
fulltopics.append(topic)
return fulltopics
class TasmotaEnvironment(object):
def __init__(self):
self.devices = []
self.lwts = []
def find_device(self, topic):
for d in self.devices:
if d.matches(topic):
return d
return None
class TasmotaDevice(QObject):
update_telemetry = pyqtSignal()
def __init__(self, topic, fulltopic, devicename=""):
super(TasmotaDevice, self).__init__()
self.p = {
"LWT": "undefined",
"Topic": topic,
"FullTopic": fulltopic,
"DeviceName": devicename,
"Template": {},
}
self.debug = False
self.env = None
self.history = []
self.property_changed = None # property changed callback pointer
self.t = None
self.modules = {} # supported modules
self.module_changed = None # module changed callback pointer
self.gpios = {} # supported GPIOs
self.gpio = {} # gpio config
self.reply = ""
self.prefix = ""
def build_topic(self, prefix):
return self.p['FullTopic'].replace("%prefix%", prefix).replace("%topic%", self.p['Topic']).rstrip("/")
def cmnd_topic(self, command=""):
if command:
return "{}/{}".format(self.build_topic("cmnd"), command)
return self.build_topic("cmnd")
def stat_topic(self):
return self.build_topic("stat")
def tele_topic(self, endpoint=""):
if endpoint:
return "{}/{}".format(self.build_topic("tele"), endpoint)
return self.build_topic("tele")
def is_default(self):
return self.p['FullTopic'] in ["%prefix%/%topic%/", "%topic%/%prefix%/"]
def update_property(self, k, v):
old = self.p.get('k') # safely get the old value
if self.property_changed and (
not old or old != v
): # If property_changed callback is set then check previous value presence and
self.property_changed(self, k) # compare with new value. Trigger the callback if value has changed
self.p[k] = v # store the new value
def module(self):
mdl = self.p.get('Module')
if mdl:
return self.modules.get(str(mdl))
if self.p['LWT'] == 'Online':
return "Fetching module name..."
def matches(self, topic):
if topic == self.p['Topic']:
return True
parsed = parse_topic(self.p['FullTopic'], topic)
self.reply = parsed.get('reply')
self.prefix = parsed.get('prefix')
return parsed.get('topic') == self.p['Topic']
def parse_message(self, topic, msg):
parse_statuses = ["STATUS{}".format(s) for s in [1, 2, 3, 4, 5, 6, 7, 9]]
if self.prefix in ("stat", "tele"):
payload = None
if self.reply == 'STATUS':
try:
payload = loads(msg)
except JSONDecodeError as e:
logging.critical("PARSER: Can't parse STATUS (%s): %s", e, msg)
if payload:
payload = payload.get('Status', {})
for k, v in payload.items():
if k == "FriendlyName":
for fnk, fnv in enumerate(v, start=1):
self.update_property("FriendlyName{}".format(fnk), fnv)
else:
self.update_property(k, v)
elif self.reply in parse_statuses:
try:
payload = loads(msg)
except JSONDecodeError as e:
logging.critical("PARSER: Can't parse %s (%s): %s", self.reply, e, msg)
if payload:
payload = payload[list(payload.keys())[0]]
for k, v in payload.items():
self.update_property(k, v)
elif self.reply in ('STATE', 'STATUS11'):
try:
payload = loads(msg)
except JSONDecodeError as e:
logging.critical("PARSER: Can't parse %s (%s): %s", self.reply, e, msg)
if payload:
if self.reply == 'STATUS11':
payload = payload['StatusSTS']
for k, v in payload.items():
if isinstance(v, dict):
for kk, vv in v.items():
self.update_property(kk, vv)
else:
self.update_property(k, v)
elif self.reply in ('SENSOR', 'STATUS8', 'STATUS10'):
try:
payload = loads(msg)
except JSONDecodeError as e:
logging.critical("PARSER: Can't parse %s (%s): %s", self.reply, e, msg)
if payload:
if self.reply in ('STATUS8', 'STATUS10'):
payload = payload['StatusSNS']
self.t = payload
self.update_telemetry.emit()
elif msg.startswith("{"):
try:
payload = loads(msg)
except JSONDecodeError as e:
logging.critical("PARSER: Can't parse %s (%s): %s", self.reply, e, msg)
if payload:
keys = list(payload.keys())
fk = keys[0]
if self.reply == 'RESULT' and fk.startswith("Modules") or self.reply == "MODULES":
for k, v in payload.items():
if isinstance(v, list):
for mdl in v:
self.modules.update(parse_payload(mdl))
elif isinstance(v, dict):
self.modules.update(v)
self.module_changed(self)
elif self.reply == 'RESULT' and fk == 'NAME' or self.reply == "TEMPLATE":
self.p['Template'] = payload
if self.module_changed:
self.module_changed(self)
elif self.reply == 'RESULT' and fk.startswith("GPIOs") or self.reply == "GPIOS":
for k, v in payload.items():
if isinstance(v, list):
for gp in v:
self.gpios.update(parse_payload(gp))
elif isinstance(v, dict):
self.gpios.update(v)
elif self.reply == 'RESULT' and fk.startswith("GPIO") or self.reply == "GPIO":
for gp, gp_val in payload.items():
if not gp == "GPIO":
if isinstance(gp_val, str):
gp_id = gp_val.split(" (")[0]
self.gpio[gp] = gp_id
elif isinstance(gp_val, dict):
self.gpio[gp] = list(gp_val.keys())[0]
else:
for k, v in payload.items():
self.update_property(k, v)
def power(self):
return {k: v for k, v in self.p.items() if k.startswith('POWER')}
def pulsetime(self):
ptime = {}
for k, v in self.p.items():
if k.startswith('PulseTime'):
val = 0
if isinstance(v, dict):
first_key = list(v.keys())[0]
if first_key == "Set":
val = v['Set']
else:
val = first_key
elif isinstance(v, str):
val = v.split(" ")[0]
ptime[k] = int(val)
return ptime
def pwm(self):
return {k: v for k, v in self.p.items() if k.startswith('PWM') or (k != "Channel" and k.startswith("Channel"))}
def color(self):
color = {k: self.p[k] for k in ["Color", "Dimmer", "HSBColor"] if k in self.p.keys()}
color.update({17: self.setoption(17), 68: self.setoption(68)})
return color
def setoption(self, o):
if 0 <= o < 32:
reg = 0
elif 32 <= o < 50:
reg = 1
else:
reg = 2
so = self.p.get('SetOption')
if so:
if reg in (0, 2, 3):
options = int(so[reg], 16)
if reg > 1:
o -= 50
state = int(options >> o & 1)
else:
o -= 32
if len(so[reg]) == 18:
split_register = [int(so[reg][opt * 2 : opt * 2 + 2], 16) for opt in range(18)]
else:
split_register = [-1] * 18
return split_register[o]
return state
return -1
@property
def name(self):
return self.p.get('DeviceName') or self.p.get('FriendlyName1', self.p['Topic'])
def __repr__(self):
return "<TasmotaDevice {}: {}>".format(self.name, self.p['Topic'])