forked from zak-45/Broadlink-Domoticz-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tst-plugin
5659 lines (4794 loc) · 209 KB
/
tst-plugin
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
# -*- coding: utf-8 -*-
#
# Broadlink Python Plugin for Domoticz
# Dev. Platform : Win10 x64 & Py 3.7.5 x86
#
# Author: zak45, 2020
#
# 1.0.0 : Initial release
#
# 1.1.0 : 13/07/2020
# modify broadlink_connect : use of broadlink.gendevice()
# possibility to overwrite the default device type
# display only ini file name + domoticz idx and not full path in manage()
# 1.1.1 : 16/07/2020
# better support for mobile device & some code clean up
# 1.2.0 : 27/07/2020
# HTML code improved
# 1.3.0 : 04/08/2020
# module Broadlink v 0.14.1
# some code improvement
# 1.4.0 : 06/08/2020
# display customname on manage()
# check if Jquery (& ui) loaded, if not load them (admin)
# use broadlink.get_devices() to have devices list
# implement iframeResizer for dynamic iframe resize (autoresize:True)
# 1.4.1 : 07/08/2020
# added MyMemory link for translation (admin-language)
# added 'Scroll to top' feature
# 1.4.2 : 10/08/2020
# no overwrite lang file during update
# added link to cmd command for code send
# 1.5.0 : 27/08/2020
# show admin html page when enter base URL
# 1.6.0 : 29/08/2020
# learn IR/RF from Web Admin Page
# 1.6.1 : 01/09/2020
# Folder browse refactor
# 1.6.2 : 09/12/2020
# Modify sp3s device creation type
# 1.6.3 : 08/01/2021
# Work now in docker env: changed to 127.0.0.1 instead domoticz ip
#
"""
<plugin key="Broadlink" name="Broadlink with Kodi Remote" author="zak45" version="1.6.3"
wikilink="http://www.domoticz.com/wiki/plugins/Broadlink.html"
externallink="https://github.com/mjg59/python-broadlink">
<description>
<h2>Broadlink Python Plugin for Domoticz</h2><br/>
<h2>Integrate Broadlink devices with Domoticz</h2>
<h3>Features</h3>
<ul style="list-style-type:square">
<li>RM2/4 mini RM3 : RF / IR learning</li>
<li>WebAdmin Page for management</li>
<li>Control SP1/2/3 plugs</li>
<li>Retrieve information from A1 device</li>
<li>Manage your Multiplug</li>
<li>Customizable & multi language plugin</li>
</ul>
</description>
<params>
<param field="Mode4" label="Broadlink IP Address" width="200px" required="true" default="192.168.1.X"/>
<param field="Mode1" label="Mac" width="100px" required="true" default="AABBDDEEFF00"/>
<param field="Mode3" label="Device Type" width="250px" required="true" default="RM2">
<options>
<option label= "Remote Control RM2/3" value="RM2"/>
<option label= "Remote Control RM2/3 with Temp" value="RM2T"/>
<option label= "Remote Control mini RM2/3" value="RM2M"/>
<option label= "Remote Control RM4" value="RM24"/>
<option label= "Remote Control RM4 with Temp" value="RM24T"/>
<option label= "Remote Control mini RM4" value="RM24M"/>
<option label= "eSensor multi sensors A1" value="A1"/>
<option label= "SmartPlug 1" value="SP1"/>
<option label= "SmartPlug 2/3" value="SP2"/>
<option label= "SmartPlug 3S" value="SP3S"/>
<option label= "MultiPlug 1" value="MP1"/>
</options>
</param>
<param field="Mode2" label="Folder to store ini files (RM2/3/4)" width="300px" required="true"
default="<plugin home>"/>
<param field="Address" label="Domoticz IP Address" width="200px" required="true" default="192.168.1.Y"/>
<param field="Port" label="Domoticz port" width="50px" required="true" default="8080"/>
<param field="Mode5" label="Listener port" width="50px" required="true" default="9000"/>
<param field="Mode6" label="Debug" width="150px">
<options>
<option label="None" value="0" default="true" />
<option label="Python Only" value="2"/>
<option label="Basic Debugging" value="62"/>
<option label="Basic+Messages" value="126"/>
<option label="Connections Only" value="16"/>
<option label="Connections+Queue" value="144"/>
<option label="All" value="-1"/>
<option label="MS Visual Studio" value="999"/>
</options>
</param>
</params>
</plugin>
"""
#
# Main Import
import uuid
import html
import json
import re
import traceback
import cgitb
import urllib.request
import urllib.parse
import urllib.error
import urllib.parse as urlparse
from urllib.parse import parse_qs
import ntpath
import Domoticz
import configparser
import datetime
import codecs
import subprocess
import socket
import os
import sys
import binascii
import struct
import time
#
import broadlink
#
from requests_toolbelt import MultipartDecoder
#
clear = False
autoresize = True
brodevices = broadlink.get_devices()
#
ISCONNECTED = False
NUMBERDEV = 9
BYPASS = False
TEMP = 0
LEARNEDCOMMAND = "None"
SENDCOMMAND = ""
LOADEDCOMMAND = ""
NBUPDATE = 1
CUSTOM = ""
REMOTECOMMAND = ""
STATE = True
STATEMP1 = {}
ENERGY = 0
UNIT = 0
REMOTEKEY = ''
REMOTETOSEND = ''
INFOLEVEL = 0
#
LANGDICT = {}
LANGTO = 'en'
CMD = ''
#
USEDPORT = False
HTTPSERVERCONN = None
HTTPCONNECTIONS = {}
HTTPCLIENT = None
#
DOMDATA = {}
URLKEY = str(uuid.getnode())
WEBROOT = True
DISPLAYPATH = ''
ADJUSTVALUE = 0
DEVICE = broadlink.rm(host=('', 80), mac=bytearray.fromhex(''), devtype=0x272a)
NEWPLUGIN = "no"
#
# find translation
# if no translation, put __ on start/end
#
def _(idata):
origdata = idata
if idata in LANGDICT:
idata = LANGDICT[idata]
else:
if type(idata) is str:
idata = '__' + origdata + '__'
else:
idata = origdata
return idata
#
# Domoticz call back functions
#
# Executed once at HW creation/ update. Can create up to 255 devices.
def onStart():
global NUMBERDEV, NBUPDATE, INFOLEVEL, CMD, LANGTO, USEDPORT, HTTPSERVERCONN, ADJUSTVALUE, DISPLAYPATH, NEWPLUGIN
cgitb.enable(logdir=Parameters['HomeFolder'] + 'log/')
if Parameters["Mode6"] == "999":
INFOLEVEL = 999
try:
import ptvsd
Domoticz.Debugging(62)
Domoticz.Log('Waiting for MS Visual Studio remote debugger connection ....')
ptvsd.enable_attach(address=('0.0.0.0', 5678))
ptvsd.wait_for_attach()
ptvsd.break_into_debugger()
except (ValueError, Exception):
Domoticz.Error(_('Not able to load debug module'))
elif Parameters["Mode6"] != "0":
Domoticz.Debugging(int(Parameters["Mode6"]))
INFOLEVEL = 9
dump_config_to_log()
#
# default ini folder
if Parameters["Mode2"] == '<plugin home>':
Parameters["Mode2"] = Parameters['HomeFolder'] + "ini/"
if not Parameters["Mode2"].endswith('/'):
Parameters["Mode2"] += "/"
# select command to launch depend of OS
if sys.platform.startswith('win32'):
CMD = "scr/dombr.cmd"
Parameters["Mode2"] = Parameters["Mode2"].replace("\\", "/")
else:
CMD = "scr/dombr.sh"
DISPLAYPATH = Parameters["HomeFolder"]
#
# Language file
LANGTO = Settings["Language"]
if load_lang():
Domoticz.Log(_('Language loaded for : {} ').format(LANGTO))
else:
Domoticz.Error(_('Language file is missing for : {}').format(LANGTO))
#
# Run web server
if is_open(Parameters['Address'], Parameters["Mode5"]):
USEDPORT = True
Domoticz.Error(_('Port already in use'))
else:
HTTPSERVERCONN = Domoticz.Connection(Name="BROWebServer", Transport="TCP/IP", Protocol="HTTP",
Port=Parameters["Mode5"])
HTTPSERVERCONN.Listen()
Domoticz.Log(_("Listen on BROWebServer - Port: {}").format(Parameters['Mode5']))
#
if INFOLEVEL > 1:
Domoticz.Log(_('Hardware ID: {} ').format(str(Parameters['HardwareID'])))
#
# Create devices : device number 1 used mainly for status
if 'RM2' in Parameters["Mode3"]:
if 1 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + '-' + _('Status'), Unit=1, Type=17, Image=17, Switchtype=17,
Used=1).Create()
if 2 not in Devices:
options = {"LevelActions": "||||",
"LevelNames": "Off|" + _('Learn') + "|" + _('Test') + "|" + _('Save') + "|" + _('Reset'),
"LevelOffHidden": "true",
"SelectorStyle": "0"
}
Domoticz.Device(Name=_("IR Commands"), Unit=2, TypeName="Selector Switch", Switchtype=18, Image=12,
Options=options, Used=1).Create()
if 3 not in Devices and (Parameters["Mode3"] != 'RM2M' or Parameters["Mode3"] != 'RM24M'):
options = {"LevelActions": "|||||",
"LevelNames": "Off|" + _('Sweep') + "|" + _('Learn') + "|" + _('Test') + "|" + _('Save') + "|" +
_('Reset'),
"LevelOffHidden": "true",
"SelectorStyle": "0"
}
Domoticz.Device(Name=_("RF Commands"), Unit=3, TypeName="Selector Switch", Switchtype=18, Image=12,
Options=options, Used=1).Create()
if Parameters["Mode3"] == 'RM2T' or Parameters["Mode3"] == 'RM24T':
if 4 not in Devices:
Domoticz.Device(Name=_("Temperature"), Unit=4, TypeName="Temperature", Used=1).Create()
adjust_value(4)
elif Parameters["Mode3"] == 'SP1' or Parameters["Mode3"] == 'SP2' or Parameters["Mode3"] == 'SP3S':
if 1 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]), Unit=1, TypeName="Switch", Image=1, Used=1).Create()
if Parameters["Mode3"] == 'SP3S':
if 2 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]), Unit=2, TypeName="Usage", Used=1).Create()
if 3 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]), Unit=3, Type=243, Subtype=29, Switchtype=0,
Used=1).Create()
if 4 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Light'), Unit=4, TypeName="Switch", Used=1).Create()
else:
if 2 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Light'), Unit=2, TypeName="Switch", Used=1).Create()
elif Parameters["Mode3"] == 'A1':
if 1 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Status'), Unit=1, Type=17, Image=17, Switchtype=17,
Used=1).Create()
if 2 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Temperature'), Unit=2, TypeName="Temperature",
Used=1).Create()
if 3 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Humidity'), Unit=3, TypeName="Humidity", Used=1).Create()
if 4 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Air Quality'), Unit=4, TypeName="Air Quality",
Used=1).Create()
if 5 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Noise'), Unit=5, TypeName="Sound Level", Used=1).Create()
if 6 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Light'), Unit=6, TypeName="Illumination",
Used=1).Create()
adjust_value(2)
elif Parameters["Mode3"] == 'MP1':
if 1 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('Status'), Unit=1, TypeName="Switch", Image=9,
Used=1).Create()
if 2 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('plug') + '1', Unit=2, TypeName="Switch", Image=1,
Used=1).Create()
if 3 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('plug') + '2', Unit=3, TypeName="Switch", Image=1,
Used=1).Create()
if 4 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('plug') + '3', Unit=4, TypeName="Switch", Image=1,
Used=1).Create()
if 5 not in Devices:
Domoticz.Device(Name=str(Parameters["Mode3"]) + _('plug') + '4', Unit=5, TypeName="Switch", Image=1,
Used=1).Create()
dump_config_to_log()
Domoticz.Heartbeat(30)
if 'RM2' in Parameters["Mode3"]:
if not os.path.exists(Parameters["Mode2"] + "import"):
os.makedirs(Parameters["Mode2"] + "import")
if not os.path.exists(Parameters["Mode2"] + "remote"):
os.makedirs(Parameters["Mode2"] + "remote")
mpath = str(Parameters["Mode2"]) + "remote/" + str(Parameters["Key"]) + "-" + str(Parameters["HardwareID"]) + \
"-" + str('{:03d}'.format(1)) + ".ini"
header = "[Custom]\ncommand = 0,"
if not os.path.exists(mpath):
try:
with open(mpath, 'w', encoding='utf-8') as fp:
fp.write(header)
Domoticz.Log(_('Ini file for remote controller created: {}').format(mpath))
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to create ini file for remote controller : {}').format(mpath))
gen_remote()
if 2 in Devices:
update_device(2, 0, 'Off')
if 3 in Devices:
update_device(3, 0, 'Off')
Domoticz.Log(_("Plugin Device count start on : {}").format(str(NUMBERDEV)))
#
# Verify if plugin need to be updated
#
checkver()
#
# Device file parameters
#
dev = ''
devfile = Parameters['HomeFolder'] + "log/" + str(Parameters['HardwareID']) + Parameters['Mode3'] + ".txt"
try:
if not os.path.exists(devfile):
if 'RM24' in Parameters["Mode3"]:
dev = "0x51da" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
elif 'RM2' in Parameters["Mode3"]:
dev = "0x2712" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
elif Parameters["Mode3"] == 'A1':
dev = "0x2714" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
elif Parameters["Mode3"] == 'SP1':
dev = "0" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
elif Parameters["Mode3"] == 'SP2' or Parameters["Mode3"] == 'SP3S':
dev = "0x2711" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
elif Parameters["Mode3"] == 'MP1':
dev = "0x4EB5" + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
with open(devfile, 'w', encoding='utf-8') as fp:
fp.write(dev)
Domoticz.Log(_('Command line file created: {}').format(devfile))
else:
with open(devfile, 'r', encoding='utf-8') as fp:
infile = fp.read().split(' ')
dev = infile[0] + " " + Parameters["Mode4"] + " " + Parameters["Mode1"]
with open(devfile, 'w', encoding='utf-8') as fp:
fp.write(dev)
Domoticz.Log(_('Command line file updated: {}').format(devfile))
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to create device file : {}').format(devfile))
Domoticz.Log(_("Connecting to: {} : {}").format(Parameters["Mode4"], Parameters["Mode1"]))
#
# Set to default state
#
if 'RM2' in Parameters["Mode3"] or Parameters["Mode3"] == 'A1':
if not broadlink_connect():
update_device(1, 0, 'Off')
else:
update_device(1, 1, 'On')
else:
if broadlink_connect() and check_power():
if STATE:
update_device(1, 1, 'On')
# if (Parameters["Mode3"] == 'MP1'):
# AllPlugOn()
else:
update_device(1, 0, 'Off')
# if (Parameters["Mode3"] == 'MP1'):
# AllPlugOff()
else:
update_device(1, 0, 'Off')
# if (Parameters["Mode3"] == 'MP1'):
# AllPlugOff()
#
# Main iframe definition
#
iframe = '''
<iframe name="adminframe"
'''
if autoresize:
iframe += '''
onload="iFrameResize({log:false,checkOrigin:false,warningTimeout:0,minHeight:600})"
'''
iframe += '''
src="http://''' + Parameters["Address"] + ''':''' + Parameters["Mode5"] + '''/manage?key=''' + URLKEY + '''"
width="100%" height="600" frameborder="0" style="border:0" allowfullscreen >
</iframe>
'''
#
# Create main admin HTML page
#
adminfile = htmladmin('WebAdmin Page', iframe)
html_file = Parameters['StartupFolder'] + 'www/templates/Broadlink-' + Parameters['Mode3'] + '-' + \
str(Parameters["HardwareID"]) + '.html'
if os.path.isdir(Parameters['StartupFolder'] + 'www/templates/'):
try:
with open(html_file, 'w', encoding='utf-8') as fp:
fp.write(adminfile)
Domoticz.Log(_('Admin html file created: {}').format(html_file))
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to create admin html file : {}').format(html_file))
else:
Domoticz.Error(_('Error to found www/templates for html file : {}').format(html_file))
#
# Exit if port not available else download remote plugin file for version test
#
if USEDPORT:
Domoticz.Error(_('We cannot continue ...'))
onStop()
else:
start_shell('remotePlugin')
return
# executed each time we click on device with domoticz GUI
def onCommand(iunit, command, level, hue):
global SENDCOMMAND, LEARNEDCOMMAND, ISCONNECTED, CUSTOM
Domoticz.Log("onCommand called for Unit " + str(iunit)
+ ": Parameter '" + str(command)
+ "', Level: " + str(level)
+ " , Connected : " + str(ISCONNECTED)
)
command = command.strip()
if command == 'Set Level':
if 'RM2' in Parameters["Mode3"]:
if iunit == 2: # Command selector for IR
if level == 10:
LEARNEDCOMMAND = "None"
CUSTOM = "IR"
update_device(1, 1, _('Learn IR command'))
update_device(2, 1, '10')
start_shell('learnir')
elif level == 20:
update_device(2, 1, '20')
SENDCOMMAND = LEARNEDCOMMAND
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to send'))
update_device(2, 0, 'Off')
else:
send()
elif level == 30:
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to save'))
else:
if loop_ini():
update_device(1, 1, _('Ini created'))
update_device(2, 0, 'Off')
LEARNEDCOMMAND = "None"
elif level == 40:
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to reset'))
reset()
else:
Domoticz.Error(_('unknown level command'))
elif iunit == 3: # Command selector for RF
if level == 10:
update_device(1, 1, _('Wait for sweep...'))
update_device(3, 1, '10')
start_shell('sweep')
elif level == 20:
update_device(3, 1, '20')
if DEVICE.check_frequency():
CUSTOM = "RF"
update_device(1, 1, _('Learn RF command'))
start_shell('learnrf')
else:
Domoticz.Log(_('Sweep first'))
update_device(3, 0, 'Off')
elif level == 30:
SENDCOMMAND = LEARNEDCOMMAND
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to send'))
else:
send()
elif level == 40:
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to save'))
else:
update_device(3, 1, '40')
if loop_ini():
update_device(1, 1, _('Ini created'))
update_device(3, 1, '20')
LEARNEDCOMMAND = "None"
elif level == 50:
if LEARNEDCOMMAND == "None":
Domoticz.Log(_('Nothing to reset'))
update_device(3, 1, '50')
reset()
else:
Domoticz.Error(_('unknown level command'))
else:
Domoticz.Error(_('Unit unknown'))
elif command == 'On':
if (iunit == 1 and (
Parameters['Mode3'] == 'SP1' or Parameters['Mode3'] == 'SP2' or Parameters['Mode3'] == 'SP3S')):
try:
DEVICE.set_power(True)
update_device(iunit, 1, 'On')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put "ON" SP1/SP2/SP3'))
ISCONNECTED = False
elif ((iunit == 2 or iunit == 4) and (
Parameters['Mode3'] == 'SP1' or Parameters['Mode3'] == 'SP2' or Parameters['Mode3'] == 'SP3S')):
try:
DEVICE.set_nightlight(True)
update_device(iunit, 1, 'On')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put "on" light for SPx'))
ISCONNECTED = False
elif Parameters['Mode3'] == 'MP1':
if 1 < iunit < 6:
try:
DEVICE.set_power(iunit - 1, True)
update_device(iunit, 1, 'On')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put "ON" MP1 for plug : {}').format(str(iunit - 1)))
else:
if 'RM2' in Parameters["Mode3"]:
if iunit == 1:
if ISCONNECTED:
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
else:
gen_command(iunit)
else:
Domoticz.Error(_('Unknown command'))
elif command == 'Off':
if (iunit == 1 and (
Parameters['Mode3'] == 'SP1' or Parameters['Mode3'] == 'SP2' or Parameters['Mode3'] == 'SP3S')):
try:
DEVICE.set_power(False)
update_device(iunit, 0, 'Off')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put Off SP1/SP2/SP3'))
ISCONNECTED = False
elif ((iunit == 2 or iunit == 4) and (
Parameters['Mode3'] == 'SP1' or Parameters['Mode3'] == 'SP2' or Parameters['Mode3'] == 'SP3S')):
try:
DEVICE.set_nightlight(False)
update_device(iunit, 0, 'Off')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put off light for SPx'))
ISCONNECTED = False
elif Parameters['Mode3'] == 'MP1':
if 1 < iunit < 6:
try:
DEVICE.set_power(iunit - 1, False)
update_device(iunit, 0, 'Off')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Error to put Off MP1 for plug : {}').format(str(iunit - 1)))
else:
try:
update_device(iunit, 0, 'Off')
except (ValueError, Exception):
Domoticz.Error(traceback.format_exc())
Domoticz.Error(_('Unit error update'))
raise
elif iunit == 1 and "RM" in Parameters["Mode3"]:
if remote_send(command):
update_device(iunit, 1, command)
else:
update_device(iunit, 1, _('undefined'))
else:
Domoticz.Error(_('Unknown command'))
return True
# execution depend of Domoticz.Heartbeat(x) x in seconds
def onHeartbeat():
global BYPASS, ISCONNECTED, STATE
now = datetime.datetime.now()
#
# we check new plugin version on day 1
#
if now.day == 1 and now.hour == 0 and now.minute == 0:
start_shell('remotePlugin')
#
# Bypass
#
if BYPASS is True:
BYPASS = False
return
#
# for RM2T/RM24T type we check temp every 2 minutes
#
if Parameters["Mode3"] == 'RM2T' or Parameters["Mode3"] == 'RM24T':
if (now.minute % 2) == 0:
BYPASS = True
if ISCONNECTED:
if check_temp():
update_device(4, 1, TEMP)
update_device(1, 1, 'On')
else:
ISCONNECTED = False
update_device(1, 0, 'Off')
else:
if broadlink_connect():
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
#
# for A1 we get sensor data every 30 seconds
#
elif Parameters["Mode3"] == 'A1':
if INFOLEVEL > 0:
Domoticz.Log(_("A1 called"))
if (now.minute % 1) == 0:
BYPASS = False
if ISCONNECTED:
if check_sensor():
update_device(1, 1, _('Get Data From Sensors'))
else:
ISCONNECTED = False
else:
if broadlink_connect():
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
#
# for SP3S we get energy/status data every 30 seconds
#
elif Parameters["Mode3"] == 'SP3S':
if INFOLEVEL > 0:
Domoticz.Log(_("SP3S called"))
if (now.minute % 1) == 0:
BYPASS = False
if ISCONNECTED:
if get_energy():
update_device(2, 0, str(ENERGY))
update_device(3, 0, str(ENERGY))
else:
ISCONNECTED = False
if check_power():
if STATE:
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
else:
ISCONNECTED = False
if check_light():
if STATE:
update_device(4, 1, 'On')
else:
update_device(4, 0, 'Off')
else:
ISCONNECTED = False
else:
broadlink_connect()
#
# for MP1 we check status every 1 minute
#
elif Parameters["Mode3"] == 'MP1':
if INFOLEVEL > 0:
Domoticz.Log(_("MP1 called"))
if (now.minute % 1) == 0:
BYPASS = True
if ISCONNECTED:
if check_power_mp1():
if STATEMP1:
update_device(1, 1, 'On')
# AllPlugOn()
else:
update_device(1, 0, 'Off')
# AllPlugOff()
else:
ISCONNECTED = False
else:
broadlink_connect()
#
# for SP1/2 we check status every 1 minute
#
elif Parameters["Mode3"] == 'SP1' or Parameters["Mode3"] == 'SP2':
if INFOLEVEL > 0:
Domoticz.Log(_("SP1/SP2 called"))
if (now.minute % 1) == 0:
BYPASS = True
if ISCONNECTED:
if check_power():
if STATE:
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
else:
ISCONNECTED = False
if check_light():
if STATE:
update_device(2, 1, 'On')
else:
update_device(2, 0, 'Off')
else:
ISCONNECTED = False
else:
broadlink_connect()
#
# for RM2 we try to connect every 5 minutes
#
else:
if now.minute % 5 == 0:
if broadlink_connect():
update_device(1, 1, 'On')
else:
update_device(1, 0, 'Off')
BYPASS = True
return True
#
def onMessage(iconnection, idata):
global WEBROOT
if INFOLEVEL > 1:
Domoticz.Log(_("onMessage called for connection: {0}:{1}").format(iconnection.Address, iconnection.Port))
urlok = ''
url = ''
todownload = False
tochunck = False
status = "200 OK"
fname = ''
if "Verb" in idata:
#
# we manage only GET / POST & OPTIONS verbs
#
str_verb = idata["Verb"]
url = idata["URL"]
#
htmldata = \
'''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<link rel="icon" href="data:,"/>
</head>
<body>
<div style="text-align:center;">
<h3><p style="background : whitesmoke;">''' + _("Broadlink response OK!") + '''</p> :-)
</h3>
</div>
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
</body>
</html>
'''
if str_verb == "GET":
if INFOLEVEL > 1:
Domoticz.Log(_("Request from : {}:{} to : {}").format(iconnection.Address, iconnection.Port, url))
if idata['Headers']['Host'] == (Parameters['Address'] + ':' + Parameters['Mode5']) or \
Parameters['Mode5'] in idata['Headers']['Host']:
if url == "/":
urlok = "base"
elif "/web/" in url:
urlok = "web"
htmldata = readf((Parameters['HomeFolder'] + url), True)
elif URLKEY in url:
if "showScan" in url:
urlok = "browser"
htmldata = readf((Parameters['HomeFolder'] + "log/" + "scan.txt"), False, False)
elif "showUsage" in url:
urlok = "browser"
htmldata = readf((Parameters['HomeFolder'] + "log/" + "usage.txt"), False, False)
elif "/info" in url:
urlok = "info"
elif "/creLanguage" in url:
urlok = 'creLanguage'
elif "/translateProgs" in url:
urlok = "translateProgs"
elif "/eControl" in url:
urlok = 'eControl'
elif "/import" in url:
urlok = 'import'
elif "/checkPlugin" in url:
urlok = 'checkPlugin'
elif "/test" in url:
urlok = "test"
iframe = \
'<iframe src="http://domoticz.com/" width="100%" height="450" ' \
'frameborder="0" style="border:0" allowfullscreen></iframe>'
htmldata = htmldata + iframe
elif "/iniList" in url:
urlok = "iniList"
WEBROOT = False
htmldata = str(list_directory(Parameters['Mode2'], False))
elif "/list" in url:
urlok = "list"
WEBROOT = True
htmldata = str(list_directory(Parameters['HomeFolder'], False))
elif "/log" in url:
urlok = "log"
htmldata = domo_log()
elif "/createDevice" in url:
urlok = "createDevice"