-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathubx_cmd.py
1700 lines (1478 loc) · 63 KB
/
ubx_cmd.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
import logging
logger = logging.getLogger(__name__)
import io
import queue
import string
import threading
import time
from enum import Enum, IntEnum, IntFlag, unique
from typing import Any, List, Tuple, Union
import serial
# class for communicating with u-blox GPS receivers
# supports UBX, NMEA, and RTCM3 protocols
# this module (mostly) supports every protocol version released
# u-blox 5 series - protocol version 10.00 - 12.02
# u-blox 6 series - protocol version 12.00 - 13.03
# u-blox M6 series (GPS+GLONASS+QZSS) - protocol version 14.00
# ref: u-blox document GPS.G6-SW-10018
# u-blox 7 series - protocol version 14.00
# ref: u-blox document GPS.G7-SW-12001-B1 - https://content.u-blox.com/sites/default/files/products/documents/u-blox7-V14_ReceiverDescriptionProtocolSpec_%28GPS.G7-SW-12001%29_Public.pdf
# u-blox 8 series - protocol version 15.00 - 23.01
# ref: u-blox document UBX-13003221 - https://content.u-blox.com/sites/default/files/products/documents/u-blox8-M8_ReceiverDescrProtSpec_UBX-13003221.pdf
# u-blox 9 series - protocol version 32.01
# ref: u-blox document UBX-21022436 - https://content.u-blox.com/sites/default/files/u-blox-M9-SPG-4.04_InterfaceDescription_UBX-21022436.pdf
# u-blox 10 series - protocol version 34.10
# ref: u-blox document UBX-21035062 - https://content.u-blox.com/sites/default/files/u-blox-M10-SPG-5.10_InterfaceDescription_UBX-21035062.pdf
# only tested with hardware I have access to, which is currently:
# MAX-M8Q
# SAM-M8Q
# MAX-7Q
class UbxCmd:
@unique
class PORT(IntEnum):
I2C = 0
UART1 = 1
UART2 = 2
USB = 3
SPI = 4
@unique
class INOUT_PROTOCOL(IntFlag):
NONE = 0
UBX = 1 << 0
NMEA = 1 << 1
RTCM = 1 << 2
RTCM3 = 1 << 5
ALL = UBX | NMEA | RTCM | RTCM3
@unique
class GNSS_ID_AUGMENT(IntEnum):
SBAS = 1
IMES = 4
QZSS = 5
@unique
class GNSS_ID_MAJOR(IntEnum):
GPS = 0
Galileo = 2
BeiDou = 3
GLONASS = 6
@unique
class SBAS_PRN(IntFlag):
NONE = 0
PRN120 = 1 << 0
PRN121 = 1 << 1
PRN122 = 1 << 2
PRN123 = 1 << 3
PRN124 = 1 << 4
PRN125 = 1 << 5
PRN126 = 1 << 6
PRN127 = 1 << 7
PRN128 = 1 << 8
PRN129 = 1 << 9
PRN130 = 1 << 10
PRN131 = 1 << 11
PRN132 = 1 << 12
PRN133 = 1 << 13
PRN134 = 1 << 14
PRN135 = 1 << 15
PRN136 = 1 << 16
PRN137 = 1 << 17
PRN138 = 1 << 18
PRN139 = 1 << 19
PRN140 = 1 << 20
PRN141 = 1 << 21
PRN142 = 1 << 22
PRN143 = 1 << 23
PRN144 = 1 << 24
PRN145 = 1 << 25
PRN146 = 1 << 26
PRN147 = 1 << 27
PRN148 = 1 << 28
PRN149 = 1 << 29
PRN150 = 1 << 30
PRN151 = 1 << 31
PRN152 = 1 << 32
PRN153 = 1 << 33
PRN154 = 1 << 34
PRN155 = 1 << 35
PRN156 = 1 << 36
PRN157 = 1 << 37
PRN158 = 1 << 38
ALL = (
PRN120
| PRN121
| PRN122
| PRN123
| PRN124
| PRN125
| PRN126
| PRN127
| PRN128
| PRN129
| PRN130
| PRN131
| PRN132
| PRN133
| PRN134
| PRN135
| PRN136
| PRN137
| PRN138
| PRN139
| PRN140
| PRN141
| PRN142
| PRN143
| PRN144
| PRN145
| PRN146
| PRN147
| PRN148
| PRN149
| PRN150
| PRN151
| PRN152
| PRN153
| PRN154
| PRN155
| PRN156
| PRN157
| PRN158
)
def thread_tx(self) -> None:
# thread that handles transmitting data frames to receiver (or file)
time.sleep(0.001) # yield to make sure all threads have started
while True:
while self.write is False or self.stream is None:
time.sleep(0.2)
# wait forever for new data
tx_item = self.tx_queue.get(block=True, timeout=None)
if tx_item is None: # canary value to break out of infinite loop
self.tx_queue.task_done()
break
self.stream.write(tx_item)
self.tx_queue.task_done()
if self.read is True:
time.sleep(0.001) # yield to read threads after TX completes
def thread_rx(self) -> None:
# thread that handles receiving data frames from receiver (or file)
time.sleep(0.001) # yield to make sure all threads have started
# handles data input by stuffing into buffers, and doing minimal parsing to look for the end of the transmission before sending to queue to be fully parsed in another thread
class rx_states(Enum):
BEGIN = 1
RX_NMEA = 2
RX_UBX = 3
RX_RTCM3 = 4
RX_BUFF_SIZE = 128
rx_buff = bytearray(RX_BUFF_SIZE)
rx_buff_pos = 0
rx_state = rx_states.BEGIN
NMEA_BUFF_SIZE = 256 # usually NMEA sentences are max 82 chars, but ubx receivers can go longer if UBX-CFG-NMEA flags limit82 is unset (default)
nmea_buff = bytearray(NMEA_BUFF_SIZE)
nmea_buff_pos = 0
UBX_BUFF_SIZE = (
2 + 4 + 0xFFFF + 2
) # max possible size for a UBX message µB + header + data + checksum
ubx_buff = bytearray(UBX_BUFF_SIZE)
ubx_buff_pos = 0
RTCM3_BUFF_SIZE = (
3 + 1023 + 3
) # max possible size for a RTCM3 message header + data + checksum
rtcm3_buff = bytearray(RTCM3_BUFF_SIZE)
rtcm3_buff_pos = 0
while True:
while self.read is False or self.stream is None:
time.sleep(0.2)
try:
self.rx_signal_queue.get_nowait()
except queue.Empty:
pass
else:
break
try:
rx_buff = self.stream.read(RX_BUFF_SIZE)
except BlockingIOError:
rx_count = 0
else:
rx_count = len(rx_buff)
if rx_count == 0:
continue
rx_buff_pos = 0
while rx_buff_pos < rx_count:
if rx_state == rx_states.BEGIN:
if rx_buff[rx_buff_pos] == 0xB5: # ISO8859.1 for µ
rx_state = rx_states.RX_UBX
ubx_buff_pos = 0
elif rx_buff[rx_buff_pos] == 0x24: # ASCII for $
rx_state = rx_states.RX_NMEA
nmea_buff_pos = 0
# FIXME - add support for receiving RTCM3
# I don't have a high-precision receiver to test this, or access to the specification
# ref: https://www.ucalgary.ca/engo_webdocs/GL/06.20236.MinminLin.pdf
# ref: https://portal.u-blox.com/s/question/0D52p00009IthhBCAR/ublox-rtcm-wrapper-specification
elif rx_buff[rx_buff_pos] == 0xD3:
rx_state = rx_states.RX_RTCM3
rtcm3_buff_pos = 0
if rx_state == rx_states.RX_NMEA:
nmea_buff[nmea_buff_pos] = rx_buff[rx_buff_pos]
# NMEA sentences start with $ and end with CRLF
if (
nmea_buff[nmea_buff_pos] == 0x0A
and nmea_buff[nmea_buff_pos - 1] == 0x0D
and nmea_buff[0] == 0x24
):
self.rx_queue.put_nowait(bytes(nmea_buff[: nmea_buff_pos + 1]))
nmea_buff_pos = 0
rx_state = rx_states.BEGIN
else:
nmea_buff_pos += 1
if nmea_buff_pos >= NMEA_BUFF_SIZE:
# either sentence is longer than buffer size, or we missed the \r\n
nmea_buff_pos = 0
rx_state = rx_states.BEGIN
if rx_state == rx_states.RX_UBX:
ubx_buff[ubx_buff_pos] = rx_buff[rx_buff_pos]
ubx_msg_len = 0xFFFF
if ubx_buff_pos >= 5:
ubx_msg_len = int.from_bytes(
ubx_buff[4:5], byteorder="little", signed=False
)
# UBX messages start with µb, have a 6-byte header that contains the length, and a 2-byte checksum after length bytes
if (
ubx_buff_pos >= (2 + 6 + ubx_msg_len + 2)
and ubx_buff[0] == 0xB5
and ubx_buff[1] == 0x62
):
self.rx_queue.put_nowait(
bytes(ubx_buff[: 2 + 4 + ubx_msg_len + 2])
)
ubx_buff_pos = 0
rx_state = rx_states.BEGIN
else:
ubx_buff_pos += 1
if rx_state == rx_states.RX_RTCM3:
# FIXME - add support for receiving RTCM3
# I don't have a high-precision receiver to test this, or access to the specification
# ref: https://www.ucalgary.ca/engo_webdocs/GL/06.20236.MinminLin.pdf
# ref: https://portal.u-blox.com/s/question/0D52p00009IthhBCAR/ublox-rtcm-wrapper-specification
rtcm3_buff[rtcm3_buff_pos] = rx_buff[rx_buff_pos]
rtcm3_msg_len = 1023
if rtcm3_buff_pos >= 3:
rtcm3_msg_len = (
int.from_bytes(
rtcm3_buff[2:3], byteorder="little", signed=False
)
& 0x03FF
)
# RTCM3 messages start with 0xD3, 6 bits reserved (set to 0), 10 bits length, and 3 byte checksum (CRC24Q)
if (
rtcm3_buff_pos >= (3 + rtcm3_msg_len + 3)
and rtcm3_buff[0] == 0xD3
and (rtcm3_buff[1] & 0xFC) == 0
):
self.rx_queue.put_nowait(
bytes(ubx_buff[: 3 + rtcm3_msg_len + 3])
)
rtcm3_buff_pos = 0
rx_state = rx_states.BEGIN
else:
rtcm3_buff_pos += 1
rx_buff_pos += 1
def thread_parse(self) -> None:
# thread that handles parsing of received data into NMEA, UBX or RTCM3 formats, verifying checksums, etc
while True:
time.sleep(0.001) # yield to read and application threads every cycle
rx_data = self.rx_queue.get(block=True, timeout=None)
# canary value to break out of infinite loop
if rx_data is None:
self.rx_queue.task_done()
break
rx_protocol = None
if rx_data[0] == 0x24: # ASCII for $
rx_protocol = self.INOUT_PROTOCOL.NMEA
nmea_checksum = 0
checksum_pos = 0
checksum_start = 1
checksum_len = len(rx_data) - 6
rx_checksum = 0
# make sure 5th-last character is a * (checksum delimiter), and ends with \r\n
if (
rx_data[-5] == 0x2A and rx_data[-2] == 0x0D and rx_data[-1] == 0x0A
): # ASCII for *, \r, \n
rx_checksum_str = str(rx_data[-4:-2], encoding="ascii").upper()
# check to make sure only hex digits in the checksum
if not all(c in string.hexdigits for c in rx_checksum_str):
self.rx_queue.task_done()
continue
rx_checksum = int(rx_checksum_str, base=16)
else:
self.rx_queue.task_done()
continue
# NMEA checksum is XOR of all data after start character
while checksum_pos < checksum_len:
nmea_checksum ^= rx_data[checksum_start + checksum_pos]
checksum_pos += 1
if nmea_checksum != rx_checksum:
self.rx_queue.task_done()
continue
elif rx_data[0] == 0xB5 and rx_data[1] == 0x62: # ISO8859.1/ASCII for µb
rx_protocol = self.INOUT_PROTOCOL.UBX
ubx_ck_a = 0
ubx_ck_b = 0
checksum_pos = 0
checksum_start = 2
checksum_len = (
int.from_bytes(rx_data[4:5], byteorder="little", signed=False) + 4
)
# UBX checksum is fletcher of all data after (excluding) start sequence
while checksum_pos < checksum_len:
ubx_ck_a = (
ubx_ck_a + rx_data[checksum_start + checksum_pos]
) & 0xFF # don't have to & 0xFF if we had uint8_t :-(
ubx_ck_b = (ubx_ck_b + ubx_ck_a) & 0xFF
checksum_pos += 1
if ubx_ck_a != rx_data[-2] or ubx_ck_b != rx_data[-1]:
self.rx_queue.task_done()
continue
# FIXME - add support for receiving RTCM3
# I don't have a high-precision receiver to test this...
# ref: https://www.ucalgary.ca/engo_webdocs/GL/06.20236.MinminLin.pdf
# ref: https://portal.u-blox.com/s/question/0D52p00009IthhBCAR/ublox-rtcm-wrapper-specification
elif rx_data[0] == 0xD3 and (rx_data[1] & 0xFC) == 0:
rx_protocol = self.INOUT_PROTOCOL.RTCM3
rtcm3_crc24q = 0 # CRC24Q seed = 0
checksum_pos = 0
checksum_start = 0
checksum_len = len(rx_data) - 3 # entire frame is checksummed
# RTCM3 checksum is CRC24Q of entire frame
crc24q_table = [
0x00000000,
0x01864CFB,
0x038AD50D,
0x020C99F6,
0x0793E6E1,
0x0615AA1A,
0x041933EC,
0x059F7F17,
0x0FA18139,
0x0E27CDC2,
0x0C2B5434,
0x0DAD18CF,
0x083267D8,
0x09B42B23,
0x0BB8B2D5,
0x0A3EFE2E,
]
while checksum_pos < checksum_len:
rtcm3_crc24q ^= rx_data[checksum_pos + checksum_start] << 16
rtcm3_crc24q = (rtcm3_crc24q << 4) ^ crc24q_table[
(rtcm3_crc24q >> 20) & 0x0F
]
rtcm3_crc24q = (rtcm3_crc24q << 4) ^ crc24q_table[
(rtcm3_crc24q >> 20) & 0x0F
]
rtcm3_crc24q &= 0xFFFFFF
# CRC24Q sums to 0
if rtcm3_crc24q != 0:
self.rx_queue.task_done()
continue
self.parse_dest_lock.acquire(blocking=True)
for dest in self.parse_dest_threads.keys():
# check for protocol mask
if self.parse_dest_threads[dest]["protocols"] & rx_protocol == 0:
continue
if rx_protocol == self.INOUT_PROTOCOL.NMEA:
# check for NMEA sentence filter mask
if len(self.parse_dest_threads[dest]["nmea_filter"]) > 0:
filter_match = False
for sentence, strmatch in self.parse_dest_threads[dest][
"nmea_filter"
]:
if sentence is not None:
if (
sentence.upper()
!= str(rx_data[3:5], encoding="ascii").upper()
):
continue
if strmatch is not None:
if (
strmatch.upper()
not in str(rx_data[6:-6], encoding="ascii").upper()
):
continue
filter_match = True
break
if filter_match is False:
continue
elif rx_protocol == self.INOUT_PROTOCOL.UBX:
# check for UBX msgid/msgclass/offset/data filter mask
if len(self.parse_dest_threads[dest]["ubx_filter"]) > 0:
filter_match = False
for msgclass, msgid, offset, data in self.parse_dest_threads[
dest
]["ubx_filter"]:
if msgclass is not None:
if msgclass != rx_data[2]:
continue
if msgid is not None:
if msgid != rx_data[3]:
continue
if offset is not None and data is not None:
if data != rx_data[6 + offset]:
continue
filter_match = True
break
if filter_match is False:
continue
elif rx_protocol == self.INOUT_PROTOCOL.RTCM:
# FIXME - add support for receiving RTCM3
# I don't have a high-precision receiver to test this...
pass
# filters passed, send it!
dest.put_nowait(rx_data)
# finished sending, release lock
self.parse_dest_lock.release()
self.rx_queue.task_done()
def transmit(self, data: bytes) -> None:
self.tx_queue.put(item=data, block=True, timeout=None)
time.sleep(0.001) # force yield out of this thread so tx/rx threads can run
def receive_queue_start(
self,
# empty filters = allow all
protocols: Union[INOUT_PROTOCOL, None], # protocols to allow: UBX or NMEA
ubx_filters=[
()
], # list of UBX message class / message id / data offset / data value - matched equal, None = allow any
nmea_filters=[()], # list of NMEA sentence type / string match
rtcm3_filters=[()], # list of RTCM3 message type / string match
) -> queue.Queue:
q = queue.Queue(0) # unlimited queue length, so that thread_parse() won't block
self.parse_dest_lock.acquire(blocking=True)
self.parse_dest_threads[q] = {}
if protocols is None:
protocols = self.INOUT_PROTOCOL.ALL
self.parse_dest_threads[q]["protocols"] = protocols
# check UBX filter is valid
for filter in ubx_filters:
if len(filter) == 0:
continue
if len(filter) != 4:
self.parse_dest_lock.release()
raise ValueError("Invalid UBX filter, must contain exactly 4 elements")
self.parse_dest_threads[q]["ubx_filter"] = ubx_filters
# check NMEA filter is valid
for filter in nmea_filters:
if len(filter) == 0:
continue
if len(filter) != 2:
self.parse_dest_lock.release()
raise ValueError("Invalid NMEA filter, must contain exactly 2 elements")
self.parse_dest_threads[q]["nmea_filter"] = nmea_filters
self.parse_dest_lock.release()
return q
def receive_queue_stop(self, queue: queue.Queue) -> None:
self.parse_dest_lock.acquire(blocking=True)
del self.parse_dest_threads[queue]
self.parse_dest_lock.release()
def ubx_msg_send(self, msgclass: int, msgid: int, data: bytes) -> None:
# maximum data size = 0xFFFF (2 bytes) - ss32.2
length = len(data)
if length > 65535:
raise ValueError("Maximum message length 65535 bytes exceeded")
new_msg = bytearray(length + 8)
# 2-byte preamble - ss32.2
new_msg[0] = 0xB5 # ISO8859.1 for µ
new_msg[1] = 0x62 # ASCII for b
# 1-byte class, 1-byte message ID - ss32.2
new_msg[2] = msgclass & 0xFF
new_msg[3] = msgid & 0xFF
# 2-byte length, little-endian - ss32.2
new_msg[4:6] = length.to_bytes(length=2, byteorder="little")
# payload - variable length (defined by length field)
if length > 0:
new_msg[6 : (length + 6)] = data
# 2-byte checksum - ss32.4
new_msg[length + 6] = 0
new_msg[length + 7] = 0
# checksum spans from the message class and ID to the end of the data
for byte in new_msg[2 : (length + 6)]:
new_msg[length + 6] = (new_msg[length + 6] + byte) & 0xFF
new_msg[length + 7] = (new_msg[length + 7] + new_msg[length + 6]) & 0xFF
self.transmit(bytes(new_msg))
def ubx_msg_poll(self, msgclass: int, msgid: int, data=b"") -> bytes:
response_queue = self.receive_queue_start(
self.INOUT_PROTOCOL.UBX, [(msgclass, msgid, None, None)]
)
self.ubx_msg_send(msgclass, msgid, data)
response = b""
response_count = 0
while response_count < 5:
response = b""
try:
response = response_queue.get(block=True, timeout=self.write_timeout)
except queue.Empty:
response_count += 1
continue
if len(response) > 0:
if int.from_bytes(response[4:5], byteorder="little", signed=False) > 0:
response_queue.task_done()
break
response_queue.task_done()
response_count += 1
self.receive_queue_stop(response_queue)
if len(response) <= 8:
return b""
else:
return bytes(response[6:-2])
def ubx_msg_acknak(self, msgclass: int, msgid: int, data: bytes) -> bool:
response_queue = self.receive_queue_start(
self.INOUT_PROTOCOL.UBX, [(0x05, None, 0, msgclass), (0x05, None, 1, msgid)]
)
self.ubx_msg_send(msgclass, msgid, data)
response = b""
acknak_count = 0
while acknak_count < 5:
response = b""
try:
response = response_queue.get(block=True, timeout=self.write_timeout)
except queue.Empty:
acknak_count += 1
continue
if len(response) > 0:
if response[6] == msgclass and response[7] == msgid:
response_queue.task_done()
break
response_queue.task_done()
acknak_count += 1
self.receive_queue_stop(response_queue)
if len(response) == 0:
return False
if response[3] == 0:
return False
else:
return True
def ubx_ver_allowed(self, ver_min: float, ver_max: float) -> bool:
if ver_min == 0 and ver_max == 0:
return True
if self.protocol_version >= ver_min and self.protocol_version <= ver_max:
return True
else:
return False
def ubx_mon_ver(
self,
) -> Any:
extensions = []
sw_version = ""
hw_version = ""
rom_version = ""
response = self.ubx_msg_poll(0x0A, 0x04)
response_pos = 0 # start of response data
while response_pos < len(response):
if response_pos == 0:
sw_version = str(response[6:35], encoding="iso-8859-1").split(
sep="\0", maxsplit=1
)[0]
response_pos += 30
elif response_pos == 30:
hw_version = str(response[36:45], encoding="iso-8859-1").split(
sep="\0", maxsplit=1
)[0]
response_pos += 10
elif response_pos == 40 and self.ubx_ver_allowed(10.00, 13.03):
rom_version = str(response[46:75], encoding="iso-8859-1").split(
sep="\0", maxsplit=1
)[0]
response_pos += 30
else:
extensions.append(
str(
response[response_pos : response_pos + 29],
encoding="iso-8859-1",
).split(sep="\0", maxsplit=1)[0]
)
response_pos += 30
if self.ubx_ver_allowed(10.00, 13.03):
return (sw_version, hw_version, rom_version, extensions)
elif self.ubx_ver_allowed(14.00, 34.10):
return (sw_version, hw_version, extensions)
def ubx_find_proto_ver(self) -> None:
MAX_KNOWN_PROTO_VER = 34.10
extensions = []
sw_version = ""
hw_version = ""
rom_version = ""
if self.ubx_ver_allowed(10.00, 13.03):
sw_version, hw_version, rom_version, extensions = self.ubx_mon_ver()
elif self.ubx_ver_allowed(14.00, 34.10):
sw_version, hw_version, extensions = self.ubx_mon_ver()
for ext in extensions:
if ext[:7] == "PROTVER":
# Protocol 17 and older (Gen5-7 and early Gen8) uses PROTVER VERSION
# Protocol 18 and newer (most Gen8 and Gen9-10) uses PROTVER=VERSION
# So just don't bother looking for the character between PROTVER and the version...
self.protocol_version = float(ext[8:])
if self.protocol_version > MAX_KNOWN_PROTO_VER:
raise ValueError(
"Receiver protocol version {} is newer than known protocol version {}".format(
self.protocol_version, MAX_KNOWN_PROTO_VER
)
)
return
# didn't find protocol version in extensions, this is probably a very old receiver?
raise ValueError("Receiver protocol version not found in extensions")
def set_logging(self, level) -> None:
logger.setLevel(level)
def set_stream(self, stream: Union[serial.Serial, io.BufferedIOBase]) -> None:
if self.stream is not None:
if stream != self.stream:
self.stream.close()
# is our data stream actually a serial connection?
if isinstance(stream, serial.Serial):
# ensure serial connection is in correct mode, and hopefully correct speed
# u-blox GPS receivers only support 8-N-1-N options on doublings of 4800 baud (4800 to 921600 baud)
stream.baudrate = self.serial_baud
stream.bytesize = serial.EIGHTBITS
stream.parity = serial.PARITY_NONE
stream.stopbits = serial.STOPBITS_ONE
stream.timeout = 0.1 # 100 msec blocking timeout
stream.xonxoff = False
stream.rtscts = False
stream.dsrdtr = False
stream.write_timeout = self.write_timeout
else:
# set timeout for blocking io
if self.read is True and self.write is True:
raise ValueError(
"Unable to both read and write on a file, use a serial.Serial object instead"
)
self.stream = stream
# if read/write we are connected to the receiver using a serial stream
# probe the receiver to determine protocol version
if self.read is True and self.write is True:
self.ubx_find_proto_ver()
def set_read(self, read: bool) -> None:
self.read = read
# force-set read OR write on files
# only serial connections can be R/W
if isinstance(self.stream, io.RawIOBase) or isinstance(
self.stream, io.BufferedIOBase
):
if self.stream.readable() and self.read is True:
self.write = False
else:
self.read = False
def set_write(self, write: bool) -> None:
self.write = write
# force-set read OR write on files
# only serial connections can be R/W
if isinstance(self.stream, io.RawIOBase) or isinstance(
self.stream, io.BufferedIOBase
):
if self.stream.writable() and self.write is True:
self.read = False
else:
self.write = False
# defaults suitable for MAX-M8Q, override to match your own receiver
def __init__(
self,
stream,
serial_baud=9600,
protocol_version=18.00,
read=False,
write=True,
log_level=getattr(logging, "INFO", None),
write_timeout=1.0,
) -> None:
self.set_logging(log_level)
# init variables
self.stream = None
self.read = read
self.write = write
self.write_timeout = write_timeout
# default speed for most u-blox GPS receivers is 9600 baud
# the following (incomplete) list of receivers default to 38400 baud:
# - NEO-M9N
# - MIA-M10Q
baud = 4800
baud_ok = False
while baud <= 921600:
if baud == serial_baud:
baud_ok = True
break
baud *= 2
if baud_ok is False:
raise ValueError(
"Serial baud rate must be a doubling of 4800, up to 921600"
)
self.serial_baud = serial_baud
# this module (mostly) supports every protocol version released
# u-blox 5 series - protocol version 10.00 - 12.02
# u-blox 6 series - protocol version 12.00 - 14.00
# ref: u-blox document GPS.G6-SW-10018
# u-blox 7 series - protocol version 14.00
# ref: u-blox document GPS.G7-SW-12001-B1 - https://content.u-blox.com/sites/default/files/products/documents/u-blox7-V14_ReceiverDescriptionProtocolSpec_%28GPS.G7-SW-12001%29_Public.pdf
# u-blox 8 series - protocol version 15.00 - 23.01
# ref: u-blox document UBX-13003221 - https://content.u-blox.com/sites/default/files/products/documents/u-blox8-M8_ReceiverDescrProtSpec_UBX-13003221.pdf
# u-blox 9 series - protocol version 32.01
# ref: u-blox document UBX-21022436 - https://content.u-blox.com/sites/default/files/u-blox-M9-SPG-4.04_InterfaceDescription_UBX-21022436.pdf
# u-blox 10 series - protocol version 34.10
# ref: u-blox document UBX-21035062 - https://content.u-blox.com/sites/default/files/u-blox-M10-SPG-5.10_InterfaceDescription_UBX-21035062.pdf
self.protocol_version = protocol_version
self.tx_queue = queue.Queue(1024)
self.tx_thread = threading.Thread(target=self.thread_tx, daemon=True)
self.tx_thread.start()
self.rx_queue = queue.Queue(
0
) # unbounded size, as rx_thread needs to be as non-blocking as possible
self.rx_signal_queue = queue.Queue(
1
) # Any entries in this queue signals Serial RX thread to exit
self.rx_thread = threading.Thread(target=self.thread_rx, daemon=True)
self.rx_thread.start()
self.parse_thread = threading.Thread(target=self.thread_parse, daemon=True)
self.parse_thread.start()
self.parse_dest_threads = {}
self.parse_dest_lock = threading.Lock()
self.set_read(read)
self.set_write(write)
self.set_stream(stream)
def __del__(self) -> None:
while self.tx_thread.is_alive():
self.tx_queue.put(item=None, block=True, timeout=None)
self.tx_thread.join(timeout=1.0)
while self.rx_thread.is_alive():
self.rx_signal_queue.put(item=None, block=True, timeout=None)
self.rx_thread.join(timeout=1.0)
def close(self) -> None:
self.__del__()
def ubx_cfg_cfg(self, data: bytes) -> None:
# NOTE - UBX receiver implementaion has changed after protocol 23.01 (i.e. 9-series and later)
# see receiver protocol specification (9- and 10-series) for details:
# officially this is deprecated in 9- and 10-series receivers,
# but it still clears/saves/loads entire configurations if any bits are set
if not self.ubx_ver_allowed(10.00, 34.10):
raise ValueError(
"ubx-cfg-cfg not supported in protocol version {}".format(
self.protocol_version
)
)
if len(data) < 12 or len(data) > 13:
raise ValueError("Data length must be 12 or 13 bytes")
# apply bitfield masks
new_data = bytearray(len(data))
new_data[0:4] = (
int.from_bytes(data[0:3], byteorder="little", signed=False)
& 0b00000000000000000001111100011111
).to_bytes(length=4, byteorder="little", signed=False)
new_data[4:8] = (
int.from_bytes(data[4:7], byteorder="little", signed=False)
& 0b00000000000000000001111100011111
).to_bytes(length=4, byteorder="little", signed=False)
new_data[8:12] = (
int.from_bytes(data[8:11], byteorder="little", signed=False)
& 0b00000000000000000001111100011111
).to_bytes(length=4, byteorder="little", signed=False)
if len(data) == 13:
new_data[12] = data[12] & 0b00010111
# if this is a cfg reset, then the receiver may not respond
self.ubx_msg_send(msgclass=0x06, msgid=0x09, data=bytes(new_data))
time.sleep(0.5)
def ubx_cfg_cfg_reset_all(self) -> None:
data = bytearray(13)
# clearMask
data[0:4] = (0b00000000000000000001111100011111).to_bytes(
length=4, byteorder="little", signed=False
)
# saveMask
data[4:8] = (0b00000000000000000000000000000000).to_bytes(
length=4, byteorder="little", signed=False
)
# loadMask
data[8:12] = (0b00000000000000000001111100011111).to_bytes(
length=4, byteorder="little", signed=False
)
# deviceMask
data[12] = 0b00010111
self.ubx_cfg_cfg(bytes(data))
def ubx_cfg_cfg_save_all(self) -> None:
data = bytearray(13)
# clearMask
data[0:4] = (0b00000000000000000000000000000000).to_bytes(
length=4, byteorder="little", signed=False
)
# saveMask
data[4:8] = (0b00000000000000000001111100011111).to_bytes(
length=4, byteorder="little", signed=False
)
# loadMask
data[8:12] = (0b00000000000000000000000000000000).to_bytes(
length=4, byteorder="little", signed=False
)
# deviceMask
data[12] = 0b00010111
self.ubx_cfg_cfg(bytes(data))
def ubx_cfg_prt(
self,
port: PORT,
in_protocol: INOUT_PROTOCOL,
out_protocol: INOUT_PROTOCOL,
flags=b"\0\0",
mode=b"\0\0\0\0",
baud=0,
txready_enable=False,
txready_polarity_low=False,
txready_pin=0,
txready_threshold=0,
) -> None:
if not self.ubx_ver_allowed(12.00, 23.01):
raise ValueError(
"ubx-cfg-prt not supported in protocol version {}".format(
self.protocol_version
)
)
# in_protocol limitations:
# 6-series - UBX|NMEA
# 7-series - UBX|NMEA|RTCM
# 8-series P <20 - UBX|NMEA|RTCM
# 8-series P>=20 - UBX|NMEA|RTCM|RTCM3
# 9-series and later - UBX|NMEA|RTCM3
if in_protocol is not None:
if self.ubx_ver_allowed(10.00, 13.03):
# 6-series and earlier
in_protocol = in_protocol & (
self.INOUT_PROTOCOL.NMEA | self.INOUT_PROTOCOL.UBX
)
elif self.ubx_ver_allowed(14.00, 19.20):
# M6, 7-series, some 8-series
in_protocol = in_protocol & (
self.INOUT_PROTOCOL.NMEA
| self.INOUT_PROTOCOL.UBX
| self.INOUT_PROTOCOL.RTCM
)
elif self.ubx_ver_allowed(20, 23.01):
# some 8-series
in_protocol = in_protocol & (
self.INOUT_PROTOCOL.NMEA
| self.INOUT_PROTOCOL.UBX
| self.INOUT_PROTOCOL.RTCM
| self.INOUT_PROTOCOL.RTCM3
)
elif self.ubx_ver_allowed(32.01, 34.10):
# 9-series and later
in_protocol = in_protocol & (
self.INOUT_PROTOCOL.NMEA
| self.INOUT_PROTOCOL.UBX
| self.INOUT_PROTOCOL.RTCM3
)
# out_protocol limitations:
# 6-series - UBX|NMEA
# 7-series - UBX|NMEA
# 8-series P <20 - UBX|NMEA
# 8-series P>=20 - UBX|NMEA|RTCM3
# 9-series and later - UBX|NMEA|RTCM3
if out_protocol is not None:
if self.ubx_ver_allowed(10.00, 19.20):