-
Notifications
You must be signed in to change notification settings - Fork 0
/
NovatelOEM4.py
1336 lines (1181 loc) · 63.6 KB
/
NovatelOEM4.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2016 Bruno Tibério
#
# 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.
""" Module NovatelOEM4
:Date: 22 Nov 2018
:Version: 0.4.1
:Author: Bruno Tibério
:Contact: bruno.tiberio@tecnico.ulisboa.pt
This module contains a few functions to interact with Novatel OEM4 GPS devices.
Currently only the most important functions and definitions are configured, but
the intention is to make it as much complete as possible.
A simple example can be run by executing the main function which creates a Gps
class object and execute the following commands on gps receiver:
- **begin:** on default port or given port by argv[1].
- **sendUnlogall**
- **setCom(baud=115200):** changes baudrate to 115200bps
- **askLog(trigger=2,period=0.1):** ask for log *bestxyz* with trigger `ONTIME`
and period `0.1`
- wait for 10 seconds
- **shutdown:** safely disconnects from gps receiver
Example:
.. code-block:: console
$python NovatelOEM4.py
"""
import binascii
import crcmod
from datetime import datetime
import logging
import os
import serial
import struct
import threading
from time import sleep
try:
import queue
except ImportError:
import Queue as queue
class Gps:
"""Novatel OEM4 GPS library class
This class contents is an approach to create a library for Novatel OEM 4 GPS
Args:
sensorName (optional): A sensor name if used with multiple devices.
Attributes:
header_keys: all field keys for the headers of messages.
MessageID: A dictionary for the types of messages sent. Not all are
implemented yet!
"""
#: all field keys for the headers of messages.
header_keys = ('sync', 'headerLength', 'messageID', 'messageType',
'portAddress', 'messageLength', 'sequence', 'idleTime',
'timeStatus', 'week', 'ms', 'receiverStatus', 'reserved',
'swVersion')
#: A dictionary for the types of messages sent. Not all are implemented yet!
MessageID = {'LOG': 1,
'COM': 4,
'RESET': 18,
'SAVECONFIG': 19,
'UNLOG': 36,
'UNLOGALL': 38,
'DATUM': 160,
'DYNAMICS': 258,
'BESTXYZ': 241,
'SBASCONTROL': 652}
def __init__(self, sensorName="GPS"):
self.myPort = ""
self.isOpen = 0 # is port open?*/
self.baudRate = 9600 # current communication baudRate*/
self.openError = 0 # if any error during any process occurs this will be set */
self.dataQueue = None
self.name = sensorName
self.isSet = False
self.exitFlag = threading.Event()
self.orders = queue.Queue()
self.current_header = []
self.Index = 1
@staticmethod
def CRC32Value(i):
"""Calculate the 32bits CRC of message.
See OEMStar Firmware Reference Manual Rev 6 page 24 for
more information.
Args:
i: message to calculate the crc-32.
Returns:
The CRC value calculated over the input message.
"""
crc = crcmod.mkCrcFun(0x104C11DB7, 0, True, 0)
return crc(i)
@staticmethod
def getDebugMessage(message):
"""Create a string which contains all bytes represented as hex values
Auxiliary function for helping with debug. Receives a binary message as
input and convert it as a string with the hexdecimal representation.
Args:
message: message to be represented.
Returns:
A string of corresponding hex representation of message.
"""
debugMessage = (binascii.hexlify(message)).upper()
debugMessage = [debugMessage[i:i + 2] for i in range(0, len(debugMessage), 2)]
debugMessage = ' '.join('0x{}'.format(item) for item in debugMessage)
return debugMessage
def parseResponces(self):
"""
A thread to parse responses from device
"""
# used definitions for keys
bestxyz_keys = ('pSolStatus', 'posType', 'position', 'positionStd',
'velSolStatus', 'velType', 'velocity', 'velocityStd',
'stnID', 'vLatency', 'diffAge', 'solAge', 'numStasVs',
'numSolSatVs', 'numGGL1', 'reserved', 'extSolStat',
'reserved2', 'sigMask', 'crc32')
self.log.info("Entering Thread logger")
if(not self.isOpen):
self.log.warning('Port is not open: {0}'.format(self.myPort))
self.log.info("Exiting Thread logger")
return
MYPORT = self.myPort
# dataFile = self.dataFile
while(self.exitFlag.isSet() == False):
header = [0] * 14
newByte = ord(MYPORT.read(1))
if newByte == 0xAA:
header[0] = [0, 0, 0]
header[0][0] = newByte
header[0][1] = ord(MYPORT.read(1))
if header[0][1] == 0x44:
header[0][2] = ord(MYPORT.read(1))
if header[0][2] == 0x12:
# got a valid header sync vector
serialBuffer = MYPORT.read(25)
header[1:] = struct.unpack('<BHBBHHBBHlLHH',
serialBuffer)
self.current_header = dict(zip(self.header_keys, header))
header = self.current_header
if header['messageID'] == self.MessageID['LOG']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("LOG response received : {0}".format(message['ascii']))
self.orders.put({'order': 'LOG', 'data': message})
elif header['messageID'] == self.MessageID['UNLOGALL']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("UNLOGALL response received : {0}".format(message['ascii']))
self.orders.put({'order': 'UNLOGALL', 'data': message})
elif header['messageID'] == self.MessageID['COM']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("COM response received : {0}".format(message['ascii']))
self.orders.put({'order': 'COM', 'data': message})
elif header['messageID'] == self.MessageID['DYNAMICS']:
# is message responce to command setDynamics?
if header['messageType'] == 130:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("DYNAMICS response received : {0}".format(message['ascii']))
self.orders.put({'order': 'DYNAMICS', 'data': message})
else:
# is a log dynamic response
message = [0] * 2
message_keys = ('dynamicID', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<L', serialBuffer)
message[1] = MYPORT.read(4)
message[1] = struct.unpack('<L', message[1])
message = dict(zip(message_keys, message))
self.log.info("DYNAMICS response received : dynamicID={0}".format(message['dynamicID'][0]))
elif header['messageID'] == self.MessageID['RESET']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("RESET response received : {0}".format(message['ascii']))
self.orders.put({'order': 'RESET', 'data': message})
elif header['messageID'] == self.MessageID['SAVECONFIG']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("SAVECONFIG response received : {0}".format(message['ascii']))
self.orders.put({'order': 'SAVECONFIG', 'data': message})
elif header['messageID'] == self.MessageID['SBASCONTROL']:
message = [0] * 3
message_keys = ('responseID', 'ascii', 'crc32')
serialBuffer = MYPORT.read(4)
message[0] = struct.unpack('<I', serialBuffer)
message[1] = MYPORT.read(self.current_header['messageLength'] - 4)
message[2] = MYPORT.read(4)
message[2] = struct.unpack('<L', message[2])
message = dict(zip(message_keys, message))
self.log.info("SBASCONTROL response received : {0}".format(message['ascii']))
self.orders.put({'order': 'SBASCONTROL', 'data': message})
elif header['messageID'] == self.MessageID['BESTXYZ']:
message = [0] * 20
serialBuffer = MYPORT.read(self.current_header['messageLength'])
message[0:2] = struct.unpack('<II', serialBuffer[0:8])
message[2] = [0, 0, 0]
message[2][0:] = struct.unpack('<ddd', serialBuffer[8:32])
message[3] = [0, 0, 0]
message[3][0:] = struct.unpack('<fff', serialBuffer[32:44])
message[4:6] = struct.unpack('<II', serialBuffer[44:52])
message[6] = [0, 0, 0]
message[6][0:] = struct.unpack('<ddd', serialBuffer[52:76])
message[7] = [0, 0, 0]
message[7][0:] = struct.unpack('<fff', serialBuffer[76:88])
message[8] = serialBuffer[88:92]
message[9:12] = struct.unpack('<fff', serialBuffer[92:104])
message[12:15] = struct.unpack('<3B', serialBuffer[104:107])
message[15] = [0, 0]
message[15][0:] = struct.unpack('<2B', serialBuffer[107:109])
message[16:19] = struct.unpack('<3B', serialBuffer[109:112])
serialBuffer = MYPORT.read(4) # crc32
message[19] = struct.unpack('<I', serialBuffer)
message = dict(zip(bestxyz_keys, message))
currentTime = datetime.now()
myTime = '{0:%Y-%m-%d %H:%M:%S}'.format(currentTime) + '.{0:02.0f}'.format(round(currentTime.microsecond / 10000.0))
outMessage = dict(Index=self.Index, Time=myTime)
outMessage.update(message)
self.dataQueue.put_nowait(outMessage)
self.Index = self.Index + 1
else:
# .. todo:: error processing.
pass
else:
self.log.debug("New Byte unexpected: 0x{0:X}".format(newByte))
self.log.info("Exiting Thread logger")
return
def begin(self, dataQueue,
comPort="/dev/ttyUSB0",
baudRate=9600):
""" Initializes the gps receiver.
This function resets the current port to factory default and setup the
gps receiver to be able to acept new commands. If connection to gps
is made, it launchs a thread used to parse messages comming from gps.
Args:
comPort: system port where receiver is connected.
dataQueue: a Queue object to store incoming bestxyz messages.
baudRate: baudrate to configure port. (should always be equal to
factory default of receiver).
Returns:
True or False if the setup has gone as expected or not.
:Example:
.. code-block:: python
Gps.begin(comPort="<port>",
dataQueue=<your Queue obj>,
baudRate=9600)
**Default values**
:comPort: "/dev/ttyUSB0"
:baudRate: 9600
.. warning::
This class uses module ``logging`` wich must be configured in your
main program using the ``basicConfig`` method. Check documentation
of `module logging`_ for more info.
**HW info:**
:Receptor: Novatel Flexpak G2L-3151W.
:Antenna: Novatel Pinwheel.
.. _module logging: https://docs.python.org/2/library/logging.html
"""
self.log = logging.getLogger(self.name)
# checking if port exists on system
if not os.path.exists(comPort):
self.log.warning('Port is not available: {0}'.format(comPort))
return False
else:
# port exists, open it
self.myPort = serial.Serial(comPort, baudrate=baudRate)
if not self.myPort.is_open:
self.log.warning("Error opening port: {0}".format(comPort))
self.isOpen = False
return False
# reset port settings to default
self.myPort.break_condition = True
self.myPort.send_break()
sleep(1.5)
self.myPort.send_break()
sleep(0.25)
self.baudRate = baudRate
self.isOpen = True
# open dataFile to save GPS data
self.dataQueue = dataQueue
# start thread to handle GPS responces
self.threadID = threading.Thread(name="Logger", target=self.parseResponces)
self.threadID.start()
self.log.info("Started Logger Thread")
sleep(0.1)
return True
def create_header(self, messageID, messageLength, portAddress=192):
"""Creates a header object to be passed to receiver.
Args:
messageID: the corresponding value of identifying the message body.
messageLength: size of message in bytes excluding CRC-32bit code.
portAddress: port from where message request is sent.
Returns:
The header of message.
The header is defined as:
+-----+--------------+-----------+-----------------------------+
|Field| Value | N Bytes | Description |
+=====+==============+===========+=============================+
|1 | sync[0] | UChar = 1 | Hexadecimal 0xAA. |
+-----+--------------+-----------+-----------------------------+
|2 | sync[1] | UChar = 1 | Hexadecimal 0x44. |
+-----+--------------+-----------+-----------------------------+
|3 | sync[2] | UChar = 1 | Hexadecimal 0x12. |
+-----+--------------+-----------+-----------------------------+
|4 | headerLength | UChar = 1 |Length of the header (should |
| | | |always be 28 unless some |
| | | |firmware update) |
+-----+--------------+-----------+-----------------------------+
|5 | messageID | UShort = 2| This is the Message ID code |
+-----+--------------+-----------+-----------------------------+
|6 | messageType | UChar = 1 |message type mask (binary and|
| | | |original message) |
+-----+--------------+-----------+-----------------------------+
|7 | portAddress | Uchar = 1 |Corresponding value of port |
+-----+--------------+-----------+-----------------------------+
|8 | messageLength| UShort = 2|Length of message body |
+-----+--------------+-----------+-----------------------------+
|9 | sequence | UShort = 2|This is used for multiple |
| | | |related logs. |
+-----+--------------+-----------+-----------------------------+
|10 | idleTime | UChar = 1 |The time that the processor |
| | | |is idle in the last second |
| | | |between successive logs with |
| | | |the same Message ID |
+-----+--------------+-----------+-----------------------------+
|11 | timeStatus | Enum = 1 |Indicates the quality of the |
| | | |GPS time |
+-----+--------------+-----------+-----------------------------+
|12 | week | UShort = 2| GPS week number. |
+-----+--------------+-----------+-----------------------------+
|13 | ms | int = 4 |Milliseconds from the |
| | | |beginning of the GPS week. |
+-----+--------------+-----------+-----------------------------+
|14 |receiverStatus| Ulong = 4 |32 bits representing the |
| | | |status of various hardware |
| | | |and software components of |
| | | |the receiver. |
+-----+--------------+-----------+-----------------------------+
|15 | reserved | UShort = 2| |
+-----+--------------+-----------+-----------------------------+
|16 | swVersion | UShort = 2|receiver software build |
| | | |number. |
+-----+--------------+-----------+-----------------------------+
.. note:: portAddress=192 (equal to thisport)
"""
header = [0] * 16
# First 3 start bytes are always.
header[0] = 0xAA
header[1] = 0x44
header[2] = 0x12
# header Length 1C
header[3] = 0x1C
# messageID
header[4] = messageID
# messageType binary and original responce = b000xxxxx = 0x02?
header[5] = 0x02
# port address
header[6] = portAddress
# message length in bytes
header[7] = messageLength
return header
def sendUnlogall(self, port=8, held=1):
"""Send command unlogall to gps device.
On sucess clears all logs on all ports even held logs.
Returns:
True or False if the request has gone as expected or not.
unlogall message is defined as:
+------+------------+----------+-------------------------------+
| Field| value | N Bytes | Description |
+======+============+==========+===============================+
|1 | header | H = 28 | Header of message |
+------+------------+----------+-------------------------------+
|2 | port | ENUM = 4 | identification of port |
+------+------------+----------+-------------------------------+
|3 | Held | ENUM = 4 | can only be 0 or 1. Clear logs|
| | | | with hold flag or not? |
+------+------------+----------+-------------------------------+
| CRC32| | UL = 4 | |
+------+------------+----------+-------------------------------+
.. note:: See: OEMStar Firmware Reference Manual Rev 6 page 161
"""
if self.isOpen:
MYPORT = self.myPort
messageSize = 8 # 2 * ENUM
header = self.create_header(messageID=38,
messageLength=messageSize)
myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
myMessage = myMessage + struct.pack('<LL', port, held)
crc_value = self.CRC32Value(myMessage)
finalMessage = myMessage + struct.pack('<L', crc_value)
# print messages to logFile
self.log.info("Requested unlogall")
self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
MYPORT.write(finalMessage)
MYPORT.flush()
# wait for data on queue with response
message = self.orders.get()
if message['order'] == 'UNLOGALL':
message = message['data']
self.log.info("Unlogall response received : {0}".format(message['ascii']))
if message['responseID'][0] == 1:
return True
else:
return False
else:
self.log.warning("Unexpected responce type: {0}".format(message['order']))
else:
self.log.info("Port not open. Couldn't request unlogall command")
return False
def setCom(self, baud, port=6, parity=0, databits=8, stopbits=1,
handshake=0, echo=0, breakCond=1):
"""Set com configuration.
Args:
baud: communication baudrate.
port: Novatel serial ports identifier (default 6 = "thisport").
parity: byte parity check (default 0).
databits: Number of data bits (default 8).
stopbits: Number of stop bits (default 1).
handshake: Handshaking (default No handshaking).
echo: echo input back to user (default false)
breakCond: Enable break detection (default true)
Return:
True or false if command was sucessfull or not.
The com request command is defined as:
+-----+------------+----------+----------------------------------+
|Field| ID | N Bytes | Description |
+=====+============+==========+==================================+
|1 | Com header | H = 28 | Header of message |
+-----+------------+----------+----------------------------------+
|2 | port | ENUM = 4 | identification of port |
+-----+------------+----------+----------------------------------+
|3 | baud | Ulong = 4| Communication baud rate (bps) |
+-----+------------+----------+----------------------------------+
|4 | parity | ENUM = 4 | Parity |
+-----+------------+----------+----------------------------------+
|5 | databits | Ulong = 4| Number of data bits (default = 8)|
+-----+------------+----------+----------------------------------+
|6 | stopbits | Ulong = 4| Number of stop bits (default = 1)|
+-----+------------+----------+----------------------------------+
|7 | handshake | ENUM = 4 | Handshaking |
+-----+------------+----------+----------------------------------+
|8 | echo | ENUM = 4 | No echo (default)(must be 0 or 1)|
+-----+------------+----------+----------------------------------+
|9 | break | ENUM = 4 |Enable break detection (default 0)|
| | | |,(must be 0 or 1) |
+-----+------------+----------+----------------------------------+
.. note:: Total byte size = header + 32 = 60 bytes
COM Serial Port Identifiers (field 2):
+-------+--------------+--------------------+
|Binary |ASCII |Description |
+=======+==============+====================+
|1 | COM1 |COM port 1 |
+-------+--------------+--------------------+
|2 | COM2 |COM port 2 |
+-------+--------------+--------------------+
|6 | THISPORT |The current COM port|
+-------+--------------+--------------------+
|8 | ALL |All COM ports |
+-------+--------------+--------------------+
|9 | XCOM1 |Virtual COM1 port |
+-------+--------------+--------------------+
|10 | XCOM2 |Virtual COM2 port |
+-------+--------------+--------------------+
|13 | USB1 |USB port 1 |
+-------+--------------+--------------------+
|14 | USB2 |USB port 2 |
+-------+--------------+--------------------+
|15 | USB3 |USB port 3 |
+-------+--------------+--------------------+
|17 | XCOM3 |Virtual COM3 port |
+-------+--------------+--------------------+
Parity(field 4):
+-------+-----------+-----------------------+
|Binary |ASCII |Description |
+=======+===========+=======================+
|0 | N | No parity (default) |
+-------+-----------+-----------------------+
|1 | E | Even parity |
+-------+-----------+-----------------------+
|2 | O | Odd parity |
+-------+-----------+-----------------------+
Handshaking (field 7):
+-------+---------+-------------------------------+
|Binary |ASCII |Description |
+=======+=========+===============================+
|0 |N |No handshaking (default) |
+-------+---------+-------------------------------+
|1 |XON |XON/XOFF software handshaking |
+-------+---------+-------------------------------+
|2 |CTS |CTS/RTS hardware handshaking |
+-------+---------+-------------------------------+
.. note:: See: OEMStar Firmware Reference Manual Rev 6 page 56
"""
if self.isOpen:
MYPORT = self.myPort
messageSize = 32 # 32bytes length
header = self.create_header(messageID=4, messageLength=messageSize)
myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
myMessage = myMessage + struct.pack('<8L', port, baud, parity, databits,
stopbits, handshake, echo, breakCond)
crc_value = self.CRC32Value(myMessage)
finalMessage = myMessage + struct.pack('<L', crc_value)
self.log.info("Requested Com command")
self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
MYPORT.write(finalMessage)
MYPORT.flush()
self.log.info("waiting for port settings to change")
sleep(1)
portOptions = MYPORT.get_settings()
# change port settings
portOptions['baudrate'] = baud
# auxiliar vector
parity_vect = [serial.PARITY_NONE, serial.PARITY_EVEN, serial.PARITY_ODD]
portOptions['parity'] = parity_vect[parity]
portOptions['bytesize'] = databits
portOptions['stopbits0'] = stopbits
if handshake == 0:
portOptions['xonxoff'] = False
portOptions['rtscts'] = False
elif handshake == 1:
portOptions['xonxoff'] = True
portOptions['rtscts'] = False
elif handshake == 2:
portOptions['xonxoff'] = False
portOptions['rtscts'] = True
MYPORT.apply_settings(portOptions)
MYPORT.reset_input_buffer()
MYPORT.reset_output_buffer()
if MYPORT.is_open:
self.log.info("changed port settings: {0}".format(MYPORT.portstr))
return True
else:
self.log.warning("Not able to change port settings: {0}".format(MYPORT.portstr))
return False
else:
self.log.info("Port not open. Couldn't request COM command")
return False
def askLog(self, logID='BESTXYZ', port=192, trigger=4, period=0, offset=0, hold=0):
"""Request a log from receiver.
Args:
logID: log type to request.
port: port to report log.
trigger: trigger identifier.
period: the period of log.
offset: offset in seconds after period.
hold: mark log with hold flag or not.
Returns:
True or false if command was sucessfull or not.
The log request command is defined as:
+-----+------------+--------------+-----------------------------------+
|Field| ID | N Bytes | Description |
+=====+============+==============+===================================+
|1 | Com header | H = 28 | Header of message |
+-----+------------+--------------+-----------------------------------+
|2 | port | ENUM = 4 | identification of port |
+-----+------------+--------------+-----------------------------------+
|3 | message | Ushort = 2 | Message ID of log to output |
+-----+------------+--------------+-----------------------------------+
|4 | messageType| char = 1 | Message type (Binary) |
+-----+------------+--------------+-----------------------------------+
|5 | RESERVED | char = 1 | |
+-----+------------+--------------+-----------------------------------+
|6 | trigger | ENUM = 4 | message trigger |
+-----+------------+--------------+-----------------------------------+
|7 | period | double = 8 | Log period (for ONTIME in secs) |
+-----+------------+--------------+-----------------------------------+
|8 | offset | double = 8 | Offset for period (ONTIME in secs |
+-----+------------+--------------+-----------------------------------+
|9 | hold | ENUM = 4 | Hold log |
+-----+------------+--------------+-----------------------------------+
|10 | crc32 | Ulong = 4 | crc32 value |
+-----+------------+--------------+-----------------------------------+
.. note:: Total byte size = header + 32 = 60 bytes
Log trigger Identifiers (field 6):
+-------+-----------+-------------------------------------------------+
|Binary |ASCII |Description |
+=======+===========+=================================================+
|0 | ONNEW | | when the message is updated (not necessarily |
| | | | changed) |
+-------+-----------+-------------------------------------------------+
|1 | ONCHANGED | | Current message and then continue to output |
| | | | when the message is changed |
+-------+-----------+-------------------------------------------------+
|2 | ONTIME |Output on a time interval |
+-------+-----------+-------------------------------------------------+
|3 | ONNEXT |Output only the next message |
+-------+-----------+-------------------------------------------------+
|4 | ONCE |Output only the current message |
+-------+-----------+-------------------------------------------------+
|5 | ONMARK | | Output when a pulse is detected on the mark 1 |
| | | | input |
+-------+-----------+-------------------------------------------------+
"""
if self.isOpen:
MYPORT = self.myPort
messageSize = 32
header = self.create_header(messageID=1, messageLength=messageSize)
myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
myMessage = myMessage + struct.pack('<LHBBLddL', port, self.MessageID[logID],
0, 0, trigger, period, offset, hold)
crc_value = self.CRC32Value(myMessage)
finalMessage = myMessage + struct.pack('<L', crc_value)
self.log.info("Requested Log command")
self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
MYPORT.write(finalMessage)
MYPORT.flush()
# wait for responce
message = self.orders.get()
if message['order'] == 'LOG':
message = message['data']
self.log.info("LOG response received : {0}".format(message['ascii']))
if message['responseID'][0] == 1:
return True
else:
return False
else:
self.log.warning("Unexpected responce type: {0}".format(message['order']))
else:
self.log.info("Port not open. Couldn't request LOG command")
return False
def setDynamics(self, dynamicID):
"""Set Dynamics of receiver.
Args:
dynamicID: identifier of the type of dynamic.
Returns:
True or False if the request has gone as expected or not.
dynamics message is defined as:
+------+------------+----------+-------------------------------+
| Field| value | N Bytes | Description |
+======+============+==========+===============================+
|1 | header | H = 28 | Header of message |
+------+------------+----------+-------------------------------+
|2 | dynamics | ENUM = 4 | identification of dynamics |
+------+------------+----------+-------------------------------+
| CRC32| | UL = 4 | |
+------+------------+----------+-------------------------------+
The dynamics identifiers (field 2) are defined as:
+-------+--------+------------------------------------------------+
|Binary |ASCII |Description |
+=======+========+================================================+
|0 | AIR | | Receiver is in an aircraft or a land vehicle,|
| | | | for example a high speed train, with velocity|
| | | | greater than 110 km/h (30 m/s). This is also |
| | | | the most suitable dynamic for a jittery |
| | | | vehicle at any speed. |
+-------+--------+------------------------------------------------+
|1 | LAND | | Receiver is in a stable land vehicle with |
| | | | velocity less than 110 km/h (30 m/s). |
+-------+--------+------------------------------------------------+
|2 | FOOT | | Receiver is being carried by a person with |
| | | | velocity less than 11 km/h (3 m/s). |
+-------+--------+------------------------------------------------+
This command adjusts the receiver dynamics to that of your environment.
It is used to optimally tune receiver parameters.
The DYNAMICS command adjusts the Tracking State transition time-out
value of the receiver.
When the receiver loses the position solution, it attempts to steer the
tracking loops for fast reacquisition (5 s time-out by default).
The DYNAMICS command allows you to adjust this time-out value,
effectively increasing the steering time. The three states 0, 1, and 2
set the time-out to 5, 10, or 20 seconds respectively.
.. note::
* The DYNAMICS command should only be used by advanced users of GPS.
The default of AIR should not be changed except under very
specific conditions.
* The DYNAMICS command affects satellite reacquisition. The
constraint of the DYNAMICS filter with FOOT is very tight and is
appropriate for a user on foot. A sudden tilted or up and down
movement, for example while a tractor is moving slowly along a
track, may trip the RTK filter to reset and cause the position to
jump. AIR should be used in this case.
"""
if self.isOpen:
if dynamicID in [0, 1, 2]:
MYPORT = self.myPort
messageSize = 4 # ENUM
header = self.create_header(messageID=self.MessageID['DYNAMICS'],
messageLength=messageSize)
myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
myMessage = myMessage + struct.pack('<L', dynamicID)
crc_value = self.CRC32Value(myMessage)
finalMessage = myMessage + struct.pack('<L', crc_value)
# print messages to logFile
self.log.info("Requested dynamics")
self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
MYPORT.write(finalMessage)
MYPORT.flush()
# wait for data on queue with response
message = self.orders.get()
if message['order'] == 'DYNAMICS':
message = message['data']
self.log.info("DYNAMICS response received : {0}".format(message['ascii']))
if message['responseID'][0] == 1:
return True
else:
return False
else:
self.log.warning("Unexpected responce type: {0}".format(message['order']))
else:
self.log.info("dynamicID not valid")
return False
else:
self.log.info("Port not open. Couldn't request DYNAMICS command")
return False
# def setPDPFilter(self, switchID):
# """ set PDPFilter type
#
# Args:
# switchID: Enable, disable or reset.
#
# Returns:
# A boolean if request was sucessful or not
#
# PDPFilter message is defined as:
#
# +------+------------+----------+-------------------------------+
# | Field| value | N Bytes | Description |
# +======+============+==========+===============================+
# |1 | header | H = 28 | Header of message |
# +------+------------+----------+-------------------------------+
# |2 | switchID | ENUM = 4 | Enable, disable or reset. |
# +------+------------+----------+-------------------------------+
# | CRC32| | UL = 4 | |
# +------+------------+----------+-------------------------------+
#
# the switchID is defined as:
#
# +-------+--------+------------------------------------------------+
# |Binary |ASCII |Description |
# +=======+========+================================================+
# |0 | DISABLE| | Enable/disable/reset the PDP filter. A reset |
# +-------+--------+ | clears the filter memory so that the pdp |
# |1 | ENABLE | | filter can start over. |
# +-------+--------+ |
# |2 | Reset | |
# +-------+--------+------------------------------------------------+
#
# This command enables, disables or resets the Pseudorange/Delta-Phase
# (PDP) filter. The main advantages of the Pseudorange/Delta-Phase
# (PDP) implementation are:
#
# * Smooths a jumpy position
# * Bridges outages in satellite coverage (the solution is degraded from
# normal but there is at least a reasonable solution without gaps)
#
# .. note::
# For channel configurations that include GPS, PDP is enabled by
# default on the OEMStar.
# With PDP enabled (default), the BESTPOS log is not updated until the
# receiver has achieved FINESTEERING.
# PDP and GLIDE are disabled for GLONASS-only applications.
# Enable the PDP filter to output the PDP solution in BESTPOS, BESTVEL
# and NMEA logs.
#
# """
# if self.isOpen:
# if switchID in [0, 1, 2]:
# MYPORT = self.myPort
# messageSize = 4 # ENUM
# header = self.create_header(messageID=self.MessageID('PDPFILTER'),
# messageLength=messageSize)
# myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
# myMessage = myMessage + struct.pack('<L', switchID)
# crc_value = self.CRC32Value(myMessage)
# finalMessage = myMessage + struct.pack('<L', crc_value)
#
# # print messages to logFile
# self.log.info("Requested PDPFilter")
# self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
# MYPORT.write(finalMessage)
# MYPORT.flush()
#
# # wait for data on queue with response
# message = self.orders.get()
# if message['order'] == 'PDPFILTER':
# message = message['data']
# self.log.info("PDPFilter response received : {0}".format(message['ascii']))
# if message['responseID'][0] == 1:
# return True
# else:
# return False
# else:
# self.log.warning("Unexpected responce type: {0}".format(message['order']))
# else:
# self.log.info("switchID not valid")
# return False
# else:
# self.log.info("Port not open. Couldn't request PDPFILTER command")
# return False
#
# def setPDPMode(self, mode, dynamics):
# pass
def reset(self, delay=0):
""" Performs a hardware reset
Args:
delay: seconds to wait before resetting. Default to zero.
Returns:
A boolean if request was sucessful or not
The reset message is defined as:
+------+------------+----------+-------------------------------+
| Field| value | N Bytes | Description |
+======+============+==========+===============================+
|1 | header | H = 28 | Header of message |
+------+------------+----------+-------------------------------+
|2 | delay | UL = 4 | Seconds to wait before reset |
+------+------------+----------+-------------------------------+
| CRC32| | UL = 4 | |
+------+------------+----------+-------------------------------+
Following a RESET command, the receiver initiates a coldstart boot up.
Therefore, the receiver configuration reverts either to the factory
default, if no user configuration was saved, or the last SAVECONFIG
settings.
The optional delay field is used to set the number of seconds the
receiver is to wait before resetting.
"""
if self.isOpen:
MYPORT = self.myPort
messageSize = 4 # Ulong
header = self.create_header(messageID=self.MessageID['RESET'],
messageLength=messageSize)
myMessage = struct.pack('<BBBBHBBHHBBHlLHH', *header)
myMessage = myMessage + struct.pack('<L', delay)
crc_value = self.CRC32Value(myMessage)
finalMessage = myMessage + struct.pack('<L', crc_value)
# print messages to logFile
self.log.info("Requested Reset")
self.log.debug('Message sent to GPS: {0}'.format(self.getDebugMessage(finalMessage)))
MYPORT.write(finalMessage)
MYPORT.flush()
# wait for data on queue with response
message = self.orders.get()
if message['order'] == 'RESET':
message = message['data']
self.log.info("RESET response received : {0}".format(message['ascii']))
if message['responseID'][0] == 1:
return True