-
Notifications
You must be signed in to change notification settings - Fork 93
/
common.py
3222 lines (2604 loc) · 105 KB
/
common.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 2017-2022, Digi International Inc.
#
# 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/.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from digi.xbee.models.mode import OperatingMode
from digi.xbee.models.address import XBee16BitAddress, XBee64BitAddress
from digi.xbee.models.status import ATCommandStatus, DiscoveryStatus, TransmitStatus, ModemStatus
from digi.xbee.packets.aft import ApiFrameType
from digi.xbee.packets.base import XBeeAPIPacket, DictKeys
from digi.xbee.util import utils
from digi.xbee.exception import InvalidOperatingModeException, InvalidPacketException
from digi.xbee.io import IOSample, IOLine
class ATCommPacket(XBeeAPIPacket):
"""
This class represents an AT command packet.
Used to query or set module parameters on the local device. This API
command applies changes after executing the command. (Changes made to
module parameters take effect once changes are applied.).
Command response is received as an :class:`.ATCommResponsePacket`.
.. seealso::
| :class:`.ATCommResponsePacket`
| :class:`.XBeeAPIPacket`
"""
__MIN_PACKET_LENGTH = 8
def __init__(self, frame_id, command, parameter=None, op_mode=OperatingMode.API_MODE):
"""
Class constructor. Instantiates a new :class:`.ATCommPacket` object
with the provided parameters.
Args:
frame_id (Integer): the frame ID of the packet.
command (String or bytearray): AT command of the packet.
parameter (Bytearray, optional): the AT command parameter.
op_mode (:class:`.OperatingMode`, optional, default=`OperatingMode.API_MODE`):
The mode in which the frame was captured.
Raises:
ValueError: if `frame_id` is less than 0 or greater than 255.
ValueError: if length of `command` is different from 2.
.. seealso::
| :class:`.XBeeAPIPacket`
"""
if not isinstance(command, (str, bytearray, bytes)):
raise ValueError("Command must be a string or bytearray")
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
if frame_id < 0 or frame_id > 255:
raise ValueError("Frame id must be between 0 and 255.")
super().__init__(ApiFrameType.AT_COMMAND, op_mode=op_mode)
self.__cmd = _encode_at_cmd(command)
self.__param = parameter
self._frame_id = frame_id
@staticmethod
def create_packet(raw, operating_mode):
"""
Override method.
Returns:
:class:`.ATCommPacket`
Raises:
InvalidPacketException: if the bytearray length is less than 8.
(start delim. + length (2 bytes) + frame type
+ frame id + command (2 bytes) + checksum = 8 bytes).
InvalidPacketException: if the length field of 'raw' is different
from its real length. (length field: bytes 2 and 3)
InvalidPacketException: if the first byte of 'raw' is not the
header byte. See :class:`.SpecialByte`.
InvalidPacketException: if the calculated checksum is different
from the checksum field value (last byte).
InvalidPacketException: if the frame type is different from
:attr:`.ApiFrameType.AT_COMMAND`.
InvalidOperatingModeException: if `operating_mode` is not supported.
.. seealso::
| :meth:`.XBeePacket.create_packet`
| :meth:`.XBeeAPIPacket._check_api_packet`
"""
if operating_mode not in (OperatingMode.ESCAPED_API_MODE,
OperatingMode.API_MODE):
raise InvalidOperatingModeException(op_mode=operating_mode)
XBeeAPIPacket._check_api_packet(raw, min_length=ATCommPacket.__MIN_PACKET_LENGTH)
if raw[3] != ApiFrameType.AT_COMMAND.code:
raise InvalidPacketException(message="This packet is not an AT command packet.")
return ATCommPacket(
raw[4], raw[5:7],
parameter=raw[7:-1] if len(raw) > ATCommPacket.__MIN_PACKET_LENGTH else None,
op_mode=operating_mode)
def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return True
def _get_api_packet_spec_data(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data`
"""
if self.__param is not None:
return bytearray(self.__cmd) + self.__param
return bytearray(self.__cmd)
def _get_api_packet_spec_data_dict(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict`
"""
return {DictKeys.COMMAND: self.__cmd,
DictKeys.PARAMETER: list(self.__param) if self.__param is not None else None}
@property
def command(self):
"""
Returns the AT command of the packet.
Returns:
String: the AT command of the packet.
"""
return _decode_at_cmd(self.__cmd)
@command.setter
def command(self, command):
"""
Sets the AT command of the packet.
Args:
command (String or bytearray): New AT command of the packet.
Must have length = 2.
Raises:
ValueError: if length of `command` is different from 2.
"""
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
self.__cmd = _encode_at_cmd(command)
@property
def parameter(self):
"""
Returns the parameter of the packet.
Returns:
Bytearray: the parameter of the packet.
"""
return self.__param
@parameter.setter
def parameter(self, param):
"""
Sets the parameter of the packet.
Args:
param (Bytearray): the new parameter of the packet.
"""
self.__param = param
class ATCommQueuePacket(XBeeAPIPacket):
"""
This class represents an AT command Queue packet.
Used to query or set module parameters on the local device.
In contrast to the :class:`.ATCommPacket` API packet, new parameter
values are queued and not applied until either an :class:`.ATCommPacket`
is sent or the `applyChanges()` method of the :class:`.XBeeDevice`
class is issued.
Command response is received as an :class:`.ATCommResponsePacket`.
.. seealso::
| :class:`.ATCommResponsePacket`
| :class:`.XBeeAPIPacket`
"""
__MIN_PACKET_LENGTH = 8
def __init__(self, frame_id, command, parameter=None, op_mode=OperatingMode.API_MODE):
"""
Class constructor. Instantiates a new :class:`.ATCommQueuePacket`
object with the provided parameters.
Args:
frame_id (Integer): the frame ID of the packet.
command (String or bytearray): the AT command of the packet.
parameter (Bytearray, optional): the AT command parameter. Optional.
op_mode (:class:`.OperatingMode`, optional, default=`OperatingMode.API_MODE`):
The mode in which the frame was captured.
Raises:
ValueError: if `frame_id` is less than 0 or greater than 255.
ValueError: if length of `command` is different from 2.
.. seealso::
| :class:`.XBeeAPIPacket`
"""
if not isinstance(command, (str, bytearray, bytes)):
raise ValueError("Command must be a string or bytearray")
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
if frame_id < 0 or frame_id > 255:
raise ValueError("Frame id must be between 0 and 255.")
super().__init__(ApiFrameType.AT_COMMAND_QUEUE, op_mode=op_mode)
self.__cmd = _encode_at_cmd(command)
self.__param = parameter
self._frame_id = frame_id
@staticmethod
def create_packet(raw, operating_mode):
"""
Override method.
Returns:
:class:`.ATCommQueuePacket`
Raises:
InvalidPacketException: if the bytearray length is less than 8.
(start delim. + length (2 bytes) + frame type
+ frame id + command + checksum = 8 bytes).
InvalidPacketException: if the length field of 'raw' is different
from its real length. (length field: bytes 2 and 3)
InvalidPacketException: if the first byte of 'raw' is not the
header byte. See :class:`.SpecialByte`.
InvalidPacketException: if the calculated checksum is different
from the checksum field value (last byte).
InvalidPacketException: if the frame type is different from
:attr:`.ApiFrameType.AT_COMMAND_QUEUE`.
InvalidOperatingModeException: if `operating_mode` is not supported.
.. seealso::
| :meth:`.XBeePacket.create_packet`
| :meth:`.XBeeAPIPacket._check_api_packet`
"""
if operating_mode not in (OperatingMode.ESCAPED_API_MODE,
OperatingMode.API_MODE):
raise InvalidOperatingModeException(op_mode=operating_mode)
XBeeAPIPacket._check_api_packet(raw, min_length=ATCommQueuePacket.__MIN_PACKET_LENGTH)
if raw[3] != ApiFrameType.AT_COMMAND_QUEUE.code:
raise InvalidPacketException(message="This packet is not an AT command Queue packet.")
return ATCommQueuePacket(
raw[4], raw[5:7],
parameter=raw[7:-1] if len(raw) > ATCommQueuePacket.__MIN_PACKET_LENGTH else None,
op_mode=operating_mode)
def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return True
def _get_api_packet_spec_data(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data`
"""
if self.__param is not None:
return bytearray(self.__cmd) + self.__param
return bytearray(self.__cmd)
def _get_api_packet_spec_data_dict(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict`
"""
return {DictKeys.COMMAND: self.__cmd,
DictKeys.PARAMETER: list(self.__param) if self.__param is not None else None}
@property
def command(self):
"""
Returns the AT command of the packet.
Returns:
String: the AT command of the packet.
"""
return _decode_at_cmd(self.__cmd)
@command.setter
def command(self, command):
"""
Sets the AT command of the packet.
Args:
command (String or bytearray): New AT command of the packet.
Must have length = 2.
Raises:
ValueError: if length of `command` is different from 2.
"""
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
self.__cmd = _encode_at_cmd(command)
@property
def parameter(self):
"""
Returns the parameter of the packet.
Returns:
Bytearray: the parameter of the packet.
"""
return self.__param
@parameter.setter
def parameter(self, param):
"""
Sets the parameter of the packet.
Args:
param (Bytearray): the new parameter of the packet.
"""
self.__param = param
class ATCommResponsePacket(XBeeAPIPacket):
"""
This class represents an AT command response packet.
In response to an AT command message, the module will send an AT command
response message. Some commands will send back multiple frames (for example,
the `ND` - Node Discover command).
This packet is received in response of an :class:`.ATCommPacket`.
Response also includes an :class:`.ATCommandStatus` object with the status
of the AT command.
.. seealso::
| :class:`.ATCommPacket`
| :class:`.ATCommandStatus`
| :class:`.XBeeAPIPacket`
"""
__MIN_PACKET_LENGTH = 9
def __init__(self, frame_id, command, response_status=ATCommandStatus.OK,
comm_value=None, op_mode=OperatingMode.API_MODE):
"""
Class constructor. Instantiates a new :class:`.ATCommResponsePacket`
object with the provided parameters.
Args:
frame_id (Integer): the frame ID of the packet. Must be between 0 and 255.
command (String or bytearray): the AT command of the packet.
response_status (:class:`.ATCommandStatus` or Integer): the status of the AT command.
comm_value (Bytearray, optional): the AT command response value.
op_mode (:class:`.OperatingMode`, optional, default=`OperatingMode.API_MODE`):
The mode in which the frame was captured.
Raises:
ValueError: if `frame_id` is less than 0 or greater than 255.
ValueError: if length of `command` is different from 2.
.. seealso::
| :class:`.ATCommandStatus`
| :class:`.XBeeAPIPacket`
"""
if frame_id < 0 or frame_id > 255:
raise ValueError("Frame id must be between 0 and 255.")
if not isinstance(command, (str, bytearray, bytes)):
raise ValueError("Command must be a string or bytearray")
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
if response_status is None:
response_status = ATCommandStatus.OK.code
elif not isinstance(response_status, (ATCommandStatus, int)):
raise TypeError("Response status must be ATCommandStatus or int not {!r}".format(
response_status.__class__.__name__))
super().__init__(ApiFrameType.AT_COMMAND_RESPONSE, op_mode=op_mode)
self._frame_id = frame_id
self.__cmd = _encode_at_cmd(command)
if isinstance(response_status, ATCommandStatus):
self.__resp_st = response_status.code
elif 0 <= response_status <= 255:
self.__resp_st = response_status
else:
raise ValueError("Response status must be between 0 and 255.")
self.__comm_val = comm_value
@staticmethod
def create_packet(raw, operating_mode):
"""
Override method.
Returns:
:class:`.ATCommResponsePacket`
Raises:
InvalidPacketException: if the bytearray length is less than 9.
(start delim. + length (2 bytes) + frame type + frame id
+ at command (2 bytes) + command status + checksum = 9 bytes).
InvalidPacketException: if the length field of 'raw' is different
from its real length. (length field: bytes 2 and 3)
InvalidPacketException: if the first byte of 'raw' is not the
header byte. See :class:`.SpecialByte`.
InvalidPacketException: if the calculated checksum is different
from the checksum field value (last byte).
InvalidPacketException: if the frame type is different from
:attr:`.ApiFrameType.AT_COMMAND_RESPONSE`.
InvalidPacketException: if the command status field is not a valid
value. See :class:`.ATCommandStatus`.
InvalidOperatingModeException: if `operating_mode` is not supported.
.. seealso::
| :meth:`.XBeePacket.create_packet`
| :meth:`.XBeeAPIPacket._check_api_packet`
"""
if operating_mode not in (OperatingMode.ESCAPED_API_MODE,
OperatingMode.API_MODE):
raise InvalidOperatingModeException(op_mode=operating_mode)
XBeeAPIPacket._check_api_packet(raw, min_length=ATCommResponsePacket.__MIN_PACKET_LENGTH)
if raw[3] != ApiFrameType.AT_COMMAND_RESPONSE.code:
raise InvalidPacketException(
message="This packet is not an AT command response packet.")
if ATCommandStatus.get(raw[7]) is None:
raise InvalidPacketException(message="Invalid command status.")
return ATCommResponsePacket(
raw[4], raw[5:7], raw[7],
comm_value=raw[8:-1] if len(raw) > ATCommResponsePacket.__MIN_PACKET_LENGTH else None,
op_mode=operating_mode)
def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return True
def _get_api_packet_spec_data(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data`
"""
ret = bytearray(self.__cmd)
ret.append(self.__resp_st)
if self.__comm_val is not None:
ret += self.__comm_val
return ret
def _get_api_packet_spec_data_dict(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict`
"""
return {DictKeys.COMMAND: self.__cmd,
DictKeys.AT_CMD_STATUS: self.__resp_st,
DictKeys.RF_DATA: list(self.__comm_val) if self.__comm_val is not None else None}
@property
def command(self):
"""
Returns the AT command of the packet.
Returns:
String: the AT command of the packet.
"""
return _decode_at_cmd(self.__cmd)
@command.setter
def command(self, command):
"""
Sets the AT command of the packet.
Args:
command (String or bytearray): New AT command of the packet.
Must have length = 2.
Raises:
ValueError: if length of `command` is different from 2.
"""
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
self.__cmd = _encode_at_cmd(command)
@property
def command_value(self):
"""
Returns the AT command response value.
Returns:
Bytearray: the AT command response value.
"""
return self.__comm_val
@command_value.setter
def command_value(self, __comm_value):
"""
Sets the AT command response value.
Args:
__comm_value (Bytearray): the new AT command response value.
"""
self.__comm_val = __comm_value
@property
def status(self):
"""
Returns the AT command response status of the packet.
Returns:
:class:`.ATCommandStatus`: the AT command response status of the packet.
.. seealso::
| :class:`.ATCommandStatus`
"""
return ATCommandStatus.get(self.__resp_st)
@property
def real_status(self):
"""
Returns the AT command response status of the packet.
Returns:
Integer: the AT command response status of the packet.
"""
return self.__resp_st
@status.setter
def status(self, response_status):
"""
Sets the AT command response status of the packet
Args:
response_status (:class:`.ATCommandStatus`) : the new AT command
response status of the packet.
.. seealso::
| :class:`.ATCommandStatus`
"""
if response_status is None:
raise ValueError("Response status cannot be None")
if isinstance(response_status, ATCommandStatus):
self.__resp_st = response_status.code
elif isinstance(response_status, int):
if 0 <= response_status <= 255:
self.__resp_st = response_status
else:
raise ValueError("Response status must be between 0 and 255.")
else:
raise TypeError(
"Response status must be ATCommandStatus or int not {!r}".
format(response_status.__class__.__name__))
class ReceivePacket(XBeeAPIPacket):
"""
This class represents a receive packet. Packet is built using the parameters
of the constructor or providing a valid byte array.
When the module receives an RF packet, it is sent out the UART using this
message type.
This packet is received when external devices send transmit request
packets to this module.
Among received data, some options can also be received indicating
transmission parameters.
.. seealso::
| :class:`.TransmitPacket`
| :class:`.ReceiveOptions`
| :class:`.XBeeAPIPacket`
"""
__MIN_PACKET_LENGTH = 16
def __init__(self, x64bit_addr, x16bit_addr, rx_options, rf_data=None,
op_mode=OperatingMode.API_MODE):
"""
Class constructor. Instantiates a new :class:`.ReceivePacket` object
with the provided parameters.
Args:
x64bit_addr (:class:`.XBee64BitAddress`): the 64-bit source address.
x16bit_addr (:class:`.XBee16BitAddress`): the 16-bit source address.
rx_options (Integer): bitfield indicating the receive options.
rf_data (Bytearray, optional): received RF data.
op_mode (:class:`.OperatingMode`, optional, default=`OperatingMode.API_MODE`):
The mode in which the frame was captured.
.. seealso::
| :class:`.ReceiveOptions`
| :class:`.XBee16BitAddress`
| :class:`.XBee64BitAddress`
| :class:`.XBeeAPIPacket`
"""
super().__init__(ApiFrameType.RECEIVE_PACKET, op_mode=op_mode)
self.__x64bit_addr = x64bit_addr
self.__x16bit_addr = x16bit_addr
self.__rx_opts = rx_options
self.__data = rf_data
@staticmethod
def create_packet(raw, operating_mode):
"""
Override method.
Returns:
:class:`.ATCommResponsePacket`
Raises:
InvalidPacketException: if the bytearray length is less than 16.
(start delim. + length (2 bytes) + frame type + 64bit addr.
+ 16bit addr. + Receive options + checksum = 16 bytes).
InvalidPacketException: if the length field of 'raw' is different
from its real length. (length field: bytes 2 and 3)
InvalidPacketException: if the first byte of 'raw' is not the
header byte. See :class:`.SpecialByte`.
InvalidPacketException: if the calculated checksum is different
from the checksum field value (last byte).
InvalidPacketException: if the frame type is not
:attr:`.ApiFrameType.RECEIVE_PACKET`.
InvalidOperatingModeException: if `operating_mode` is not supported.
.. seealso::
| :meth:`.XBeePacket.create_packet`
| :meth:`.XBeeAPIPacket._check_api_packet`
"""
if operating_mode not in (OperatingMode.ESCAPED_API_MODE,
OperatingMode.API_MODE):
raise InvalidOperatingModeException(op_mode=operating_mode)
XBeeAPIPacket._check_api_packet(raw, min_length=ReceivePacket.__MIN_PACKET_LENGTH)
if raw[3] != ApiFrameType.RECEIVE_PACKET.code:
raise InvalidPacketException(message="This packet is not a receive packet.")
return ReceivePacket(
XBee64BitAddress(raw[4:12]), XBee16BitAddress(raw[12:14]), raw[14],
rf_data=raw[15:-1] if len(raw) > ReceivePacket.__MIN_PACKET_LENGTH else None,
op_mode=operating_mode)
def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return False
def is_broadcast(self):
"""
Override method.
.. seealso::
| :meth:`XBeeAPIPacket.is_broadcast`
"""
return utils.is_bit_enabled(self.__rx_opts, 1)
def _get_api_packet_spec_data(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data`
"""
ret = self.__x64bit_addr.address
ret += self.__x16bit_addr.address
ret.append(self.__rx_opts)
if self.__data is not None:
return ret + self.__data
return ret
def _get_api_packet_spec_data_dict(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict`
"""
return {DictKeys.X64BIT_ADDR: self.__x64bit_addr.address,
DictKeys.X16BIT_ADDR: self.__x16bit_addr.address,
DictKeys.RECEIVE_OPTIONS: self.__rx_opts,
DictKeys.RF_DATA: list(self.__data) if self.__data is not None else None}
@property
def effective_len(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.effective_len`
"""
return len(self) - 2 - 8 # Remove 16-bit and 64-bit addresses
@property
def x64bit_source_addr(self):
"""
Returns the 64-bit source address.
Returns:
:class:`.XBee64BitAddress`: the 64-bit source address.
.. seealso::
| :class:`.XBee64BitAddress`
"""
return self.__x64bit_addr
@x64bit_source_addr.setter
def x64bit_source_addr(self, x64bit_addr):
"""
Sets the 64-bit source address.
Args:
x64bit_addr (:class:`.XBee64BitAddress`): the new 64-bit source address.
.. seealso::
| :class:`.XBee64BitAddress`
"""
self.__x64bit_addr = x64bit_addr
@property
def x16bit_source_addr(self):
"""
Returns the 16-bit source address.
Returns:
:class:`.XBee16BitAddress`: the 16-bit source address.
.. seealso::
| :class:`.XBee16BitAddress`
"""
return self.__x16bit_addr
@x16bit_source_addr.setter
def x16bit_source_addr(self, x16bit_addr):
"""
Sets the 16-bit source address.
Args:
x16bit_addr (:class:`.XBee16BitAddress`): the new 16-bit source address.
.. seealso::
| :class:`.XBee16BitAddress`
"""
self.__x16bit_addr = x16bit_addr
@property
def receive_options(self):
"""
Returns the receive options bitfield.
Returns:
Integer: the receive options bitfield.
.. seealso::
| :class:`.ReceiveOptions`
"""
return self.__rx_opts
@receive_options.setter
def receive_options(self, receive_options):
"""
Sets the receive options bitfield.
Args:
receive_options (Integer): the new receive options bitfield.
.. seealso::
| :class:`.ReceiveOptions`
"""
self.__rx_opts = receive_options
@property
def rf_data(self):
"""
Returns the received RF data.
Returns:
Bytearray: the received RF data.
"""
if self.__data is None:
return None
return self.__data.copy()
@rf_data.setter
def rf_data(self, rf_data):
"""
Sets the received RF data.
Args:
rf_data (Bytearray): the new received RF data.
"""
if rf_data is None:
self.__data = None
else:
self.__data = rf_data.copy()
class RemoteATCommandPacket(XBeeAPIPacket):
"""
This class represents a Remote AT command Request packet. Packet is built
using the parameters of the constructor or providing a valid byte array.
Used to query or set module parameters on a remote device. For parameter
changes on the remote device to take effect, changes must be applied, either
by setting the apply changes options bit, or by sending an `AC` command
to the remote node.
Remote command options are set as a bitfield.
If configured, command response is received as a :class:`.RemoteATCommandResponsePacket`.
.. seealso::
| :class:`.RemoteATCommandResponsePacket`
| :class:`.XBeeAPIPacket`
"""
__MIN_PACKET_LENGTH = 19
def __init__(self, frame_id, x64bit_addr, x16bit_addr, tx_options,
command, parameter=None, op_mode=OperatingMode.API_MODE):
"""
Class constructor. Instantiates a new :class:`.RemoteATCommandPacket`
object with the provided parameters.
Args:
frame_id (integer): the frame ID of the packet.
x64bit_addr (:class:`.XBee64BitAddress`): the 64-bit destination address.
x16bit_addr (:class:`.XBee16BitAddress`): the 16-bit destination address.
tx_options (Integer): bitfield of supported transmission options.
command (String or bytearray): AT command to send.
parameter (Bytearray, optional): AT command parameter.
op_mode (:class:`.OperatingMode`, optional, default=`OperatingMode.API_MODE`):
The mode in which the frame was captured.
Raises:
ValueError: if `frame_id` is less than 0 or greater than 255.
ValueError: if length of `command` is different from 2.
.. seealso::
| :class:`.RemoteATCmdOptions`
| :class:`.XBee16BitAddress`
| :class:`.XBee64BitAddress`
| :class:`.XBeeAPIPacket`
"""
if frame_id < 0 or frame_id > 255:
raise ValueError("Frame id must be between 0 and 255.")
if not isinstance(command, (str, bytearray, bytes)):
raise ValueError("Command must be a string or bytearray")
if len(command) != 2:
raise ValueError("Invalid command %s"
% str(command, encoding='utf8', errors='ignore'))
super().__init__(ApiFrameType.REMOTE_AT_COMMAND_REQUEST, op_mode=op_mode)
self._frame_id = frame_id
self.__x64bit_addr = x64bit_addr
self.__x16bit_addr = x16bit_addr
self.__tx_opts = tx_options
self.__cmd = _encode_at_cmd(command)
self.__param = parameter
@staticmethod
def create_packet(raw, operating_mode):
"""
Override method.
Returns:
:class:`.RemoteATCommandPacket`
Raises:
InvalidPacketException: if the Bytearray length is less than 19.
(start delim. + length (2 bytes) + frame type + frame id
+ 64bit addr. + 16bit addr. + transmit options
+ command (2 bytes) + checksum = 19 bytes).
InvalidPacketException: if the length field of 'raw' is different
from its real length. (length field: bytes 2 and 3)
InvalidPacketException: if the first byte of 'raw' is not the
header byte. See :class:`.SpecialByte`.
InvalidPacketException: if the calculated checksum is different
from the checksum field value (last byte).
InvalidPacketException: if the frame type is not
:attr:`.ApiFrameType.REMOTE_AT_COMMAND_REQUEST`.
InvalidOperatingModeException: if `operating_mode` is not supported.
.. seealso::
| :meth:`.XBeePacket.create_packet`
| :meth:`.XBeeAPIPacket._check_api_packet`
"""
if operating_mode not in (OperatingMode.ESCAPED_API_MODE,
OperatingMode.API_MODE):
raise InvalidOperatingModeException(op_mode=operating_mode)
XBeeAPIPacket._check_api_packet(raw, min_length=RemoteATCommandPacket.__MIN_PACKET_LENGTH)
if raw[3] != ApiFrameType.REMOTE_AT_COMMAND_REQUEST.code:
raise InvalidPacketException(
message="This packet is not a remote AT command request packet.")
return RemoteATCommandPacket(
raw[4], XBee64BitAddress(raw[5:13]), XBee16BitAddress(raw[13:15]),
raw[15], raw[16:18],
parameter=raw[18:-1] if len(raw) > RemoteATCommandPacket.__MIN_PACKET_LENGTH else None,
op_mode=operating_mode)
def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return True
def _get_api_packet_spec_data(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data`
"""
ret = self.__x64bit_addr.address
ret += self.__x16bit_addr.address
ret.append(self.__tx_opts)
ret += self.__cmd
return ret if self.__param is None else ret + self.__param
def _get_api_packet_spec_data_dict(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict`
"""
return {DictKeys.X64BIT_ADDR: self.__x64bit_addr.address,
DictKeys.X16BIT_ADDR: self.__x16bit_addr.address,
DictKeys.TRANSMIT_OPTIONS: self.__tx_opts,
DictKeys.COMMAND: self.__cmd,
DictKeys.PARAMETER: list(self.__param) if self.__param is not None else None}
@property
def effective_len(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.effective_len`
"""
return len(self) - 2 - 8 # Remove 16-bit and 64-bit addresses