forked from digidotcom/cp4pc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zigbee.py
2139 lines (1895 loc) · 90.5 KB
/
zigbee.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
#
# Copyright (c) 2009-2012 Digi International Inc.
# All rights not expressly granted are reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
#
# WARNING:
#
# This library is not officially supported and is provided for testing
# purposes. Use at your own risk.
# Requirements:
# Must have pySerial and associated libraries (win32 module for Windows)
# Serial connection to XBee must be configured in simulator_settings ('com_port' and 'baud').
# XBee must be API mode firmware. ZB, ZNet2.5 or Smart Energy.
# Limitations:
# Must import zigbee before doing either "from socket import *" or "from select import *"
# Must import zigbee to use zigbee socket.
# Must import zigbee to use zigbee select.
# Zigbee socket options not support (except non_blocking)
# Incomplete error checking.
# Anything else not implemented from the TODO list below.
# TODO List:
# Add socket options (mostly counters needed).
# Check message size before sending (could split into multiple messages).
# Add more error checking and match ConnectPort errors
# Support for blocking calls for sendto
# Add new parameters to getnodelist, ddo_get_param, ddo_set_param
import struct
import string
import time
import socket
import select
import logging
from threading import RLock
# set up logger
logger = logging.getLogger("cp4pc.xbee")
logger.setLevel(logging.INFO)
MESH_TRACEBACK = False
"Set this to true to enable printing of all ZigBee traffic"
# set parameters
__all__ = ["ddo_get_param", "ddo_set_param", "getnodelist", "get_node_list", "register_joining_device"]
# Globals
"Set this to function that accepts string to get passed MESH_TRACEBACK data"
debug_callback = None
com_port_opened = False #set to True when the COM port has been successfully opened (see bottom of this file)
# PySerial calls will need to be protected from multiple threads:
_global_lock = RLock()
# A lock used to manage the com-port management threads:
_com_mgmt_lock = RLock()
def __register_with_socket_module(object_name):
"Register object with socket module (add to __all__)"
try:
if socket.__all__ is not None:
if object_name not in socket.__all__:
socket.__all__.append(object_name)
except:
# there is no __all__ defined for socket object
pass
def MAC_to_address_string(MAC_address, num_bytes = 8):
"""Convert a MAC address to a string with "[" and "]" """
address_string = "["
for index in range(num_bytes - 1, -1, -1):
address_string += string.hexdigits[0xF & (MAC_address >> (index * 8 + 4))]
address_string += string.hexdigits[0xF & (MAC_address >> (index * 8))]
if index:
address_string += ":"
else:
address_string += "]!"
return address_string
def address_string_to_MAC(address_string):
"Convert an address string to a MAC address"
if address_string[0] == "[":
return int("0x" + str.replace(address_string[1:-2], ":", ""), 16)
else:
return int("0x" + str.replace(address_string[0:-1], ":", ""), 16)
def short_to_address_string(short_address):
"Convert a short (network) address to a string"
return "[%02X%02X]!" % ((short_address >> 8) & 0xFF, short_address & 0xFF)
def address_string_to_short(address_string):
"Convert an address string to a short (network) address"
return int("0x" + address_string[1:-2], 16)
class API_Data:
"""Base class for storing data in an API message
Also stores a static frame ID for different messages to use."""
xbee_frame_id = 1
"Frame ID for transmitting to the XBee node"
rx_id = 0
"Receive API message type ID"
tx_id = 0
"Transmit API message type ID"
def __init__(self):
"Creates API_Data object"
self.data = b""
self.frame_id = 0
@staticmethod
def next_frame():
"Returns the next frame ID for sending a message"
API_Data.xbee_frame_id += 1
if API_Data.xbee_frame_id >= 256:
API_Data.xbee_frame_id = 1
return API_Data.xbee_frame_id
def extract(self, cmd_data):
"Base class just grabs the whole buffer"
self.data = cmd_data
def export(self):
"Returns the whole buffer as a string"
return self.data
class IEEE_802_15_4_64_Data(API_Data):
"Extracts an 802.15.4 frame from the XBee Rx message and outputs a XBee transmit frame."
BROADCAST_RADIUS = 0
"Number of hops on the XBee network."
rx_id = 0x80
"Receive API message type ID"
tx_id = 0x00
"Transmit API message type ID"
def __init__(self, source_address=None, destination_address=None, payload=b""):
"Initializes the zb_data with no data."
API_Data.__init__(self)
self.source_address = source_address
self.destination_address = destination_address
self.payload = payload
self.rssi = 0
def extract(self, cmd_data):
"Extract a XBee message from a 0x80 XBee frame cmd_data"
if len(cmd_data) < 10:
#Message too small, return error
logger.warn("Malformed message - too small")
return -1
source_address_64, self.rssi, options = struct.unpack(">QBB", cmd_data[:10])
self.payload = cmd_data[10:]
# use the device's EUI address
address_string = MAC_to_address_string(source_address_64)
# convert source address to proper string format, create address tuple
# NOTE: 6th parameter is only used for TX Status - always set to zero.
self.source_address = (address_string, 0, 0, 0, options, 0)
self.destination_address = ("", 0, 0, 0)
return 0
def export(self):
"Export a XBee message as a 0x00 XBee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,)) #frame id
cmd_data += struct.pack(">Q", address_string_to_MAC(self.destination_address[0])) # destination_address_64
if len(self.destination_address) > 4:
cmd_data += bytearray((self.destination_address[4],))
else:
cmd_data += bytearray((0,)) # default to no options
cmd_data += self.payload
return cmd_data
class IEEE_802_15_4_16_Data(API_Data):
"Extracts an 802.15.4 frame from the XBee Rx message and outputs a XBee transmit frame."
BROADCAST_RADIUS = 0
"Number of hops on the XBee network."
rx_id = 0x81
"Receive API message type ID"
tx_id = 0x01
"Transmit API message type ID"
def __init__(self, source_address=None, destination_address=None, payload=b""):
"Initializes the zb_data with no data."
API_Data.__init__(self)
self.source_address = source_address
self.destination_address = destination_address
self.payload = payload
self.rssi = 0
def extract(self, cmd_data):
"Extract a XBee message from a 0x81 XBee frame cmd_data"
if len(cmd_data) < 4:
#Message too small, return error
logger.warning("Malformed message - too small")
return -1
source_address_16, self.rssi, options = struct.unpack(">HBB", cmd_data[:4])
self.payload = cmd_data[4:]
# use the device's short address
address_string = short_to_address_string(source_address_16)
# convert source address to proper string format, create address tuple
# NOTE: 6th parameter is only used for TX Status - always set to zero.
self.source_address = (address_string, 0, 0, 0, options, 0)
self.destination_address = ("", 0, 0, 0)
return 0
def export(self):
"Export a XBee message as a 0x01 XBee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,)) #frame id
cmd_data += struct.pack(">H", address_string_to_short(self.destination_address[0])) # destination_address_16
if len(self.destination_address) > 4:
cmd_data += bytearray((self.destination_address[4],))
else:
cmd_data += bytearray((0,)) # default to no options
cmd_data += self.payload
return cmd_data
class ZB_Data(API_Data):
"Extracts a ZigBee frame from the XBee Rx message and outputs a XBee transmit frame."
BROADCAST_RADIUS = 0
"Number of hops on the XBee network."
rx_id = 0x91
"Receive API message type ID"
tx_id = 0x11
"Transmit API message type ID"
def __init__(self, source_address=None, destination_address=None, payload=b""):
"Initializes the zb_data with no data."
API_Data.__init__(self)
self.source_address = source_address
self.destination_address = destination_address
self.payload = payload
def extract(self, cmd_data):
"Extract a XBee message from a 0x91 XBee frame cmd_data"
if len(cmd_data) < 17:
# Message too small, return error
logger.warning("Malformed message - too small")
return -1
source_address_64, source_address_16, source_endpoint, destination_endpoint, \
cluster_id, profile_id, options = struct.unpack(">QHBBHHB", cmd_data[:17])
self.payload = cmd_data[17:]
if source_address_64 == 0xFFFFFFFFFFFFFFFF:
# only short address information available
address_string = short_to_address_string(source_address_16)
#print "Using short address: ", address_string
else:
# use the device's EUI address
address_string = MAC_to_address_string(source_address_64)
# convert source address to proper string format, create address tuple
# NOTE: 6th parameter is only used for TX Status - always set to zero.
self.source_address = (address_string, source_endpoint, profile_id, cluster_id, options, 0)
self.destination_address = ("", destination_endpoint, profile_id, cluster_id)
return 0
def export(self):
"Export a XBee message as a 0x11 XBee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,)) #frame id
if len(self.destination_address[0]) == 7: # [XXXX]! short address
cmd_data += struct.pack(">Q", 0xFFFFFFFFFFFFFFFF)
cmd_data += struct.pack(">H", address_string_to_short(self.destination_address[0]))
else: # long address
cmd_data += struct.pack(">Q", address_string_to_MAC(self.destination_address[0])) # destination_address_64
# TTDO: should set to last know short address to improve performance
cmd_data += bytearray((0xFF, 0xFE)) # destination_address_16
cmd_data += struct.pack(">BBHHB", self.source_address[1], # source_endpoint
self.destination_address[1], # destination_endpoint
self.destination_address[3], # cluster_id
self.destination_address[2], # profile_id
self.BROADCAST_RADIUS) # broadcast radius
if len(self.destination_address) > 4:
cmd_data += bytearray((self.destination_address[4],))
else:
cmd_data += bytearray((0,)) # default to no options
cmd_data += self.payload
return cmd_data
class Local_AT_Data(API_Data):
"Extracts from an AT Response frame and exports to an AT Command frame."
rx_id = 0x88
"Receive API message type ID"
tx_id = 0x08
"Transmit API message type ID"
def __init__(self, AT_cmd=b"", value=b""):
API_Data.__init__(self)
"Initializes the AT frame with no data."
self.AT_cmd = AT_cmd
"Two character string of the character command"
self.status = 0
"Status of a received message"
self.value = value
"Value received or to be set for the AT command"
def extract(self, cmd_data):
"Extract an AT response message from a 0x88 xbee frame cmd_data"
if len(cmd_data) < 4:
# Message too small, return error
return -1
self.frame_id = cmd_data[0]
self.AT_cmd = cmd_data[1:3]
self.status = cmd_data[3]
self.value = cmd_data[4:] # NOTE: some messages have no value
return 0
def export(self):
"Export an AT message as a 0x08 xbee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,))
cmd_data += self.AT_cmd
cmd_data += self.value
return cmd_data
class Remote_AT_Data(API_Data):
"Extracts from a Remote AT Response frame and exports to a Remote AT Command frame."
rx_id = 0x97
"Receive API message type ID"
tx_id = 0x17
"Transmit API message type ID"
def __init__(self, remote_address=None, AT_cmd="", value=""):
API_Data.__init__(self)
"Initializes the AT frame with no data."
self.remote_address = remote_address
"Extended address of XBee that is having AT parameter set, stored as formatted string."
self.AT_cmd = AT_cmd
"Two character string of the character command"
self.status = 0
"Status of a received message"
self.value = value
"Value received or to be set for the AT command"
def extract(self, cmd_data):
"Extract a remote AT response message from a 0x97 xbee frame cmd_data"
if len(cmd_data) < 14: #TODO: make sure this is the right number.
#Message too small, return error
return -1
self.frame_id, source_address_64, source_address_16 = struct.unpack(">BQH", cmd_data[:11])
self.remote_address = MAC_to_address_string(source_address_64)
self.AT_cmd = cmd_data[11:13]
self.status = cmd_data[13]
self.value = cmd_data[14:] #NOTE: some messages have no value
return 0
def export(self):
"Export a remote AT message as a 0x17 xbee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,))
cmd_data += struct.pack(">Q", address_string_to_MAC(self.remote_address)) # destination_address_64
cmd_data += bytearray((0xFF, 0xFE)) # destination_address_16
cmd_data += bytearray((0x02,)) # Command Options (Always set immediately)
cmd_data += bytearray(self.AT_cmd, 'ascii')
cmd_data += bytearray(self.value, 'ascii')
return cmd_data
class Register_Device_Data(API_Data):
"Extracts from a Register Joining Device Status frame and exports to a Register Device frame."
rx_id = 0xA4
"Receive Register Joining Device Status message type ID"
tx_id = 0x24
"Register Device message type ID"
# status values
SUCCESS = 0x00
INVALID_ADDRESS = 0xB3
KEY_NOT_FOUND = 0xFF
def __init__(self, remote_address=None, link_key=""):
API_Data.__init__(self)
"Initializes the register device with no data."
self.remote_address = remote_address
"Extended address of device that is being added to the network, stored as formatted string."
self.link_key = link_key
"Big-endian binary string containing link key (up to 16 bytes)"
self.status = 0
"Status of device registration"
def extract(self, cmd_data):
"Extract a register device response message from a 0xA4 xbee frame cmd_data"
if len(cmd_data) < 2:
# Message too small, return error
return -1
self.frame_id = cmd_data[0]
self.status = cmd_data[1]
return 0
def export(self):
"Export a register device message as a 0x24 xbee frame cmd_data"
self.frame_id = self.next_frame()
cmd_data = bytearray((self.frame_id,))
cmd_data += struct.pack(">Q", address_string_to_MAC(self.remote_address)) # destination_address_64
cmd_data += bytearray((0xFF, 0xFE)) # destination_address_16, always set to 0xFFFE
cmd_data += bytearray((0x00,)) # Key Options (Always set to 0)
cmd_data += bytearray(self.link_key, 'ascii')
return cmd_data
class IEEE_802_15_4_Tx_Status_Data(API_Data):
"Extracts from an 802.15.4 Tx Status frame."
rx_id = 0x89
"Receive ZigBee Tx Status message type ID"
# Delivery Status
SUCCESS = 0x00
NO_ACK_RECEIVED = 0x01
CCA_FAILURE = 0x02
PURGED = 0x03
def __init__(self, delivery_status=SUCCESS):
API_Data.__init__(self)
"Initializes the register device with no data."
self.delivery_status = delivery_status
"If the message was delivered or if there was an error"
def extract(self, cmd_data):
"Extract a ZigBee Tx Status message from a 0x8B xbee frame cmd_data"
if len(cmd_data) < 2:
# Message too small, return error
return -1
# extract data
self.frame_id, self.delivery_status = struct.unpack(">BB", cmd_data[:2])
return 2
def export(self):
"Will export a TX Status Message. May be used for local message routing."
cmd_data = bytearray((self.frame_id,))
cmd_data += bytearray((self.delivery_status,))
return cmd_data
class ZigBee_Tx_Status_Data(API_Data):
"Extracts from a ZigBee Tx Status frame."
rx_id = 0x8B
"Receive ZigBee Tx Status message type ID"
# Delivery Status
SUCCESS = 0x00
CCA_FAILURE = 0x02
NETWORK_ACK_FAILURE = 0x21
NOT_JOINED_TO_NETWORK = 0x22
SELF_ADDRESSED = 0x23
ADDRESS_NOT_FOUND = 0x24
NO_ROUTE_FOUND = 0x25
INVALID_BINDING_TABLE_INDEX = 0x2B
INVALID_ENDPOINT = 0x2C
DATA_PAYLOAD_TOO_BIG = 0x74
KEY_NOT_AUTHORIZED = 0xBB
# Discovery Status
NO_DISCOVERY_OVERHEAD = 0x00
ADDRESS_DISCOVERY = 0x01
ROUTE_DISCOVERY = 0x02
ADDRESS_AND_ROUTE_DISCOVERY = 0x03
def __init__(self, remote_network_address="[FFFE]!", transmit_retry_count=0, delivery_status=SUCCESS, discovery_status=NO_DISCOVERY_OVERHEAD):
API_Data.__init__(self)
"Initializes the register device with no data."
self.remote_network_address = remote_network_address
"Short address of device that is ACKing the message we sent."
self.transmit_retry_count = transmit_retry_count
"How many transmission attempts the Xbee made"
self.delivery_status = delivery_status
"If the message was delivered or if there was an error"
self.discovery_status = discovery_status
"If there was any address or route discovery overhead"
def extract(self, cmd_data):
"Extract a ZigBee Tx Status message from a 0x8B xbee frame cmd_data"
if len(cmd_data) < 6:
# Message too small, return error
return -1
# extract data
self.frame_id, short_address, self.transmit_retry_count, self.delivery_status, self.discovery_status = struct.unpack(">BHBBB", cmd_data)
# convert short network address to string
self.remote_network_address = short_to_address_string(short_address)
return 6
def export(self):
"Will export a TX Status Message. May be used for local message routing."
cmd_data = bytearray((self.frame_id,))
cmd_data += struct.pack(">H", address_string_to_short(self.remote_network_address)) # remote_address_16
cmd_data += bytearray((self.transmit_retry_count,))
cmd_data += bytearray((self.delivery_status,))
cmd_data += bytearray((self.discovery_status,))
return cmd_data
class IEEE_802_15_4_64_IO(API_Data):
"Extracts from an 802.15.4 Receive 64-bit Address IO."
rx_id = 0x82
def __init__(self, source_address=None, destination_address=None, rssi=None, payload=b""):
"Initializes the IO data with no data."
API_Data.__init__(self)
self.source_address = source_address
self.rssi = rssi
self.payload = payload
def extract(self, cmd_data):
"Extract a XBee message from a 0x82 XBee frame cmd_data"
if len(cmd_data) < 10:
# Message too small, return error
logger.warn("Malformed message - too small")
return -1
source_address_64, self.rssi, options = struct.unpack(">QBB", cmd_data[:10])
self.payload = cmd_data[10:]
# use the device's EUI address
address_string = MAC_to_address_string(source_address_64)
# convert source address to proper string format, create address tuple
# NOTE: 6th parameter is only used for TX Status - always set to zero.
self.source_address = (address_string, 0xe8, 0x0, 0x92, options, 0) # NOTE: 0xe8 is quirk of socket
return 0
class IEEE_802_15_4_16_IO(API_Data):
"Extracts from an 802.15.4 Receive 16-bit Address IO."
rx_id = 0x83
def __init__(self, source_address=None, destination_address=None, rssi=None, payload=b""):
"Initializes the IO data with no data."
API_Data.__init__(self)
self.source_address = source_address
self.rssi = rssi
self.payload = payload
def extract(self, cmd_data):
"Extract a XBee message from a 0x83 XBee frame cmd_data"
if len(cmd_data) < 4:
# Message too small, return error
logger.warn("Malformed message - too small")
return -1
source_address_16, self.rssi, options = struct.unpack(">HBB", cmd_data[:4])
self.payload = cmd_data[4:]
# use the device's EUI address
address_string = short_to_address_string(source_address_16)
# convert source address to proper string format, create address tuple
# NOTE: 6th parameter is only used for TX Status - always set to zero.
self.source_address = (address_string, 0xe8, 0x0, 0x93, options, 0) #NOTE: 0xe8 is quirk of socket
return 0
class API_Message:
"Creates API message for the XBee"
API_IDs = {ZB_Data.rx_id: ZB_Data,
Local_AT_Data.rx_id: Local_AT_Data,
Remote_AT_Data.rx_id: Remote_AT_Data,\
Register_Device_Data.rx_id: Register_Device_Data,
ZigBee_Tx_Status_Data.rx_id: ZigBee_Tx_Status_Data,
IEEE_802_15_4_Tx_Status_Data.rx_id: IEEE_802_15_4_Tx_Status_Data,
IEEE_802_15_4_64_Data.rx_id: IEEE_802_15_4_64_Data,
IEEE_802_15_4_16_Data.rx_id: IEEE_802_15_4_16_Data,
IEEE_802_15_4_64_IO.rx_id: IEEE_802_15_4_64_IO,
IEEE_802_15_4_16_IO.rx_id: IEEE_802_15_4_16_IO}
"Stores the different APIs"
def __init__(self):
self.length = 0
"Length field of the frame"
self.API_ID = 0
"Frame message ID."
self.cmd_data = ""
"Data payload for the frame"
self.api_data = API_Data()
"Formatted command data"
self.checksum = 0
"Checksum value for the message"
def __len__(self):
"Length of the entire message"
return self.length + 4
def calc_checksum(self):
"Calculates the checksum, based on cmd_data"
checksum = self.API_ID
for byte in self.cmd_data:
checksum += byte
checksum &= 0xFF
return 0xFF - checksum
def set_length(self):
"Calculates the length and sets it, based on cmd_data"
self.length = len(self.cmd_data) + 1
def set_API_ID(self):
"Sets the API_ID from the message data type"
if self.api_data.tx_id:
self.API_ID = self.api_data.tx_id
def is_valid(self):
"Verifies that the checksum is correct"
return self.checksum == self.calc_checksum()
def extract(self, buffer):
"""Extracts the message from a string
returns number of bytes used on success
-1 when the buffer is not big enough(string not long enough)"""
if len(buffer) < 5:
return -1
# pull out length (MSB)
length = buffer[1] * 255 + buffer[2]
if len(buffer) < length + 4:
return -1
# we have a full XBee message, lets extract it.
self.length = length
self.API_ID = buffer[3]
self.cmd_data = buffer[4:length+3]
if self.API_ID in self.API_IDs.keys():
self.api_data = self.API_IDs[self.API_ID]()
else:
self.api_data = API_Data()
self.api_data.extract(self.cmd_data)
self.checksum = buffer[length + 3]
return len(self)
def export(self, recalculate_checksum=1):
"""Exports the message to a string, will recalculate checksum by default.
Will also re-calculate the length field and lookup API_ID from message type."""
self.set_API_ID() # must be done before calculating checksum
self.cmd_data = self.api_data.export() # must be done before calculating checksum
self.checksum = self.calc_checksum() # calculate the new checksum and set it
self.set_length() # set the new length
return bytearray((0x7E, self.length // 255, self.length & 0xFF, self.API_ID)) + self.cmd_data + bytearray((self.checksum,))
class ZDO_Frame:
def __init__(self, buf=None, address=None):
"""Parse frame and store the address, create blank frame if no buffer."""
self.address = address
if buf is None:
self.transaction_sequence_number = 0
self.payload = b""
else:
self.transaction_sequence_number = buf[0]
self.payload = buf[1:]
def export(self):
"""Create frame as a string of bytes"""
return bytearray((self.transaction_sequence_number,)) + self.payload
class Conversation:
"""Base class for managing command/response pairs by matching frame IDs."""
default_timeout = 40
"""Default timeout period for waiting for response for conversation"""
def __init__(self, frame, callback=None, timeout_callback=None, timeout=None, extra_data=None):
self.start_time = time.time()
self.active = True # will switch to false once this conversation has finished
self.frame = frame
# The address attribute is primarily used in error reporting.
# Some conversations may not have a valid frame but will override self.address appropriately.
if frame is not None:
self.address = frame.address
else:
self.address = None
self.callback = callback
self.timeout_callback = timeout_callback
if timeout is None:
self.timeout = self.default_timeout
else:
self.timeout = timeout
self.extra_data = extra_data # there are times when it is useful to store additional information in a conversation
def match_frame(self, frame):
# a base conversation object should always fail matches
return False
def tick_sec(self):
if time.time() - self.start_time > self.timeout:
# we timed out on the response
self.active = False
if self.timeout_callback is not None:
self.timeout_callback(self)
else:
#TTDO: this is now an uncommon case; should we just print an error or still rely
#on a raise (and catch in tick_sec)?
#raise Exception("Conversation Timeout: Address = %s" % str(self.frame.address))
pass
class ZDO_Conversation(Conversation):
def match_frame(self, frame):
matched = False
if (self.frame.address[0] == frame.address[0] and
self.frame.transaction_sequence_number == frame.transaction_sequence_number):
matched = True
self.active = False #terminate one-shot conversation if a match occurs
return matched
class ZDO_Device_annce_cluster_server:
cluster_id = 0x0013
#command format:
#2 - NWK address
#8 - IEEE address
#1 - Device capability bitmap
#Note that device announce is broadcast to other devices and does not expect a response.
#The device announce is sent automatically when the device joins the network, so no
#send_command method is needed.
def __init__(self, callback = None):
self.callback = callback
"A callback to be called when a device announce message comes in"
def register_callback(self, callback):
"Set the callback to be called when a device announce message comes in"
self.callback = callback
def handle_message(self, frame):
if self.callback is not None:
try:
record = Device_Annce()
record.extract(frame.payload)
# TODO: should this be a record list?
self.callback(record)
except Exception as e:
logger.debug("Error: ZDO_Device_annce_cluster_server: %s" % str(e))
class ZDO_Mgmt_Lqi_cluster_client:
cluster_id = 0x0031
def __init__(self, xbee = None):
self.conversations = []
self.xbee = xbee
self.sequence_number = 0
def send_frame(self, frame):
self.xbee.send_zb(0, frame.address, frame.export())
def send_command(self, dest_address, start_index, callback=None):
if callback is None:
callback = self.default_callback
frame = ZDO_Frame()
frame.transaction_sequence_number = self.next_sequence_number()
frame.payload = bytearray((start_index,))
frame.address = (dest_address, 0, 0, self.cluster_id)
self.send_frame(frame)
self.conversations.append(ZDO_Conversation(frame, callback))
def next_sequence_number(self):
"Get the next transaction sequence number to use for sending a message."
self.sequence_number += 1
self.sequence_number &= 0xFF # limit from 0-255 (8-bit value)
return self.sequence_number
def handle_message(self, frame):
#print "Received LQI message from %s" % str(source_address)
#purge any dead conversations
for temp_conversation in self.conversations[:]:
if temp_conversation.active is False:
self.conversations.remove(temp_conversation)
#check all conversations for matches with the frame; if no conversations match raise exception
conversation = None
for temp_conversation in self.conversations:
if temp_conversation.match_frame(frame):
conversation = temp_conversation
break
if conversation is not None:
if conversation.callback is not None:
#print [hex(ord(x)) for x in frame.payload]
mgmt_lqi_rsp = Mgmt_Lqi_rsp()
mgmt_lqi_rsp.extract(frame.payload)
conversation.callback(conversation, frame, mgmt_lqi_rsp)
return True
else: #no conversation matched, raise exception
#raise Exception("ZDO_Mgmt_Lqi_cluster_client: Received an unexpected message from %s" % str(source_address))
return False
def default_callback(self, conversation, frame, record_list):
pass
class LQI_aggregator:
def __init__(self, client_lqi_cluster, dest_address, start_index=0, callback=None):
self.client_lqi_cluster = client_lqi_cluster
self.dest_address = dest_address
self.start_index = start_index
self.neighbor_table_descriptors = []
self.final_callback = callback
self.client_lqi_cluster.send_command(self.dest_address, start_index, self.callback)
def callback(self, conversation, frame, lqi_record):
#print "Internal LQI_aggregator callback"
self.neighbor_table_descriptors.extend(lqi_record.neighbor_table_list)
end_index = lqi_record.start_index + len(lqi_record.neighbor_table_list)
if end_index < lqi_record.neighbor_table_entries:
#send another command
self.client_lqi_cluster.send_command(self.dest_address, end_index)
else:
self.final_callback(self.neighbor_table_descriptors)
def default_callback(self, conversation, frame, record_list):
pass
class NeighborTableDescriptorRecord:
def __init__(self,
pan_extended=None,
addr_extended=None,
addr_short=None,
device_type=None,
rx_on_when_idle=None,
relationship=None,
permit_joining=None,
depth=None,
lqi=None):
self.pan_extended = pan_extended
self.addr_extended = addr_extended
self.addr_short = addr_short
self.device_type = device_type
self.rx_on_when_idle = rx_on_when_idle
self.relationship = relationship
self.permit_joining = permit_joining
self.depth = depth
self.lqi = lqi
def extract(self, buf):
try:
self.pan_extended,\
self.addr_extended,\
self.addr_short,\
byte1,\
byte2,\
self.depth,\
self.lqi = struct.unpack("<QQHBBBB", buf[:22])
self.device_type = byte1 & 0x03
self.rx_on_when_idle = (byte1 & 0x0C) >> 2
self.relationship = (byte1 & 0x70) >> 4
self.permit_joining = (byte2 & 0x03)
self.addr_extended = MAC_to_address_string(self.addr_extended, 8)
self.addr_short = short_to_address_string(self.addr_short)
return 22
except Exception as e:
raise Exception("Error: NeighborTableListRecord.extract() - %s" % e)
def export(self):
byte1 = self.device_type | (self.rx_on_when_idle << 2) | (self.relationship << 4)
buf = struct.pack("<QQHBBBB",\
self.pan_extended,\
self.addr_extended,\
self.addr_short,\
byte1,\
self.permit_joining,\
self.depth,\
self.lqi)
return buf
class Mgmt_Lqi_rsp:
def __init__(self,
status = None,
neighbor_table_entries = None,
start_index = None,
neighbor_table_list = None):
if neighbor_table_list is None:
neighbor_table_list = []
self.status = status
self.neighbor_table_entries = neighbor_table_entries
self.start_index = start_index
self.neighbor_table_list = neighbor_table_list
def extract(self, buffer):
self.status = buffer[0]
if self.status == 0: #SUCCESS
self.neighbor_table_entries, self.start_index, neighbor_table_list_count = struct.unpack("<BBB", buffer[1:4])
if neighbor_table_list_count > 0:
offset = 4
for i in range(neighbor_table_list_count):
record = NeighborTableDescriptorRecord()
offset += record.extract(buffer[offset:])
self.neighbor_table_list.append(record)
def export(self):
buffer = struct.pack("<BBBB",\
self.status,\
self.neighbor_table_entries,\
self.start_index,\
len(self.neighbor_table_list))
for neighbor_table_entry in self.neighbor_table_list:
buffer += neighbor_table_entry.export()
return buffer
class Device_Annce:
def __init__(self,
nwk_addr = None,
IEEE_addr = None,
capability = None):
self.nwk_addr = nwk_addr
self.IEEE_addr = IEEE_addr
self.capability = capability
def extract(self, buffer):
#message format:
#2 - NWK address of this device
#8 - IEEE address of this device
#1 - Capability of the local device
#Capability Format:
#Field Name Length (Bits)
#Alternate PAN coordinator 1
#Device type 1
#Power source 1
#Receiver on when idle 1
#Reserved 2
#Security capability 1
#Allocate address 1
try:
self.nwk_addr, self.IEEE_addr, self.capability = struct.unpack("<HQB", buffer[0:11])
except Exception as e:
raise Exception("Error: Device_Annce.extract() - %s" % e)
class XBee:
"Handles the connection to an XBee module"
DIGI_PROFILE_ID = 0xC105
DIGI_MANUFACTURER_ID = 0x101E
device_types = ["coordinator", "router", "end"]
def __init__(self, serial = None):
# mutual exclusion lock:
global _global_lock
_global_lock = RLock()
"Creates the connection to the XBee using the serial port."
self.serial = serial
"Serial port that connects to the xbee"
self.rx_messages = {}
"Messages received from the XBee. Key = endpoint_id, value = (payload, full_source_address)"
self.rx_buffer = b""
"Receive buffer for the serial port"
self.node_list = []
"Node list for the get_node_list function"
self.tx_status = {}
"Tx Status message buffer, key = XBee frame ID, value = (transaction_id, endpoint_id)"
# This needs to be here to allow us to support broadcasts at the top of ZigBee_Node.tick()
self.rx_messages[0xFF] = []
self.lqi_cluster = ZDO_Mgmt_Lqi_cluster_client(self)
self.device_annce_cluster = ZDO_Device_annce_cluster_server(self.device_announce_handler)
self.hw_version = None
self.sw_version = None
def close_serial(self):
global com_port_opened
try:
_global_lock.acquire(True) # make sure other operations aren't happening
if self.serial:
self.serial.close()
self.serial = None
self.rx_buffer = ""
self.node_list = []
#NOTE: leaving any messages that had been completely received
com_port_opened = False
finally:
_global_lock.release()
def set_version(self):
self.hw_version = struct.unpack(">H", self.ddo_get_param(None, "HV", force_com=True))[0]
self.sw_version = struct.unpack(">H", self.ddo_get_param(None, "VR", force_com=True))[0]
def is_series_1(self):
return (self.hw_version & 0xFF00) in (0x1700,)
def is_802_15_4(self):
return self.is_series_1() and ((self.sw_version & 0xF000) == 0x1000)
def register_endpoint(self, endpoint_id):
"Registers an endpoint to save messages for"
if endpoint_id not in self.rx_messages:
self.rx_messages[endpoint_id] = []
def unregister_endpoint(self, endpoint_id):
"Un-registers an endpoint, so that the messages are no long saved"
if endpoint_id in self.rx_messages:
del self.rx_messages[endpoint_id]
def recv(self, endpoint_id):
"Reads the messages from the XBee. Returns from address and payload as a string"
_global_lock.acquire(True)
try: