forked from bensherlock/nm3-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnm3driver.py
More file actions
1580 lines (1221 loc) · 60.4 KB
/
nm3driver.py
File metadata and controls
1580 lines (1221 loc) · 60.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
#! /usr/bin/env python
#
# Python Driver for NM3
#
# This file is part of NM3 Python Driver. https://github.com/bensherlock/nm3-python-driver
#
#
# MIT License
#
# Copyright (c) 2019 Benjamin Sherlock <benjamin.sherlock@ncl.ac.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""Python driver for the NM3 over serial port."""
from collections import deque
import struct
from typing import Tuple, Union, List
import time
class MessagePacket:
"""NM3 Message Packet Structure."""
# Packet Type "Enums"
PACKETTYPE_BROADCAST, PACKETTYPE_UNICAST = 'B', 'U'
PACKETTYPE_NAMES = {
PACKETTYPE_BROADCAST: 'Broadcast',
PACKETTYPE_UNICAST: 'Unicast',
}
NAMES_PACKETTYPE = {
'Broadcast': PACKETTYPE_BROADCAST,
'Unicast': PACKETTYPE_UNICAST,
}
PACKETTYPES = (PACKETTYPE_BROADCAST, PACKETTYPE_UNICAST)
def __init__(self, source_address=None, destination_address=None, packet_type=None, packet_payload=None,
packet_lqi=None, packet_doppler=None,
packet_timestamp_count=None):
self._source_address = source_address
self._destination_address = destination_address
self._packet_type = packet_type
self._packet_payload = packet_payload
self._packet_lqi = packet_lqi # Optional link quality indicator (LQI)
self._packet_doppler = packet_doppler # Optional Doppler tracking
self._packet_timestamp_count = packet_timestamp_count # Optional timestamp
self._serial_string = None # The processed received uart string
def __call__(self):
return self
@property
def source_address(self) -> int:
"""Gets the source address."""
return self._source_address
@source_address.setter
def source_address(self,
source_address: int):
"""Sets the the source address (0-255)."""
if source_address and (source_address < 0 or source_address > 255):
raise ValueError('Invalid Address Value (0-255): {!r}'.format(source_address))
self._source_address = source_address
@property
def destination_address(self) -> int:
"""Gets the destination address."""
return self._destination_address
@destination_address.setter
def destination_address(self,
destination_address: int):
"""Sets the the destination address (0-255)."""
if destination_address and (destination_address < 0 or destination_address > 255):
raise ValueError('Invalid Address Value (0-255): {!r}'.format(destination_address))
self._destination_address = destination_address
@property
def packet_type(self):
"""Gets the packet type (unicast, broadcast)."""
return self._packet_type
@packet_type.setter
def packet_type(self,
packet_type):
"""Sets the the packet type (unicast, broadcast)."""
if packet_type not in self.PACKETTYPES:
raise ValueError('Invalid Packet Type: {!r}'.format(packet_type))
self._packet_type = packet_type
@property
def packet_payload(self):
"""Gets the packet payload bytes."""
return self._packet_payload
@packet_payload.setter
def packet_payload(self,
packet_payload):
"""Sets the the packet payload bytes ."""
self._packet_payload = packet_payload
@property
def packet_lqi(self):
"""Gets the packet LQI - a number between 00 and 99 inclusive."""
return self._packet_lqi
@packet_lqi.setter
def packet_lqi(self, packet_lqi):
self._packet_lqi = packet_lqi
@property
def packet_doppler(self):
"""Gets the packet Doppler - a number between +/-999 and 999 inclusive."""
return self._packet_doppler
@packet_doppler.setter
def packet_doppler(self, packet_doppler):
self._packet_doppler = packet_doppler
@property
def packet_timestamp_count(self):
"""Gets the packet timestamp count - a counter at 1MHz."""
return self._packet_timestamp_count
@packet_timestamp_count.setter
def packet_timestamp_count(self,
packet_timestamp_count):
"""Sets the packet timestamp count - a counter at 1MHz."""
self._packet_timestamp_count = packet_timestamp_count
@property
def serial_string(self) -> str:
return self._serial_string
@serial_string.setter
def serial_string(self, serial_string: str):
self._serial_string = serial_string
def json(self):
"""Returns a json dictionary representation."""
jason = {"SourceAddress": self._source_address,
"DestinationAddress": self._destination_address,
"PacketType": MessagePacket.PACKETTYPE_NAMES[self._packet_type],
"PayloadLength": len(self._packet_payload),
"PayloadBytes": self._packet_payload,
"PacketLqi": self._packet_lqi,
"PacketDoppler": self._packet_doppler,
"PacketTimestampCount": self._packet_timestamp_count
}
return jason
@classmethod
def from_json(cls, jason):
"""Constructs a MessagePacket from a json dictionary representation."""
# convert packet type name to packet Type
packet_type_name = jason.get("PacketType")
packet_type = None
if packet_type_name:
packet_type = cls.NAMES_PACKETTYPE.get(packet_type_name)
message_packet = cls(source_address=jason.get("SourceAddress"),
destination_address=jason.get("DestinationAddress"),
packet_type=packet_type,
packet_payload=jason.get("PayloadBytes"),
packet_lqi=jason.get("PacketLqi"),
packet_doppler=jason.get("PacketDoppler"),
packet_timestamp_count=jason.get("PacketTimestampCount")
)
return message_packet
class MessagePacketParser:
"""Message Packet Parser takes bytes and uses a state machine to construct
MessagePacket structures"""
PARSERSTATE_IDLE, PARSERSTATE_TYPE, \
PARSERSTATE_ADDRESS, PARSERSTATE_LENGTH, \
PARSERSTATE_PAYLOAD, PARSERSTATE_ADDENDUMFLAG, PARSERSTATE_LQI, PARSERSTATE_DOPPLER, PARSERSTATE_TIMESTAMP = range(9)
PARSERSTATE_NAMES = {
PARSERSTATE_IDLE: 'Idle',
PARSERSTATE_TYPE: 'Type',
PARSERSTATE_ADDRESS: 'Address',
PARSERSTATE_LENGTH: 'Length',
PARSERSTATE_PAYLOAD: 'Payload',
PARSERSTATE_ADDENDUMFLAG: 'AddendumFlag',
PARSERSTATE_LQI: 'Lqi',
PARSERSTATE_DOPPLER: 'Doppler',
PARSERSTATE_TIMESTAMP: 'Timestamp'
}
PARSERSTATES = (PARSERSTATE_IDLE, PARSERSTATE_TYPE,
PARSERSTATE_ADDRESS, PARSERSTATE_LENGTH,
PARSERSTATE_PAYLOAD, PARSERSTATE_ADDENDUMFLAG, PARSERSTATE_LQI, PARSERSTATE_DOPPLER, PARSERSTATE_TIMESTAMP)
def __init__(self):
self._parser_state = self.PARSERSTATE_IDLE
self._current_message_packet = None
self._current_byte_counter = 0
self._current_integer = 0
self._current_integer_sign = 1
self._current_serial_string = None
self._packet_queue = deque()
def __call__(self):
return self
def reset(self):
"""Resets the parser state machine."""
self._parser_state = self.PARSERSTATE_IDLE
self._current_message_packet = None
self._current_byte_counter = 0
self._current_integer = 0
self._current_integer_sign = 1
self._current_serial_string = None
def process(self, next_byte) -> bool:
"""Process the next byte. Returns True if a packet completes on this byte."""
# Received Message Structures:
# '#B25500' + payload bytes + '\r\n'
# '#U00' + payload bytes + '\r\n'
# Or for some NM3 firmware versions:
# '#B25500' + payload bytes + 'T' + timestamp + '\r\n'
# '#U00' + payload bytes + 'T' + timestamp + '\r\n'
# Where timestamp is a 10 digit (fixed width) number representing a 32-bit counter value
# on a 24 MHz clock which is latched when the synch waveform arrives
# Or for future release firmware versions (v1.1.0+)
# '#B25500' + payload bytes + 'Q' + lqi + 'D' + doppler + '\r\n'
# '#U00' + payload bytes + 'Q' + lqi + 'D' + doppler + '\r\n'
# And if we end up with mix and match addendums/addenda
# '#B25500' + payload bytes + 'Q' + lqi + 'D' + doppler + 'T' + timestamp + '\r\n'
# '#U00' + payload bytes + 'T' + timestamp + 'Q' + lqi + 'D' + doppler + '\r\n'
return_flag = False
# decoding_str = 'utf-8' # If payload bytes are 0xaa etc they're invalid in utf-8
decoding_str = 'iso-8859-1' # Shouldn't balk in the same way that utf-8 does
# print('next_byte: ' + bytes([next_byte]).decode(decoding_str))
if self._parser_state != self.PARSERSTATE_IDLE:
# Store bytes
self._current_serial_string = self._current_serial_string + bytes([next_byte]).decode(decoding_str)
if self._parser_state == self.PARSERSTATE_IDLE:
if bytes([next_byte]).decode(decoding_str) == '#':
self._current_serial_string = '#'
# Next state
self._parser_state = self.PARSERSTATE_TYPE
elif self._parser_state == self.PARSERSTATE_TYPE:
if bytes([next_byte]).decode(decoding_str) == 'B':
self._current_message_packet = MessagePacket()
self._current_message_packet.source_address = 0
self._current_message_packet.destination_address = None
self._current_message_packet.packet_type = MessagePacket.PACKETTYPE_BROADCAST
self._current_message_packet.packet_payload = []
self._current_message_packet.packet_timestamp_count = 0
self._current_byte_counter = 3
self._current_integer = 0
self._parser_state = self.PARSERSTATE_ADDRESS
elif bytes([next_byte]).decode(decoding_str) == 'U':
self._current_message_packet = MessagePacket()
self._current_message_packet.source_address = None
self._current_message_packet.destination_address = None
self._current_message_packet.packet_type = MessagePacket.PACKETTYPE_UNICAST
self._current_message_packet.packet_payload = []
self._current_message_packet.packet_timestamp_count = 0
self._current_byte_counter = 2
self._current_integer = 0
self._parser_state = self.PARSERSTATE_LENGTH
else:
# Unknown packet type
self._parser_state = self.PARSERSTATE_IDLE
elif self._parser_state == self.PARSERSTATE_ADDRESS:
self._current_byte_counter = self._current_byte_counter - 1
# Append the next ascii string integer digit
self._current_integer = (self._current_integer * 10) + int(bytes([next_byte]).decode(decoding_str))
if self._current_byte_counter == 0:
self._current_message_packet.source_address = self._current_integer
self._current_integer = 0
self._current_byte_counter = 2
self._parser_state = self.PARSERSTATE_LENGTH
elif self._parser_state == self.PARSERSTATE_LENGTH:
self._current_byte_counter = self._current_byte_counter - 1
# Append the next ascii string integer digit
self._current_integer = (self._current_integer * 10) + int(bytes([next_byte]).decode(decoding_str))
if self._current_byte_counter == 0:
self._current_byte_counter = self._current_integer
self._parser_state = self.PARSERSTATE_PAYLOAD
elif self._parser_state == self.PARSERSTATE_PAYLOAD:
self._current_byte_counter = self._current_byte_counter - 1
self._current_message_packet.packet_payload.append(next_byte)
if self._current_byte_counter == 0:
# Completed this packet
self._parser_state = self.PARSERSTATE_ADDENDUMFLAG
elif self._parser_state == self.PARSERSTATE_ADDENDUMFLAG:
# Timestamp Addendum
if bytes([next_byte]).decode(decoding_str) == 'T':
self._current_byte_counter = 14
self._current_integer = 0
self._current_integer_sign = 1
self._parser_state = self.PARSERSTATE_TIMESTAMP
# LQI Addendum
elif bytes([next_byte]).decode(decoding_str) == 'Q':
self._current_byte_counter = 2
self._current_integer = 0
self._current_integer_sign = 1
self._parser_state = self.PARSERSTATE_LQI
# Doppler Addendum
elif bytes([next_byte]).decode(decoding_str) == 'D':
self._current_byte_counter = 4
self._current_integer = 0
self._current_integer_sign = 1
self._parser_state = self.PARSERSTATE_DOPPLER
# Unrecognised or no addendum
else:
# No recognised addendum on this message. Completed Packet
self._current_message_packet.serial_string = self._current_serial_string
self._current_serial_string = None
self._packet_queue.append(self._current_message_packet)
self._current_message_packet = None
return_flag = True
self._parser_state = self.PARSERSTATE_IDLE
elif self._parser_state == self.PARSERSTATE_TIMESTAMP:
self._current_byte_counter = self._current_byte_counter - 1
# Append the next ascii string integer digit
self._current_integer = (self._current_integer * 10) + int(bytes([next_byte]).decode(decoding_str))
if self._current_byte_counter == 0:
# Completed this addendum
self._current_message_packet.packet_timestamp_count = self._current_integer
# Back to checking for further addendums/addenda
self._parser_state = self.PARSERSTATE_ADDENDUMFLAG
elif self._parser_state == self.PARSERSTATE_LQI:
self._current_byte_counter = self._current_byte_counter - 1
# Append the next ascii string integer digit
self._current_integer = (self._current_integer * 10) + int(bytes([next_byte]).decode(decoding_str))
if self._current_byte_counter == 0:
# Completed this addendum
self._current_message_packet.packet_lqi = self._current_integer
# Back to checking for further addendums/addenda
self._parser_state = self.PARSERSTATE_ADDENDUMFLAG
elif self._parser_state == self.PARSERSTATE_DOPPLER:
self._current_byte_counter = self._current_byte_counter - 1
# Check for + or -
if bytes([next_byte]).decode(decoding_str) == '+':
self._current_integer_sign = 1
elif bytes([next_byte]).decode(decoding_str) == '-':
self._current_integer_sign = -1
else:
# Append the next ascii string integer digit
self._current_integer = (self._current_integer * 10) + (self._current_integer_sign * int(bytes([next_byte]).decode(decoding_str)))
if self._current_byte_counter == 0:
# Completed this addendum
self._current_message_packet.packet_doppler = self._current_integer
# Back to checking for further addendums/addenda
self._parser_state = self.PARSERSTATE_ADDENDUMFLAG
else:
# Unknown state
self._parser_state = self.PARSERSTATE_IDLE
return return_flag
def has_packet(self) -> bool:
"""Has packets in the queue."""
if self._packet_queue:
return True
return False
def get_packet(self) -> Union[MessagePacket, None]:
"""Gets the next received packet or None if the queue is empty.
"""
if not self._packet_queue:
return None
# Pop the packet from the queue
packet = self._packet_queue.popleft()
return packet
class Nm3ResponseParser:
"""Parser for responses to commands."""
PARSERSTATE_IDLE, PARSERSTATE_STRING = range(2)
PARSERSTATE_NAMES = {
PARSERSTATE_IDLE: 'Idle',
PARSERSTATE_STRING: 'String',
}
PARSERSTATES = (PARSERSTATE_IDLE, PARSERSTATE_STRING)
def __init__(self):
self._parser_state = self.PARSERSTATE_IDLE
self._current_bytes = []
self._current_byte_counter = 0
self._delimiter_byte = ord('\n')
self._has_response_flag = False
def reset(self):
"""Resets the parser state machine."""
self._parser_state = self.PARSERSTATE_IDLE
self._current_bytes = []
self._current_byte_counter = 0
self._has_response_flag = False
def set_delimiter_byte(self, delimiter_byte):
self._delimiter_byte = delimiter_byte
def process(self, next_byte) -> bool:
"""Process the next byte. Returns True if a response completes on this byte."""
return_flag = False
# decoding_str = 'utf-8' # If payload bytes are 0xaa etc they're invalid in utf-8
decoding_str = 'iso-8859-1' # Shouldn't balk in the same way that utf-8 does
# print('next_byte: ' + bytes([next_byte]).decode(decoding_str))
if self._parser_state == self.PARSERSTATE_IDLE:
if (bytes([next_byte]).decode(decoding_str) == '#') or (bytes([next_byte]).decode(decoding_str) == '$'):
# Next state
self._current_bytes = [next_byte] # Include the '#' or '$' character.
self._current_byte_counter = 1
self._parser_state = self.PARSERSTATE_STRING
elif self._parser_state == self.PARSERSTATE_STRING:
self._current_bytes.append(next_byte)
self._current_byte_counter = self._current_byte_counter + 1
# Check delimiter
if next_byte == self._delimiter_byte:
self._has_response_flag = True
return_flag = True
self._parser_state = self.PARSERSTATE_IDLE
else:
# Unknown
self._parser_state = self.PARSERSTATE_IDLE
return return_flag
def has_response(self):
return self._has_response_flag
def get_last_response_string(self):
# decoding_str = 'utf-8' # If payload bytes are 0xaa etc they're invalid in utf-8
decoding_str = 'iso-8859-1' # Shouldn't balk in the same way that utf-8 does
return bytes(self._current_bytes).decode(decoding_str)
class Nm3:
"""NM3 Driver over Serial Port."""
RESPONSE_TIMEOUT = 0.5
def __init__(self, input_stream, output_stream):
"""Constructor. input_stream and output_stream need to be (bytes) IO with
non-blocking Read() and Write() binary functions."""
self._input_stream = input_stream
self._output_stream = output_stream
self._incoming_bytes_buffer = deque() # List/Deque of integers
self._received_packet_parser = MessagePacketParser()
def __call__(self):
return self
def query_status(self):
"""Query the modem status ($? command).
Returns the address and battery voltage.
In newer firmware versions (v1.1.0+) it also returns the semantic version number and the build date."""
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$?'
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp_bytes = self._input_stream.read()
for b in resp_bytes:
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# 0123456789012 012345678901234567890123456789012345678901234
# Expecting '#A255V21941\r\n' or '#A255V21941R001.001.000B2021-05-26T09:23:46\r\n'
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 11 or resp_string[0:2] != '#A':
return -1
addr_string = resp_string[2:5]
addr_int = int(addr_string)
adc_string = resp_string[6:11]
adc_int = int(adc_string)
# Convert the ADC value to a float voltage. V = adc_int * 15 / 65536.
voltage = float(adc_int) * 15.0 / 65536.0
version_string = ''
build_date_string = ''
if len(resp_string) >= 23:
version_string = resp_string[12:23]
if len(resp_string) >= 43:
build_date_string = resp_string[24:43]
return addr_int, voltage, version_string, build_date_string
def get_address(self) -> int:
"""Gets the NM3 Address (000-255)."""
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$?'
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp_bytes = self._input_stream.read()
for b in resp_bytes:
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '#A255V21941\r\n'
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 5 or resp_string[0:2] != '#A':
return -1
addr_string = resp_string[2:5]
addr_int = int(addr_string)
return addr_int
def set_address(self,
address: int) -> int:
"""Sets the NM3 Address (000-255)."""
# Checks on parameters
if address < 0 or address > 255:
print('Invalid address (0-255): ' + str(address))
return -1
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$A' + '{:03d}'.format(address)
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp_bytes = self._input_stream.read()
for b in resp_bytes:
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '#A255\r\n' 7 bytes
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 5 or resp_string[0:2] != '#A':
return -1
addr_string = resp_string[2:5]
addr_int = int(addr_string)
return addr_int
def get_battery_voltage(self) -> float:
"""Gets the NM3 Battery Voltage."""
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$?'
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp_bytes = self._input_stream.read()
for b in resp_bytes:
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '#A255V21941\r\n'
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 11 or resp_string[0:2] != '#A':
return -1
adc_string = resp_string[6:11]
adc_int = int(adc_string)
# Convert the ADC value to a float voltage. V = adc_int * 15 / 65536.
voltage = float(adc_int) * 15.0 / 65536.0
return voltage
def measure_local_ambient_noise(self):
"""Measure the local ambient noise for a duration of around 1 second.
Returns RMS, P2P (peak-to-peak) and MM (mean magnitude) values in ADC units.
rms_int, p2p_int, mm_int"""
timeout = 2.0 # 2 second fixed timeout
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$N'
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
resp_bytes = deque() # Create the queue object for first response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp = self._input_stream.read()
if resp:
for b in resp:
resp_bytes.append(b)
if resp_bytes:
while resp_bytes:
b = resp_bytes.popleft()
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '$N\r\n' 4 bytes
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 4 or resp_string[0:2] != '$N': # E
return -1
# Now await the measurement after around 1 second
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + timeout
while awaiting_response and (time.time() < timeout_time):
resp = self._input_stream.read()
if resp:
for b in resp:
resp_bytes.append(b)
if resp_bytes:
while resp_bytes:
b = resp_bytes.popleft()
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# 0123456789012345678901234
# Expecting '#NR123456P123456M123456\r\n' 25 bytes
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 25 or resp_string[0:2] != '#N': #
return -1
rms_string = resp_string[3:9]
rms_int = int(rms_string)
p2p_string = resp_string[10:16]
p2p_int = int(p2p_string)
mm_string = resp_string[17:23]
mm_int = int(mm_string)
return rms_int, p2p_int, mm_int
def measure_local_noise_spectrum(self):
"""Measure the local noise spectrum for a duration of around 2 seconds.
Returns bin count and FFT values in ADC units.
Returned bin count is equivalent to NFFT/2 + 1, the returned values occupy the positive frequency bins
from DC to Nyquist/2 inclusive.
Sampling frequency on the device is 160kHz, for NFFT=512 the bin width = 312.5Hz."""
# decoding_str = 'utf-8' # If payload bytes are 0xaa etc they're invalid in utf-8
decoding_str = 'iso-8859-1' # Shouldn't balk in the same way that utf-8 does
timeout = 6.0 # 6 second fixed timeout
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$S'
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
resp_bytes = deque() # Create the queue object for first response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp = self._input_stream.read()
if resp:
for b in resp:
resp_bytes.append(b)
if resp_bytes:
while resp_bytes:
b = resp_bytes.popleft()
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '$S\r\n' 4 bytes
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 4 or resp_string[0:2] != '$S': # E
return -1
# Now await the measurement after around 2 seconds
# '#Snnnnnbbbbbbbbbbbbb\r\n Expected response is ascii count then binary data.
#
# Await the response
PARSERSTATE_IDLE, PARSERSTATE_HASH, PARSERSTATE_COUNT, PARSERSTATE_DATA = range(4)
parser_state = PARSERSTATE_IDLE
current_byte_counter = 5 # For ascii integer
current_integer = 0 # For ascii integer
current_data_bytes = []
data_count = 0
data_value_size = 2
data_values = []
awaiting_response = True
timeout_time = time.time() + timeout
while awaiting_response and (time.time() < timeout_time):
resp = self._input_stream.read()
if resp:
for b in resp:
resp_bytes.append(b)
if resp_bytes:
while resp_bytes:
b = resp_bytes.popleft()
if parser_state == PARSERSTATE_IDLE:
if bytes([b]).decode(decoding_str) == '#':
parser_state = PARSERSTATE_HASH
pass
elif parser_state == PARSERSTATE_HASH:
if bytes([b]).decode(decoding_str) == 'S':
current_byte_counter = 5 # For ascii integer
current_integer = 0 # For ascii integer
parser_state = PARSERSTATE_COUNT
pass
elif parser_state == PARSERSTATE_COUNT:
current_byte_counter = current_byte_counter - 1
# Append the next ascii string integer digit
current_integer = (current_integer * 10) + int(bytes([b]).decode(decoding_str))
if current_byte_counter == 0:
data_count = current_integer
current_integer = 0
current_byte_counter = data_count * data_value_size
current_data_bytes = []
parser_state = PARSERSTATE_DATA
pass
elif parser_state == PARSERSTATE_DATA:
current_byte_counter = current_byte_counter - 1
current_data_bytes.append(b)
if current_byte_counter == 0:
# Convert the bytes into integers - https://docs.python.org/3/library/struct.html
data_values = struct.unpack('<' + str(data_count) + 'H', bytes(bytearray(current_data_bytes)))
parser_state = PARSERSTATE_IDLE
# Got a response
awaiting_response = False
pass
else:
# Unknown state
parser_state = PARSERSTATE_IDLE
pass
if awaiting_response:
return -1
return data_count, data_values
def send_ping(self,
address: int,
timeout: float = 5.0) -> float:
"""Sends a ping to the addressed node and returns the one way time of flight in seconds
from this device to the node address provided.
"""
# Checks on parameters
if address < 0 or address > 255:
print('Invalid address (0-255): ' + str(address))
return -1
# Absorb any incoming bytes into the receive buffers to process later
self.poll_receiver()
response_parser = Nm3ResponseParser()
# Write the command to the serial port
cmd_string = '$P' + '{:03d}'.format(address)
cmd_bytes = cmd_string.encode('utf-8')
# Check that it has written all the bytes. Return error if not.
if self._output_stream.write(cmd_bytes) != len(cmd_bytes):
print('Error writing command')
return -1
# Await the response
resp_bytes = deque() # Create the queue object for first response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + Nm3.RESPONSE_TIMEOUT
while awaiting_response and (time.time() < timeout_time):
resp = self._input_stream.read()
if resp:
for b in resp:
resp_bytes.append(b)
if resp_bytes:
while resp_bytes:
b = resp_bytes.popleft()
if response_parser.process(b):
# Got a response
awaiting_response = False
break
if not response_parser.has_response():
return -1
# Expecting '$P255\r\n' 7 bytes
resp_string = response_parser.get_last_response_string()
if not resp_string or len(resp_string) < 5 or resp_string[0:2] != '$P': # E
return -1
# Now await the range or TO after 4 seconds
# Await the response
response_parser.reset()
awaiting_response = True
timeout_time = time.time() + timeout