-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathreader.py
More file actions
2237 lines (1810 loc) · 80.4 KB
/
reader.py
File metadata and controls
2237 lines (1810 loc) · 80.4 KB
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-2025, 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 concurrent.futures import ThreadPoolExecutor
from queue import Queue, Empty
from threading import Event
import logging
import threading
import time
from serial import SerialException
import digi.xbee.devices
from digi.xbee.models.address import XBee64BitAddress, XBee16BitAddress
from digi.xbee.models.atcomm import ATStringCommand
from digi.xbee.models.hw import HardwareVersion
from digi.xbee.models.message import (
XBeeMessage, ExplicitXBeeMessage, IPMessage, SMSMessage,
UserDataRelayMessage, BLEGAPScanLegacyAdvertisementMessage,
BLEGAPScanExtendedAdvertisementMessage, BLEGAPScanStatusMessage
)
from digi.xbee.models.mode import OperatingMode
from digi.xbee.models.options import XBeeLocalInterface
from digi.xbee.models.protocol import XBeeProtocol
from digi.xbee.models.status import ATCommandStatus
from digi.xbee.packets import factory
from digi.xbee.packets.aft import ApiFrameType
from digi.xbee.packets.common import ReceivePacket, IODataSampleRxIndicatorPacket
from digi.xbee.packets.raw import RX64Packet, RX16Packet
from digi.xbee.util import utils
from digi.xbee.exception import TimeoutException, InvalidPacketException
from digi.xbee.io import IOSample
# Maximum number of parallel callbacks.
MAX_PARALLEL_CALLBACKS = 50
EXECUTOR = ThreadPoolExecutor(max_workers=MAX_PARALLEL_CALLBACKS)
class XBeeEvent(list):
"""
This class represents a generic XBee event.
New event callbacks can be added here following this prototype:
::
def callback_prototype(*args, **kwargs):
#do something...
All of them will be executed when the event is fired.
.. seealso::
| list (Python standard class)
"""
def __call__(self, *args, **kwargs):
for func in self:
future = EXECUTOR.submit(func, *args, **kwargs)
future.add_done_callback(self.__execution_finished)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
def __iadd__(self, other):
self.append(other)
return self
def __isub__(self, other):
self.remove(other)
return self
def __execution_finished(self, future):
"""
Called when the execution of the callable has finished.
Args:
future (:class:`.Future`): Future associated to the execution of
the callable.
Raises:
Exception: If the execution of the callable raised any exception.
"""
if future.exception():
raise future.exception()
class PacketReceived(XBeeEvent):
"""
This event is fired when an XBee receives any packet, independent of
its frame type.
The callbacks for handle this events will receive the following arguments:
1. received_packet (:class:`.XBeeAPIPacket`): Received packet.
.. seealso::
| :class:`.XBeeAPIPacket`
| :class:`.XBeeEvent`
"""
class PacketReceivedFrom(XBeeEvent):
"""
This event is fired when an XBee receives any packet, independent of
its frame type.
The callbacks for handle this events will receive the following arguments:
1. received_packet (:class:`.XBeeAPIPacket`): Received packet.
2. sender (:class:`.RemoteXBeeDevice`): Remote XBee who sent the packet.
.. seealso::
| :class:`.RemoteXBeeDevice`
| :class:`.XBeeAPIPacket`
| :class:`.XBeeEvent`
"""
class DataReceived(XBeeEvent):
"""
This event is fired when an XBee receives data.
The callbacks for handle this events will receive the following arguments:
1. message (:class:`.XBeeMessage`): Message containing the data
received, the sender and the time.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.XBeeMessage`
"""
class ModemStatusReceived(XBeeEvent):
"""
This event is fired when a XBee receives a modem status packet.
The callbacks for handle this events will receive the following arguments:
1. modem_status (:class:`.ModemStatus`): Modem status received.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.ModemStatus`
"""
class IOSampleReceived(XBeeEvent):
"""
This event is fired when a XBee receives an IO packet.
This includes:
1. IO data sample RX indicator packet.
2. RX IO 16 packet.
3. RX IO 64 packet.
The callbacks that handle this event will receive the following arguments:
1. io_sample (:class:`.IOSample`): Received IO sample.
2. sender (:class:`.RemoteXBeeDevice`): Remote XBee who sent the packet.
3. time (Integer): the time in which the packet was received.
.. seealso::
| :class:`.IOSample`
| :class:`.RemoteXBeeDevice`
| :class:`.XBeeEvent`
"""
class NetworkModified(XBeeEvent):
"""
This event is fired when the network is being modified by the addition of a
new node, an existing node information is updated, a node removal, or when
the network items are cleared.
The callbacks that handle this event will receive the following arguments:
1. event_type (:class:`digi.xbee.devices.NetworkEventType`): Network
event type.
2. reason (:class:`digi.xbee.devices.NetworkEventReason`): Reason of
the event.
3. node (:class:`digi.xbee.devices.XBeeDevice` or
:class:`digi.xbee.devices.RemoteXBeeDevice`): Node added, updated
or removed from the network.
.. seealso::
| :class:`digi.xbee.devices.NetworkEventReason`
| :class:`digi.xbee.devices.NetworkEventType`
| :class:`digi.xbee.devices.RemoteXBeeDevice`
| :class:`digi.xbee.devices.XBeeDevice`
| :class:`.XBeeEvent`
"""
class DeviceDiscovered(XBeeEvent):
"""
This event is fired when an XBee discovers another remote XBee
during a discovering operation.
The callbacks that handle this event will receive the following arguments:
1. discovered_device (:class:`.RemoteXBeeDevice`): Discovered remote XBee.
.. seealso::
| :class:`.RemoteXBeeDevice`
| :class:`.XBeeEvent`
"""
class DiscoveryProcessFinished(XBeeEvent):
"""
This event is fired when the discovery process finishes, either
successfully or due to an error.
The callbacks that handle this event will receive the following arguments:
1. status (:class:`.NetworkDiscoveryStatus`): Network discovery status.
2. description (String, optional): Description of the discovery status.
.. seealso::
| :class:`.NetworkDiscoveryStatus`
| :class:`.XBeeEvent`
"""
class ExplicitDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives an explicit data packet.
The callbacks for handle this events will receive the following arguments:
1. message (:class:`.ExplicitXBeeMessage`): Message containing the
received data, the sender, the time, and explicit data message
parameters.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.XBeeMessage`
"""
class IPDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives IP data.
The callbacks for handle this events will receive the following arguments:
1. message (:class:`.IPMessage`): Message containing containing the IP
address the message belongs to, source and destination ports, IP
protocol, and the content (data) of the message.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.IPMessage`
"""
class SMSReceived(XBeeEvent):
"""
This event is fired when an XBee receives an SMS.
The callbacks for handle this events will receive the following arguments:
1. message (:class:`.SMSMessage`): Message containing the phone number
that sent the message and the content (data) of the message.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.SMSMessage`
"""
class RelayDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives a user data relay output packet.
The callbacks to handle these events will receive the following arguments:
1. message (:class:`.UserDataRelayMessage`): Message containing the
source interface and the content (data) of the message.
.. seealso::
| :class:`.XBeeEvent`
| :class:`.UserDataRelayMessage`
"""
class BluetoothDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives data from the Bluetooth interface.
The callbacks to handle these events will receive the following arguments:
1. data (Bytearray): Received Bluetooth data.
.. seealso::
| :class:`.XBeeEvent`
"""
class MicroPythonDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives data from the MicroPython interface.
The callbacks to handle these events will receive the following arguments:
1. data (Bytearray): Received MicroPython data.
.. seealso::
| :class:`.XBeeEvent`
"""
class SocketStateReceived(XBeeEvent):
"""
This event is fired when an XBee receives a socket state packet.
The callbacks to handle these events will receive the following arguments:
1. socket_id (Integer): Socket ID for state reported.
2. state (:class:`.SocketState`): Received state.
.. seealso::
| :class:`.XBeeEvent`
"""
class SocketDataReceived(XBeeEvent):
"""
This event is fired when an XBee receives a socket receive data packet.
The callbacks to handle these events will receive the following arguments:
1. socket_id (Integer): ID of the socket that received the data.
2. payload (Bytearray): Received data.
.. seealso::
| :class:`.XBeeEvent`
"""
class SocketDataReceivedFrom(XBeeEvent):
"""
This event is fired when an XBee receives a socket receive from data packet.
The callbacks to handle these events will receive the following arguments:
1. socket_id (Integer): ID of the socket that received the data.
2. address (Tuple): Pair (host, port) of the source address where
host is a string representing an IPv4 address like '100.50.200.5',
and port is an integer.
3. payload (Bytearray): Received data.
.. seealso::
| :class:`.XBeeEvent`
"""
class RouteRecordIndicatorReceived(XBeeEvent):
"""
This event is fired when a route record packet is received.
The callbacks to handle these events will receive the following arguments:
1. Source (:class:`.RemoteXBeeDevice`): Remote node that sent the
route record.
2. Hops (List): List of intermediate hops 16-bit addresses from closest
to source (who sent the route record) to closest to destination
(:class:`.XBee16BitAddress`).
.. seealso::
| :class:`.XBeeEvent`
"""
class RouteInformationReceived(XBeeEvent):
"""
This event is fired when a route information packet is received.
The callbacks to handle these events will receive the following arguments:
1. Source event (Integer): Source event (0x11: NACK, 0x12: Trace route)
2. Timestamp (Integer): System timer value on the node generating
this package. The timestamp is in microseconds.
3. ACK timeout count (Integer): Number of MAC ACK timeouts that occur.
4. TX blocked count (Integer): Number of times the transmissions was
blocked due to reception in progress.
5. Destination address (:class:`.XBee64BitAddress`): 64-bit address of
the final destination node.
6. Source address (:class:`.XBee64BitAddress`): 64-bit address of
the source node.
7. Responder address (:class:`.XBee64BitAddress`): 64-bit address of
of the node that generates this packet after it sends (or attempts
to send) the packet to the next hop (successor node)
8. Successor address (:class:`.XBee64BitAddress`): 64-bit address of
of the next node after the responder in the route towards the
destination.
.. seealso::
| :class:`.XBeeEvent`
"""
class RouteReceived(XBeeEvent):
"""
This event is fired when a route is received.
The callbacks to handle these events will receive the following arguments:
1. source (:class:`.XBeeDevice`): Local node.
2. destination (:class:`.RemoteXBeeDevice`): Remote node.
3. hops (List): List of intermediate hops from source node to
closest to destination (:class:`.RemoteXBeeDevice`).
.. seealso::
| :class:`.XBeeEvent`
"""
class InitDiscoveryScan(XBeeEvent):
"""
This event is fired when a new network discovery scan is about to start.
The callbacks to handle these events will receive the following arguments:
1. Number of scan to start (starting with 1).
2. Total number of scans.
.. seealso::
| :class:`.XBeeEvent`
"""
class EndDiscoveryScan(XBeeEvent):
"""
This event is fired when a network discovery scan has just finished.
The callbacks to handle these events will receive the following arguments:
1. Number of scan that has finished (starting with 1).
2. Total number of scans.
.. seealso::
| :class:`.XBeeEvent`
"""
class FileSystemFrameReceived(XBeeEvent):
"""
This event is fired when a file system packet is received.
The callbacks to handle these events will receive the following arguments:
1. Source (:class:`.AbstractXBeeDevice`): Node that sent the file
system frame.
2. Frame id (Integer): Received frame id.
3. Command (:class:`.FSCmd`): File system command.
4. Status (:class: `.FSCommandStatus`): Status code.
5. Receive options (Integer): Bitfield indicating receive options.
See :class:`.ReceiveOptions`.
.. seealso::
| :class:`.XBeeEvent`
"""
class BLEGAPScanReceived(XBeeEvent):
"""
This event is fired when an XBee receives data from the BLE scan interface.
The callbacks to handle these events will receive the following arguments:
1. data (Bytearray): Received Bluetooth data.
.. seealso::
| :class:`.XBeeEvent`
"""
class BLEGAPScanStatusReceived(XBeeEvent):
"""
This event is fired when an XBee receives status from the BLE
scan interface.
The callbacks for handle this events will receive the following arguments:
1. Status (:class:`.BLEGAPScanStatus`): Gap scan Status code.
.. seealso::
| :class:`.XBeeEvent`
"""
class NetworkUpdateProgress(XBeeEvent):
"""
This event is fired when the progress of a running firmware update changes.
The callbacks to handle these events will receive the following arguments:
1. The XBee being updated.
2. The current update task as a String.
3. The current update task percentage as an Integer.
.. seealso::
| :class:`.XBeeEvent`
"""
class PacketListener(threading.Thread):
"""
This class represents a packet listener, which is a thread that's always
listening for incoming packets to the XBee.
When it receives a packet, this class throws an event depending on which
packet it is. You can add your own callbacks for this events via certain
class methods. This callbacks must have a certain header, see each event
documentation.
This class has fields that are events. Its recommended to use only the
append() and remove() method on them, or -= and += operators.
If you do something more with them, it's for your own risk.
Here are the parameters which will be received by the event callbacks,
depending on which event it is in each case:
The following parameters are passed via \\*\\*kwargs to event callbacks of:
1. PacketReceived:
1.1 received_packet (:class:`.XBeeAPIPacket`): Received packet.
2. DataReceived
2.1 message (:class:`.XBeeMessage`): Message containing the data
received, the sender and the time.
3. ModemStatusReceived
3.1 modem_status (:class:`.ModemStatus`): Modem status received.
"""
__DEFAULT_QUEUE_MAX_SIZE = 40
"""
Default max. size that the queue has.
"""
_LOG_PATTERN = "{comm_iface:s} - {event:s} - {fr_type:s}: {sender:s} - {more_data:s}"
"""
Generic pattern for display received messages (high-level) with logger.
"""
_LOG_PACKET_PATTERN = "{comm_iface:s} - {event:s} - {opmode:s}: {content:s}"
"""
Pattern used to log packet events.
"""
_log = logging.getLogger(__name__)
"""
Logger.
"""
def __init__(self, comm_iface, xbee_device, queue_max_size=None):
"""
Class constructor. Instantiates a new :class:`.PacketListener` object
with the provided parameters.
Args:
comm_iface (:class:`.XBeeCommunicationInterface`): Hardware
interface to listen to.
xbee_device (:class:`.XBeeDevice`): XBee that is the listener owner.
queue_max_size (Integer): Maximum size of the XBee queue.
"""
threading.Thread.__init__(self)
self.daemon = True
# User callbacks:
self.__packet_received = PacketReceived()
self.__packet_received_from = PacketReceivedFrom()
self.__data_received = DataReceived()
self.__modem_status_received = ModemStatusReceived()
self.__io_sample_received = IOSampleReceived()
self.__explicit_packet_received = ExplicitDataReceived()
self.__ip_data_received = IPDataReceived()
self.__sms_received = SMSReceived()
self.__relay_data_received = RelayDataReceived()
self.__bluetooth_data_received = BluetoothDataReceived()
self.__micropython_data_received = MicroPythonDataReceived()
self.__socket_state_received = SocketStateReceived()
self.__socket_data_received = SocketDataReceived()
self.__socket_data_received_from = SocketDataReceivedFrom()
self.__route_record_indicator_received_from = RouteRecordIndicatorReceived()
self.__dm_route_information_received_from = RouteInformationReceived()
self.__fs_frame_received = FileSystemFrameReceived()
self.__ble_gap_scan_received = BLEGAPScanReceived()
self.__ble_gap_scan_status_received = BLEGAPScanStatusReceived()
self.__error_callbacks = []
# API internal callbacks:
self.__packet_received_api = xbee_device.get_xbee_device_callbacks()
self.__xbee = xbee_device
self.__comm_iface = comm_iface
self.__stop = True
self.__started = Event()
self.__queue_max_size = (queue_max_size if queue_max_size is not None
else self.__DEFAULT_QUEUE_MAX_SIZE)
self.__xbee_queue = XBeeQueue(self.__queue_max_size)
self.__data_xbee_queue = XBeeQueue(self.__queue_max_size)
self.__explicit_xbee_queue = XBeeQueue(self.__queue_max_size)
self.__ip_xbee_queue = XBeeQueue(self.__queue_max_size)
def _trigger_error_callbacks(self, error):
"""Call all registered error callbacks with the exception."""
for callback in self.__error_callbacks:
try:
callback(error)
except Exception as e:
# Log errors in user callbacks without crashing
self._log.error("Error in callback: %s", str(e))
def add_error_callback(self, callback):
"""Public method to let users register error callbacks."""
if callback not in self.__error_callbacks:
self.__error_callbacks.append(callback)
def remove_error_callback(self, callback):
"""Public method to remove a callback."""
if callback in self.__error_callbacks:
self.__error_callbacks.remove(callback)
def wait_until_started(self, timeout=None):
"""
Blocks until the thread has fully started. If already started, returns
immediately.
Args:
timeout (Float): Timeout for the operation in seconds.
"""
self.__started.wait(timeout)
def run(self):
"""
This is the method that will be executing for listening packets.
For each packet, it will execute the proper callbacks.
"""
try:
self.__stop = False
self.__started.set()
while not self.__stop:
try:
# Try to read a packet. Read packet is unescaped.
raw_packet = self.__comm_iface.wait_for_frame(
self.__xbee.operating_mode)
except SerialException as exc:
# SerialException: device reports readiness to read but
# returned no data (device disconnected or multiple access on port?)
# if "device reports readiness to read but returned no data" in str(exc):
# self._log.warning("Serial exception while reading: %s", exc)
# continue
# raise exc
self._trigger_error_callbacks(exec)
self.__stop = True
break
if raw_packet is not None:
# If the current protocol is 802.15.4, the packet may have
# to be discarded.
if (self.__xbee.get_protocol() == XBeeProtocol.RAW_802_15_4
and not self.__check_packet_802_15_4(raw_packet)):
continue
# Build the packet.
try:
read_packet = factory.build_frame(
raw_packet, self.__xbee.operating_mode)
except InvalidPacketException as exc:
if self.__xbee.is_open():
self._log.error("Error processing packet '%s': %s",
utils.hex_to_string(raw_packet), str(exc))
continue
self._log.debug(self._LOG_PACKET_PATTERN.format(
comm_iface=str(self.__xbee.comm_iface),
event="RECEIVED", opmode=self.__xbee.operating_mode,
content=utils.hex_to_string(raw_packet)))
# Add the packet to the queue.
self.__add_packet_queue(read_packet)
# If the packet has information about a remote device,
# extract it and add/update this remote device to/in this
# XBee's network.
remote = self.__try_add_remote_device(read_packet)
# Execute API internal callbacks.
self.__packet_received_api(read_packet)
# Execute all user callbacks.
self.__execute_user_callbacks(read_packet, remote)
except Exception as exc:
if not self.__stop:
self._log.exception(exc)
finally:
if not self.__stop:
self.__stop = True
if self.__comm_iface.is_interface_open:
self.__comm_iface.close()
def stop(self):
"""
Stops listening.
"""
self.__stop = True
self.__comm_iface.quit_reading()
# Wait until thread fully stops.
self.join()
def is_running(self):
"""
Returns whether this instance is running or not.
Returns:
Boolean: `True` if this instance is running, `False` otherwise.
"""
return not self.__stop
def get_queue(self):
"""
Returns the packets queue.
Returns:
:class:`.XBeeQueue`: Packets queue.
"""
return self.__xbee_queue
def get_data_queue(self):
"""
Returns the data packets queue.
Returns:
:class:`.XBeeQueue`: Data packets queue.
"""
return self.__data_xbee_queue
def get_explicit_queue(self):
"""
Returns the explicit packets queue.
Returns:
:class:`.XBeeQueue`: Explicit packets queue.
"""
return self.__explicit_xbee_queue
def get_ip_queue(self):
"""
Returns the IP packets queue.
Returns:
:class:`.XBeeQueue`: IP packets queue.
"""
return self.__ip_xbee_queue
def add_packet_received_callback(self, callback):
"""
Adds a callback for the event :class:`.PacketReceived`.
Args:
callback (Function or List of functions): Callback.
Receives one argument.
* The received packet as a :class:`.XBeeAPIPacket`
"""
if isinstance(callback, list):
self.__packet_received.extend(callback)
elif callback:
self.__packet_received += callback
def add_packet_received_from_callback(self, callback):
"""
Adds a callback for the event :class:`.PacketReceivedFrom`.
Args:
callback (Function or List of functions): Callback. Receives
two arguments.
* The received packet as a :class:`.XBeeAPIPacket`
* The remote XBee device who has sent the packet as a
:class:`.RemoteXBeeDevice`
"""
if isinstance(callback, list):
self.__packet_received_from.extend(callback)
elif callback:
self.__packet_received_from += callback
def add_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.DataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as an :class:`.XBeeMessage`
"""
if isinstance(callback, list):
self.__data_received.extend(callback)
elif callback:
self.__data_received += callback
def add_modem_status_received_callback(self, callback):
"""
Adds a callback for the event :class:`.ModemStatusReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The modem status as a :class:`.ModemStatus`
"""
if isinstance(callback, list):
self.__modem_status_received.extend(callback)
elif callback:
self.__modem_status_received += callback
def add_io_sample_received_callback(self, callback):
"""
Adds a callback for the event :class:`.IOSampleReceived`.
Args:
callback (Function or List of functions): Callback. Receives three
arguments.
* The received IO sample as an :class:`.IOSample`
* The remote XBee device who has sent the packet as a
:class:`.RemoteXBeeDevice`
* The time in which the packet was received as an Integer
"""
if isinstance(callback, list):
self.__io_sample_received.extend(callback)
elif callback:
self.__io_sample_received += callback
def add_explicit_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.ExplicitDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The explicit data received as an :class:`.ExplicitXBeeMessage`
"""
if isinstance(callback, list):
self.__explicit_packet_received.extend(callback)
elif callback:
self.__explicit_packet_received += callback
def add_ip_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.IPDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as an :class:`.IPMessage`
"""
if isinstance(callback, list):
self.__ip_data_received.extend(callback)
elif callback:
self.__ip_data_received += callback
def add_sms_received_callback(self, callback):
"""
Adds a callback for the event :class:`.SMSReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as an :class:`.SMSMessage`
"""
if isinstance(callback, list):
self.__sms_received.extend(callback)
elif callback:
self.__sms_received += callback
def add_user_data_relay_received_callback(self, callback):
"""
Adds a callback for the event :class:`.RelayDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as a :class:`.UserDataRelayMessage`
"""
if isinstance(callback, list):
self.__relay_data_received.extend(callback)
elif callback:
self.__relay_data_received += callback
def add_bluetooth_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.BluetoothDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as a Bytearray
"""
if isinstance(callback, list):
self.__bluetooth_data_received.extend(callback)
elif callback:
self.__bluetooth_data_received += callback
def add_micropython_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.MicroPythonDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives one
argument.
* The data received as a Bytearray
"""
if isinstance(callback, list):
self.__micropython_data_received.extend(callback)
elif callback:
self.__micropython_data_received += callback
def add_socket_state_received_callback(self, callback):
"""
Adds a callback for the event :class:`.SocketStateReceived`.
Args:
callback (Function or List of functions): Callback. Receives two
arguments.
* The socket ID as an Integer.
* The state received as a :class:`.SocketState`
"""
if isinstance(callback, list):
self.__socket_state_received.extend(callback)
elif callback:
self.__socket_state_received += callback
def add_socket_data_received_callback(self, callback):
"""
Adds a callback for the event :class:`.SocketDataReceived`.
Args:
callback (Function or List of functions): Callback. Receives two
arguments.
* The socket ID as an Integer.
* The status received as a :class:`.SocketStatus`
"""
if isinstance(callback, list):
self.__socket_data_received.extend(callback)
elif callback:
self.__socket_data_received += callback
def add_socket_data_received_from_callback(self, callback):
"""
Adds a callback for the event :class:`.SocketDataReceivedFrom`.
Args:
callback (Function or List of functions): Callback. Receives three
arguments.
* The socket ID as an Integer.
* A pair (host, port) of the source address where host is a
string representing an IPv4 address like '100.50.200.5',
and port is an integer.
* The status received as a :class:`.SocketStatus`
"""
if isinstance(callback, list):
self.__socket_data_received_from.extend(callback)
elif callback:
self.__socket_data_received_from += callback
def add_route_record_received_callback(self, callback):
"""
Adds a callback for the event :class:`.RouteRecordIndicatorReceived`.
Args:
callback (Function or List of functions): Callback. Receives two
arguments.
* Source (:class:`.RemoteXBeeDevice`): Remote node that sent
the route record.
* Hops (List): List of intermediate hops 16-bit addresses from
closest to source (who sent the route record) to closest to
destination.
"""
if isinstance(callback, list):
self.__route_record_indicator_received_from.extend(callback)
elif callback:
self.__route_record_indicator_received_from += callback
def add_route_info_received_callback(self, callback):
"""
Adds a callback for the event :class:`.RouteInformationReceived`.
Args:
callback (Function or List of functions): Callback. Receives eight
arguments.
* Source event (Integer): Source event (0x11: NACK,
0x12: Trace route)
* Timestamp (Integer): System timer value on the node