forked from emontnemery/domoticz_mqtt_discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
1928 lines (1776 loc) · 75.5 KB
/
plugin.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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MQTT discovery plugin
#
"""
<plugin key="MQTTDiscovery" name="MQTT discovery" version="0.0.6">
<description>
MQTT discovery, compatible with home-assistant.<br/><br/>
Specify MQTT server and port.<br/>
<br/>
Automatically creates Domoticz device entries for all discovered devices.<br/>
</description>
<params>
<param field="Address" label="MQTT Server address" width="300px" required="true" default="127.0.0.1"/>
<param field="Port" label="Port" width="300px" required="true" default="1883"/>
<!-- <param field="Mode5" label="MQTT QoS" width="300px" default="0"/> -->
<param field="Username" label="Username" width="300px"/>
<param field="Password" label="Password" width="300px"/>
<!-- <param field="Mode1" label="CA Filename" width="300px"/> -->
<param field="Mode2" label="Discovery topic" width="300px" default="homeassistant"/>
<param field="Mode4" label="Ignored device topics (comma separated)" width="300px" default="tasmota/sonoff/"/>
<param field="Mode3" label="Options" width="300px"/>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="Extra verbose: (Framework logs 2+4+8+16+64 + MQTT dump)" value="Verbose+"/>
<option label="Verbose: (Framework logs 2+4+8+16+64 + MQTT dump)" value="Verbose"/>
<option label="Normal: (Framework logs 2+4+8)" value="Debug"/>
<option label="None" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import Domoticz
# from Domoticz import Devices # Used for local debugging without Domoticz
# from Domoticz import Settings # Used for local debugging without Domoticz
from datetime import datetime
from itertools import count, filterfalse
import json
import re
import time
import traceback
class MqttClient:
Address = ""
Port = ""
mqttConn = None
isConnected = False
mqttConnectedCb = None
mqttDisconnectedCb = None
mqttPublishCb = None
def __init__(
self,
destination,
port,
mqttConnectedCb,
mqttDisconnectedCb,
mqttPublishCb,
mqttSubackCb,
):
Domoticz.Debug("MqttClient::__init__")
self.Address = destination
self.Port = port
self.mqttConnectedCb = mqttConnectedCb
self.mqttDisconnectedCb = mqttDisconnectedCb
self.mqttPublishCb = mqttPublishCb
self.mqttSubackCb = mqttSubackCb
self.Open()
def __str__(self):
Domoticz.Debug("MqttClient::__str__")
if self.mqttConn != None:
return str(self.mqttConn)
else:
return "None"
def Open(self):
Domoticz.Debug("MqttClient::Open")
if self.mqttConn != None:
self.Close()
self.isConnected = False
self.mqttConn = Domoticz.Connection(
Name=self.Address,
Transport="TCP/IP",
Protocol="MQTT",
Address=self.Address,
Port=self.Port,
)
self.mqttConn.Connect()
def Connect(self):
Domoticz.Debug("MqttClient::Connect")
if self.mqttConn == None:
self.Open()
else:
ID = (
"Domoticz_"
+ Parameters["Key"]
+ "_"
+ str(Parameters["HardwareID"])
+ "_"
+ str(int(time.time()))
)
Domoticz.Log("MQTT CONNECT ID: '" + ID + "'")
self.mqttConn.Send({"Verb": "CONNECT", "ID": ID})
def Ping(self):
Domoticz.Debug("MqttClient::Ping")
if self.mqttConn == None or not self.isConnected:
self.Open()
else:
self.mqttConn.Send({"Verb": "PING"})
def Publish(self, topic, payload, retain=0):
Domoticz.Log("MqttClient::Publish " + topic + " (" + payload + ")")
if self.mqttConn == None or not self.isConnected:
self.Open()
else:
self.mqttConn.Send(
{
"Verb": "PUBLISH",
"Topic": topic,
"Payload": bytearray(payload, "utf-8"),
"Retain": retain,
}
)
def Subscribe(self, topics):
Domoticz.Debug("MqttClient::Subscribe")
subscriptionlist = []
for topic in topics:
subscriptionlist.append({"Topic": topic, "QoS": 0})
if self.mqttConn == None or not self.isConnected:
self.Open()
else:
self.mqttConn.Send({"Verb": "SUBSCRIBE", "Topics": subscriptionlist})
def Close(self):
Domoticz.Log("MqttClient::Close")
# TODO: Disconnect from server
self.mqttConn = None
self.isConnected = False
def onConnect(self, Connection, Status, Description):
Domoticz.Debug("MqttClient::onConnect")
if Status == 0:
Domoticz.Log(
"Successful connect to: " + Connection.Address + ":" + Connection.Port
)
self.Connect()
else:
Domoticz.Log(
"Failed to connect to: "
+ Connection.Address
+ ":"
+ Connection.Port
+ ", Description: "
+ Description
)
def onDisconnect(self, Connection):
Domoticz.Log(
"MqttClient::onDisonnect Disconnected from: "
+ Connection.Address
+ ":"
+ Connection.Port
)
self.Close()
# TODO: Reconnect?
if self.mqttDisconnectedCb != None:
self.mqttDisconnectedCb()
def onMessage(self, Connection, Data):
topic = ""
if "Topic" in Data:
topic = Data["Topic"]
payloadStr = ""
if "Payload" in Data:
payloadStr = Data["Payload"].decode("utf8", "replace")
payloadStr = str(payloadStr.encode("unicode_escape"))
# Domoticz.Debug("MqttClient::onMessage called for connection: '"+Connection.Name+"' type:'"+Data['Verb']+"' topic:'"+topic+"' payload:'" + payloadStr + "'")
if Data["Verb"] == "CONNACK":
self.isConnected = True
if self.mqttConnectedCb != None:
self.mqttConnectedCb()
if Data["Verb"] == "SUBACK":
if self.mqttSubackCb != None:
self.mqttSubackCb()
if Data["Verb"] == "PUBLISH":
if self.mqttPublishCb != None:
self.mqttPublishCb(topic, Data["Payload"])
CONF_DEVICE = "device"
TOPIC_BASE = "~"
ABBREVIATIONS = {
"aux_cmd_t": "aux_command_topic",
"aux_stat_tpl": "aux_state_template",
"aux_stat_t": "aux_state_topic",
"avty_t": "availability_topic",
"away_mode_cmd_t": "away_mode_command_topic",
"away_mode_stat_tpl": "away_mode_state_template",
"away_mode_stat_t": "away_mode_state_topic",
"bri_cmd_t": "brightness_command_topic",
"bri_scl": "brightness_scale",
"bri_stat_t": "brightness_state_topic",
"bri_val_tpl": "brightness_value_template",
"clr_temp_cmd_tpl": "color_temp_command_template",
"bat_lev_t": "battery_level_topic",
"bat_lev_tpl": "battery_level_template",
"chrg_t": "charging_topic",
"chrg_tpl": "charging_template",
"clr_temp_cmd_t": "color_temp_command_topic",
"clr_temp_stat_t": "color_temp_state_topic",
"clr_temp_val_tpl": "color_temp_value_template",
"cln_t": "cleaning_topic",
"cln_tpl": "cleaning_template",
"cmd_t": "command_topic",
"curr_temp_t": "current_temperature_topic",
"dev": "device",
"dev_cla": "device_class",
"dock_t": "docked_topic",
"dock_tpl": "docked_template",
"err_t": "error_topic",
"err_tpl": "error_template",
"fanspd_t": "fan_speed_topic",
"fanspd_tpl": "fan_speed_template",
"fanspd_lst": "fan_speed_list",
"fx_cmd_t": "effect_command_topic",
"fx_list": "effect_list",
"fx_stat_t": "effect_state_topic",
"fx_val_tpl": "effect_value_template",
"exp_aft": "expire_after",
"fan_mode_cmd_t": "fan_mode_command_topic",
"fan_mode_stat_tpl": "fan_mode_state_template",
"fan_mode_stat_t": "fan_mode_state_topic",
"frc_upd": "force_update",
"hold_cmd_t": "hold_command_topic",
"hold_stat_tpl": "hold_state_template",
"hold_stat_t": "hold_state_topic",
"ic": "icon",
"init": "initial",
"json_attr": "json_attributes",
"json_attr_t": "json_attributes_topic",
"max_temp": "max_temp",
"min_temp": "min_temp",
"mode_cmd_t": "mode_command_topic",
"mode_stat_tpl": "mode_state_template",
"mode_stat_t": "mode_state_topic",
"name": "name",
"on_cmd_type": "on_command_type",
"opt": "optimistic",
"osc_cmd_t": "oscillation_command_topic",
"osc_stat_t": "oscillation_state_topic",
"osc_val_tpl": "oscillation_value_template",
"pl_arm_away": "payload_arm_away",
"pl_arm_home": "payload_arm_home",
"pl_avail": "payload_available",
"pl_cls": "payload_close",
"pl_disarm": "payload_disarm",
"pl_hi_spd": "payload_high_speed",
"pl_lock": "payload_lock",
"pl_lo_spd": "payload_low_speed",
"pl_med_spd": "payload_medium_speed",
"pl_not_avail": "payload_not_available",
"pl_off": "payload_off",
"pl_on": "payload_on",
"pl_open": "payload_open",
"pl_osc_off": "payload_oscillation_off",
"pl_osc_on": "payload_oscillation_on",
"pl_stop": "payload_stop",
"pl_unlk": "payload_unlock",
"pow_cmd_t": "power_command_topic",
"ret": "retain",
"rgb_cmd_tpl": "rgb_command_template",
"rgb_cmd_t": "rgb_command_topic",
"rgb_stat_t": "rgb_state_topic",
"rgb_val_tpl": "rgb_value_template",
"send_cmd_t": "send_command_topic",
"send_if_off": "send_if_off",
"set_pos_tpl": "set_position_template",
"set_pos_t": "set_position_topic",
"spd_cmd_t": "speed_command_topic",
"spd_stat_t": "speed_state_topic",
"spd_val_tpl": "speed_value_template",
"spds": "speeds",
"stat_clsd": "state_closed",
"stat_off": "state_off",
"stat_on": "state_on",
"stat_open": "state_open",
"stat_t": "state_topic",
"stat_val_tpl": "state_value_template",
"sup_feat": "supported_features",
"swing_mode_cmd_t": "swing_mode_command_topic",
"swing_mode_stat_tpl": "swing_mode_state_template",
"swing_mode_stat_t": "swing_mode_state_topic",
"temp_cmd_t": "temperature_command_topic",
"temp_stat_tpl": "temperature_state_template",
"temp_stat_t": "temperature_state_topic",
"tilt_clsd_val": "tilt_closed_value",
"tilt_cmd_t": "tilt_command_topic",
"tilt_inv_stat": "tilt_invert_state",
"tilt_max": "tilt_max",
"tilt_min": "tilt_min",
"tilt_opnd_val": "tilt_opened_value",
"tilt_status_opt": "tilt_status_optimistic",
"tilt_status_t": "tilt_status_topic",
"t": "topic",
"uniq_id": "unique_id",
"unit_of_meas": "unit_of_measurement",
"val_tpl": "value_template",
"whit_val_cmd_t": "white_value_command_topic",
"whit_val_scl": "white_value_scale",
"whit_val_stat_t": "white_value_state_topic",
"whit_val_tpl": "white_value_template",
"xy_cmd_t": "xy_command_topic",
"xy_stat_t": "xy_state_topic",
"xy_val_tpl": "xy_value_template",
}
DEVICE_ABBREVIATIONS = {
"cns": "connections",
"ids": "identifiers",
"name": "name",
"mf": "manufacturer",
"mdl": "model",
"sw": "sw_version",
}
class BasePlugin:
# MQTT settings
mqttClient = None
mqttserveraddress = ""
mqttserverport = ""
debugging = "Normal"
cachedDeviceNames = {}
options = {
"addDiscoveredDeviceUsed": True, # Newly discovered devices added as "used" (visible in swithces tab) or not (only visible in devices list)
"updateRSSI": False, # Store Tasmota RSSI
"updateVCC": False,
} # Store Tasmota VCC as battery level
def copyDevices(self):
# self.cachedDevices = copy.deepcopy(Devices)
for k, Device in Devices.items():
self.cachedDeviceNames[k] = Device.Name
def deviceStr(self, unit):
name = "<UNKNOWN>"
if unit in Devices:
name = Devices[unit].Name
return format(unit, "03d") + "/" + name
def getUnit(self, device):
unit = -1
for k, dev in Devices.items():
if dev == device:
unit = k
return unit
def onStart(self):
# Parse options
self.debugging = Parameters["Mode6"]
DumpConfigToLog()
if self.debugging == "Verbose+":
Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
if self.debugging == "Verbose":
Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
if self.debugging == "Debug":
Domoticz.Debugging(2 + 4 + 8)
self.mqttserveraddress = Parameters["Address"].replace(" ", "")
self.mqttserverport = Parameters["Port"].replace(" ", "")
self.discoverytopic = Parameters["Mode2"]
self.ignoredtopics = Parameters["Mode4"].split(",")
options = ""
try:
options = json.loads(Parameters["Mode3"])
except ValueError:
options = Parameters["Mode3"]
if type(options) == str or type(options) == int:
# JSON decoding failed, check for deprecated used/unused setting
# <options>
# <option label="Unused" value="0"/>
# <option label="Used" value="1" default="true" />
# </options>
Domoticz.Log(
"Warning: could not load plugin options '"
+ Parameters["Mode3"]
+ "' as JSON object"
)
try:
if int(options) == 0:
self.options["addDiscoveredDeviceUsed"] = False
if int(options) == 1:
self.options["addDiscoveredDeviceUsed"] = True
except ValueError: # Options not a valid int
pass
elif type(options) == dict:
self.options.add(options)
Domoticz.Log("Plugin options: " + str(self.options))
# Enable heartbeat
Domoticz.Heartbeat(10)
# Connect to MQTT server
self.prefixpos = 0
self.topicpos = 0
self.discoverytopiclist = self.discoverytopic.split("/")
self.mqttClient = MqttClient(
self.mqttserveraddress,
self.mqttserverport,
self.onMQTTConnected,
self.onMQTTDisconnected,
self.onMQTTPublish,
self.onMQTTSubscribed,
)
self.copyDevices()
def onConnect(self, Connection, Status, Description):
self.mqttClient.onConnect(Connection, Status, Description)
def onDisconnect(self, Connection):
self.mqttClient.onDisconnect(Connection)
def onMessage(self, Connection, Data):
self.mqttClient.onMessage(Connection, Data)
def onMQTTConnected(self):
Domoticz.Debug("onMQTTConnected")
self.mqttClient.Subscribe(self.getTopics())
def onMQTTDisconnected(self):
Domoticz.Debug("onMQTTDisconnected")
def onMQTTPublish(self, topic, rawmessage):
validJSON = False
message = ""
try:
message = json.loads(rawmessage.decode("utf8"))
validJSON = True
except ValueError:
message = rawmessage.decode("utf8")
topiclist = topic.split("/")
if self.debugging == "Verbose" or self.debugging == "Verbose+":
DumpMQTTMessageToLog(topic, rawmessage, "onMQTTPublish: ")
if topic in self.ignoredtopics:
Domoticz.Debug(
"Topic: '" + topic + "' included in ignored topics, message ignored"
)
return
if topic.startswith(self.discoverytopic):
discoverytopiclen = len(self.discoverytopiclist)
# Discovery topic format:
# <discovery_prefix>/<component>/[<node_id>/]<object_id>/<action>
if (
len(topiclist) == discoverytopiclen + 3
or len(topiclist) == discoverytopiclen + 4
):
component = topiclist[discoverytopiclen]
if len(topiclist) == discoverytopiclen + 3:
node_id = ""
object_id = topiclist[discoverytopiclen + 1]
action = topiclist[discoverytopiclen + 2]
else:
node_id = topiclist[discoverytopiclen + 1]
object_id = topiclist[discoverytopiclen + 2]
action = topiclist[discoverytopiclen + 3]
# Sensor support
if (component == "sensor") and (node_id != ""):
object_id = node_id
if (
validJSON
and action == "config"
and (
"command_topic" in message
or "state_topic" in message
or "cmd_t" in message
or "stat_t" in message
)
):
# Do expansion of the message
payload = dict(message)
for key in list(payload.keys()):
abbreviated_key = key
key = ABBREVIATIONS.get(key, key)
payload[key] = payload.pop(abbreviated_key)
if CONF_DEVICE in payload:
device = payload[CONF_DEVICE]
for key in list(device.keys()):
abbreviated_key = key
key = DEVICE_ABBREVIATIONS.get(key, key)
device[key] = device.pop(abbreviated_key)
base = payload.pop(TOPIC_BASE, None)
if base:
for key, value in payload.items():
if isinstance(value, str) and value:
if value[0] == TOPIC_BASE and key.endswith("_topic"):
payload[key] = "{}{}".format(base, value[1:])
if value[-1] == TOPIC_BASE and key.endswith("_topic"):
payload[key] = "{}{}".format(value[:-1], base)
# Add / update the device
self.updateDeviceSettings(object_id, component, payload)
else:
matchingDevices = self.getDevices(topic=topic)
for device in matchingDevices:
self.updateSwitch(device, topic, message)
# Try to update availability
self.updateAvailability(device, topic, message)
# Try to update sensor
self.updateSensor(device, topic, message)
# TODO: Try to update binary sensor
# self.updateBinarySensor(device, topic, message)
# TODO: Try to update tasmota status
self.updateTasmotaStatus(device, topic, message)
# Special handling of Tasmota STATE message
topic2, matches = re.subn(r"\/STATUS\d+$", "/STATE", topic)
if matches > 0:
topic2, matches = re.subn(r"\/stat\/", "/tele/", topic2)
if matches > 0:
matchingDevices = self.getDevices(topic=topic2)
for device in matchingDevices:
# Try to update tasmota settings
self.updateTasmotaSettings(device, topic, message)
def onMQTTSubscribed(self):
# (Re)subscribed, refresh device info
Domoticz.Debug("onMQTTSubscribed")
matchingDevices = self.getDevices(hasconfigkey="tasmota_tele_topic")
topics = set()
for device in matchingDevices:
# Refresh Tasmota specific data
try:
configdict = json.loads(device.Options["config"])
cmnd_topic = re.sub(
r"^tele\/", "cmnd/", configdict["tasmota_tele_topic"]
) # Replace tele with cmnd
cmnd_topic = re.sub(
r"\/tele\/", "/cmnd/", cmnd_topic
) # Replace tele with cmnd
cmnd_topic = re.sub(r"\/STATE", "", cmnd_topic) # Remove '/STATE'
if cmnd_topic not in topics:
self.refreshConfiguration(cmnd_topic)
topics.add(cmnd_topic)
except (ValueError, KeyError, TypeError) as e:
# Domoticz.Error("onMQTTSubscribed: Error: " + str(e))
Domoticz.Error(traceback.format_exc())
# ==========================================================DASHBOARD COMMAND=============================================================
def onCommand(self, Unit, Command, Level, sColor):
Domoticz.Log(
"onCommand "
+ self.deviceStr(Unit)
+ ": Command: '"
+ str(Command)
+ "', Level: "
+ str(Level)
+ ", Color:"
+ str(sColor)
)
if Unit in Devices:
try:
# TODO: Make sure the relevant command topic exists
configdict = json.loads(Devices[Unit].Options["config"])
if Command == "Set Level" and "set_position_topic" in configdict:
self.mqttClient.Publish(
configdict["set_position_topic"], str(Level)
)
elif Command == "Set Brightness" or Command == "Set Level":
self.mqttClient.Publish(
configdict["brightness_command_topic"], str(Level)
)
elif Command == "On":
payload = "ON"
if "payload_on" in configdict:
payload = configdict["payload_on"]
elif "payload_close" in configdict:
payload = configdict["payload_close"]
self.mqttClient.Publish(configdict["command_topic"], payload)
elif Command == "Off":
payload = "OFF"
if "payload_off" in configdict:
payload = configdict["payload_off"]
elif "payload_open" in configdict:
payload = configdict["payload_open"]
self.mqttClient.Publish(configdict["command_topic"], payload)
elif Command == "Stop":
payload = "STOP"
if "payload_stop" in configdict:
payload = configdict["payload_stop"]
self.mqttClient.Publish(configdict["command_topic"], payload)
elif Command == "Set Color":
try:
Color = json.loads(sColor)
except (ValueError, KeyError, TypeError) as e:
Domoticz.Error(
"onCommand: Illegal color: '" + str(sColor) + "'"
)
# TODO: This is not really correct, should check color mode
r = int(Color["r"] * Level / 100)
g = int(Color["g"] * Level / 100)
b = int(Color["b"] * Level / 100)
cw = int(Color["cw"] * Level / 100)
ww = int(Color["ww"] * Level / 100)
if (
"rgb_command_topic" in configdict
and "brightness_command_topic" in configdict
):
self.mqttClient.Publish(
configdict["rgb_command_topic"],
format(r, "02x")
+ format(g, "02x")
+ format(b, "02x")
+ format(cw, "02x")
+ format(ww, "02x"),
)
self.mqttClient.Publish(
configdict["brightness_command_topic"], str(Level)
)
elif (
"color_temp_command_topic" in configdict
and "brightness_command_topic" in configdict
):
self.mqttClient.Publish(
configdict["color_temp_command_topic"],
str(Color["t"] * (500 - 153) / 255 + 153),
)
self.mqttClient.Publish(
configdict["brightness_command_topic"], str(Level)
)
except (ValueError, KeyError, TypeError) as e:
Domoticz.Error("onCommand: Error: " + str(e))
else:
Domoticz.Debug("Device not found, ignoring command")
def onDeviceAdded(self, Unit):
Domoticz.Log("onDeviceAdded " + self.deviceStr(Unit))
self.copyDevices()
# TODO: Update subscribed topics
def onDeviceModified(self, Unit):
Domoticz.Log("onDeviceModified " + self.deviceStr(Unit))
if Unit in Devices and Devices[Unit].Name != self.cachedDeviceNames[Unit]:
Domoticz.Log(
"Device name changed, new name: "
+ Devices[Unit].Name
+ ", old name: "
+ self.cachedDeviceNames[Unit]
)
Device = Devices[Unit]
try:
configdict = json.loads(Device.Options["config"])
if (
"tasmota_tele_topic" in configdict and Device.SwitchType != 9
): # Do not set friendly name for button, they don't have their own friendly name
# Tasmota device!
device_nbr = ""
m = re.match(r".*_(\d)$", str(Device.Options["devicename"]))
if m:
device_nbr = m.group(1)
cmnd_topic = re.sub(
r"\/POWER\d?", "", configdict["command_topic"]
) # Remove '/POWER'
self.mqttClient.Publish(
cmnd_topic + "/FriendlyName" + str(device_nbr), Device.Name
)
except (ValueError, KeyError, TypeError) as e:
Domoticz.Debug("onDeviceModified: Error: " + str(e))
pass
self.copyDevices()
def onDeviceRemoved(self, Unit):
Domoticz.Log("onDeviceRemoved " + self.deviceStr(Unit))
if Unit in Devices and "devicename" in Devices[Unit].Options:
Device = Devices[Unit]
# Clear retained topic
devicetype = ""
if (
Device.Type == 0xF4
and Device.SubType == 0x49 # pTypeGeneralSwitch
and Device.SwitchType == 0 # sSwitchGeneralSwitch
): # OnOff
devicetype = "switch"
elif (
Device.Type == 0xF4
and Device.SubType == 0x49 # pTypeGeneralSwitch
and Device.SwitchType == 7 # sSwitchGeneralSwitch
): # Dimmer
devicetype = "light"
elif Device.Type == 0xF1: # pTypeColorSwitch
devicetype = "light"
elif (
Device.Type == 0xF4
and Device.SubType == 0x49 # pTypeGeneralSwitch
and ( # sSwitchGeneralSwitch
(Device.SwitchType == 3)
or (Device.SwitchType == 15) # Blind (up/down buttons)
or ( # Venetian blinds EU (up/down/stop buttons)
Device.SwitchType == 13
)
)
): # Blinds Percentage
devicetype = "blinds"
elif (
Device.Type == 0xF4
and Device.SubType == 0x49 # pTypeGeneralSwitch
and Device.SwitchType == 9 # sSwitchGeneralSwitch
): # STYPE_PushOn
devicetype = "binary_sensor"
elif self.isMQTTSensor(Device):
devicetype = "sensor"
if devicetype:
topic = (
self.discoverytopic
+ "/"
+ devicetype
+ "/"
+ Devices[Unit].Options["devicename"]
+ "/config"
)
Domoticz.Log("Clearing topic '" + topic + "'")
self.mqttClient.Publish(topic, "", 1)
self.copyDevices()
# TODO: Update subscribed topics
def onHeartbeat(self):
Domoticz.Debug("Heartbeating...")
# Reconnect if connection has dropped
if self.mqttClient.mqttConn is None or (
not self.mqttClient.mqttConn.Connecting()
and not self.mqttClient.mqttConn.Connected()
or not self.mqttClient.isConnected
):
Domoticz.Debug("Reconnecting")
self.mqttClient.Open()
else:
self.mqttClient.Ping()
# Timing out sensors
# Domoticz.Debug( "OnHeartbeat: Settings " + str( Settings ) )
now = datetime.now()
update_timeout = int(Settings["SensorTimeout"])
# Domoticz.Debug( "OnHeartbeat: " + str( Devices.items() ) + " " + str( type( Devices ) ) )
for k, device in Devices.items():
if self.isMQTTSensor(device):
if len(device.LastUpdate) > 0:
# Domoticz.Debug( "OnHeartbeat: Device " + device.Name + ", Last update " + str( device.LastUpdate ) )
# Workaround of Python issue https://bugs.python.org/issue27400
last_update = None
try:
last_update = datetime.strptime(
device.LastUpdate, "%Y-%m-%d %H:%M:%S"
)
except TypeError:
last_update = datetime.fromtimestamp(
time.mktime(
time.strptime(device.LastUpdate, "%Y-%m-%d %H:%M:%S")
)
)
time_delta = now - last_update
# Domoticz.Debug( "OnHeartbeat: " + device.Name + ", Time delta " + str( time_delta ) + ", Timeout " + str( update_timeout ) + ", Actual " + str( time_delta.total_seconds() / 60 ) )
if (time_delta.total_seconds() / 60) >= update_timeout:
if device.TimedOut == 0:
device.Update(
nValue=device.nValue, sValue=device.sValue, TimedOut=1
) # , SuppressTriggers=True)
Domoticz.Status(
self.deviceStr(self.getUnit(device))
+ ": Offline for more than "
+ str(update_timeout)
+ " minutes, Setting TimedOut: 1"
)
self.copyDevices()
else:
# Domoticz.Debug( "OnHeartbeat: Device " + device.Name + " already timed out, do nothing" )
pass
# Pull configuration and status from tasmota device
def refreshConfiguration(self, Topic):
Domoticz.Debug("refreshConfiguration for device with topic: '" + Topic + "'")
# Refresh relay / dimmer configuration
self.mqttClient.Publish(Topic + "/Status", "11")
# Refresh sensor configuration
# self.mqttClient.Publish(Topic+"/Status",'10')
# Refresh IP configuration
self.mqttClient.Publish(Topic + "/Status", "5")
# Returns list of topics to subscribe to
def getTopics(self):
topics = set()
for key, Device in Devices.items():
# Domoticz.Debug("getTopics: '" + str(Device.Options) +"'")
try:
configdict = json.loads(Device.Options["config"])
# Domoticz.Debug("getTopics: '" + str(configdict) +"'")
for key, value in configdict.items():
# Domoticz.Debug("getTopics: key:'" + str(key) +"' value: '" + str(value) + "'")
try:
# if key.endswith('_topic'):
if (
key == "availability_topic"
or key == "state_topic"
or key == "brightness_state_topic"
or key == "rgb_state_topic"
or key == "color_temp_state_topic"
or key == "position_topic"
):
topics.add(value)
except (TypeError) as e:
Domoticz.Error("getTopics: Error: " + str(e))
pass
if "tasmota_tele_topic" in configdict:
# Subscribe to all Tasmota state topics
state_topic = re.sub(
r"^tele\/", "stat/", configdict["tasmota_tele_topic"]
) # Replace tele with stat
state_topic = re.sub(
r"\/tele\/", "/stat/", state_topic
) # Replace tele with stat
state_topic = re.sub(
r"\/STATE", "/#", state_topic
) # Replace '/STATE' with /#
topics.add(state_topic)
except (ValueError, KeyError, TypeError) as e:
Domoticz.Error("getTopics: Error: " + str(e))
pass
topics.add(self.discoverytopic + "/#")
Domoticz.Debug("getTopics: '" + str(topics) + "'")
return list(topics)
# Returns list of matching devices
def getDevices(
self,
key="",
configkey="",
hasconfigkey="",
value="",
config="",
topic="",
type="",
channel="",
):
Domoticz.Debug(
"getDevices key: '"
+ key
+ "' configkey: '"
+ configkey
+ "' hasconfigkey: '"
+ hasconfigkey
+ "' value: '"
+ value
+ "' config: '"
+ config
+ "' topic: '"
+ topic
+ "'"
)
matchingDevices = set()
if key != "":
for k, Device in Devices.items():
try:
if Device.Options[key] == value:
matchingDevices.add(Device)
except (ValueError, KeyError) as e:
pass
if configkey != "":
for k, Device in Devices.items():
try:
configdict = json.loads(Device.Options["config"])
if configdict[configkey] == value:
matchingDevices.add(Device)
except (ValueError, KeyError) as e:
pass
elif hasconfigkey != "":
for k, Device in Devices.items():
try:
configdict = json.loads(Device.Options["config"])
if hasconfigkey in configdict:
matchingDevices.add(Device)
except (ValueError, KeyError) as e:
pass
elif config != "":
for k, Device in Devices.items():
try:
if Device.Options["config"] == config:
matchingDevices.add(Device)
except KeyError:
pass
elif topic != "":
for k, Device in Devices.items():
try:
configdict = json.loads(Device.Options["config"])
for key, value in configdict.items():
if value == topic:
matchingDevices.add(Device)
except (ValueError, KeyError) as e:
pass
Domoticz.Debug("getDevices found " + str(len(matchingDevices)) + " devices")
return list(matchingDevices)
def makeDevice(self, devicename, TypeName, switchTypeDomoticz, config):
iUnit = next(
filterfalse(set(Devices).__contains__, count(1))
) # First unused 'Unit'
Domoticz.Log("Creating device with unit: " + str(iUnit))
Options = {"config": json.dumps(config), "devicename": devicename}
# DeviceName = topic+' - '+type
DeviceName = config["name"]
Domoticz.Device(
Name=DeviceName,
Unit=iUnit,
TypeName=TypeName,
Switchtype=switchTypeDomoticz,
Options=Options,
Used=self.options["addDiscoveredDeviceUsed"],
).Create()
def makeDeviceRaw(self, devicename, Type, Subtype, switchTypeDomoticz, config):
iUnit = next(
filterfalse(set(Devices).__contains__, count(1))
) # First unused 'Unit'
Domoticz.Log("Creating device with unit: " + str(iUnit))
Options = {"config": json.dumps(config), "devicename": devicename}
# DeviceName = topic+' - '+type
DeviceName = config["name"]
Domoticz.Device(
Name=DeviceName,
Unit=iUnit,
Type=Type,
Subtype=Subtype,
Switchtype=switchTypeDomoticz,
Options=Options,
Used=self.options["addDiscoveredDeviceUsed"],
).Create()
def isDeviceIgnored(self, config):
ignore = False
for ignoredtopic in self.ignoredtopics:
for key, value in config.items():
if key.endswith("_topic"):
if value.startswith(ignoredtopic):
ignore = True
Domoticz.Debug("isDeviceIgnored: " + str(ignore))
return ignore
def addTasmotaTopics(self, config):
isTasmota = False
# TODO: Something smarter to detect Tasmota device
try:
# if "/cmnd/" in config["command_topic"] and "/POWER" in config["command_topic"] and "/tele/" in config["availability_topic"] and "/LWT" in config["availability_topic"]:
if (
(
(
"/stat/" in config["state_topic"]
and "/RESULT" in config["state_topic"]
)
or (
"/cmnd/" in config["state_topic"]