forked from sparkfun/SparkFun_Ublox_Arduino_Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparkFun_Ublox_Arduino_Library.cpp
3500 lines (3022 loc) · 130 KB
/
SparkFun_Ublox_Arduino_Library.cpp
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
/*
This is a library written for the Ublox ZED-F9P and NEO-M8P-2
SparkFun sells these at its website: www.sparkfun.com
Do you like this library? Help support SparkFun. Buy a board!
https://www.sparkfun.com/products/15136
https://www.sparkfun.com/products/15005
https://www.sparkfun.com/products/15733
https://www.sparkfun.com/products/15193
https://www.sparkfun.com/products/15210
Written by Nathan Seidle @ SparkFun Electronics, September 6th, 2018
This library handles configuring and handling the responses
from a Ublox GPS module. Works with most modules from Ublox including
the Zed-F9P, NEO-M8P-2, NEO-M9N, ZOE-M8Q, SAM-M8Q, and many others.
https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library
Development environment specifics:
Arduino IDE 1.8.5
SparkFun code, firmware, and software is released under the MIT License(http://opensource.org/licenses/MIT).
The MIT License (MIT)
Copyright (c) 2016 SparkFun Electronics
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.
*/
#include "SparkFun_Ublox_Arduino_Library.h"
SFE_UBLOX_GPS::SFE_UBLOX_GPS(void)
{
// Constructor
currentGeofenceParams.numFences = 0; // Zero the number of geofences currently in use
moduleQueried.versionNumber = false;
if (checksumFailurePin >= 0)
{
pinMode((uint8_t)checksumFailurePin, OUTPUT);
digitalWrite((uint8_t)checksumFailurePin, HIGH);
}
}
//Initialize the Serial port
boolean SFE_UBLOX_GPS::begin(TwoWire &wirePort, uint8_t deviceAddress)
{
commType = COMM_TYPE_I2C;
_i2cPort = &wirePort; //Grab which port the user wants us to use
//We expect caller to begin their I2C port, with the speed of their choice external to the library
//But if they forget, we start the hardware here.
//We're moving away from the practice of starting Wire hardware in a library. This is to avoid cross platform issues.
//ie, there are some platforms that don't handle multiple starts to the wire hardware. Also, every time you start the wire
//hardware the clock speed reverts back to 100kHz regardless of previous Wire.setClocks().
//_i2cPort->begin();
_gpsI2Caddress = deviceAddress; //Store the I2C address from user
return (isConnected());
}
//Initialize the Serial port
boolean SFE_UBLOX_GPS::begin(Stream &serialPort)
{
commType = COMM_TYPE_SERIAL;
_serialPort = &serialPort; //Grab which port the user wants us to use
return (isConnected());
}
//Enable or disable the printing of sent/response HEX values.
//Use this in conjunction with 'Transport Logging' from the Universal Reader Assistant to see what they're doing that we're not
void SFE_UBLOX_GPS::enableDebugging(Stream &debugPort, boolean printLimitedDebug)
{
_debugSerial = &debugPort; //Grab which port the user wants us to use for debugging
if (printLimitedDebug == false)
{
_printDebug = true; //Should we print the commands we send? Good for debugging
}
else
{
_printLimitedDebug = true; //Should we print limited debug messages? Good for debugging high navigation rates
}
}
void SFE_UBLOX_GPS::disableDebugging(void)
{
_printDebug = false; //Turn off extra print statements
_printLimitedDebug = false;
}
//Safely print messages
void SFE_UBLOX_GPS::debugPrint(char *message)
{
if (_printDebug == true)
{
_debugSerial->print(message);
}
}
//Safely print messages
void SFE_UBLOX_GPS::debugPrintln(char *message)
{
if (_printDebug == true)
{
_debugSerial->println(message);
}
}
const char *SFE_UBLOX_GPS::statusString(sfe_ublox_status_e stat)
{
switch (stat)
{
case SFE_UBLOX_STATUS_SUCCESS:
return "Success";
break;
case SFE_UBLOX_STATUS_FAIL:
return "General Failure";
break;
case SFE_UBLOX_STATUS_CRC_FAIL:
return "CRC Fail";
break;
case SFE_UBLOX_STATUS_TIMEOUT:
return "Timeout";
break;
case SFE_UBLOX_STATUS_COMMAND_NACK:
return "Command not acknowledged (NACK)";
break;
case SFE_UBLOX_STATUS_OUT_OF_RANGE:
return "Out of range";
break;
case SFE_UBLOX_STATUS_INVALID_ARG:
return "Invalid Arg";
break;
case SFE_UBLOX_STATUS_INVALID_OPERATION:
return "Invalid operation";
break;
case SFE_UBLOX_STATUS_MEM_ERR:
return "Memory Error";
break;
case SFE_UBLOX_STATUS_HW_ERR:
return "Hardware Error";
break;
case SFE_UBLOX_STATUS_DATA_SENT:
return "Data Sent";
break;
case SFE_UBLOX_STATUS_DATA_RECEIVED:
return "Data Received";
break;
case SFE_UBLOX_STATUS_I2C_COMM_FAILURE:
return "I2C Comm Failure";
break;
case SFE_UBLOX_STATUS_DATA_OVERWRITTEN:
return "Data Packet Overwritten";
break;
default:
return "Unknown Status";
break;
}
return "None";
}
void SFE_UBLOX_GPS::factoryReset()
{
// Copy default settings to permanent
// Note: this does not load the permanent configuration into the current configuration. Calling factoryDefault() will do that.
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_CFG;
packetCfg.len = 13;
packetCfg.startingSpot = 0;
for (uint8_t i = 0; i < 4; i++)
{
payloadCfg[0 + i] = 0xff; // clear mask: copy default config to permanent config
payloadCfg[4 + i] = 0x00; // save mask: don't save current to permanent
payloadCfg[8 + i] = 0x00; // load mask: don't copy permanent config to current
}
payloadCfg[12] = 0xff; // all forms of permanent memory
sendCommand(&packetCfg, 0); // don't expect ACK
hardReset(); // cause factory default config to actually be loaded and used cleanly
}
void SFE_UBLOX_GPS::hardReset()
{
// Issue hard reset
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_RST;
packetCfg.len = 4;
packetCfg.startingSpot = 0;
payloadCfg[0] = 0xff; // cold start
payloadCfg[1] = 0xff; // cold start
payloadCfg[2] = 0; // 0=HW reset
payloadCfg[3] = 0; // reserved
sendCommand(&packetCfg, 0); // don't expect ACK
}
//Changes the serial baud rate of the Ublox module, can't return success/fail 'cause ACK from modem
//is lost due to baud rate change
void SFE_UBLOX_GPS::setSerialRate(uint32_t baudrate, uint8_t uartPort, uint16_t maxWait)
{
//Get the current config values for the UART port
getPortSettings(uartPort, maxWait); //This will load the payloadCfg array with current port settings
if (_printDebug == true)
{
_debugSerial->print(F("Current baud rate: "));
_debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]);
}
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_PRT;
packetCfg.len = 20;
packetCfg.startingSpot = 0;
//payloadCfg is now loaded with current bytes. Change only the ones we need to
payloadCfg[8] = baudrate;
payloadCfg[9] = baudrate >> 8;
payloadCfg[10] = baudrate >> 16;
payloadCfg[11] = baudrate >> 24;
if (_printDebug == true)
{
_debugSerial->print(F("New baud rate:"));
_debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]);
}
sfe_ublox_status_e retVal = sendCommand(&packetCfg, maxWait);
if (_printDebug == true)
{
_debugSerial->print(F("setSerialRate: sendCommand returned: "));
_debugSerial->println(statusString(retVal));
}
}
//Changes the I2C address that the Ublox module responds to
//0x42 is the default but can be changed with this command
boolean SFE_UBLOX_GPS::setI2CAddress(uint8_t deviceAddress, uint16_t maxWait)
{
//Get the current config values for the I2C port
getPortSettings(COM_PORT_I2C, maxWait); //This will load the payloadCfg array with current port settings
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_PRT;
packetCfg.len = 20;
packetCfg.startingSpot = 0;
//payloadCfg is now loaded with current bytes. Change only the ones we need to
payloadCfg[4] = deviceAddress << 1; //DDC mode LSB
if (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT) // We are only expecting an ACK
{
//Success! Now change our internal global.
_gpsI2Caddress = deviceAddress; //Store the I2C address from user
return (true);
}
return (false);
}
//Want to see the NMEA messages on the Serial port? Here's how
void SFE_UBLOX_GPS::setNMEAOutputPort(Stream &nmeaOutputPort)
{
_nmeaOutputPort = &nmeaOutputPort; //Store the port from user
}
//Called regularly to check for available bytes on the user' specified port
boolean SFE_UBLOX_GPS::checkUblox(uint8_t requestedClass, uint8_t requestedID)
{
return checkUbloxInternal(&packetCfg, requestedClass, requestedID);
}
//Called regularly to check for available bytes on the user' specified port
boolean SFE_UBLOX_GPS::checkUbloxInternal(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID)
{
if (commType == COMM_TYPE_I2C)
return (checkUbloxI2C(incomingUBX, requestedClass, requestedID));
else if (commType == COMM_TYPE_SERIAL)
return (checkUbloxSerial(incomingUBX, requestedClass, requestedID));
return false;
}
//Polls I2C for data, passing any new bytes to process()
//Returns true if new bytes are available
boolean SFE_UBLOX_GPS::checkUbloxI2C(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID)
{
if (millis() - lastCheck >= i2cPollingWait)
{
//Get the number of bytes available from the module
uint16_t bytesAvailable = 0;
_i2cPort->beginTransmission(_gpsI2Caddress);
_i2cPort->write(0xFD); //0xFD (MSB) and 0xFE (LSB) are the registers that contain number of bytes available
if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus.
return (false); //Sensor did not ACK
_i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)2);
if (_i2cPort->available())
{
uint8_t msb = _i2cPort->read();
uint8_t lsb = _i2cPort->read();
if (lsb == 0xFF)
{
//I believe this is a Ublox bug. Device should never present an 0xFF.
if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging
{
_debugSerial->println(F("checkUbloxI2C: Ublox bug, length lsb is 0xFF"));
}
if (checksumFailurePin >= 0)
{
digitalWrite((uint8_t)checksumFailurePin, LOW);
delay(10);
digitalWrite((uint8_t)checksumFailurePin, HIGH);
}
lastCheck = millis(); //Put off checking to avoid I2C bus traffic
return (false);
}
bytesAvailable = (uint16_t)msb << 8 | lsb;
}
if (bytesAvailable == 0)
{
if (_printDebug == true)
{
_debugSerial->println(F("checkUbloxI2C: OK, zero bytes available"));
}
lastCheck = millis(); //Put off checking to avoid I2C bus traffic
return (false);
}
//Check for undocumented bit error. We found this doing logic scans.
//This error is rare but if we incorrectly interpret the first bit of the two 'data available' bytes as 1
//then we have far too many bytes to check. May be related to I2C setup time violations: https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library/issues/40
if (bytesAvailable & ((uint16_t)1 << 15))
{
//Clear the MSbit
bytesAvailable &= ~((uint16_t)1 << 15);
if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging
{
_debugSerial->print(F("checkUbloxI2C: Bytes available error:"));
_debugSerial->println(bytesAvailable);
if (checksumFailurePin >= 0)
{
digitalWrite((uint8_t)checksumFailurePin, LOW);
delay(10);
digitalWrite((uint8_t)checksumFailurePin, HIGH);
}
}
}
if (bytesAvailable > 100)
{
if (_printDebug == true)
{
_debugSerial->print(F("checkUbloxI2C: Large packet of "));
_debugSerial->print(bytesAvailable);
_debugSerial->println(F(" bytes received"));
}
}
else
{
if (_printDebug == true)
{
_debugSerial->print(F("checkUbloxI2C: Reading "));
_debugSerial->print(bytesAvailable);
_debugSerial->println(F(" bytes"));
}
}
while (bytesAvailable)
{
_i2cPort->beginTransmission(_gpsI2Caddress);
_i2cPort->write(0xFF); //0xFF is the register to read data from
if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus.
return (false); //Sensor did not ACK
//Limit to 32 bytes or whatever the buffer limit is for given platform
uint16_t bytesToRead = bytesAvailable;
if (bytesToRead > I2C_BUFFER_LENGTH)
bytesToRead = I2C_BUFFER_LENGTH;
TRY_AGAIN:
_i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)bytesToRead);
if (_i2cPort->available())
{
for (uint16_t x = 0; x < bytesToRead; x++)
{
uint8_t incoming = _i2cPort->read(); //Grab the actual character
//Check to see if the first read is 0x7F. If it is, the module is not ready
//to respond. Stop, wait, and try again
if (x == 0)
{
if (incoming == 0x7F)
{
if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging
{
_debugSerial->println(F("checkUbloxU2C: Ublox error, module not ready with data"));
}
delay(5); //In logic analyzation, the module starting responding after 1.48ms
if (checksumFailurePin >= 0)
{
digitalWrite((uint8_t)checksumFailurePin, LOW);
delay(10);
digitalWrite((uint8_t)checksumFailurePin, HIGH);
}
goto TRY_AGAIN;
}
}
process(incoming, incomingUBX, requestedClass, requestedID); //Process this valid character
}
}
else
return (false); //Sensor did not respond
bytesAvailable -= bytesToRead;
}
}
return (true);
} //end checkUbloxI2C()
//Checks Serial for data, passing any new bytes to process()
boolean SFE_UBLOX_GPS::checkUbloxSerial(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID)
{
while (_serialPort->available())
{
process(_serialPort->read(), incomingUBX, requestedClass, requestedID);
}
return (true);
} //end checkUbloxSerial()
//Processes NMEA and UBX binary sentences one byte at a time
//Take a given byte and file it into the proper array
void SFE_UBLOX_GPS::process(uint8_t incoming, ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID)
{
if ((currentSentence == NONE) || (currentSentence == NMEA))
{
if (incoming == 0xB5) //UBX binary frames start with 0xB5, aka μ
{
//This is the start of a binary sentence. Reset flags.
//We still don't know the response class
ubxFrameCounter = 0;
currentSentence = UBX;
//Reset the packetBuf.counter even though we will need to reset it again when ubxFrameCounter == 2
packetBuf.counter = 0;
ignoreThisPayload = false; //We should not ignore this payload - yet
//Store data in packetBuf until we know if we have a requested class and ID match
activePacketBuffer = SFE_UBLOX_PACKET_PACKETBUF;
}
else if (incoming == '$')
{
currentSentence = NMEA;
}
else if (incoming == 0xD3) //RTCM frames start with 0xD3
{
rtcmFrameCounter = 0;
currentSentence = RTCM;
}
else
{
//This character is unknown or we missed the previous start of a sentence
}
}
//Depending on the sentence, pass the character to the individual processor
if (currentSentence == UBX)
{
//Decide what type of response this is
if ((ubxFrameCounter == 0) && (incoming != 0xB5)) //ISO 'μ'
currentSentence = NONE; //Something went wrong. Reset.
else if ((ubxFrameCounter == 1) && (incoming != 0x62)) //ASCII 'b'
currentSentence = NONE; //Something went wrong. Reset.
// Note to future self:
// There may be some duplication / redundancy in the next few lines as processUBX will also
// load information into packetBuf, but we'll do it here too for clarity
else if (ubxFrameCounter == 2) //Class
{
// Record the class in packetBuf until we know what to do with it
packetBuf.cls = incoming; // (Duplication)
rollingChecksumA = 0; //Reset our rolling checksums here (not when we receive the 0xB5)
rollingChecksumB = 0;
packetBuf.counter = 0; //Reset the packetBuf.counter (again)
packetBuf.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; // Reset the packet validity (redundant?)
packetBuf.startingSpot = incomingUBX->startingSpot; //Copy the startingSpot
}
else if (ubxFrameCounter == 3) //ID
{
// Record the ID in packetBuf until we know what to do with it
packetBuf.id = incoming; // (Duplication)
//We can now identify the type of response
//If the packet we are receiving is not an ACK then check for a class and ID match
if (packetBuf.cls != UBX_CLASS_ACK)
{
//This is not an ACK so check for a class and ID match
if ((packetBuf.cls == requestedClass) && (packetBuf.id == requestedID))
{
//This is not an ACK and we have a class and ID match
//So start diverting data into incomingUBX (usually packetCfg)
activePacketBuffer = SFE_UBLOX_PACKET_PACKETCFG;
incomingUBX->cls = packetBuf.cls; //Copy the class and ID into incomingUBX (usually packetCfg)
incomingUBX->id = packetBuf.id;
incomingUBX->counter = packetBuf.counter; //Copy over the .counter too
}
else
{
//This is not an ACK and we do not have a class and ID match
//so we should keep diverting data into packetBuf and ignore the payload
ignoreThisPayload = true;
}
}
else
{
// This is an ACK so it is to early to do anything with it
// We need to wait until we have received the length and data bytes
// So we should keep diverting data into packetBuf
}
}
else if (ubxFrameCounter == 4) //Length LSB
{
//We should save the length in packetBuf even if activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG
packetBuf.len = incoming; // (Duplication)
}
else if (ubxFrameCounter == 5) //Length MSB
{
//We should save the length in packetBuf even if activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG
packetBuf.len |= incoming << 8; // (Duplication)
}
else if (ubxFrameCounter == 6) //This should be the first byte of the payload unless .len is zero
{
if (packetBuf.len == 0) // Check if length is zero (hopefully this is impossible!)
{
if (_printDebug == true)
{
_debugSerial->print(F("process: ZERO LENGTH packet received: Class: 0x"));
_debugSerial->print(packetBuf.cls, HEX);
_debugSerial->print(F(" ID: 0x"));
_debugSerial->println(packetBuf.id, HEX);
}
//If length is zero (!) this will be the first byte of the checksum so record it
packetBuf.checksumA = incoming;
}
else
{
//The length is not zero so record this byte in the payload
packetBuf.payload[0] = incoming;
}
}
else if (ubxFrameCounter == 7) //This should be the second byte of the payload unless .len is zero or one
{
if (packetBuf.len == 0) // Check if length is zero (hopefully this is impossible!)
{
//If length is zero (!) this will be the second byte of the checksum so record it
packetBuf.checksumB = incoming;
}
else if (packetBuf.len == 1) // Check if length is one
{
//The length is one so this is the first byte of the checksum
packetBuf.checksumA = incoming;
}
else // Length is >= 2 so this must be a payload byte
{
packetBuf.payload[1] = incoming;
}
// Now that we have received two payload bytes, we can check for a matching ACK/NACK
if ((activePacketBuffer == SFE_UBLOX_PACKET_PACKETBUF) // If we are not already processing a data packet
&& (packetBuf.cls == UBX_CLASS_ACK) // and if this is an ACK/NACK
&& (packetBuf.payload[0] == requestedClass) // and if the class matches
&& (packetBuf.payload[1] == requestedID)) // and if the ID matches
{
if (packetBuf.len == 2) // Check if .len is 2
{
// Then this is a matching ACK so copy it into packetAck
activePacketBuffer = SFE_UBLOX_PACKET_PACKETACK;
packetAck.cls = packetBuf.cls;
packetAck.id = packetBuf.id;
packetAck.len = packetBuf.len;
packetAck.counter = packetBuf.counter;
packetAck.payload[0] = packetBuf.payload[0];
packetAck.payload[1] = packetBuf.payload[1];
}
else // Length is not 2 (hopefully this is impossible!)
{
if (_printDebug == true)
{
_debugSerial->print(F("process: ACK received with .len != 2: Class: 0x"));
_debugSerial->print(packetBuf.payload[0], HEX);
_debugSerial->print(F(" ID: 0x"));
_debugSerial->print(packetBuf.payload[1], HEX);
_debugSerial->print(F(" len: "));
_debugSerial->println(packetBuf.len);
}
}
}
}
//Divert incoming into the correct buffer
if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETACK)
processUBX(incoming, &packetAck, requestedClass, requestedID);
else if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG)
processUBX(incoming, incomingUBX, requestedClass, requestedID);
else // if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETBUF)
processUBX(incoming, &packetBuf, requestedClass, requestedID);
//Finally, increment the frame counter
ubxFrameCounter++;
}
else if (currentSentence == NMEA)
{
processNMEA(incoming); //Process each NMEA character
}
else if (currentSentence == RTCM)
{
processRTCMframe(incoming); //Deal with RTCM bytes
}
}
//This is the default or generic NMEA processor. We're only going to pipe the data to serial port so we can see it.
//User could overwrite this function to pipe characters to nmea.process(c) of tinyGPS or MicroNMEA
//Or user could pipe each character to a buffer, radio, etc.
void SFE_UBLOX_GPS::processNMEA(char incoming)
{
//If user has assigned an output port then pipe the characters there
if (_nmeaOutputPort != NULL)
_nmeaOutputPort->write(incoming); //Echo this byte to the serial port
}
//We need to be able to identify an RTCM packet and then the length
//so that we know when the RTCM message is completely received and we then start
//listening for other sentences (like NMEA or UBX)
//RTCM packet structure is very odd. I never found RTCM STANDARD 10403.2 but
//http://d1.amobbs.com/bbs_upload782111/files_39/ourdev_635123CK0HJT.pdf is good
//https://dspace.cvut.cz/bitstream/handle/10467/65205/F3-BP-2016-Shkalikava-Anastasiya-Prenos%20polohove%20informace%20prostrednictvim%20datove%20site.pdf?sequence=-1
//Lead me to: https://forum.u-blox.com/index.php/4348/how-to-read-rtcm-messages-from-neo-m8p
//RTCM 3.2 bytes look like this:
//Byte 0: Always 0xD3
//Byte 1: 6-bits of zero
//Byte 2: 10-bits of length of this packet including the first two-ish header bytes, + 6.
//byte 3 + 4 bits: Msg type 12 bits
//Example: D3 00 7C 43 F0 ... / 0x7C = 124+6 = 130 bytes in this packet, 0x43F = Msg type 1087
void SFE_UBLOX_GPS::processRTCMframe(uint8_t incoming)
{
if (rtcmFrameCounter == 1)
{
rtcmLen = (incoming & 0x03) << 8; //Get the last two bits of this byte. Bits 8&9 of 10-bit length
}
else if (rtcmFrameCounter == 2)
{
rtcmLen |= incoming; //Bits 0-7 of packet length
rtcmLen += 6; //There are 6 additional bytes of what we presume is header, msgType, CRC, and stuff
}
/*else if (rtcmFrameCounter == 3)
{
rtcmMsgType = incoming << 4; //Message Type, MS 4 bits
}
else if (rtcmFrameCounter == 4)
{
rtcmMsgType |= (incoming >> 4); //Message Type, bits 0-7
}*/
rtcmFrameCounter++;
processRTCM(incoming); //Here is where we expose this byte to the user
if (rtcmFrameCounter == rtcmLen)
{
//We're done!
currentSentence = NONE; //Reset and start looking for next sentence type
}
}
//This function is called for each byte of an RTCM frame
//Ths user can overwrite this function and process the RTCM frame as they please
//Bytes can be piped to Serial or other interface. The consumer could be a radio or the internet (Ntrip broadcaster)
void SFE_UBLOX_GPS::processRTCM(uint8_t incoming)
{
//Radio.sendReliable((String)incoming); //An example of passing this byte to a radio
//_debugSerial->write(incoming); //An example of passing this byte out the serial port
//Debug printing
// _debugSerial->print(F(" "));
// if(incoming < 0x10) _debugSerial->print(F("0"));
// if(incoming < 0x10) _debugSerial->print(F("0"));
// _debugSerial->print(incoming, HEX);
// if(rtcmFrameCounter % 16 == 0) _debugSerial->println();
}
//Given a character, file it away into the uxb packet structure
//Set valid to VALID or NOT_VALID once sentence is completely received and passes or fails CRC
//The payload portion of the packet can be 100s of bytes but the max array
//size is MAX_PAYLOAD_SIZE bytes. startingSpot can be set so we only record
//a subset of bytes within a larger packet.
void SFE_UBLOX_GPS::processUBX(uint8_t incoming, ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID)
{
//Add all incoming bytes to the rolling checksum
//Stop at len+4 as this is the checksum bytes to that should not be added to the rolling checksum
if (incomingUBX->counter < incomingUBX->len + 4)
addToChecksum(incoming);
if (incomingUBX->counter == 0)
{
incomingUBX->cls = incoming;
}
else if (incomingUBX->counter == 1)
{
incomingUBX->id = incoming;
}
else if (incomingUBX->counter == 2) //Len LSB
{
incomingUBX->len = incoming;
}
else if (incomingUBX->counter == 3) //Len MSB
{
incomingUBX->len |= incoming << 8;
}
else if (incomingUBX->counter == incomingUBX->len + 4) //ChecksumA
{
incomingUBX->checksumA = incoming;
}
else if (incomingUBX->counter == incomingUBX->len + 5) //ChecksumB
{
incomingUBX->checksumB = incoming;
currentSentence = NONE; //We're done! Reset the sentence to being looking for a new start char
//Validate this sentence
if ((incomingUBX->checksumA == rollingChecksumA) && (incomingUBX->checksumB == rollingChecksumB))
{
incomingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_VALID; // Flag the packet as valid
// Let's check if the class and ID match the requestedClass and requestedID
// Remember - this could be a data packet or an ACK packet
if ((incomingUBX->cls == requestedClass) && (incomingUBX->id == requestedID))
{
incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_VALID; // If we have a match, set the classAndIDmatch flag to valid
}
// If this is an ACK then let's check if the class and ID match the requestedClass and requestedID
else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->id == UBX_ACK_ACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID))
{
incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_VALID; // If we have a match, set the classAndIDmatch flag to valid
}
// If this is a NACK then let's check if the class and ID match the requestedClass and requestedID
else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->id == UBX_ACK_NACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID))
{
incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_NOTACKNOWLEDGED; // If we have a match, set the classAndIDmatch flag to NOTACKNOWLEDGED
if (_printDebug == true)
{
_debugSerial->print(F("processUBX: NACK received: Requested Class: 0x"));
_debugSerial->print(incomingUBX->payload[0], HEX);
_debugSerial->print(F(" Requested ID: 0x"));
_debugSerial->println(incomingUBX->payload[1], HEX);
}
}
if (_printDebug == true)
{
_debugSerial->print(F("Incoming: Size: "));
_debugSerial->print(incomingUBX->len);
_debugSerial->print(F(" Received: "));
printPacket(incomingUBX);
if (incomingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID)
{
_debugSerial->println(F("packetCfg now valid"));
}
if (packetAck.valid == SFE_UBLOX_PACKET_VALIDITY_VALID)
{
_debugSerial->println(F("packetAck now valid"));
}
if (incomingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID)
{
_debugSerial->println(F("packetCfg classAndIDmatch"));
}
if (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID)
{
_debugSerial->println(F("packetAck classAndIDmatch"));
}
}
//We've got a valid packet, now do something with it but only if ignoreThisPayload is false
if (ignoreThisPayload == false)
{
processUBXpacket(incomingUBX);
}
}
else // Checksum failure
{
incomingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID;
// Let's check if the class and ID match the requestedClass and requestedID.
// This is potentially risky as we are saying that we saw the requested Class and ID
// but that the packet checksum failed. Potentially it could be the class or ID bytes
// that caused the checksum error!
if ((incomingUBX->cls == requestedClass) && (incomingUBX->id == requestedID))
{
incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID; // If we have a match, set the classAndIDmatch flag to not valid
}
// If this is an ACK then let's check if the class and ID match the requestedClass and requestedID
else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID))
{
incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID; // If we have a match, set the classAndIDmatch flag to not valid
}
if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging
{
//Drive an external pin to allow for easier logic analyzation
if (checksumFailurePin >= 0)
{
digitalWrite((uint8_t)checksumFailurePin, LOW);
delay(10);
digitalWrite((uint8_t)checksumFailurePin, HIGH);
}
_debugSerial->print(F("Checksum failed:"));
_debugSerial->print(F(" checksumA: "));
_debugSerial->print(incomingUBX->checksumA);
_debugSerial->print(F(" checksumB: "));
_debugSerial->print(incomingUBX->checksumB);
_debugSerial->print(F(" rollingChecksumA: "));
_debugSerial->print(rollingChecksumA);
_debugSerial->print(F(" rollingChecksumB: "));
_debugSerial->print(rollingChecksumB);
_debugSerial->println();
_debugSerial->print(F("Failed : "));
_debugSerial->print(F("Size: "));
_debugSerial->print(incomingUBX->len);
_debugSerial->print(F(" Received: "));
printPacket(incomingUBX);
}
}
}
else //Load this byte into the payload array
{
//If a UBX_NAV_PVT packet comes in asynchronously, we need to fudge the startingSpot
uint16_t startingSpot = incomingUBX->startingSpot;
if (incomingUBX->cls == UBX_CLASS_NAV && incomingUBX->id == UBX_NAV_PVT)
startingSpot = 0;
//Begin recording if counter goes past startingSpot
if ((incomingUBX->counter - 4) >= startingSpot)
{
//Check to see if we have room for this byte
if (((incomingUBX->counter - 4) - startingSpot) < MAX_PAYLOAD_SIZE) //If counter = 208, starting spot = 200, we're good to record.
{
// Check if this is payload data which should be ignored
if (ignoreThisPayload == false)
{
incomingUBX->payload[incomingUBX->counter - 4 - startingSpot] = incoming; //Store this byte into payload array
}
}
}
}
//Increment the counter
incomingUBX->counter++;
if (incomingUBX->counter == MAX_PAYLOAD_SIZE)
{
//Something has gone very wrong
currentSentence = NONE; //Reset the sentence to being looking for a new start char
if (_printDebug == true)
{
_debugSerial->println(F("processUBX: counter hit MAX_PAYLOAD_SIZE"));
}
}
}
//Once a packet has been received and validated, identify this packet's class/id and update internal flags
//Note: if the user requests a PVT or a HPPOSLLH message using a custom packet, the data extraction will
// not work as expected beacuse extractLong etc are hardwired to packetCfg payloadCfg. Ideally
// extractLong etc should be updated so they receive a pointer to the packet buffer.
void SFE_UBLOX_GPS::processUBXpacket(ubxPacket *msg)
{
switch (msg->cls)
{
case UBX_CLASS_NAV:
if (msg->id == UBX_NAV_PVT && msg->len == 92)
{
//Parse various byte fields into global vars
constexpr int startingSpot = 0; //fixed value used in processUBX
timeOfWeek = extractLong(0);
gpsMillisecond = extractLong(0) % 1000; //Get last three digits of iTOW
gpsYear = extractInt(4);
gpsMonth = extractByte(6);
gpsDay = extractByte(7);
gpsHour = extractByte(8);
gpsMinute = extractByte(9);
gpsSecond = extractByte(10);
gpsDateValid = extractByte(11) & 0x01;
gpsTimeValid = (extractByte(11) & 0x02) >> 1;
gpsNanosecond = extractLong(16); //Includes milliseconds
fixType = extractByte(20 - startingSpot);
carrierSolution = extractByte(21 - startingSpot) >> 6; //Get 6th&7th bits of this byte
SIV = extractByte(23 - startingSpot);
longitude = extractLong(24 - startingSpot);
latitude = extractLong(28 - startingSpot);
altitude = extractLong(32 - startingSpot);
altitudeMSL = extractLong(36 - startingSpot);
groundSpeed = extractLong(60 - startingSpot);
headingOfMotion = extractLong(64 - startingSpot);
pDOP = extractInt(76 - startingSpot);
//Mark all datums as fresh (not read before)
moduleQueried.gpsiTOW = true;
moduleQueried.gpsYear = true;
moduleQueried.gpsMonth = true;
moduleQueried.gpsDay = true;
moduleQueried.gpsHour = true;
moduleQueried.gpsMinute = true;
moduleQueried.gpsSecond = true;
moduleQueried.gpsDateValid = true;
moduleQueried.gpsTimeValid = true;
moduleQueried.gpsNanosecond = true;
moduleQueried.all = true;
moduleQueried.longitude = true;
moduleQueried.latitude = true;
moduleQueried.altitude = true;
moduleQueried.altitudeMSL = true;
moduleQueried.SIV = true;
moduleQueried.fixType = true;
moduleQueried.carrierSolution = true;
moduleQueried.groundSpeed = true;
moduleQueried.headingOfMotion = true;
moduleQueried.pDOP = true;
}
else if (msg->id == UBX_NAV_HPPOSLLH && msg->len == 36)
{
timeOfWeek = extractLong(4);
highResLongitude = extractLong(8);
highResLatitude = extractLong(12);
elipsoid = extractLong(16);
meanSeaLevel = extractLong(20);
highResLongitudeHp = extractSignedChar(24);
highResLatitudeHp = extractSignedChar(25);
elipsoidHp = extractSignedChar(26);
meanSeaLevelHp = extractSignedChar(27);
horizontalAccuracy = extractLong(28);
verticalAccuracy = extractLong(32);
highResModuleQueried.all = true;
highResModuleQueried.highResLatitude = true;
highResModuleQueried.highResLatitudeHp = true;
highResModuleQueried.highResLongitude = true;
highResModuleQueried.highResLongitudeHp = true;
highResModuleQueried.elipsoid = true;
highResModuleQueried.elipsoidHp = true;
highResModuleQueried.meanSeaLevel = true;
highResModuleQueried.meanSeaLevelHp = true;
highResModuleQueried.geoidSeparation = true;
highResModuleQueried.horizontalAccuracy = true;
highResModuleQueried.verticalAccuracy = true;
moduleQueried.gpsiTOW = true; // this can arrive via HPPOS too.
if (_printDebug == true)
{
_debugSerial->print(F("Sec: "));
_debugSerial->print(((float)extractLong(4)) / 1000.0f);
_debugSerial->print(F(" "));
_debugSerial->print(F("LON: "));
_debugSerial->print(((float)(int32_t)extractLong(8)) / 10000000.0f);
_debugSerial->print(F(" "));
_debugSerial->print(F("LAT: "));
_debugSerial->print(((float)(int32_t)extractLong(12)) / 10000000.0f);
_debugSerial->print(F(" "));
_debugSerial->print(F("ELI M: "));
_debugSerial->print(((float)(int32_t)extractLong(16)) / 1000.0f);
_debugSerial->print(F(" "));
_debugSerial->print(F("MSL M: "));
_debugSerial->print(((float)(int32_t)extractLong(20)) / 1000.0f);
_debugSerial->print(F(" "));
_debugSerial->print(F("LON HP: "));
_debugSerial->print(extractSignedChar(24));
_debugSerial->print(F(" "));
_debugSerial->print(F("LAT HP: "));
_debugSerial->print(extractSignedChar(25));
_debugSerial->print(F(" "));
_debugSerial->print(F("ELI HP: "));
_debugSerial->print(extractSignedChar(26));
_debugSerial->print(F(" "));
_debugSerial->print(F("MSL HP: "));
_debugSerial->print(extractSignedChar(27));