-
Notifications
You must be signed in to change notification settings - Fork 21
/
core.py
3385 lines (3096 loc) · 130 KB
/
core.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
#! /usr/bin/python3
#
# Copyright (c) 2018 Sébastien RAMAGE
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
from binascii import hexlify
import traceback
from time import (sleep, strftime, monotonic)
import logging
import json
import os
from pydispatch import dispatcher
from .transport import (ThreadSerialConnection,
ThreadSocketConnection,
FakeTransport)
from .responses import (RESPONSES, Response)
from .const import (ACTIONS_COLOR, ACTIONS_LEVEL, ACTIONS_LOCK, ACTIONS_HUE,
ACTIONS_ONOFF, ACTIONS_TEMPERATURE, ACTIONS_COVER,
ACTIONS_THERMOSTAT, ACTIONS_IAS,
OFF, ON, TYPE_COORDINATOR, STATUS_CODES,
ZIGATE_ATTRIBUTE_ADDED, ZIGATE_ATTRIBUTE_UPDATED,
ZIGATE_DEVICE_ADDED, ZIGATE_DEVICE_REMOVED,
ZIGATE_DEVICE_UPDATED, ZIGATE_DEVICE_ADDRESS_CHANGED,
ZIGATE_PACKET_RECEIVED, ZIGATE_DEVICE_NEED_DISCOVERY,
ZIGATE_RESPONSE_RECEIVED, DATA_TYPE, BASE_PATH)
from .clusters import (Cluster, get_cluster)
import functools
import struct
import threading
import random
from enum import Enum
import colorsys
import datetime
try:
import RPi.GPIO as GPIO
except Exception:
# Fake GPIO
class GPIO:
def fake(self, *args, **kwargs):
LOGGER.error('GPIO Not available')
def __getattr__(self, *args, **kwargs):
return self.fake
GPIO = GPIO()
import usb
LOGGER = logging.getLogger('zigate')
AUTO_SAVE = 5 * 60 # 5 minutes
BIND_REPORT = True # automatically bind and report state for light
SLEEP_INTERVAL = 0.1
ACTIONS = {}
WAIT_TIMEOUT = 5
DETECT_FASTCHANGE = False # enable fast change detection
DELAY_FASTCHANGE = 1.0 # delay fast change for cluster 0x0006
# Device id
ACTUATORS = [0x0009, 0x0010, 0x0051, 0x000a,
0x010a, 0x010b, 0x010c, 0x010d,
0x0100, 0x0101, 0x0102, 0x0103, 0x0105, 0x0110,
0x0200, 0x0202, 0x0210, 0x0220,
0x0301,
0x0403]
# On/off light 0x0000
# On/off plug-in unit 0x0010
# Dimmable light 0x0100
# Dimmable plug-in unit 0x0110
# Color light 0x0200
# Extended color light 0x0210
# Color temperature light 0x0220
# On/Off Light 0x0100 Section 3.1
# Dimmable Light 0x0101 Section 3.2
# Colour Dimmable Light 0x0102 Section 3.3
# On/Off Light Switch 0x0103 Section 3.4
# Dimmer Switch 0x0104 Section 3.5
# Colour Dimmer Switch 0x0105 Section 3.6
# Light Sensor 0x0106 Section 3.7
# Occupancy Sensor 0x0107 Section 3.8
# On/Off Ballast 0x0108 Section 3.9
# Dimmable Ballast 0x0109 Section 3.10
# On/Off Plug-in Unit 0x010A Section 3.11
# Dimmable Plug-in Unit 0x010B Section 3.12
# Colour Temperature Light 0x010C Section 3.13
# Extended Colour Light 0x010D Section 3.14
# Light Level Sensor 0x010E Section 3.15
# Colour Controller 0x0800 Section 3.16
# Colour Scene Controller 0x0810 Section 3.17
# Non-Colour Controller 0x0820 Section 3.18
# Non-Colour Scene Controller 0x0830 Section 3.19
# Control Bridge 0x0840 Section 3.20
# On/Off Sensor 0x0850 Section 3.21
def register_actions(action):
def decorator(func):
if action not in ACTIONS:
ACTIONS[action] = []
ACTIONS[action].append(func.__name__)
return func
return decorator
class AddrMode(Enum):
bound = 0
group = 1
short = 2
ieee = 3
def hex_to_rgb(h):
''' convert hex color to rgb tuple '''
h = h.strip('#')
return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
def rgb_to_xy(rgb):
''' convert rgb tuple to xy tuple '''
red, green, blue = rgb
r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92)
g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92)
b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92)
X = r * 0.664511 + g * 0.154324 + b * 0.162028
Y = r * 0.283881 + g * 0.668433 + b * 0.047685
Z = r * 0.000088 + g * 0.072310 + b * 0.986039
cx = 0
cy = 0
if (X + Y + Z) != 0:
cx = X / (X + Y + Z)
cy = Y / (X + Y + Z)
return (cx, cy)
def hex_to_xy(h):
''' convert hex color to xy tuple '''
return rgb_to_xy(hex_to_rgb(h))
def dispatch_signal(signal=dispatcher.Any, sender=dispatcher.Anonymous,
*arguments, **named):
'''
Dispatch signal with exception proof
'''
LOGGER.debug('Dispatch %s', signal)
try:
dispatcher.send(signal, sender, *arguments, **named)
except Exception:
LOGGER.error('Exception dispatching signal %s', signal)
LOGGER.error(traceback.format_exc())
def ftdi_set_bitmode(dev, bitmask):
'''
Set mode for ZiGate DIN module
'''
BITMODE_CBUS = 0x20
SIO_SET_BITMODE_REQUEST = 0x0b
bmRequestType = usb.util.build_request_type(usb.util.CTRL_OUT,
usb.util.CTRL_TYPE_VENDOR,
usb.util.CTRL_RECIPIENT_DEVICE)
wValue = bitmask | (BITMODE_CBUS << BITMODE_CBUS)
dev.ctrl_transfer(bmRequestType, SIO_SET_BITMODE_REQUEST, wValue)
class ZiGate(object):
def __init__(self, port='auto', path='~/.zigate.json',
auto_start=True,
auto_save=True,
channel=None,
adminpanel=False):
self._model = 'TTL' # TTL, WiFI, DIN, GPIO
self._devices = {}
self._groups = {}
self._scenes = {}
self._led = True
self._neighbours_table_cache = []
self._building_neighbours_table = False
self._path = path
self._version = None
self._port = port
self._last_response = {} # response to last command type
self._last_status = {} # status to last command type
self._save_lock = threading.Lock()
self._autosavetimer = None
self._closing = False
self.connection = None
self._addr = '0000'
self._ieee = None
self.panid = 0
self.extended_panid = 0
self.channel = 0
self._started = False
self._no_response_count = 0
self._ota_reset_local_variables()
if self.model == 'DIN':
self.set_running_mode()
if adminpanel:
self.start_adminpanel()
if auto_start:
self.startup(channel)
if auto_save:
self.start_auto_save()
@property
def model(self):
'''
return ZiGate model:
TTL, WiFi, GPIO, DIN
'''
if self.connection:
if self.connection.vid_pid() == (0x0403, 0x6001):
self._model = 'DIN'
return self._model
def set_bootloader_mode(self):
'''
configure ZiGate DIN in flash mode
'''
if self.model != 'DIN':
LOGGER.warning('Method only supported on ZiGate DIN')
return
dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
if not dev:
LOGGER.error('ZiGate DIN not found.')
return
ftdi_set_bitmode(dev, 0x00)
sleep(0.5)
# Set CBUS2/3 high...
ftdi_set_bitmode(dev, 0xCC)
sleep(0.5)
# Set CBUS2/3 low...
ftdi_set_bitmode(dev, 0xC0)
sleep(0.5)
ftdi_set_bitmode(dev, 0xC4)
sleep(0.5)
# Set CBUS2/3 back to tristate
ftdi_set_bitmode(dev, 0xCC)
sleep(0.5)
def set_running_mode(self):
'''
configure ZiGate DIN in running mode
'''
if self.model != 'DIN':
LOGGER.warning('Method only supported on ZiGate DIN')
return
dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
if not dev:
LOGGER.error('ZiGate DIN not found.')
return
ftdi_set_bitmode(dev, 0xC8)
sleep(0.5)
ftdi_set_bitmode(dev, 0xCC)
sleep(0.5)
def flash_firmware(self, path, erase_eeprom=False):
'''
flash specified firmware
'''
if self.model != 'DIN':
LOGGER.warning('Method only supported on ZiGate DIN')
return
from .flasher import flash
self.set_bootloader_mode()
flash(self._port, write=path, erase=erase_eeprom)
self.set_running_mode()
@property
def ieee(self):
return self._ieee
@property
def addr(self):
return self._addr
def start_adminpanel(self, port=None, mount=None, prefix=None, debug=False):
'''
Start Admin panel in other thread
'''
from .adminpanel import start_adminpanel, ADMINPANEL_PORT
port = port or ADMINPANEL_PORT
self.adminpanel = start_adminpanel(self, port=port, mount=mount, prefix=prefix, quiet=not debug, debug=debug)
return self.adminpanel
def _event_loop(self):
while not self._closing:
if self.connection and not self.connection.received.empty():
packet = self.connection.received.get()
dispatch_signal(ZIGATE_PACKET_RECEIVED, self, packet=packet)
t = threading.Thread(target=self.decode_data, args=(packet,),
name='ZiGate-Decode data')
t.setDaemon(True)
t.start()
else:
sleep(SLEEP_INTERVAL)
def setup_connection(self):
self.connection = ThreadSerialConnection(self, self._port)
def close(self):
self._closing = True
if self._autosavetimer:
self._autosavetimer.cancel()
try:
if self.connection:
self.connection.close()
except Exception:
LOGGER.error('Exception during closing')
LOGGER.error(traceback.format_exc())
self.connection = None
self._started = False
def save_state(self, path=None):
LOGGER.debug('Saving persistent file')
path = path or self._path
if path is None:
LOGGER.warning('Persistent file is disabled')
if self._autosavetimer:
self._autosavetimer.cancel()
return
self._path = os.path.expanduser(path)
LOGGER.debug('Acquire Lock to save persistent file')
r = self._save_lock.acquire(True, 5)
if not r:
LOGGER.error('Failed to acquire Lock to save persistent file')
return
try:
data = {'devices': list(self._devices.values()),
'groups': self._groups,
'scenes': self._scenes,
'neighbours_table': self._neighbours_table_cache,
'led': self._led
}
with open(self._path, 'w') as fp:
json.dump(data, fp, cls=DeviceEncoder,
sort_keys=True, indent=4, separators=(',', ': '))
except Exception:
LOGGER.error('Failed to save persistent file %s', self._path)
LOGGER.error(traceback.format_exc())
LOGGER.debug('Release Lock of persistent file')
self._save_lock.release()
def load_state(self, path=None):
LOGGER.debug('Try loading persistent file')
path = path or self._path
if path is None:
LOGGER.warning('Persistent file is disabled')
return
self._path = os.path.expanduser(path)
LOGGER.debug('Trying to load %s', self._path)
if not os.path.exists(self._path):
LOGGER.warning('Persistent file %s doesn\'t exist', self._path)
return False
try:
with open(self._path) as fp:
data = json.load(fp)
if not isinstance(data, dict): # old version
data = {'devices': data, 'groups': {}}
groups = data.get('groups', {})
for k, v in groups.items():
groups[k] = set([tuple(r) for r in v])
self._groups = groups
self._scenes = data.get('scenes', {})
self._led = data.get('led', True)
self._neighbours_table_cache = data.get('neighbours_table', [])
LOGGER.debug('Load neighbours cache: %s', self._neighbours_table_cache)
devices = data.get('devices', [])
for data in devices:
try:
device = Device.from_json(data, self)
self._devices[device.addr] = device
device._create_actions()
except Exception:
LOGGER.error('Error loading device %s', data)
LOGGER.debug('Load success')
return True
except Exception:
LOGGER.error('Failed to load persistent file %s', self._path)
LOGGER.error(traceback.format_exc())
LOGGER.debug('No file to load')
return False
def start_auto_save(self):
LOGGER.debug('Auto saving %s', self._path)
self.save_state()
self._autosavetimer = threading.Timer(AUTO_SAVE, self.start_auto_save)
self._autosavetimer.setDaemon(True)
self._autosavetimer.start()
# check if we're still connected to zigate
if self.send_data(0x0010) is None:
self.connection.reconnect()
def __del__(self):
self.close()
def _start_event_thread(self):
self._event_thread = threading.Thread(target=self._event_loop,
name='ZiGate-Event Loop')
self._event_thread.setDaemon(True)
self._event_thread.start()
def autoStart(self, channel=None):
self.startup(channel)
def startup(self, channel=None):
'''
Startup sequence:
- Load persistent file
- setup connection
- Set Channel mask
- Set Type Coordinator
- Start Network
- Refresh devices list
'''
if self._started:
return
self._closing = False
self._start_event_thread()
self.load_state()
self.setup_connection()
self.set_led(self._led)
version = self.get_version()
self.set_channel(channel)
self.set_type(TYPE_COORDINATOR)
LOGGER.debug('Check network state')
# self.start_network()
network_state = self.get_network_state()
if not network_state:
LOGGER.error('Failed to get network state')
if not network_state or network_state.get('extended_panid') == 0 or \
network_state.get('addr') == 'ffff':
LOGGER.debug('Network is down, start it')
self.start_network(True)
tries = 3
while tries > 0:
sleep(1)
tries -= 1
network_state = self.get_network_state()
if network_state and \
network_state.get('extended_panid') != 0 and \
network_state.get('addr') != 'ffff':
break
if tries <= 0:
LOGGER.error('Failed to start network')
self.reset()
return
if version and version['version'] >= '3.1a':
LOGGER.debug('Set Zigate normal mode (firmware >= 3.1a)')
self.set_raw_mode(False)
if version and version['version'] >= '3.0f':
LOGGER.debug('Set Zigate Time (firmware >= 3.0f)')
self.set_time()
self.get_devices_list(True)
t = threading.Thread(target=self.need_discovery)
t.setDaemon(True)
t.start()
# self.need_discovery()
def need_discovery(self):
'''
scan device which need discovery
auto discovery if possible
else dispatch signal
'''
for device in self.devices:
if device.need_discovery():
if device.receiver_on_when_idle():
LOGGER.debug('Auto discover device %s', device)
device.discover_device()
else:
dispatch_signal(ZIGATE_DEVICE_NEED_DISCOVERY,
self, **{'zigate': self,
'device': device})
def zigate_encode(self, data):
encoded = bytearray()
for b in data:
if b < 0x10:
encoded.extend([0x02, 0x10 ^ b])
else:
encoded.append(b)
return encoded
def zigate_decode(self, data):
flip = False
decoded = bytearray()
for b in data:
if flip:
flip = False
decoded.append(b ^ 0x10)
elif b == 0x02:
flip = True
else:
decoded.append(b)
return decoded
def checksum(self, *args):
chcksum = 0
for arg in args:
if isinstance(arg, int):
chcksum ^= arg
continue
for x in arg:
chcksum ^= x
return chcksum
def send_to_transport(self, data):
if not self.connection or not self.connection.is_connected():
LOGGER.error('Not connected to zigate')
return
self.connection.send(data)
def send_data(self, cmd, data="", wait_response=None, wait_status=True):
'''
send data through ZiGate
'''
LOGGER.debug('REQUEST : 0x{:04x} {}'.format(cmd, data))
self._last_status[cmd] = None
if wait_response:
self._clear_response(wait_response)
if isinstance(cmd, int):
byte_cmd = struct.pack('!H', cmd)
elif isinstance(data, str):
byte_cmd = bytes.fromhex(cmd)
else:
byte_cmd = cmd
if isinstance(data, str):
byte_data = bytes.fromhex(data)
else:
byte_data = data
assert type(byte_cmd) == bytes
assert type(byte_data) == bytes
length = len(byte_data)
byte_length = struct.pack('!H', length)
checksum = self.checksum(byte_cmd, byte_length, byte_data)
msg = struct.pack('!HHB%ds' % length, cmd, length, checksum, byte_data)
LOGGER.debug('Msg to send %s', hexlify(msg))
enc_msg = self.zigate_encode(msg)
enc_msg.insert(0, 0x01)
enc_msg.append(0x03)
encoded_output = bytes(enc_msg)
LOGGER.debug('Encoded Msg to send %s', hexlify(encoded_output))
self.send_to_transport(encoded_output)
if wait_status:
status = self._wait_status(cmd)
if wait_response and status is not None:
r = self._wait_response(wait_response)
return r
return status
return False
def decode_data(self, packet):
'''
Decode raw packet message
'''
try:
decoded = self.zigate_decode(packet[1:-1])
msg_type, length, checksum, value, lqi = \
struct.unpack('!HHB%dsB' % (len(decoded) - 6), decoded)
except Exception:
LOGGER.error('Failed to decode packet : %s', hexlify(packet))
return
if length != len(value) + 1: # add lqi length
LOGGER.error('Bad length %s != %s : %s', length, len(value) + 1, value)
return
computed_checksum = self.checksum(decoded[:4], lqi, value)
if checksum != computed_checksum:
LOGGER.error('Bad checksum %s != %s', checksum, computed_checksum)
return
LOGGER.debug('Received response 0x{:04x}: {}'.format(msg_type, hexlify(value)))
try:
response = RESPONSES.get(msg_type, Response)(value, lqi)
except Exception:
LOGGER.error('Error decoding response 0x{:04x}: {}'.format(msg_type, hexlify(value)))
LOGGER.error(traceback.format_exc())
return
if msg_type != response.msg:
LOGGER.warning('Unknown response 0x{:04x}'.format(msg_type))
LOGGER.debug(response)
self._last_response[msg_type] = response
self.interpret_response(response)
dispatch_signal(ZIGATE_RESPONSE_RECEIVED, self, response=response)
def interpret_response(self, response):
if response.msg == 0x8000: # status
if response['status'] != 0:
LOGGER.error('Command 0x{:04x} failed {} : {}'.format(response['packet_type'],
response.status_text(),
response['error']))
self._last_status[response['packet_type']] = response
elif response.msg == 0x8011: # APS_DATA_ACK
if response['status'] != 0:
LOGGER.error('Device {} doesn\'t receive last command to '
'endpoint {} cluster {}: 0x{:02x}'.format(response['addr'],
response['endpoint'],
response['cluster'],
response['status']))
elif response.msg == 0x8007: # factory reset
if response['status'] == 0:
self._devices = {}
self.start_network()
elif response.msg == 0x8015: # device list
keys = set(self._devices.keys())
known_addr = set([d['addr'] for d in response['devices']])
LOGGER.debug('Known devices in zigate : %s', known_addr)
missing = keys.difference(known_addr)
LOGGER.debug('Previous devices missing : %s', missing)
for addr in missing:
self._tag_missing(addr)
# self._remove_device(addr)
for d in response['devices']:
if d['ieee'] == '0000000000000000':
continue
device = Device(dict(d), self)
self._set_device(device)
elif response.msg == 0x8042: # node descriptor
addr = response['addr']
d = self.get_device_from_addr(addr)
if d:
d.update_info(response.cleaned_data())
self.discover_device(addr)
elif response.msg == 0x8043: # simple descriptor
addr = response['addr']
endpoint = response['endpoint']
d = self.get_device_from_addr(addr)
if d:
ep = d.get_endpoint(endpoint)
ep.update(response.cleaned_data())
ep['in_clusters'] = response['in_clusters']
ep['out_clusters'] = response['out_clusters']
self.discover_device(addr)
d._create_actions()
elif response.msg == 0x8045: # endpoint list
addr = response['addr']
d = self.get_device_from_addr(addr)
if d:
for endpoint in response['endpoints']:
ep = d.get_endpoint(endpoint['endpoint'])
self.simple_descriptor_request(addr, endpoint['endpoint'])
self.discover_device(addr)
elif response.msg == 0x8048: # leave
device = self.get_device_from_ieee(response['ieee'])
if device:
if response['rejoin_status'] == 1:
device.missing = True
else:
self._remove_device(device.addr)
elif response.msg == 0x8062: # Get group membership response
data = response.cleaned_data()
self._sync_group_membership(data['addr'], data['endpoint'], data['groups'])
elif response.msg in (0x8100, 0x8102, 0x8110, 0x8401,
0x8085, 0x8095, 0x80A7): # attribute report or IAS Zone status change
if response.get('status', 0) != 0:
LOGGER.debug('Received Bad status')
# handle special case, no model identifier
if response['status'] == 0x86 and response['cluster'] == 0 and response['attribute'] == 5:
response['data'] = 'unsupported'
else:
return
# ignore if related to zigate
if response['addr'] == self.addr:
return
device = self._get_device(response['addr'])
device.lqi = response['lqi']
device.set_attribute(response['endpoint'],
response['cluster'],
response.cleaned_data())
elif response.msg == 0x004D: # device announce
LOGGER.debug('Device Announce %s', response)
device = Device(response.data, self)
self._set_device(device)
elif response.msg == 0x8140: # attribute discovery
if 'addr' in response:
# ignore if related to zigate
if response['addr'] == self.addr:
return
device = self._get_device(response['addr'])
device.set_attribute(response['endpoint'],
response['cluster'],
response.cleaned_data())
elif response.msg == 0x8501: # OTA image block request
LOGGER.debug('Client is requesting ota image data')
self._ota_send_image_data(response)
elif response.msg == 0x8503: # OTA Upgrade end request
LOGGER.debug('Client ended ota process')
self._ota_handle_upgrade_end_request(response)
elif response.msg == 0x8702: # APS Data confirm Fail
LOGGER.warning(response)
# else:
# LOGGER.debug('Do nothing special for response {}'.format(response))
def _get_device(self, addr):
'''
get device from addr
create it if necessary
'''
d = self.get_device_from_addr(addr)
if not d:
LOGGER.warning('Device not found, create it (this isn\'t normal)')
d = Device({'addr': addr}, self)
self._set_device(d)
self.get_devices_list() # since device is missing, request info
return d
def _tag_missing(self, addr):
'''
tag a device as missing
'''
last_24h = datetime.datetime.now() - datetime.timedelta(hours=24)
last_24h = last_24h.strftime('%Y-%m-%d %H:%M:%S')
if addr in self._devices:
if self._devices[addr].last_seen and self._devices[addr].last_seen < last_24h:
self._devices[addr].missing = True
LOGGER.warning('The device %s is missing', addr)
dispatch_signal(ZIGATE_DEVICE_UPDATED,
self, **{'zigate': self,
'device': self._devices[addr]})
def get_missing(self):
'''
return missing devices
'''
return [device for device in self._devices.values() if device.missing]
def cleanup_devices(self):
'''
remove devices tagged missing
'''
to_remove = [device.addr for device in self.get_missing()]
for addr in to_remove:
self._remove_device(addr)
def _remove_device(self, addr):
'''
remove device from addr
'''
device = self._devices.pop(addr)
dispatch_signal(ZIGATE_DEVICE_REMOVED, **{'zigate': self,
'addr': addr,
'device': device})
def _set_device(self, device):
'''
add/update device to cache list
'''
assert type(device) == Device
if device.addr in self._devices:
self._devices[device.addr].update(device)
dispatch_signal(ZIGATE_DEVICE_UPDATED, self, **{'zigate': self,
'device': self._devices[device.addr]})
else:
# check if device already exist with other address
d = self.get_device_from_ieee(device.ieee)
if d:
LOGGER.warning('Device already exists with another addr %s, rename it.', d.addr)
old_addr = d.addr
new_addr = device.addr
d.discovery = ''
d.update(device)
self._devices[new_addr] = d
del self._devices[old_addr]
dispatch_signal(ZIGATE_DEVICE_ADDRESS_CHANGED, self,
**{'zigate': self,
'device': d,
'old_addr': old_addr,
'new_addr': new_addr,
})
else:
self._devices[device.addr] = device
dispatch_signal(ZIGATE_DEVICE_ADDED, self, **{'zigate': self,
'device': device})
self.discover_device(device.addr)
def get_status_text(self, status_code):
return STATUS_CODES.get(status_code,
'Failed with event code: %s', status_code)
def _clear_response(self, msg_type):
if msg_type in self._last_response:
del self._last_response[msg_type]
def _wait_response(self, msg_type):
'''
wait for next msg_type response
'''
LOGGER.debug('Waiting for message 0x{:04x}'.format(msg_type))
t1 = monotonic()
while self._last_response.get(msg_type) is None:
sleep(0.01)
t2 = monotonic()
if t2 - t1 > WAIT_TIMEOUT: # no response timeout
LOGGER.warning('No response waiting command 0x{:04x}'.format(msg_type))
return
LOGGER.debug('Stop waiting, got message 0x{:04x}'.format(msg_type))
return self._last_response.get(msg_type)
def _wait_status(self, cmd):
'''
wait for status of cmd
'''
LOGGER.debug('Waiting for status message for command 0x{:04x}'.format(cmd))
t1 = monotonic()
while self._last_status.get(cmd) is None:
sleep(0.01)
t2 = monotonic()
if t2 - t1 > WAIT_TIMEOUT: # no response timeout
self._no_response_count += 1
LOGGER.warning('No response after command 0x{:04x} ({})'.format(cmd, self._no_response_count))
return
self._no_response_count = 0
LOGGER.debug('STATUS code to command 0x{:04x}:{}'.format(cmd, self._last_status.get(cmd)))
return self._last_status.get(cmd)
def __addr(self, addr):
''' convert hex string addr to int '''
if isinstance(addr, str):
addr = int(addr, 16)
return addr
def __haddr(self, int_addr, length=4):
''' convert int addr to hex '''
return '{0:0{1}x}'.format(int_addr, length)
@property
def devices(self):
return list(self._devices.values())
def get_device_from_addr(self, addr):
return self._devices.get(addr)
def get_device_from_ieee(self, ieee):
if ieee:
for d in self._devices.values():
if d.ieee == ieee:
return d
def get_devices_list(self, wait=False):
'''
refresh device list from zigate
'''
wait_response = None
if wait:
wait_response = 0x8015
self.send_data(0x0015, wait_response=wait_response)
def set_raw_mode(self, enable=True):
'''
Set Blue Led state ON/OFF
'''
data = struct.pack('!B', enable)
return self.send_data(0x0002, data)
def get_version(self, refresh=False):
'''
get zigate firmware version
'''
if not self._version or refresh:
r = self.send_data(0x0010, wait_response=0x8010)
if r:
self._version = r.data
else:
LOGGER.warning('Failed to retrieve zigate firmware version')
return self._version
def get_version_text(self, refresh=False):
'''
get zigate firmware version as text
'''
v = self.get_version(refresh)
if v:
return v['version']
def reset(self):
'''
reset zigate
'''
return self.send_data(0x0011, wait_status=False)
def erase_persistent(self):
'''
erase persistent data in zigate
'''
return self.send_data(0x0012, wait_status=False)
def factory_reset(self):
'''
ZLO/ZLL "Factory New" Reset
'''
return self.send_data(0x0013, wait_status=False)
def is_permitting_join(self):
'''
check if zigate is permitting join
'''
r = self.send_data(0x0014, wait_response=0x8014)
if r:
r = r.get('status', False)
return r
def set_time(self, dt=None):
'''
Set internal zigate time
dt should be datetime.datetime object
'''
dt = dt or datetime.datetime.now()
# timestamp from 2000-01-01 00:00:00
timestamp = int((dt - datetime.datetime(2000, 1, 1)).total_seconds())
data = struct.pack('!L', timestamp)
self.send_data(0x0016, data)
def get_time(self):
'''
get internal zigate time
'''
r = self.send_data(0x0017, wait_response=0x8017)
dt = None
if r:
timestamp = r.get('timestamp')
dt = datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds=timestamp)
return dt
def set_led(self, on=True):
'''
Set Blue Led state ON/OFF
'''
self._led = on
data = struct.pack('!?', on)
return self.send_data(0x0018, data)
def set_certification(self, standard='CE'):
'''
Set Certification CE=1, FCC=2
'''
cert = {'CE': 1, 'FCC': 2}
data = struct.pack('!B', cert[standard])
return self.send_data(0x0019, data)
def permit_join(self, duration=60):
'''
start permit join
duration in secs, 0 means stop permit join
'''
return self.send_data(0x0049, 'FFFC{:02X}00'.format(duration))
def stop_permit_join(self):
'''
convenient function to stop permit_join
'''
return self.permit_join(0)
def set_extended_panid(self, panid):
'''
Set Extended PANID
'''
data = struct.pack('!Q', panid)
return self.send_data(0x0020, data)
def set_channel(self, channels=None):
'''
set channel
'''
channels = channels or [11, 14, 15, 19, 20, 24, 25, 26]
if not isinstance(channels, list):
channels = [channels]
mask = functools.reduce(lambda acc, x: acc ^ 2 ** x, channels, 0)
mask = struct.pack('!I', mask)
return self.send_data(0x0021, mask)
def set_type(self, typ=TYPE_COORDINATOR):
'''
set zigate mode type
'''
data = struct.pack('!B', typ)
self.send_data(0x0023, data)
def get_network_state(self):
''' get network state '''
r = self.send_data(0x0009, wait_response=0x8009)
if r:
data = r.cleaned_data()
self._addr = data['addr']
self._ieee = data['ieee']
self.panid = data['panid']
self.extended_panid = data['extended_panid']