forked from theyosh/TerrariumPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terrariumSwitch.py
1082 lines (828 loc) · 39.1 KB
/
terrariumSwitch.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
# -*- coding: utf-8 -*-
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
import RPi.GPIO as GPIO
import pigpio
import math
import os
import sys
import subprocess
import re
import pywemo
import datetime
try:
import thread as _thread
except ImportError as ex:
import _thread
# Dirty hack to include someone his code... to lazy to make it myself :)
# https://github.com/perryflynn/energenie-connect0r
sys.path.insert(0, './energenie-connect0r')
import energenieconnector
from hashlib import md5
from pylibftdi import Driver, BitBangDevice, SerialDevice, Device
from gpiozero import Energenie
from time import time
from gevent import sleep
try:
from meross_iot.api import MerossHttpClient, UnauthorizedException
except ImportError as ex:
# Python 2 does not support Meross XXX Power Switches
pass
from terrariumUtils import terrariumUtils, terrariumTimer, terrariumCache
class terrariumPowerSwitchSource(object):
TYPE = None
def __init__(self, switchid, address, name = '', prev_state = None, callback = None):
logger.info('Initialising \'{}\' power switch object'.format(self.get_type()))
self.power_wattage = 0.0
self.water_flow = 0.0
self.manual_mode = False
self.hardware_replacement = '2019-01-01'
self.switchid = switchid
self.set_name(name)
self.set_address(address)
self.callback = callback
self.timer = terrariumTimer('00:00','00:00',0,0,False)
self.load_hardware()
self.state = None
if self.get_type() not in [terrariumPowerSwitchWeMo.TYPE, terrariumPowerSwitchMSS425E.TYPE]:
# Do not toggle off switches during scanning.....
prev_state = prev_state if prev_state is not None else terrariumPowerSwitch.OFF
self.set_state(prev_state,True)
logger.info('Loaded power switch \'{}\' with values: power {}W and waterflow {}L/s'.format(self.get_name(),self.get_power_wattage(),self.get_water_flow()))
def get_type(self):
return self.TYPE
def get_id(self):
if self.switchid in [None,'None','']:
self.switchid = md5(b'' + self.get_type() + self.get_address()).hexdigest()
return self.switchid
def set_name(self,name):
self.name = name
def get_name(self):
return self.name
def set_address(self,value):
self.address = value
def get_address(self):
return self.address
def set_power_wattage(self,value):
if terrariumUtils.is_float(value):
self.power_wattage = float(value)
def get_power_wattage(self):
return self.power_wattage
def set_water_flow(self,value):
if terrariumUtils.is_float(value):
self.water_flow = float(value)
def get_water_flow(self):
return self.water_flow
def on(self):
return self.set_state(terrariumPowerSwitch.ON)
def off(self):
return self.set_state(terrariumPowerSwitch.OFF)
def is_on(self):
return self.get_state() == terrariumPowerSwitch.ON
def is_off(self):
return not self.is_on()
def go_up(self):
self.on()
def go_down(self):
self.off()
def is_dimmer(self):
return False
def is_pwm_dimmer(self):
return False
def is_at_max_power(self):
return self.is_on()
def is_at_min_power(self):
return self.is_off()
def get_current_power_wattage(self):
return (0.0 if self.is_off() else self.get_power_wattage())
def get_current_water_flow(self):
return (0.0 if self.is_off() else self.get_water_flow())
def toggle(self):
if self.is_on():
self.off()
else:
self.on()
def load_hardware(self):
pass
def set_hardware_state(self, value, force = False):
pass
def get_hardware_state(self):
return None
def set_last_hardware_replacement(self,replacement_date = None):
if replacement_date is None:
replacement_date = datetime.date.today().strftime('%Y-%m-%d')
self.hardware_replacement = replacement_date
def get_last_hardware_replacement(self):
return self.hardware_replacement
def set_state(self, state, force = False):
changed = False
logger.debug('Changing power switch \'{}\' of type \'{}\' at address \'{}\' from state \'{}\' to state \'{}\' (Forced:{})'.format(self.get_name(),
self.get_type(),
self.get_address(),
self.get_state(),
state,force))
if self.get_state() is not state or terrariumUtils.is_true(force):
old_state = self.get_state()
try:
self.set_hardware_state(state,force)
self.state = state
logger.info('Changed power switch \'{}\' of type \'{}\' at address \'{}\' from state \'{}\' to state \'{}\' (Forced:{})'.format(self.get_name(),
self.get_type(),
self.get_address(),
old_state,
state,
force))
except Exception as ex:
print(ex)
logger.error('Failed changing power switch \'{}\' of type \'{}\' at address \'{}\' from state \'{}\' to state \'{}\' (Forced:{})'.format(self.get_name(),
self.get_type(),
self.get_address(),
self.get_state(),
state,force))
if (old_state is not None) or (old_state is None and state == 0):
# This is due to a bug that will graph 0 watt usage in the graph after rebooting.
# Fix is to add power and water usage in constructor
changed = old_state != self.get_state()
if changed and self.callback is not None:
self.callback(self.get_data())
return changed
def get_state(self):
return self.state
def stop(self):
pass
def in_manual_mode(self):
return terrariumUtils.is_true(self.manual_mode)
def set_manual_mode(self,mode):
self.manual_mode = terrariumUtils.is_true(mode)
def update(self):
starttime = time()
old_state = self.get_state()
self.timer_update()
data = self.get_hardware_state()
if data is not None:
self.set_state(data)
if self.get_state() != old_state:
logger.info('Power switch changed from {} state to new {} state'.format(old_state,self.get_state()))
logger.info('Updated {} power switch \'{}\' status in {:.5f} seconds'.format(self.get_type(),self.get_name(),time()-starttime))
def timer_update(self):
if not self.in_manual_mode() and self.timer.is_enabled():
if self.timer.is_time():
self.on()
else:
self.off()
def set_timer(self,start,stop,on_duration,off_duration,enabled):
self.timer = terrariumTimer(start,stop,on_duration,off_duration,enabled)
self.timer_update()
def get_data(self):
data = {'id' : self.get_id(),
'hardwaretype' : self.get_type(),
'address' : self.get_address(),
'name' : self.get_name(),
'power_wattage' : self.get_power_wattage(),
'current_power_wattage' : self.get_current_power_wattage(),
'water_flow' : self.get_water_flow(),
'current_water_flow' : self.get_current_water_flow(),
'state' : self.get_state(),
'manual_mode' : self.in_manual_mode(),
'last_replacement_date' : self.get_last_hardware_replacement()}
data.update(self.timer.get_data())
return data
class terrariumPowerSwitchFTDI(terrariumPowerSwitchSource):
TYPE = 'ftdi'
BITBANG_ADDRESSES = {
"1":"2",
"2":"8",
"3":"20",
"4":"80",
"5":"1",
"6":"4",
"7":"10",
"8":"40",
"all":"FF"
}
def load_hardware(self):
self.__device_type = None
for device in Driver().list_devices():
vendor, product, self.__device = [x.decode('latin1') for x in device]
self.__device_type = 'Serial' if product.endswith('UART') else 'BitBang'
logger.debug('Found switch board {}, {}, {}, of type {}'.format(vendor,product,self.__device,self.__device_type))
break # For now, we only support 1 switch board!
def set_address(self,value):
if value in terrariumPowerSwitchFTDI.BITBANG_ADDRESSES:
self.address = value
def set_hardware_state(self, state, force = False):
if 'BitBang' == self.__device_type:
with BitBangDevice(self.__device) as device:
device.baudrate = 9600
if state is terrariumPowerSwitch.ON:
device.port |= int(terrariumPowerSwitchFTDI.BITBANG_ADDRESSES[str(self.get_address())], 16)
else:
device.port &= ~int(terrariumPowerSwitchFTDI.BITBANG_ADDRESSES[str(self.get_address())], 16)
device.close()
elif 'Serial' == self.__device_type:
with SerialDevice(self.__device) as device:
device.baudrate = 9600
cmd = chr(0xff) + chr(0x0 + int(self.get_address())) + chr(0x0 + (1 if state is terrariumPowerSwitch.ON else 0))
device.write(cmd)
device.close()
class terrariumPowerSwitchGPIO(terrariumPowerSwitchSource):
TYPE = 'gpio'
def load_hardware(self):
GPIO.setup(terrariumUtils.to_BCM_port_number(self.get_address()), GPIO.OUT)
def stop(self):
GPIO.cleanup(terrariumUtils.to_BCM_port_number(self.get_address()))
def set_hardware_state(self, state, force = False):
if self.get_type() == terrariumPowerSwitchGPIO.TYPE:
GPIO.output(terrariumUtils.to_BCM_port_number(self.get_address()), ( GPIO.HIGH if state is terrariumPowerSwitch.ON else GPIO.LOW ))
elif self.get_type() == terrariumPowerSwitchGPIOInverse.TYPE:
GPIO.output(terrariumUtils.to_BCM_port_number(self.get_address()), ( GPIO.LOW if state is terrariumPowerSwitch.ON else GPIO.HIGH ))
class terrariumPowerSwitchGPIOInverse(terrariumPowerSwitchGPIO):
TYPE = 'gpio-inverse'
class terrariumPowerSwitchWeMo(terrariumPowerSwitchSource):
TYPE = 'wemo'
URL = 'http://{}:{}/setup.xml'
def set_hardware_state(self, state, force = False):
port = pywemo.ouimeaux_device.probe_wemo(self.get_address())
device = pywemo.discovery.device_from_description(terrariumPowerSwitchWeMo.URL.format(self.get_address(), port), None)
if state is terrariumPowerSwitch.ON:
device.on()
else:
device.off()
def get_hardware_state(self):
data = None
try:
port = pywemo.ouimeaux_device.probe_wemo(self.get_address())
if port is not None:
device = pywemo.discovery.device_from_description(terrariumPowerSwitchWeMo.URL.format(self.get_address(), port), None)
data = device.get_state()
except Exception as err:
# Ignore for now
print(err)
return terrariumPowerSwitch.ON if terrariumUtils.is_true(data) else terrariumPowerSwitch.OFF
@staticmethod
def scan_power_switches(callback=None, **kwargs):
for device in pywemo.discover_devices():
yield terrariumPowerSwitch(md5((terrariumPowerSwitchWeMo.TYPE + device.serialnumber).encode()).hexdigest(),
terrariumPowerSwitchWeMo.TYPE,
device.host,
device.name,
None,
callback)
class terrariumPowerSwitchEnergenieUSB(terrariumPowerSwitchSource):
TYPE = 'eg-pm-usb'
def load_hardware(self):
# We have per device 4 outlets.... so outlet 7 is device 1
self.__device = (int(self.get_address())-1) / 4
if self.__device < 0:
self.__device = 0
def set_hardware_state(self, state, force = False):
address = int(self.get_address()) % 4
if address == 0:
address = 4
cmd = ['/usr/bin/sispmctl', '-d',str(self.__device),('-o' if state is terrariumPowerSwitch.ON else '-f'),str(address)]
subprocess.check_output(cmd)
class terrariumPowerSwitchEnergenieLAN(terrariumPowerSwitchSource):
TYPE = 'eg-pm-lan'
VALID_SOURCE = '^http:\/\/((?P<passwd>[^@]+)@)?(?P<host>[^#\/]+)(\/)?#(?P<switch>[1-4])$'
# def set_address(self,value):
# super(terrariumPowerSwitchEnergenieLAN, self).set_address(value)
# self.load_hardware()
def load_hardware(self):
self.__device = None
# Input format should be either:
# - http://[HOST]#[POWER_SWITCH_NR]
# - http://[HOST]/#[POWER_SWITCH_NR]
# - http://[PASSWORD]@[HOST]#[POWER_SWITCH_NR]
# - http://[PASSWORD]@[HOST]/#[POWER_SWITCH_NR]
data = re.match(terrariumPowerSwitchEnergenieLAN.VALID_SOURCE,self.get_address())
if data:
data = data.groupdict()
if 'passwd' not in data:
data['passwd'] = ''
try:
# https://github.com/perryflynn/energenie-connect0r
self.__device = energenieconnector.EnergenieConnector('http://' + data['host'],data['passwd'])
status = self.__device.getstatus()
if status['login'] == 1:
if self.__device.login():
logger.info('Connection to remote Energenie LAN \'%s\' is successfull at location %s' % (self.get_name(), self.get_address()))
status = self.__device.getstatus()
self.__device.logout()
if status['login'] != 0:
logger.error('Could not login to the Energenie LAN device %s at location %s. Error status %s(%s)' % (self.get_name(),self.get_address(),status['logintxt'],status['login']))
self.__device = None
except Exception as ex:
logger.exception('Could not login to the Energenie LAN device %s at location %s. Error status %s' % (self.get_name(),self.get_address(),ex))
def set_hardware_state(self, state, force = False):
changed = True
if self.__device is None:
logger.error('Energenie LAN device is not connected. Cannot trigger power switch')
changed = False
else:
data = re.match(terrariumPowerSwitchEnergenieLAN.VALID_SOURCE,self.get_address())
if data:
power_socket = int(data.group('switch')) % 4
if power_socket == 0:
power_socket = 4
#try:
webstatus = self.__device.getstatus()
if webstatus['login'] == 1:
logger.debug('Logged in at remote Energenie LAN power switch %s' % (self.get_address(),))
if self.__device.login():
webstatus = self.__device.getstatus()
if webstatus['login'] == 0:
self.__device.changesocket(power_socket, ( 1 if state is terrariumPowerSwitch.ON else 0 ))
self.__device.logout()
else:
# raise exception here...
logger.error('Could not login to the Energenie LAN device %s at location %s. Error status %s(%s)' % (self.get_name(),self.get_address(),webstatus['logintxt'],webstatus['login']))
return changed
def stop(self):
self.__device.logout()
class terrariumPowerSwitchEnergenieRF(terrariumPowerSwitchSource):
TYPE = 'eg-pm-rf'
def load_hardware(self):
self.__device = Energenie(int(self.get_address()))
def set_hardware_state(self, state, force = False):
if state:
self.__device.on()
else:
self.__device.off()
def stop(self):
self.__device.close()
class terrariumPowerSwitchSonoff(terrariumPowerSwitchSource):
TYPE = 'sonoff'
VALID_SOURCE = '^http:\/\/((?P<user>[^:]+):(?P<passwd>[^@]+)@)?(?P<host>[^#\/]+)(\/)?$'
def load_hardware(self):
self.__firmware = None
# Input format should be either:
# - http://[HOST]#[POWER_SWITCH_NR]
# - http://[HOST]/#[POWER_SWITCH_NR]
# - http://[PASSWORD]@[HOST]#[POWER_SWITCH_NR]
# - http://[PASSWORD]@[HOST]/#[POWER_SWITCH_NR]
data = re.match(self.VALID_SOURCE,self.get_address())
if data:
data = data.groupdict()
try:
# Try Tasmota
# http://sonoff/cm?cmnd=Power%20TOGGLE
# http://sonoff/cm?cmnd=Power%20On
# http://sonoff/cm?cmnd=Power%20off
# http://sonoff/cm?user=admin&password=joker&cmnd=Power%20Toggle
url = 'http://{}/cm?cmnd=Power'.format(data['host'])
if 'user' in data and 'password' in data:
url += '&user={}&password={}'.format(data['user'],data['password'])
state = terrariumUtils.get_remote_data(url)
if state is None:
raise Exception('No data, jump to next test')
self.__firmware = 'tasmota'
except Exception as ex:
print('Tasmota exceptions')
print(ex)
if self.__firmware is None:
try:
# Try ESP Easy
# url_switch_on = 'http://192.168.1.42/control?cmd=event,T1'
# url_switch_off = 'http://192.168.1.42/control?cmd=event,T0'
print('Test ESP Easy')
url = 'http://{}/json'.format(data['host'])
# No information about using username and password:
# https://www.letscontrolit.com/wiki/index.php?title=ESPEasy_Command_Reference
# https://www.letscontrolit.com/wiki/index.php?title=ESP_Easy_web_interface#JSON_page_.28hidden_prior_to_version_2.0.2B.29
print(url)
state = terrariumUtils.get_remote_data(url)
print('Result')
print(state)
if state is None:
raise Exception('No data, jump to next test')
self.__firmware = 'espeasy'
except Exception as ex:
print('ESP Easy exceptions')
print(ex)
if self.__firmware is None:
try:
# Try ESPurna
# https://github.com/xoseperez/espurna/wiki/RESTAPI
# http://192.168.1.108/apis?apikey=C62ED7BE7593B658
# http://192.168.1.108/api/relay/0?apikey=C62ED7BE7593B658&value=0 (off)
# http://192.168.1.108/api/relay/0?apikey=C62ED7BE7593B658&value=1 (on)
# http://192.168.1.108/api/relay/0?apikey=C62ED7BE7593B658&value=2 (toggle)
print('Test ESPurna')
if 'password' not in data:
# Just add dummy value...
data['password'] = 'password'
url = 'http://{}/apis?apikey={}'.format(data['host'],data['password'])
print(url)
state = terrariumUtils.get_remote_data(url,json=True)
print('Result')
print(state)
if state is None:
raise Exception('No data, this was the last attempt...')
self.__firmware = 'espurna'
except Exception as ex:
print('ESPurna exceptions')
print(ex)
def set_hardware_state(self, state, force = False):
changed = True
if self.__firmware is None:
logger.error('Sonoff device is not connected. Cannot trigger power switch')
changed = False
else:
data = re.match(self.VALID_SOURCE,self.get_address())
if data:
data = data.groupdict()
url = None
if 'tasmota' == self.__firmware:
url = 'http://{}/cm?cmnd=Power%20{}'.format(data['host'],('1' if state else '0'))
if 'user' in data and 'password' in data:
url += '&user={}&password={}'.format(data['user'],data['password'])
elif 'espeasy' == self.__firmware:
url = 'http://{}/control?cmd=event,T{}'.format(data['host'],('1' if state else '0'))
elif 'espurna' == self.__firmware:
url = 'http://{}/api/relay/0?apikey={}&value={}'.format(data['host'],data['password'],('1' if state else '0'))
state = terrariumUtils.get_remote_data(url)
if state is None:
changed = False
return changed
def get_hardware_state(self):
data = None
if self.__firmware is None:
logger.error('Sonoff device is not connected. Cannot read power switch state')
return terrariumPowerSwitch.OFF
else:
data = re.match(self.VALID_SOURCE,self.get_address())
if data:
data = data.groupdict()
url = None
if 'tasmota' == self.__firmware:
url = 'http://{}/cm?cmnd=Power'.format(data['host'])
if 'user' in data and 'password' in data:
url += '&user={}&password={}'.format(data['user'],data['password'])
elif 'espeasy' == self.__firmware:
url = 'http://{}/json'.format(data['host'])
elif 'espurna' == self.__firmware:
if 'password' not in data:
# Just add dummy value...
data['password'] = 'password'
url = 'http://{}/apis?apikey={}'.format(data['host'],data['password'])
state = terrariumUtils.get_remote_data(url)
if 'tasmota' == self.__firmware:
return terrariumPowerSwitch.ON if terrariumUtils.is_true(state['POWER']) else terrariumPowerSwitch.OFF
elif 'espeasy' == self.__firmware:
return terrariumPowerSwitch.ON if terrariumUtils.is_true(state['POWER']) else terrariumPowerSwitch.OFF
elif 'espurna' == self.__firmware:
return terrariumPowerSwitch.ON if terrariumUtils.is_true(state['POWER']) else terrariumPowerSwitch.OFF
return terrariumPowerSwitch.OFF
class terrariumPowerSwitchDenkoviV2(terrariumPowerSwitchSource):
TYPE = 'denkovi_v2'
def __init__(self, switchid, address, name = '', prev_state = None, callback = None):
self.__cache = terrariumCache()
super(terrariumPowerSwitchDenkoviV2,self).__init__(switchid, address, name, prev_state, callback)
def __get_cache_key(self):
key = md5((self.get_type() + str(self.__device)).encode()).hexdigest()
return key
def _get_relay_count(self):
return int(self.TYPE.split('_')[-1])
def _get_board_type(self):
return '{}{}'.format(self._get_relay_count(),self.__version)
def load_hardware(self):
serial_regex = r"^(?P<serial>[^ ]+)\W(\[[^\]]+\])\W\[id=\d\]$"
self.__device = None
self.__version = ''
# We only support one board for now...
cmd = ['/usr/bin/sudo','/usr/bin/java','-jar','DenkoviRelayCommandLineTool/DenkoviRelayCommandLineTool.jar','list']
logger.debug('Running load hardware command {}'.format(cmd))
try:
data = subprocess.check_output(cmd).strip().decode('utf-8')
for line in data.split("\n"):
match = re.match(r"^(?P<serial>[^ ]+)\W(?P<device>\[[^\]]+\])\W\[id=\d\]$",line,re.MULTILINE)
if match:
self.__device = str(match.group('serial'))
self.__version = 'v2' if 'MCP2200' in match.group('device') else ''
break
except Exception as err:
# Ignore for now
logger.error('Error loading hardware for switch type {}, with error: {}'.format(self.get_type(),err))
def get_hardware_state(self):
#data = None
#print('Get hardware state cache data')
data = self.__cache.get_data(self.__get_cache_key())
#print(data)
#print('IS running: {}' .format(self.__cache.is_running(self.__get_cache_key())))
if data is None and not self.__cache.is_running(self.__get_cache_key()):
self.__cache.set_running(self.__get_cache_key())
cmd = ['/usr/bin/sudo','/usr/bin/java','-jar','DenkoviRelayCommandLineTool/DenkoviRelayCommandLineTool.jar',self.__device,self._get_board_type(),'all','status']
logger.debug('Running get hardware state command {}'.format(cmd))
#print('Running cmd: {}'.format(cmd))
try:
data = subprocess.check_output(cmd).strip().decode('utf-8')
#print('Got data: *{}*'.format(data))
self.__cache.set_data(self.__get_cache_key(),data)
except Exception as err:
# Ignore for now
logger.error('Error getting hardware state for switch type {}, with error: {}'.format(self.get_type(),err))
self.__cache.clear_running(self.__get_cache_key())
if data is None:
return terrariumPowerSwitch.OFF
address = int(self.get_address()) % self._get_relay_count()
if address == 0:
address = self._get_relay_count()
#print('Final state data at address{} : {}'.format(address,data[address-1:address]))
return terrariumPowerSwitch.ON if terrariumUtils.is_true(data[address-1:address]) else terrariumPowerSwitch.OFF
def set_hardware_state(self, state, force = False):
address = int(self.get_address()) % self._get_relay_count()
if address == 0:
address = self._get_relay_count()
cmd = ['/usr/bin/sudo','/usr/bin/java','-jar','DenkoviRelayCommandLineTool/DenkoviRelayCommandLineTool.jar',self.__device,self._get_board_type(),str(address),str(1 if state is terrariumPowerSwitch.ON else 0)]
logger.debug('Running set hardware state command {}'.format(cmd))
#print('Running set hardware state cmd: {}'.format(cmd))
try:
subprocess.check_output(cmd)
# After change, clear the cache so next run actual data is forced fetched
#print('Clear caching')
self.__cache.clear_data(self.__get_cache_key())
#print('Clear caching DONE!')
return True
except Exception as err:
# Ignore for now
logger.error('Error setting hardware state for switch type {}, with error: {}'.format(self.get_type(),err))
#print(err)
class terrariumPowerSwitchDenkoviV2_4(terrariumPowerSwitchDenkoviV2):
TYPE = 'denkovi_v2_4'
class terrariumPowerSwitchDenkoviV2_8(terrariumPowerSwitchDenkoviV2):
TYPE = 'denkovi_v2_8'
class terrariumPowerSwitchDenkoviV2_16(terrariumPowerSwitchDenkoviV2):
TYPE = 'denkovi_v2_16'
class terrariumPowerSwitchScript(terrariumPowerSwitchSource):
TYPE = 'script'
def set_hardware_state(self, state, force = False):
value = (100 if state else 0)
try:
logger.info('Running script: %s.' % (self.get_address()))
data = subprocess.check_output('{} {}'.format(self.get_address(),value), shell=True)
logger.info('Output was: %s.' % (data))
except Exception as ex:
logger.exception('Error parsing script data for script %s. Exception %s' % (self.get_address(), ex))
return state
class terrariumPowerDimmerSource(terrariumPowerSwitchSource):
TYPE = 'dimmer'
# General Dimmer settings
DIMMER_MIN_TIMEOUT = 0.1
DIMMER_MIN_STEP = 0.1
def __init__(self, switchid, address, name = '', prev_state = None, callback = None):
self.duration = 0.0
self.step = 0.0
self.on_duration = 0.0
self.off_duration = 0.0
self.on_percentage = 100.0
self.off_percentage = 0.0
self.__dimmer_state = 0.0
super(terrariumPowerDimmerSource,self).__init__(switchid, address, name, prev_state, callback)
def get_state(self):
return self.__dimmer_state
def load_hardware(self):
self.__dimmer_running = False
pigpio.exceptions = False
self.__pigpio = pigpio.pi('localhost')
if not self.__pigpio.connected:
self.__pigpio = pigpio.pi()
if not self.__pigpio.connected:
logger.error('PiGPIOd process is not running')
self.__pigpio = False
pigpio.exceptions = True
self.__pigpio.set_pull_up_down(terrariumUtils.to_BCM_port_number(self.get_address()), pigpio.PUD_OFF)
def is_dimmer(self):
return True
def is_pwm_dimmer(self):
return True
def get_current_power_wattage(self):
return (float(self.get_state()) / 100) * self.get_power_wattage()
def get_current_water_flow(self):
return (float(self.get_state()) / 100) * self.get_water_flow()
def is_at_max_power(self):
return self.get_state() >= self.get_dimmer_on_percentage()
def is_at_min_power(self):
return self.get_state() <= self.get_dimmer_off_percentage()
def is_on(self):
return self.is_at_max_power()
def __go_up_down(self,direction):
if not self.__dimmer_running:
new_value = self.get_state() + (direction * self.get_dimmer_step())
if new_value > self.get_dimmer_on_percentage():
new_value = self.get_dimmer_on_percentage()
if new_value < self.get_dimmer_off_percentage():
new_value = self.get_dimmer_off_percentage()
self.set_state(new_value)
def go_up(self):
self.__go_up_down(1)
def go_down(self):
self.__go_up_down(-1)
def set_dimmer(self,duration,step,on_duration,off_duration,on_percentage,off_percentage):
self.duration = float(duration)
self.step = float(step)
self.on_duration = float(on_duration)
self.off_duration = float(off_duration)
self.on_percentage = float(on_percentage)
self.off_percentage = float(off_percentage)
def get_dimmer_duration(self):
return self.duration
def get_dimmer_step(self):
return self.step
def get_dimmer_on_duration(self):
return self.on_duration
def get_dimmer_off_duration(self):
return self.off_duration
def get_dimmer_on_percentage(self):
return self.on_percentage
def get_dimmer_off_percentage(self):
return self.off_percentage
def set_hardware_state(self, value, force = False):
if not self.__dimmer_running:
duration = self.get_dimmer_duration()
# State 100 = full on which means 0 dim.
# State is inverse of dim
if value is terrariumPowerSwitch.ON:
value = self.get_dimmer_on_percentage()
duration = self.get_dimmer_on_duration()
elif value is terrariumPowerSwitch.OFF or not (0.0 <= float(value) <= 100.0):
value = self.get_dimmer_off_percentage()
duration = self.get_dimmer_off_duration()
if force:
duration = 0
_thread.start_new_thread(self.__dim_switch, (value,duration))
return True
def __dim_switch(self,value,duration):
# When the dimmer is working, ignore new state changes.
if not self.__dimmer_running:
self.__dimmer_running = True
self.__dimmer_state = (0.0 if not terrariumUtils.is_float(self.get_state()) else float(self.get_state()))
value = (0.0 if not terrariumUtils.is_float(value) else float(value))
duration = (0.0 if not terrariumUtils.is_float(duration) else float(duration))
direction = (1.0 if self.__dimmer_state <= value else -1.0)
distance = abs(self.__dimmer_state - value)
if int(duration) == 0 or int(distance) == 0:
steps = 1.0
else:
steps = math.floor(min( (abs(duration) / terrariumPowerDimmerSource.DIMMER_MIN_TIMEOUT),
(distance / terrariumPowerDimmerSource.DIMMER_MIN_STEP)))
distance /= steps
duration /= steps
logger.debug('Dimmer settings: Steps: %s, Distance per step: %s%%, Time per step: %s, Direction: %s',steps, distance, duration, direction)
for counter in range(int(steps)):
self.__dimmer_state += (direction * distance)
if self.get_type() == terrariumPowerDimmerPWM.TYPE:
dim_value = terrariumPowerDimmerPWM.DIMMER_MAXDIM * ((100.0 - float(self.__dimmer_state)) / 100.0)
dim_freq = terrariumPowerDimmerPWM.DIMMER_FREQ
elif self.get_type() == terrariumPowerDimmerDC.TYPE:
dim_value = terrariumPowerDimmerDC.DIMMER_MAXDIM * (float(self.__dimmer_state) / 100.0)
dim_freq = terrariumPowerDimmerDC.DIMMER_FREQ
for gpiopin in self.get_address().split(','):
if terrariumUtils.to_BCM_port_number(gpiopin) is False:
continue
logger.debug('Dimmer animation: Step: %s, value %s%%, Dim value: %s, timeout %s',counter+1, self.__dimmer_state, dim_value, duration)
self.__pigpio.hardware_PWM(terrariumUtils.to_BCM_port_number(gpiopin), dim_freq, int(dim_value) * 1000) # 5000Hz state*1000% dutycycle
if duration > 0.0:
sleep(duration)
# For impatient people... Put the dimmer at the current state value if it has changed during the animation (DISABLED FOR NOW)
# dim_value = terrariumSwitch.PWM_DIMMER_MAXDIM * ((100.0 - self.get_state()) / 100.0)
# self.__pigpio.hardware_PWM(terrariumUtils.to_BCM_port_number(self.get_address()), 5000, int(dim_value) * 1000) # 5000Hz state*1000% dutycycle
self.__dimmer_state = value
self.__dimmer_running = False
if self.callback is not None:
self.callback(self.get_data())
logger.info('Power switch \'{}\' at address \'{}\' is done at value {}% in {} seconds'.format(self.get_name(),
self.get_address(),
self.get_state(),
duration*steps))
#else:
# logger.warning('Dimmer %s is already working. Ignoring state change!. Will switch to latest state value when done', self.get_name())
def get_data(self):
data = super(terrariumPowerDimmerSource,self).get_data()
data.update({
'dimmer_duration' : self.get_dimmer_duration(),
'dimmer_step' : self.get_dimmer_step(),
'dimmer_on_duration' : self.get_dimmer_on_duration(),
'dimmer_on_percentage' : self.get_dimmer_on_percentage(),
'dimmer_off_duration' : self.get_dimmer_off_duration(),
'dimmer_off_percentage': self.get_dimmer_off_percentage()
})
return data
class terrariumPowerDimmerPWM(terrariumPowerDimmerSource):
TYPE = 'pwm-dimmer'
# PWM dimmer settings
# According to http://www.esp8266-projects.com/2017/04/raspberry-pi-domoticz-ac-dimmer-part-1/
# is 860 DIM value equal to 95% dimming -> 905 is 100% dimming
DIMMER_MAXDIM = 870
DIMMER_FREQ = 5000
class terrariumPowerDimmerDC(terrariumPowerDimmerSource):
TYPE = 'dc-dimmer'
# DC dimmer settings
DIMMER_MAXDIM = 1000 # https://github.com/theyosh/TerrariumPI/issues/178#issuecomment-412667010
DIMMER_FREQ = 15000 # https://github.com/theyosh/TerrariumPI/issues/178#issuecomment-413697246
class terrariumPowerSwitchRemote(terrariumPowerSwitchSource):
TYPE = 'remote'
def set_hardware_state(self, state, force = False):
pass
def get_hardware_state(self):
data = None
url_data = terrariumUtils.parse_url(self.get_address())
if url_data is False:
logger.error('Remote url \'%s\' for switch \'%s\' is not a valid remote source url!' % (self.get_address(),self.get_name()))
else:
data = terrariumUtils.get_remote_data(self.get_address())
return terrariumPowerSwitch.ON if terrariumUtils.is_true(data) else terrariumPowerSwitch.OFF
class terrariumPowerSwitchMSS425E(terrariumPowerSwitchSource):
TYPE = 'mss425e'
def __init__(self, switch_id, address, name = '', prev_state = None, callback = None):
self.__device = address[0]
super(terrariumPowerSwitchMSS425E,self).__init__(switch_id, address[1], name, prev_state, callback)
def set_hardware_state(self, state, force = False):
if state is terrariumPowerSwitch.ON:
self.__device.turn_on_channel(int(self.get_address()))
else:
self.__device.turn_off_channel(int(self.get_address()))
def get_hardware_state(self):
data = None
try:
tmpdata = self.__device.get_sys_data()
for channel_data in tmpdata['all']['digest']['togglex']:
if int(self.get_address()) == int(channel_data['channel']):
data = channel_data['onoff']
break
except Exception as ex:
print('Get hardware ex')
print(ex)
return terrariumPowerSwitch.ON if terrariumUtils.is_true(data) else terrariumPowerSwitch.OFF
@staticmethod
def scan_power_switches(callback=None, **kwargs):
if '' == kwargs['meross_username'] or '' == kwargs['meross_password']:
logger.info('Meross cloud is not enabled.')
return