-
Notifications
You must be signed in to change notification settings - Fork 23
/
plugin.py
855 lines (706 loc) · 28.4 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
# IKEA Tradfri Plugin - Pycoap version
#
# Author: Moroen
#
#
# Battery-icons from wpclipart.com (PD), prepared for Domoticz by Logread (https://www.domoticz.com/forum/memberlist.php?mode=viewprofile&u=11209)
#
"""
<plugin key="IKEA-Tradfri" name="IKEA Tradfri Plugin - version 0.10.7" author="moroen" version="0.10.7" externallink="https://github.com/moroen/IKEA-Tradfri-plugin">
<description>
<h2>IKEA Tradfri</h2><br/>
</description>
<params>
<param field="Mode1" label="Add groups as devices" width="75px">
<options>
<option label="Yes" value="True"/>
<option label="No" value="False" default="true" />
</options>
</param>
<param field="Mode2" label="Monitor changes" width="75px">
<options>
<option label="No" value="none" default="true" />
<option label="Poll" value="poll"/>
<!–– <option label="Observe" value="observe"/> -->
</options>
</param>
<param field="Mode3" label="Polling interval (seconds)" width="75px" required="true" default="300"/>
<!–– <param field="Port" label="Observe port" width="30px" required="true" default="5000"/> -->
<param field="Mode5" label="Montior batteries" width="75px">
<options>
<option label="No" value="False"/>
<option label="On value changed" value="onChanged" default="true"/>
<option label="On every poll" value="onPoll"/>
</options>
</param>
<param field="Mode4" label="Transition time (tenth of a second)" width="75px" required="false" default="10"/>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import os, platform, math
import json
import site
import sys
import threading
import time
import datetime
# Get full import PATH
site.main()
_globalError = None
_version = "0.10.7"
_use_local_tradfricoap = False
# See if there is a local tradfricoap-directory
_use_local_tradfricoap = os.path.isdir(
"{}/tradfricoap".format(os.path.dirname(os.path.realpath(__file__)))
)
if _use_local_tradfricoap:
# Check if local tradfricoap is usable
from pkg_resources import get_distribution, DistributionNotFound
if not os.path.isdir(
"{}/tradfricoap/tradfricoap".format(os.path.dirname(os.path.realpath(__file__)))
):
_globalError = "There seems to be an empty tradfricoap directory present. Please remove it before running the plugin!"
else:
try:
get_distribution("tradfricoap")
_globalError = "Tradfricoap appears to be installed both as a system- and local module. Please remove the tradfricoap directory before running the plugin!"
except DistributionNotFound:
pass
if _globalError is None:
# Need to set config before import from module
try:
if _use_local_tradfricoap:
from tradfricoap.tradfricoap.config import get_config, host_config
from tradfricoap.tradfricoap import ApiNotFoundError
from tradfricoap.tradfricoap.coapcmd_api import set_coapcmd
else:
from tradfricoap.config import get_config, host_config
from tradfricoap import ApiNotFoundError
from tradfricoap.coapcmd_api import set_coapcmd
if os.path.isdir("/config"):
# Running in the moroen/domoticz-tradfri docker container
CONFIGFILE = "/config/tradfri.json"
else:
# Running on system
CONFIGFILE = "{}/config.json".format(
os.path.dirname(os.path.realpath(__file__))
)
CONF = get_config(CONFIGFILE).configuation
if platform.system() == "Windows":
set_coapcmd(
"{}/bin/coapcmd.exe".format(os.path.dirname(os.path.realpath(__file__)))
)
else:
set_coapcmd(
"{}/bin/coapcmd".format(os.path.dirname(os.path.realpath(__file__)))
)
except ImportError:
_globalError = "Module 'tradfricoap' not found"
if __name__ == "__main__":
if _globalError is not None:
print(_globalError)
exit()
if _use_local_tradfricoap:
from tradfricoap.tradfricoap.cli import process_args, get_args
from tradfricoap.tradfricoap.version import get_version_info
else:
from tradfricoap.cli import process_args, get_args
from tradfricoap.version import get_version_info
try:
args = get_args()
if args.command == "version":
print("IKEA Tradfri Plugin: {}".format(_version))
process_args(args)
except ApiNotFoundError as e:
print("Error: {}".format(e.message))
exit()
## Domoticz Plugin
import Domoticz
try:
if _use_local_tradfricoap:
from tradfricoap.tradfricoap.device import (
get_device,
get_devices,
set_transition_time,
)
from tradfricoap.tradfricoap.errors import (
HandshakeError,
UriNotFoundError,
ReadTimeoutError,
WriteTimeoutError,
set_debug_level,
DeviceNotFoundError,
MethodNotAllowedError,
)
from tradfricoap.tradfricoap.colors import WhiteOptions, colorOptions
from tradfricoap.tradfricoap.gateway import close_connection
else:
from tradfricoap.device import get_device, get_devices, set_transition_time
from tradfricoap.errors import (
HandshakeError,
UriNotFoundError,
ReadTimeoutError,
WriteTimeoutError,
set_debug_level,
DeviceNotFoundError,
MethodNotAllowedError,
)
from tradfricoap.colors import WhiteOptions, colorOptions
from tradfricoap.gateway import close_connection
# from tradfricoap.observe import observe_start, observe_stop
except ImportError:
_globalError = "Unable to find tradfricoap"
except SystemExit:
_globalError = "Unable to initialize tradfricoap"
except ApiNotFoundError as e:
_globalError = e.message
class BasePlugin:
enabled = False
tradfri_devices = {}
batteries = []
includeGroups = False
updateMode = "none"
monitor_batteries = False
monitor_batteries_method = "onChanged"
lastPollTime = None
pollInterval = None
hasTimedOut = False
devicesMoving = []
commandQueue = []
httpServerConn = None
httpServerConns = {}
icons = {
"IKEA-Tradfri_batterylevelfull": "icons/battery_full.zip",
"IKEA-Tradfri_batterylevelok": "icons/battery_ok.zip",
"IKEA-Tradfri_batterylevellow": "icons/battery_low.zip",
"IKEA-Tradfri_batterylevelempty": "icons/battery_empty.zip",
}
def __init__(self):
return
def indexRegisteredDevices(self):
if len(Devices) > 0:
# Some devices are already defined
try:
for aUnit in Devices:
dev_id = Devices[aUnit].DeviceID.split(":")
if len(dev_id) > 1:
if dev_id[1] == "Battery":
pass
self.updateDevice(aUnit)
return [dev.DeviceID for key, dev in Devices.items()]
except (HandshakeError, ReadTimeoutError, WriteTimeoutError):
self.hasTimedOut = True
return
else:
self.hasTimedOut = False
else:
deviceID = [-1]
return deviceID
def updateDevice(self, Unit, override_level=None):
# Domoticz.Debug("Updating device {} - Type {} Subtype {} Switchtype {}".format(Devices[Unit].DeviceID, Devices[Unit].Type, Devices[Unit].SubType, Devices[Unit].SwitchType))
deviceUpdated = False
# try:
try:
devID = int(str(Devices[Unit].DeviceID).split(":")[0])
if devID in self.tradfri_devices:
ikea_device = self.tradfri_devices[devID]
else:
return
except TypeError:
self.hasTimedOut = True
return
if self.updateMode == "poll":
ikea_device.Update()
if Devices[Unit].Type == 244:
# Switches
if Devices[Unit].SwitchType == 0:
# On/off - device
if (Devices[Unit].nValue != ikea_device.State) or (
Devices[Unit].sValue != str(ikea_device.Level)
):
Devices[Unit].Update(
nValue=ikea_device.State,
sValue=str(ikea_device.Level),
)
elif Devices[Unit].SwitchType == 7:
# Dimmer
if ikea_device.Level is not None:
if override_level is None:
level = str(int(round_half_up(ikea_device.Level / 2.54)))
else:
level = override_level
if (Devices[Unit].nValue != ikea_device.State) or (
Devices[Unit].sValue != str(level)
):
Devices[Unit].Update(
nValue=2 if ikea_device.State else 0, sValue=str(level)
)
elif Devices[Unit].SwitchType == 13:
# Blinds
if (Devices[Unit].nValue != ikea_device.State) or (
Devices[Unit].sValue != str(ikea_device.Level)
):
Devices[Unit].Update(
nValue=ikea_device.State,
sValue=str(ikea_device.Level),
)
deviceUpdated = True
elif Devices[Unit].SwitchType == 18:
# Selector
if (
Devices[Unit].DeviceID[-3:] == ":WS"
or Devices[Unit].DeviceID[-4:] == ":CWS"
):
if (Devices[Unit].nValue != ikea_device.State) or (
Devices[Unit].sValue != str(ikea_device.Color_level)
):
Devices[Unit].Update(
nValue=ikea_device.State,
sValue=str(ikea_device.Color_level),
)
elif Devices[Unit].Type == 243 and self.monitor_batteries:
if Devices[Unit].SubType == 31:
# Custom sensor
if ikea_device.Battery_level >= 75:
image = "IKEA-Tradfri_batterylevelfull"
elif ikea_device.Battery_level >= 50 and ikea_device.Battery_level < 75:
image = "IKEA-Tradfri_batterylevelok"
elif ikea_device.Battery_level >= 25 and ikea_device.Battery_level < 50:
image = "IKEA-Tradfri_batterylevellow"
else:
image = "IKEA-Tradfri_batterylevelempty"
if (
Devices[Unit].sValue != str(ikea_device.Battery_level)
) or self.monitor_batteries_method == "onPoll":
Devices[Unit].Update(
nValue=0,
sValue=str(ikea_device.Battery_level),
Image=Images[image].ID,
)
self.hasTimedOut = False
return deviceUpdated
# except (HandshakeError, ReadTimeoutError, WriteTimeoutError):
# Domoticz.Debug(
# "Error updating device {}: Connection time out".format(devID)
# )
# self.hasTimedOut = True
# except Exception as err:
# raise
def registerDevices(self):
try:
if self.includeGroups:
self.tradfri_devices = get_devices(groups=True)
else:
self.tradfri_devices = get_devices()
except (HandshakeError, ReadTimeoutError, WriteTimeoutError):
Domoticz.Debug("Connection to gateway timed out")
self.hasTimedOut = True
return
if self.hasTimedOut:
return
unitIds = self.indexRegisteredDevices()
# Fallback if json fails with unraised error
if self.tradfri_devices == None:
Domoticz.Error("Failed to get Tradfri-devices")
self.hasTimedOut = True
return
# Add unregistred ikea_devices
for id, aLight in self.tradfri_devices.items():
devID = str(id)
if not devID in unitIds:
Domoticz.Debug(
"Processing: {0} - {1}".format(aLight.Description, aLight.Type)
)
new_unit_id = firstFree()
if aLight.Type == "Plug":
Domoticz.Device(
Name=aLight.Name,
Unit=new_unit_id,
Type=244,
Subtype=73,
Switchtype=0,
Image=1,
DeviceID=devID,
).Create()
self.updateDevice(new_unit_id)
if aLight.Type == "Remote":
Domoticz.Device(
Name=aLight.Name + " - Battery level",
Unit=new_unit_id,
Type=243,
Subtype=6,
DeviceID=devID,
).Create()
if aLight.Type == "Blind":
deviceType = 244
subType = 73
switchType = 13
Domoticz.Device(
Name=aLight.Name,
Unit=new_unit_id,
Type=deviceType,
Subtype=subType,
Switchtype=switchType,
DeviceID=devID,
).Create()
self.updateDevice(new_unit_id)
if aLight.Type == "Light" or aLight.Type == "Group":
deviceType = 244
subType = 73
switchType = 7
# Basic device
Domoticz.Device(
Name=aLight.Name,
Unit=new_unit_id,
Type=deviceType,
Subtype=subType,
Switchtype=switchType,
DeviceID=devID,
).Create()
self.updateDevice(new_unit_id)
if aLight.Color_space == "W":
continue
if self.monitor_batteries:
if (
aLight.Battery_level is not None
and devID + ":Battery" not in unitIds
):
new_unit_id = firstFree()
Domoticz.Debug("Registering: {0}:Battery".format(aLight.DeviceID))
Domoticz.Device(
Name=aLight.Name + " - Battery",
Unit=new_unit_id,
TypeName="Custom",
Options={"Custom": "1;%"},
DeviceID=devID + ":Battery",
).Create()
self.updateDevice(new_unit_id)
if aLight.Color_space == "CWS" and devID + ":CWS" not in unitIds:
new_unit_id = firstFree()
Domoticz.Debug("Registering: {0}:CWS".format(aLight.DeviceID))
Domoticz.Device(
Name=aLight.Name + " - Color",
Unit=new_unit_id,
TypeName="Selector Switch",
Switchtype=18,
Options=colorOptions,
DeviceID=devID + ":CWS",
).Create()
self.updateDevice(new_unit_id)
if aLight.Color_space == "WS" and devID + ":WS" not in unitIds:
new_unit_id = firstFree()
Domoticz.Debug("Registering: {0}:WS".format(aLight.DeviceID))
Domoticz.Device(
Name=aLight.Name + " - Color",
Unit=new_unit_id,
TypeName="Selector Switch",
Switchtype=18,
Options=WhiteOptions,
DeviceID=devID + ":WS",
).Create()
self.updateDevice(new_unit_id)
# Add reboot button
if "15011" not in unitIds:
new_unit_id = firstFree()
Domoticz.Debug("Registering 15011")
Domoticz.Device(
Name="Reboot Tradfri Gateway",
Unit=new_unit_id,
TypeName="Push On",
DeviceID="15011",
).Create()
# Remove registered ikea_devices no longer found on the gateway
for aUnit in list(Devices.keys()):
devID = str(Devices[aUnit].DeviceID).split(":")
if devID[0] == "15011":
continue
if not int(devID[0]) in self.tradfri_devices:
Devices[aUnit].Delete()
if not self.monitor_batteries and len(devID) == 2:
if devID[1] == "Battery":
Devices[aUnit].Delete()
self.hasTimedOut = False
def onStart(self):
if _globalError is not None:
Domoticz.Error("Failed to initialize tradfri module.")
Domoticz.Error(_globalError)
return
try:
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
set_debug_level(1)
except ValueError:
Domoticz.Debugging(0)
try:
if Parameters["Mode1"] == "True":
self.includeGroups = True
except ValueError:
Domoticz.Error(
"Illegal value for 'Add groups as devices'. Using default (No)"
)
try:
if Parameters["Mode2"] == "poll":
self.updateMode = "poll"
self.lastPollTime = datetime.datetime.now()
elif Parameters["Mode2"] == "observe":
self.updateMode = "observe"
elif Parameters["Mode2"] == "none":
self.updateMode = "none"
except ValueError:
Domoticz.Error("Illegal value for 'Observe changes'. Using default (No)")
self.updateMode = "none"
Domoticz.Debug("Monitor changes method: {}".format(self.updateMode))
try:
self.pollInterval = int(Parameters["Mode3"])
except ValueError:
Domoticz.Error("Illegal value for 'Polling interval'. Using default (300)")
self.pollInterval = 300
try:
self.monitor_batteries_method = Parameters["Mode5"]
self.monitor_batteries = False if Parameters["Mode5"] == "False" else True
except ValueError:
Domoticz.Error(
"Illegal value for 'Montior batteries'. Using default (On value changed)"
)
self.monitor_batteries = True
self.monitor_batteries_method = "onChanged"
try:
set_transition_time(int(Parameters["Mode4"]))
except ValueError:
Domoticz.Error("Illegal value for 'Transition time'. Using default (10)")
set_transition_time(10)
for key, filename in self.icons.items():
if key not in Images:
Domoticz.Image(filename).Create()
Domoticz.Debug("Number of icons loaded = " + str(len(Images)))
for image in Images:
Domoticz.Debug("Icon {} {}".format(Images[image].ID, Images[image].Name))
try:
self.registerDevices()
# Observe
if Parameters["Mode2"] == "observe":
Domoticz.Debug("Observing changes")
self.httpServerConn = Domoticz.Connection(
Name="Server Connection",
Transport="TCP/IP",
Protocol="HTTP",
Port=Parameters["Port"],
)
self.httpServerConn.Listen()
observe_start()
except ApiNotFoundError as e:
Domoticz.Error("Failed to initialize tradfri module.")
Domoticz.Error(e.message)
def onStop(self):
Domoticz.Debug("Stopping IKEA Tradfri plugin")
if Parameters["Mode2"] == "observe":
pass
# Domoticz.Debug("Stopping observe")
# observe_stop()
Domoticz.Debug(
"Threads still active: " + str(threading.active_count()) + ", should be 1."
)
while threading.active_count() > 1:
for thread in threading.enumerate():
if thread.name != threading.current_thread().name:
Domoticz.Debug(
"'"
+ thread.name
+ "' is still running, waiting otherwise Domoticz will crash on plugin exit."
)
time.sleep(1.0)
Domoticz.Debugging(0)
def onConnect(self, Connection, Status, Description):
Domoticz.Debug("onConnect called")
def onMessage(self, Connection, Data):
Domoticz.Log(
"onMessage called for connection: "
+ Connection.Address
+ ":"
+ Connection.Port
)
# DumpHTTPResponseToLog(Data)
print(Data["Data"].decode("utf-8"))
# test = json.loads(Data.decode("utf-8"))
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Debug(
"onCommand called for Unit "
+ str(Unit)
+ ": Parameter '"
+ str(Command)
+ "', Level: "
+ str(Level)
)
devID = int(str(Devices[Unit].DeviceID).split(":")[0])
try:
# Reboot
if devID == 15011:
if _use_local_tradfricoap:
from tradfricoap.tradfricoap.gateway import reboot
else:
from tradfricoap.gateway import reboot
Domoticz.Debug("Reboot IKEA Gateway called")
reboot()
elif Command == "On":
self.tradfri_devices[devID].State = 1
self.updateDevice(Unit)
if self.tradfri_devices[devID].Type == "Blind":
self.devicesMoving.append(Unit)
# return
elif Command == "Off":
self.tradfri_devices[devID].State = 0
self.updateDevice(Unit)
if self.tradfri_devices[devID].Type == "Blind":
self.devicesMoving.append(Unit)
# return
elif Command == "Set Level":
Domoticz.Debug("Command Level: {}".format(Level))
Level = int(Level)
if Devices[Unit].DeviceID[-4:] == ":CWS":
self.tradfri_devices[devID].Color_level = Level
elif Devices[Unit].DeviceID[-3:] == ":WS":
self.tradfri_devices[devID].Color_level = Level
else:
if Level not in range(0, 101):
Level = 100 if Level > 100 else 0
if self.tradfri_devices[devID].Type == "Blind":
self.tradfri_devices[devID].Level = Level
self.devicesMoving.append(Unit)
else:
self.tradfri_devices[devID].Level = int(
round_half_up((Level * 2.54))
)
if self.tradfri_devices[devID].Type == "Group":
self.updateDevice(Unit, override_level=Level)
else:
self.updateDevice(Unit)
Domoticz.Debug(
"Ikea Level: {}".format(self.tradfri_devices[devID].Level)
)
Domoticz.Debug("Finnished command")
except KeyError:
Domoticz.Error(
"OnCommand failed for device: {} with command: {} and level: {}".format(
devID, Command, Level
)
)
except (HandshakeError, ReadTimeoutError, WriteTimeoutError):
comObj = {"Unit": Unit, "Command": Command, "Level": Level}
Domoticz.Debug(
"Command timed out. Pushing {} onto commandQueue".format(comObj)
)
self.commandQueue.append(comObj)
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Domoticz.Debug(
"Notification: "
+ Name
+ ","
+ Subject
+ ","
+ Text
+ ","
+ Status
+ ","
+ str(Priority)
+ ","
+ Sound
+ ","
+ ImageFile
)
def onDisconnect(self, Connection):
Domoticz.Debug("onDisconnect called")
def onHeartbeat(self):
# Domoticz.Debug("onHeartbeat called")
for aUnit in self.devicesMoving:
Domoticz.Debug(
"Device {} has moving flag set".format(Devices[aUnit].DeviceID)
)
if self.updateDevice(aUnit) is False:
self.devicesMoving.remove(aUnit)
for aCommand in self.commandQueue:
Domoticz.Log("Command in queue")
Domoticz.Debug("Trying to execute {} from commandQueue".format(aCommand))
self.commandQueue.remove(aCommand)
self.onCommand(
aCommand["Unit"], aCommand["Command"], aCommand["Level"], None
)
if self.hasTimedOut:
Domoticz.Debug("Timeout flag set, retrying...")
self.hasTimedOut = False
self.registerDevices()
else:
if self.updateMode == "poll":
if self.lastPollTime is None:
self.lastPollTime = datetime.datetime.now()
else:
interval = (datetime.datetime.now() - self.lastPollTime).seconds
if interval + 1 > self.pollInterval:
self.lastPollTime = datetime.datetime.now()
self.indexRegisteredDevices()
close_connection()
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data):
global _plugin
_plugin.onMessage(Connection, Data)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
global _plugin
_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
#
# Generic helper functions
#
def round_half_up(n, decimals=0):
multiplier = 10 ** decimals
return math.floor(n * multiplier + 0.5) / multiplier
def DumpConfigToLog():
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug("'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: " + str(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x]))
Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'")
Domoticz.Debug("Device Name: '" + Devices[x].Name + "'")
Domoticz.Debug("Device nValue: " + str(Devices[x].nValue))
Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'")
Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
return
def firstFree():
for num in range(1, 250):
if num not in Devices:
return num
return
def DumpHTTPResponseToLog(httpDict):
if isinstance(httpDict, dict):
Domoticz.Log("HTTP Details (" + str(len(httpDict)) + "):")
for x in httpDict:
if isinstance(httpDict[x], dict):
Domoticz.Log("--->'" + x + " (" + str(len(httpDict[x])) + "):")
for y in httpDict[x]:
Domoticz.Log("------->'" + y + "':'" + str(httpDict[x][y]) + "'")
else:
Domoticz.Log("--->'" + x + "':'" + str(httpDict[x]) + "'")