-
Notifications
You must be signed in to change notification settings - Fork 93
/
devices.py
executable file
·6072 lines (4844 loc) · 229 KB
/
devices.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, 2018, 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 abc import ABCMeta, abstractmethod
import logging
from ipaddress import IPv4Address
import threading
import time
import serial
from serial.serialutil import SerialTimeoutException
from digi.xbee.packets.cellular import TXSMSPacket
from digi.xbee.models.accesspoint import AccessPoint, WiFiEncryptionType
from digi.xbee.models.atcomm import ATCommandResponse, ATCommand
from digi.xbee.models.hw import HardwareVersion
from digi.xbee.models.mode import OperatingMode, APIOutputMode, IPAddressingMode
from digi.xbee.models.address import XBee64BitAddress, XBee16BitAddress, XBeeIMEIAddress
from digi.xbee.models.message import XBeeMessage, ExplicitXBeeMessage, IPMessage
from digi.xbee.models.options import TransmitOptions, RemoteATCmdOptions, DiscoveryOptions
from digi.xbee.models.protocol import XBeeProtocol, IPProtocol
from digi.xbee.models.status import ATCommandStatus, TransmitStatus, PowerLevel, \
ModemStatus, CellularAssociationIndicationStatus, WiFiAssociationIndicationStatus, AssociationIndicationStatus,\
NetworkDiscoveryStatus
from digi.xbee.packets.aft import ApiFrameType
from digi.xbee.packets.base import XBeeAPIPacket
from digi.xbee.packets.common import ATCommPacket, TransmitPacket, RemoteATCommandPacket, ExplicitAddressingPacket, \
ATCommQueuePacket, ATCommResponsePacket, RemoteATCommandResponsePacket
from digi.xbee.packets.network import TXIPv4Packet
from digi.xbee.packets.raw import TX64Packet, TX16Packet
from digi.xbee.util import utils
from digi.xbee.exception import XBeeException, TimeoutException, InvalidOperatingModeException, \
ATCommandException, OperationNotSupportedException
from digi.xbee.io import IOSample, IOMode
from digi.xbee.reader import PacketListener, PacketReceived, DeviceDiscovered, DiscoveryProcessFinished
from digi.xbee.serial import FlowControl
from digi.xbee.serial import XBeeSerialPort
from functools import wraps
class AbstractXBeeDevice(object):
"""
This class provides common functionality for all XBee devices.
"""
__metaclass__ = ABCMeta
_DEFAULT_TIMEOUT_SYNC_OPERATIONS = 4
"""
The default timeout for all synchronous operations, in seconds.
"""
LOG_PATTERN = "{port:<6s}{event:<12s}{opmode:<20s}{content:<50s}"
"""
Pattern used to log packet events.
"""
_log = logging.getLogger(__name__)
"""
Logger.
"""
def __init__(self, local_xbee_device=None, serial_port=None, sync_ops_timeout=_DEFAULT_TIMEOUT_SYNC_OPERATIONS):
"""
Class constructor. Instantiates a new :class:`.AbstractXBeeDevice` object with the provided parameters.
Args:
local_xbee_device (:class:`.XBeeDevice`, optional): only necessary if XBee device is remote. The local
XBee device that will behave as connection interface to communicate with the remote XBee one.
serial_port (:class:`.XBeeSerialPort`, optional): only necessary if the XBee device is local. The serial
port that will be used to communicate with this XBee.
sync_ops_timeout (Integer, default: :attr:`AbstractXBeeDevice._DEFAULT_TIMEOUT_SYNC_OPERATIONS`): the
timeout (in seconds) that will be applied for all synchronous operations.
.. seealso::
| :class:`.XBeeDevice`
| :class:`.XBeeSerialPort`
"""
self.__current_frame_id = 0x00
self._16bit_addr = None
self._64bit_addr = None
self._apply_changes_flag = True
self._is_open = False
self._operating_mode = None
self._local_xbee_device = local_xbee_device
self._serial_port = serial_port
self._timeout = sync_ops_timeout
self.__io_packet_received = False
self.__io_packet_payload = None
self._hardware_version = None
self._firmware_version = None
self._protocol = None
self._node_id = None
self._packet_listener = None
self._log_handler = logging.StreamHandler()
self._log.addHandler(self._log_handler)
self.__generic_lock = threading.Lock()
def __del__(self):
self._log.removeHandler(self._log_handler)
def __eq__(self, other):
"""
Operator '=='. Compares two :class:`.AbstractXBeeDevice` instances.
Returns:
If at least one XBee device has 64 bit address (not ``None``), this method returns ``True`` if both
XBee device's addresses are equal, ``False`` otherwise.
If at least one XBee device has 16 bit address (not ``None``), this method returns ``True`` if both
XBee device addresses are equal, ``False`` otherwise.
If at least one XBee device has node id (not ``None``), this method returns ``True`` if both
XBee device IDs are equal, ``False`` otherwise.
Else (all parameters of both devices are ``None``) returns ``True``.
"""
if other is None:
return False
if not isinstance(self, AbstractXBeeDevice) or not isinstance(other, AbstractXBeeDevice):
return False
if self.get_64bit_addr() is not None and other.get_64bit_addr() is not None:
return self.get_64bit_addr() == other.get_64bit_addr()
if self.get_16bit_addr() is not None and other.get_16bit_addr() is not None:
return self.get_16bit_addr() == other.get_16bit_addr()
return False
def update_device_data_from(self, device):
"""
Updates the current device reference with the data provided for the given device.
This is only for internal use.
Args:
device (:class:`.AbstractXBeeDevice`): the XBee device to get the data from.
"""
if device.get_node_id() is not None:
self._node_id = device.get_node_id()
addr64 = device.get_64bit_addr()
if (addr64 is not None and
addr64 != XBee64BitAddress.UNKNOWN_ADDRESS and
addr64 != self._64bit_addr and
(self._64bit_addr is None or self._64bit_addr == XBee64BitAddress.UNKNOWN_ADDRESS)):
self._64bit_addr = addr64
addr16 = device.get_16bit_addr()
if addr16 is not None and addr16 != self._16bit_addr:
self._16bit_addr = addr16
def get_parameter(self, parameter):
"""
Returns the value of the provided parameter via an AT Command.
Args:
parameter (String): parameter to get.
Returns:
Bytearray: the parameter value.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
value = self.__send_parameter(parameter)
# Check if the response is null, if so throw an exception (maybe it was a write-only parameter).
if value is None:
raise OperationNotSupportedException("Could not get the %s value." % parameter)
return value
def set_parameter(self, parameter, value):
"""
Sets the value of a parameter via an AT Command.
If you send parameter to a local XBee device, all changes
will be applied automatically, except for non-volatile memory,
in which case you will need to execute the parameter "WR" via
:meth:`.AbstractXBeeDevice.execute_command` method, or
:meth:`.AbstractXBeeDevice.apply_changes` method.
If you are sending parameters to a remote XBee device,
the changes will be not applied automatically, unless the "apply_changes"
flag is activated.
You can set this flag via the method :meth:`.AbstractXBeeDevice.enable_apply_changes`.
This flag only works for volatile memory, if you want to save
changed parameters in non-volatile memory, even for remote devices,
you must execute "WR" command by one of the 2 ways mentioned above.
Args:
parameter (String): parameter to set.
value (Bytearray): value of the parameter.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
ValueError: if ``parameter`` is ``None`` or ``value`` is ``None``.
"""
if value is None:
raise ValueError("Value of the parameter cannot be None.")
self.__send_parameter(parameter, value)
# Refresh cached parameters if this method modifies some of them.
self._refresh_if_cached(parameter, value)
def execute_command(self, parameter):
"""
Executes the provided command.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
self.__send_parameter(parameter, None)
def __send_parameter(self, parameter, parameter_value=None):
"""
Sends the given AT parameter to this XBee device with an optional
argument or value and returns the response (likely the value) of that
parameter in a byte array format.
Args:
parameter (String): The name of the AT command to be executed.
parameter_value (bytearray, optional): The value of the parameter to set (if any).
Returns:
Bytearray: A byte array containing the value of the parameter.
Raises:
ValueError: if ``parameter`` is ``None`` or if ``len(parameter) != 2``.
"""
if parameter is None:
raise ValueError("Parameter cannot be None.")
if len(parameter) != 2:
raise ValueError("Parameter must contain exactly 2 characters.")
at_command = ATCommand(parameter, parameter_value)
# Send the AT command.
response = self._send_at_command(at_command)
self._check_at_cmd_response_is_valid(response)
return response.response
def _check_at_cmd_response_is_valid(self, response):
"""
Checks if the provided ``ATCommandResponse`` is valid throwing an
:class:`.ATCommandException` in case it is not.
Args:
response: The AT command response to check.
Raises:
ATCommandException: if ``response`` is ``None`` or
if ``response.response != OK``.
"""
if response is None or not isinstance(response, ATCommandResponse) or response.status is None:
raise ATCommandException(None)
elif response.status != ATCommandStatus.OK:
raise ATCommandException(response.status)
def _send_at_command(self, command):
"""
Sends the given AT command and waits for answer or until the configured
receive timeout expires.
Args:
command (:class:`.ATCommand`): AT command to be sent.
Returns:
:class:`.ATCommandResponse`: object containing the response of the command
or ``None`` if there is no response.
Raises:
ValueError: if ``command`` is ``None``.
InvalidOperatingModeException: if the operating mode is different than ``API`` or ``ESCAPED_API_MODE``.
"""
if command is None:
raise ValueError("AT command cannot be None.")
operating_mode = self._get_operating_mode()
if operating_mode != OperatingMode.API_MODE and operating_mode != OperatingMode.ESCAPED_API_MODE:
raise InvalidOperatingModeException.from_operating_mode(operating_mode)
if self.is_remote():
remote_at_cmd_opts = RemoteATCmdOptions.NONE.value
if self.is_apply_changes_enabled():
remote_at_cmd_opts |= RemoteATCmdOptions.APPLY_CHANGES.value
remote_16bit_addr = self.get_16bit_addr()
if remote_16bit_addr is None:
remote_16bit_addr = XBee16BitAddress.UNKNOWN_ADDRESS
packet = RemoteATCommandPacket(self._get_next_frame_id(), self.get_64bit_addr(), remote_16bit_addr,
remote_at_cmd_opts, command.command, command.parameter)
else:
if self.is_apply_changes_enabled():
packet = ATCommPacket(self._get_next_frame_id(), command.command, command.parameter)
else:
packet = ATCommQueuePacket(self._get_next_frame_id(), command.command, command.parameter)
if self.is_remote():
answer_packet = self._local_xbee_device.send_packet_sync_and_get_response(packet)
else:
answer_packet = self._send_packet_sync_and_get_response(packet)
response = None
if isinstance(answer_packet, ATCommResponsePacket) or isinstance(answer_packet, RemoteATCommandResponsePacket):
response = ATCommandResponse(command, answer_packet.command_value, answer_packet.status)
return response
def apply_changes(self):
"""
Applies changes via ``AC`` command.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
self.execute_command("AC")
def write_changes(self):
"""
Writes configurable parameter values to the non-volatile memory of the
XBee device so that parameter modifications persist through subsequent
resets.
Parameters values remain in this device's memory until overwritten by
subsequent use of this method.
If changes are made without writing them to non-volatile memory, the
module reverts back to previously saved parameters the next time the
module is powered-on.
Writing the parameter modifications does not mean those values are
immediately applied, this depends on the status of the 'apply
configuration changes' option. Use method
:meth:`is_apply_configuration_changes_enabled` to get its status and
:meth:`enable_apply_configuration_changes` to enable/disable the
option. If it is disabled, method :meth:`apply_changes` can be used in
order to manually apply the changes.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
self.execute_command("WR")
@abstractmethod
def reset(self):
"""
Performs a software reset on this XBee device and blocks until the process is completed.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
pass
def read_device_info(self):
"""
Updates all instance parameters reading them from the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
if self.is_remote():
if not self._local_xbee_device.serial_port.is_open:
raise XBeeException("Local XBee device's serial port closed")
else:
if (self._operating_mode != OperatingMode.API_MODE and
self._operating_mode != OperatingMode.ESCAPED_API_MODE):
raise InvalidOperatingModeException("Not supported operating mode: " + str(self._operating_mode))
if not self._serial_port.is_open:
raise XBeeException("XBee device's serial port closed")
# Hardware version:
self._hardware_version = HardwareVersion.get(self.get_parameter("HV")[0])
# Firmware version:
self._firmware_version = self.get_parameter("VR")
# Original value of the protocol:
orig_protocol = self.get_protocol()
# Protocol:
self._protocol = XBeeProtocol.determine_protocol(self._hardware_version.code, self._firmware_version)
if orig_protocol is not None and orig_protocol != XBeeProtocol.UNKNOWN and orig_protocol != self._protocol:
raise XBeeException("Error reading device information: "
"Your module seems to be %s and NOT %s. " % (self._protocol, orig_protocol) +
"Check if you are using the appropriate device class.")
# 64-bit address:
sh = self.get_parameter("SH")
sl = self.get_parameter("SL")
self._64bit_addr = XBee64BitAddress(sh + sl)
# Node ID:
self._node_id = self.get_parameter("NI").decode()
# 16-bit address:
if self._protocol in [XBeeProtocol.ZIGBEE,
XBeeProtocol.RAW_802_15_4,
XBeeProtocol.XTEND,
XBeeProtocol.SMART_ENERGY,
XBeeProtocol.ZNET]:
r = self.get_parameter("MY")
self._16bit_addr = XBee16BitAddress(r)
def get_node_id(self):
"""
Returns the Node Identifier (``NI``) value of the XBee device.
Returns:
String: the Node Identifier (``NI``) of the XBee device.
"""
return self._node_id
def set_node_id(self, node_id):
"""
Sets the Node Identifier (``NI``) value of the XBee device..
Args:
node_id (String): the new Node Identifier (``NI``) of the XBee device.
Raises:
ValueError: if ``node_id`` is ``None`` or its length is greater than 20.
TimeoutException: if the response is not received before the read timeout expires.
"""
if node_id is None:
raise ValueError("Node ID cannot be None")
if len(node_id) > 20:
raise ValueError("Node ID length must be less than 21")
self.set_parameter("NI", bytearray(node_id, 'utf8'))
self._node_id = node_id
def get_hardware_version(self):
"""
Returns the hardware version of the XBee device.
Returns:
:class:`.HardwareVersion`: the hardware version of the XBee device.
.. seealso::
| :class:`.HardwareVersion`
"""
return self._hardware_version
def get_firmware_version(self):
"""
Returns the firmware version of the XBee device.
Returns:
Bytearray: the hardware version of the XBee device.
"""
return self._firmware_version
def get_protocol(self):
"""
Returns the current protocol of the XBee device.
Returns:
:class:`.XBeeProtocol`: the current protocol of the XBee device.
.. seealso::
| :class:`.XBeeProtocol`
"""
return self._protocol
def get_16bit_addr(self):
"""
Returns the 16-bit address of the XBee device.
Returns:
:class:`.XBee16BitAddress`: the 16-bit address of the XBee device.
.. seealso::
| :class:`.XBee16BitAddress`
"""
return self._16bit_addr
def set_16bit_addr(self, value):
"""
Sets the 16-bit address of the XBee device.
Args:
value (:class:`.XBee16BitAddress`): the new 16-bit address of the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
OperationNotSupportedException: if the current protocol is not 802.15.4.
"""
if self.get_protocol() != XBeeProtocol.RAW_802_15_4:
raise OperationNotSupportedException("16-bit address can only be set in 802.15.4 protocol")
self.set_parameter("MY", value.address)
self._16bit_addr = value
def get_64bit_addr(self):
"""
Returns the 64-bit address of the XBee device.
Returns:
:class:`.XBee64BitAddress`: the 64-bit address of the XBee device.
.. seealso::
| :class:`.XBee64BitAddress`
"""
return self._64bit_addr
def get_current_frame_id(self):
"""
Returns the last used frame ID.
Returns:
Integer: the last used frame ID.
"""
return self.__current_frame_id
def enable_apply_changes(self, value):
"""
Sets the apply_changes flag.
Args:
value (Boolean): ``True`` to enable the apply changes flag, ``False`` to disable it.
"""
self._apply_changes_flag = value
def is_apply_changes_enabled(self):
"""
Returns whether the apply_changes flag is enabled or not.
Returns:
Boolean: ``True`` if the apply_changes flag is enabled, ``False`` otherwise.
"""
return self._apply_changes_flag
@abstractmethod
def is_remote(self):
"""
Determines whether the XBee device is remote or not.
Returns:
Boolean: ``True`` if the XBee device is remote, ``False`` otherwise.
"""
pass
def set_sync_ops_timeout(self, sync_ops_timeout):
"""
Sets the serial port read timeout.
Args:
sync_ops_timeout (Integer): the read timeout, expressed in seconds.
"""
self._timeout = sync_ops_timeout
if self.is_remote():
self._local_xbee_device.serial_port.timeout = self._timeout
else:
self._serial_port.timeout = self._timeout
def get_sync_ops_timeout(self):
"""
Returns the serial port read timeout.
Returns:
Integer: the serial port read timeout in seconds.
"""
return self._timeout
def get_dest_address(self):
"""
Returns the 64-bit address of the XBee device that data will be reported to.
Returns:
:class:`.XBee64BitAddress`: the address.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
.. seealso::
| :class:`.XBee64BitAddress`
"""
dh = self.get_parameter("DH")
dl = self.get_parameter("DL")
return XBee64BitAddress(dh + dl)
def set_dest_address(self, addr):
"""
Sets the 64-bit address of the XBee device that data will be reported to.
Args:
addr(:class:`.XBee64BitAddress` or :class:`.RemoteXBeeDevice`): the address itself or the remote XBee device
that you want to set up its address as destination address.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
All exceptions raised by :meth:`.XBeeDevice.set_parameter`.
"""
if isinstance(addr, RemoteXBeeDevice):
addr = addr.get_64bit_addr()
apply_changes = None
with self.__generic_lock:
try:
apply_changes = self.is_apply_changes_enabled()
self.enable_apply_changes(False)
self.set_parameter("DH", addr.address[:4])
self.set_parameter("DL", addr.address[4:])
except (TimeoutException, XBeeException, InvalidOperatingModeException, ATCommandException) as e:
# Raise the exception.
raise e
finally:
if apply_changes:
self.enable_apply_changes(True)
self.apply_changes()
def get_pan_id(self):
"""
Returns the operating PAN ID of the XBee device.
Returns:
Bytearray: operating PAN ID of the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
"""
if self.get_protocol() == XBeeProtocol.ZIGBEE:
return self.get_parameter("OP")
return self.get_parameter("ID")
def set_pan_id(self, value):
"""
Sets the operating PAN ID of the XBee device.
Args:
value (Bytearray): the new operating PAN ID of the XBee device.. Must have only 1 or 2 bytes.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
"""
self.set_parameter("ID", value)
def get_power_level(self):
"""
Returns the power level of the XBee device.
Returns:
:class:`.PowerLevel`: the power level of the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
.. seealso::
| :class:`.PowerLevel`
"""
return PowerLevel.get(self.get_parameter("PL")[0])
def set_power_level(self, power_level):
"""
Sets the power level of the XBee device.
Args:
power_level (:class:`.PowerLevel`): the new power level of the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
.. seealso::
| :class:`.PowerLevel`
"""
self.set_parameter("PL", bytearray([power_level.code]))
def set_io_configuration(self, io_line, io_mode):
"""
Sets the configuration of the provided IO line.
Args:
io_line (:class:`.IOLine`): the IO line to configure.
io_mode (:class:`.IOMode`): the IO mode to set to the IO line.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
.. seealso::
| :class:`.IOLine`
| :class:`.IOMode`
"""
self.set_parameter(io_line.at_command, bytearray([io_mode.value]))
def get_io_configuration(self, io_line):
"""
Returns the configuration of the provided IO line.
Args:
io_line (:class:`.IOLine`): the io line to configure.
Returns:
:class:`.IOMode`: the IO mode of the IO line provided.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
OperationNotSupportedException: if the received data is not an IO mode.
"""
try:
mode = IOMode.get(self.get_parameter(io_line.at_command)[0])
except ValueError:
raise OperationNotSupportedException("The received value is not an IO mode.")
return mode
def get_io_sampling_rate(self):
"""
Returns the IO sampling rate of the XBee device.
Returns:
Integer: the IO sampling rate of XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
resp = self.get_parameter("IR")
return utils.bytes_to_int(resp) / 1000.00
def set_io_sampling_rate(self, rate):
"""
Sets the IO sampling rate of the XBee device in seconds. A sample rate of 0 means the IO sampling feature is
disabled.
Args:
rate (Integer): the new IO sampling rate of the XBee device in seconds.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
"""
self.set_parameter("IR", utils.int_to_bytes(int(rate * 1000)))
def read_io_sample(self):
"""
Returns an IO sample from the XBee device containing the value of all enabled digital IO and
analog input channels.
Returns:
:class:`.IOSample`: the IO sample read from the XBee device.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
.. seealso::
| :class:`.IOSample`
"""
# The response to the IS command in local 802.15.4 devices is empty,
# so we have to use callbacks to read the packet.
if not self.is_remote() and self.get_protocol() == XBeeProtocol.RAW_802_15_4:
lock = threading.Condition()
self.__io_packet_received = False
self.__io_packet_payload = None
def io_sample_callback(received_packet):
# Discard non API packets.
if not isinstance(received_packet, XBeeAPIPacket):
return
# If we already have received an IO packet, ignore this packet.
if self.__io_packet_received:
return
frame_type = received_packet.get_frame_type()
# Save the packet value (IO sample payload).
if (frame_type == ApiFrameType.IO_DATA_SAMPLE_RX_INDICATOR
or frame_type == ApiFrameType.RX_IO_16
or frame_type == ApiFrameType.RX_IO_64):
self.__io_packet_payload = received_packet.rf_data
else:
return
# Set the IO packet received flag.
self.__io_packet_received = True
# Continue execution by notifying the lock object.
lock.acquire()
lock.notify()
lock.release()
self._add_packet_received_callback(io_sample_callback)
try:
# Execute command.
self.execute_command("IS")
lock.acquire()
lock.wait(self.get_sync_ops_timeout())
lock.release()
if self.__io_packet_payload is None:
raise TimeoutException("Timeout waiting for the IO response packet.")
sample_payload = self.__io_packet_payload
finally:
self._del_packet_received_callback(io_sample_callback)
else:
sample_payload = self.get_parameter("IS")
try:
return IOSample(sample_payload)
except Exception as e:
raise XBeeException("Could not create the IO sample.", e)
def get_adc_value(self, io_line):
"""
Returns the analog value of the provided IO line.
The provided IO line must be previously configured as ADC. To do so,
use :meth:`.AbstractXBeeDevice.set_io_configuration` and :attr:`.IOMode.ADC`.
Args:
io_line (:class:`.IOLine`): the IO line to get its ADC value.
Returns:
Integer: the analog value corresponding to the provided IO line.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
OperationNotSupportedException: if the response does not contain the value for the given IO line.
.. seealso::
| :class:`.IOLine`
"""
io_sample = self.read_io_sample()
if not io_sample.has_analog_values() or io_line not in io_sample.analog_values.keys():
raise OperationNotSupportedException("Answer does not contain analog values for the given IO line.")
return io_sample.analog_values[io_line]
def set_pwm_duty_cycle(self, io_line, cycle):
"""
Sets the duty cycle in % of the provided IO line.
The provided IO line must be PWM-capable, previously configured as PWM output.
Args:
io_line (:class:`.IOLine`): the IO Line to be assigned.
cycle (Integer): duty cycle in % to be assigned. Must be between 0 and 100.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
ValueError: if the given IO line does not have PWM capability or ``cycle`` is not between 0 and 100.
.. seealso::
| :class:`.IOLine`
| :attr:`.IOMode.PWM`
"""
if not io_line.has_pwm_capability():
raise ValueError("%s has no PWM capability." % io_line)
if cycle < 0 or cycle > 100:
raise ValueError("Cycle must be between 0% and 100%.")
duty_cycle = int(round(cycle * 1023.00 / 100.00))
self.set_parameter(io_line.pwm_at_command, bytearray(utils.int_to_bytes(duty_cycle)))
def get_pwm_duty_cycle(self, io_line):
"""
Returns the PWM duty cycle in % corresponding to the provided IO line.
Args:
io_line (:class:`.IOLine`): the IO line to get its PWM duty cycle.
Returns:
Integer: the PWM duty cycle of the given IO line or ``None`` if the response is empty.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
ValueError: if the passed :class:`.IO_LINE` has no PWM capability.
.. seealso::
| :class:`.IOLine`
"""
if not io_line.has_pwm_capability():
raise ValueError("%s has no PWM capability." % io_line)
value = utils.bytes_to_int(self.get_parameter(io_line.pwm_at_command))
return round(((value * 100.0 / 1023.0) * 100.0) / 100.0)
def get_dio_value(self, io_line):
"""
Returns the digital value of the provided IO line.
The provided IO line must be previously configured as digital I/O.
To do so, use :meth:`.AbstractXBeeDevice.set_io_configuration`.
Args:
io_line (:class:`.IOLine`): the DIO line to gets its digital value.
Returns:
:class:`.IOValue`: current value of the provided IO line.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This
method only checks the cached value of the operating mode.
ATCommandException: if the response is not as expected.
OperationNotSupportedException: if the response does not contain the value for the given IO line.
.. seealso::
| :class:`.IOLine`
| :class:`.IOValue`
"""
sample = self.read_io_sample()
if not sample.has_digital_values() or io_line not in sample.digital_values.keys():
raise OperationNotSupportedException("Answer does not contain digital values for the given IO_LINE")
return sample.digital_values[io_line]
def set_dio_value(self, io_line, io_value):
"""
Sets the digital value (high or low) to the provided IO line.
Args:
io_line (:class:`.IOLine`): the digital IO line to sets its value.
io_value (:class:`.IOValue`): the IO value to set to the IO line.
Raises:
TimeoutException: if the response is not received before the read timeout expires.
XBeeException: if the XBee device's serial port is closed.
InvalidOperatingModeException: if the XBee device's operating mode is not API or ESCAPED API. This