-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathgps.cpp
More file actions
1590 lines (1478 loc) · 54.4 KB
/
gps.cpp
File metadata and controls
1590 lines (1478 loc) · 54.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2019-2021 OpenBikeSensor Contributors
* Contact: https://openbikesensor.org
*
* This file is part of the OpenBikeSensor firmware.
*
* The OpenBikeSensor firmware is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* OpenBikeSensor firmware is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the OpenBikeSensor firmware. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include "gps.h"
#include "utils/timeutils.h"
/* Most input from u-blox6_ReceiverDescrProtSpec_(GPS.G6-SW-10018)_Public.pdf */
const String Gps::INF_SEVERITY_STRING[] = {
String("ERR"), String("WRN"), String("NTC"),
String("TST"), String("DBG")
};
bool Gps::is_neo6() const {
if (String(hwString).substring(0,4) == String("0004")) {
return true;
}
return false;
}
bool Gps::is_neo8() const {
if (String(hwString).substring(0,4) == String("0008")) {
return true;
}
return false;
}
bool Gps::is_neo10() const {
if (String(hwString).substring(0,4) == String("000A")) {
return true;
}
return false;
}
String Gps::hw() const {
if (is_neo6()){
return "Neo6";
}
if (is_neo8()){
return "Neo8";
}
if (is_neo10()) {
return "NeoA";
}
return "Neo" + String(hwString).substring(3,4);
}
void Gps::begin() {
setBaud();
softResetGps();
if (mGpsNeedsConfigUpdate) {
configureGpsModule();
}
pollStatistics();
if((!is_neo6()) || (!SD.exists(AID_INI_DATA_FILE_NAME))) {
// we're on a non-6 neo and avoid AID_INI because is deprecated
// or we're on a neo6 but last boot we didn't get far enough to receive fresh
// ALP_INI data after initializing
// so restart GPS for good measure.
if (is_neo6()) log_i("We found no AID_INI on with neo6 on boot - coldstart gps in case its in a state where it doesn't get fixes");
if (!is_neo6()) log_i("Coldstart because we found that newer neos profit from that.");
coldStartGps();
}
pollStatistics();
if (is_neo6()) {
enableAlpIfDataIsAvailable();
}
if (mLastTimeTimeSet == 0) {
#ifdef UBX_M10
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_TIMEGPS_UART1, 1);
#endif
#ifdef UBX_M6
setMessageInterval(UBX_MSG::NAV_TIMEGPS, 1);
#endif
} else {
#ifdef UBX_M10
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_TIMEGPS_UART1, 240);
#endif
#ifdef UBX_M6
setMessageInterval(UBX_MSG::NAV_TIMEGPS, 240);
#endif
}
//Serial.updateBaudRate(9600);
//mSerial.begin(9600, SERIAL_8N1);
// Debug - forward gps serial to normal serial
/*
log_e("--------_STARTING LOOP");
while(1)
{
int val = mSerial.read();
if(val >= 0)
Serial.write(val);
val = Serial.read();
if(val >= 0)
mSerial.write(val);
}*/
}
void Gps::sendUbx(UBX_MSG ubxMsgId, const uint8_t payload[], uint16_t length) {
sendUbx(static_cast<uint16_t>(ubxMsgId), payload, length);
}
void Gps::sendUbx(uint16_t ubxMsgId, const uint8_t payload[], uint16_t length) {
// We copy over all in one go, assume to be more efficient than byte by byte to serial
uint8_t buffer[length + 8];
uint8_t chkA = 0;
uint8_t chkB = 0;
buffer[0] = 0xb5;
buffer[1] = 0x62;
buffer[2] = ubxMsgId & 0xFFU;
chkA += buffer[2]; chkB += chkA;
buffer[3] = ubxMsgId >> 8;
chkA += buffer[3]; chkB += chkA;
buffer[4] = length & 0xFFU;
chkA += buffer[4]; chkB += chkA;
buffer[5] = length >> 8;
chkA += buffer[5]; chkB += chkA;
for (int i = 0; i < length; i++) {
const uint8_t data = payload[i];
buffer[i + 6] = data;
chkA += data; chkB += chkA;
}
buffer[6 + length] = chkA;
buffer[7 + length] = chkB;
mSerial.write(buffer, length + 8);
}
#ifdef UBX_M10
// Send a CFG_VALSET ubx command to write a configuration
// Only available in M10 devices
void Gps::sendUbxCfg(enum UBX_CFG_LAYER layer, UBX_CFG_KEY_ID keyId, uint32_t value)
{
uint8_t ubxCfgMsg[] = {0x00, layer, 0x00, 0x00,
(uint8_t)((uint32_t)keyId), (uint8_t)(((uint32_t)keyId)>>8), (uint8_t)(((uint32_t)keyId)>>16), (uint8_t)(((uint32_t)keyId)>>24),
(uint8_t)((uint32_t)value), (uint8_t)(((uint32_t)value)>>8), (uint8_t)(((uint32_t)value)>>16), (uint8_t)(((uint32_t)value)>>24)};
uint16_t length = 0;
uint8_t lengthId = (((uint32_t)keyId)>>28)&0x07;
if(lengthId == 0x01 || lengthId == 0x02)
length = 1;
else if(lengthId == 0x03)
length = 2;
else if(lengthId == 0x04)
length = 4;
sendUbx(UBX_MSG::CFG_VALSET, ubxCfgMsg, length + 8);
}
#endif
/* Method sends the message in the receive buffer! */
void Gps::sendUbxDirect() {
const uint16_t length = mGpsBuffer.ubxHeader.length;
uint8_t chkA = 0;
uint8_t chkB = 0;
for (int i = 2; i < length + 6; i++) {
chkA += mGpsBuffer.u1Data[i]; chkB += chkA;
}
mGpsBuffer.u1Data[length + 6] = chkA;
mGpsBuffer.u1Data[length + 7] = chkB;
const size_t didSend = mSerial.write(mGpsBuffer.u1Data, length + 8);
if (didSend != (length + 8)) {
log_e("GPS, did send: %d expected %d", didSend, length + 8);
}
}
/* Resets the stored GPS config and stores our config! */
void Gps::configureGpsModule() {
// The CFG_CFG_CLR caused trouble on newer modules - connection settings get reset.
// no CFG_CFG_CLR for now if this fails we might need more fine-grained
// reset
// const uint8_t UBX_CFG_CFG_CLR[] = {
// 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0xFE, 0xFF, 0x00, 0x00, 0x03
// };
log_i("Start GPS CFG");
#ifdef UBX_M6
// INF messages via UBX only
const uint8_t UBX_CFG_INF_UBX[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0x00, 0x00, 0x00, 0x00,
};
sendAndWaitForAck(UBX_MSG::CFG_INF, UBX_CFG_INF_UBX, sizeof(UBX_CFG_INF_UBX));
// INF messages via UBX only
const uint8_t UBX_CFG_INF_NMEA[] = {
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
sendAndWaitForAck(UBX_MSG::CFG_INF, UBX_CFG_INF_NMEA, sizeof(UBX_CFG_INF_NMEA));
#endif
#ifdef UBX_M6
// Only required for M6 modules, NMEA is globally deactivated for M10 during begin()
setMessageInterval(UBX_MSG::NMEA_GGA, 0);
setMessageInterval(UBX_MSG::NMEA_RMC, 0);
setMessageInterval(UBX_MSG::NMEA_GLL, 0);
setMessageInterval(UBX_MSG::NMEA_GSA, 0);
setMessageInterval(UBX_MSG::NMEA_GSV, 0);
setMessageInterval(UBX_MSG::NMEA_VTG, 0);
#endif
setStatisticsIntervalInSeconds(0);
#ifdef UBX_M6
// AID is not available on M10 modules? At least I could not find it
setMessageInterval(UBX_MSG::AID_ALPSRV, 0);
#endif
enableSbas();
#ifdef UBX_M10
// Enable Glonass for M10, GPS and Galileo are enabled by default
sendCfgAndWaitForAck(UBX_CFG_LAYER::RAM, UBX_CFG_KEY_ID::CFG_SIGNAL_GLO_ENA, 1);
#endif
#ifdef UBX_M6
setMessageInterval(UBX_MSG::NAV_SBAS, 59);
setMessageInterval(UBX_MSG::NAV_POSLLH, 1);
setMessageInterval(UBX_MSG::NAV_DOP, 1);
setMessageInterval(UBX_MSG::NAV_SOL, 1);
setMessageInterval(UBX_MSG::NAV_VELNED, 1);
setMessageInterval(UBX_MSG::NAV_TIMEGPS, 1);
#endif
#ifdef UBX_M10
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_SBAS_UART1, 59);
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_POSLLH_UART1, 1);
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_DOP_UART1, 1);
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_VELNED_UART1, 1);
// SOL not available in M10, the message NAV-PVT is used instead
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_PVT_UART1, 1);
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_TIMEGPS_UART1, 1);
#endif
#ifdef UBX_M6
// "dynModel" - "3: pedestrian"
// "static hold" - 80cm/s == 2.88 km/h
// "staticHoldMaxDist" - 20m (not supported by our GPS receivers)
const uint8_t UBX_CFG_NAV5[] = {
0xff, 0xff, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00,
0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xfa, 0x00,
0xfa, 0x00, 0x64, 0x00, 0x2c, 0x01, 0x50, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
sendAndWaitForAck(UBX_MSG::CFG_NAV5, UBX_CFG_NAV5, sizeof(UBX_CFG_NAV5));
// on m8n enable all nav systems but baidou - baidou fails when used together with galileo
const uint8_t UBX_CFG_GNSS[] = {
0x00, 0x20, 0x20, 0x07, 0x00, 0x08, 0x10, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x01, 0x03,
0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x04, 0x08, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x08,
0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05,
0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x06, 0x08, 0x0e, 0x00, 0x01, 0x00, 0x01, 0x00
} ;
bool success = sendAndWaitForAck(UBX_MSG::CFG_GNSS, UBX_CFG_GNSS, sizeof(UBX_CFG_GNSS));
if (success) {
addStatisticsMessage("Successfully set GNSS");
}
else {
addStatisticsMessage("GNSS not configured, likely older GPS");
}
#endif
#ifdef UBX_M10
sendCfgAndWaitForAck(UBX_CFG_LAYER::RAM, UBX_CFG_KEY_ID::CFG_NAVSPG_DYNMODEL, 4); // Set dynamic model to 4 (automotive)
#endif
#ifdef UBX_M6
// Not used for M10, as OBSPro does not have a GPS LED
// "timepulse" - affecting the led, switching to 10ms pulse every 10sec,
// to be clearly differentiable from the default (100ms each second)
const uint8_t UBX_CFG_TP[] = {
0x80, 0x96, 0x98, 0x00, 0x10, 0x27, 0x00, 0x00,
0x01, 0x01, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
success = sendAndWaitForAck(UBX_MSG::CFG_TP, UBX_CFG_TP, sizeof(UBX_CFG_TP));
// newer gps (m8n) use tp5 for timepulse config
if (!success) {
const uint8_t UBX_CFG_TP5[] = { 0x00, 0x01, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00};
if (!sendAndWaitForAck(UBX_MSG::CFG_TP5, UBX_CFG_TP5, sizeof(UBX_CFG_TP5))) {
addStatisticsMessage("Successfully set timepulse for newer gps");
} else {
addStatisticsMessage("No ack for setting timepulse in either new or old format");
}
}
#endif
#ifdef UBX_M6
// What is this good for? Not bothering implementing that for OBSPro
// Leave some info in the GPS module
String inv = String("\x01openbikesensor.org/") + OBSVersion;
sendAndWaitForAck(UBX_MSG::CFG_RINV, reinterpret_cast<const uint8_t *>(inv.c_str()),
inv.length());
#endif
#ifdef UBX_M6
// AID only available in M6 modules
// Used to store GPS AID data every 3 minutes+
setMessageInterval(UBX_MSG::AID_INI, 185);
#endif
// Persist configuration
#ifdef UBX_M6
const uint8_t UBX_CFG_CFG_SAVE[] = {
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x17
};
#endif
#ifdef UBX_M10
const uint8_t UBX_CFG_CFG_SAVE[] = {
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x03
};
#endif
// write cfg takes longer.
if (sendAndWaitForAck(UBX_MSG::CFG_CFG, UBX_CFG_CFG_SAVE, sizeof(UBX_CFG_CFG_SAVE), 3000)) {
addStatisticsMessage("OBS: Did update GPS settings.");
} else {
addStatisticsMessage("OBS: Failed to save updated GPS settings.");
}
handle(20);
log_i("Config GPS done!");
}
void Gps::softResetGps() {
log_i("Soft-RESET GPS!");
handle();
const uint8_t UBX_CFG_RST[] = {0x00, 0x00, 0x02, 0x00}; // WARM START
// we had the case where the reset took several seconds
// see https://github.com/openbikesensor/OpenBikeSensorFirmware/issues/309
// Newer firmware (like M10 and likely also M8) will not ack this
// message so we do not wait for the ACK
sendUbx(UBX_MSG::CFG_RST, UBX_CFG_RST, 4);
waitForData(1000);
handle();
log_i("Soft-RESET GPS! Done");
}
void Gps::coldStartGps() {
log_i("Cold-Start GPS!");
handle();
const uint8_t UBX_CFG_RST[] = {0xFF, 0xFF, 0x00, 0x00};
// we had the case where the reset took several seconds
// see https://github.com/openbikesensor/OpenBikeSensorFirmware/issues/309
// Newer firmware (like M10 and likely also M8) will not ack this
// message so we do not wait for the ACK
sendUbx(UBX_MSG::CFG_RST, UBX_CFG_RST, 4);
waitForData(3000);
handle();
log_i("Cold Start GPS! Done");
}
/* There had been changes for the satellites used for SBAS
* in europe since the firmware of our GPS module was built
* we configure the module to use the 2 satellites that are
* in productive use as of 2021. This needs to be changed
* if used outside europa or might be in the future.
* We use EGNOS sats 123, 136 as of 2021 see
* https://de.wikipedia.org/wiki/European_Geostationary_Navigation_Overlay_Service
*/
void Gps::enableSbas() {// Enable SBAS subsystem!
const uint8_t UBX_CFG_SBAS[] = {
0x01, // ON
0x03, // Ranging | Correction | !integrity (like default)
0x02, // max 2 sats, default is 3
// NEO8-default: 120, 123, 127-129, 133, 135-138
// NEO8-egnos: 120, 123-124, 126, 131
// NEO6-egnos: 120, 123-124, 126, 131
// Wikipedia-egnos: 123, 136 (Test: 120) aus: 124 & 126
0x00, 0x08, 0x00, 0x01, 0x00 //
};
sendAndWaitForAck(UBX_MSG::CFG_SBAS, UBX_CFG_SBAS, sizeof(UBX_CFG_SBAS));
sendAndWaitForAck(UBX_MSG::CFG_SBAS); // get setting once
}
void Gps::enableAlpIfDataIsAvailable() {
#ifdef UBX_M6
if (AlpData::available()) {
log_i("Enable ALP");
// don't wait for ack - newer modules do not support this old ALPSRV
setMessageInterval(UBX_MSG::AID_ALPSRV, 1, false);
handle(100);
} else {
log_w("Disable ALP - no data!");
setMessageInterval(UBX_MSG::AID_ALPSRV, 0);
}
#endif
}
/* Poll or refresh one time statistics, also spends some time
* to collect the results.
*/
void Gps::pollStatistics() {
handle();
sendUbx(UBX_MSG::MON_VER);
handle(20);
if (is_neo6()){
// AID_ALP is a neo6-only thing
sendUbx(UBX_MSG::AID_ALP);
}
handle();
sendUbx(UBX_MSG::MON_HW);
handle();
sendUbx(UBX_MSG::NAV_STATUS);
handle();
sendAndWaitForAck(UBX_MSG::CFG_NAV5);
handle();
sendAndWaitForAck(UBX_MSG::CFG_RINV);
handle(40);
}
/* Prefer to subscribe to messages rather than polling. This lets
* the GPS module decide when to send the informative, none essential
* messages.
* Zero seconds means never.
*/
void Gps::setStatisticsIntervalInSeconds(uint16_t seconds) {
#ifdef UBX_M6
setMessageInterval(UBX_MSG::NAV_STATUS, seconds);
setMessageInterval(UBX_MSG::MON_HW, seconds);
#endif
#ifdef UBX_M10
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_NAV_STATUS_UART1, seconds);
setMessageInterval(UBX_CFG_KEY_ID::CFG_MSGOUT_UBX_MON_HW_UART1, seconds);
#endif
}
#ifdef UBX_M6
bool Gps::setMessageInterval(UBX_MSG msgId, uint8_t seconds, bool waitForAck) {
uint8_t ubxCfgMsg[] = {
0x0A, 0x09, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
};
ubxCfgMsg[0] = ((uint16_t) msgId) & 0xFFU;
ubxCfgMsg[1] = ((uint16_t) msgId) >> 8U;
ubxCfgMsg[3] = seconds;
bool result;
if (waitForAck) {
result = sendAndWaitForAck(UBX_MSG::CFG_MSG, ubxCfgMsg, sizeof(ubxCfgMsg));
} else {
result = true;
sendUbx(UBX_MSG::CFG_MSG, ubxCfgMsg, sizeof(ubxCfgMsg));
}
if (!result) {
log_e("Failed for CFG_MSG of 0x%04x!", msgId);
}
return result;
}
#endif
#ifdef UBX_M10
bool Gps::setMessageInterval(UBX_CFG_KEY_ID msgId, uint8_t seconds, bool waitForAck) {
bool result;
if (waitForAck) {
result = sendCfgAndWaitForAck(UBX_CFG_LAYER::RAM, msgId, seconds);
} else {
result = true;
sendUbxCfg(UBX_CFG_LAYER::RAM, msgId, seconds);
}
if (!result) {
log_e("Failed for sendUbxCfg of 0x%08x!", msgId);
}
return result;
}
#endif
/* Initialize the GPS module to talk 115200.
* If 115200 is not on by default the module is also configured,
* otherwise it is assumed that we have already configured the module.
*/
bool Gps::setBaud() {
mSerial.end();
mSerial.setRxBufferSize(512);
mSerial.begin(115200, SERIAL_8N1);
while(mSerial.read() >= 0) ;
if (checkCommunication()) {
log_i("GPS startup already 115200");
return true;
}
mSerial.updateBaudRate(9600);
// switch to 115200 "blind", switch off NMEA
#ifdef UBX_M6
const uint8_t UBX_CFG_PRT[] = {
0x01, 0x00, 0x00, 0x00, 0xd0, 0x08, 0x00, 0x00,
0x00, 0xc2, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00
};
sendUbx(UBX_MSG::CFG_PRT, UBX_CFG_PRT, sizeof(UBX_CFG_PRT));
#endif
#ifdef UBX_M10
sendCfgAndWaitForAck(UBX_CFG_LAYER::RAM, UBX_CFG_KEY_ID::CFG_UART1OUTPROT_NMEA, 0); // Disable NMEA
sendUbxCfg(UBX_CFG_LAYER::RAM, UBX_CFG_KEY_ID::CFG_UART1_BAUDRATE, 115200); // Blindly set baudrate
log_i("Blindly switched to 115200 baud rate");
#endif
mSerial.flush();
mSerial.updateBaudRate(115200);
// check if connected:
bool connected = checkCommunication();
if (!connected) {
log_e("Switch to 115200 was not possible, back to 9600.");
mSerial.updateBaudRate(9600);
connected = checkCommunication();
}
if (!connected) {
log_e("NO GPS????");
delay(5000);
}
else
log_i("Connected to GPS");
if (connected && mSerial.baudRate() / 10 != 115200 / 10) {
log_e("Reported rate: %d", mSerial.baudRate());
#ifdef UBX_M6
if (sendAndWaitForAck(UBX_MSG::CFG_PRT, UBX_CFG_PRT, sizeof(UBX_CFG_PRT))) {
mSerial.updateBaudRate(115200);
}
#endif
}
if (checkCommunication()) {
configureGpsModule();
}
return checkCommunication();
}
/* Send a "ping" message to the gps module and check,
* if we get a response. */
bool Gps::checkCommunication() {
return sendAndWaitForAck(UBX_MSG::CFG_RINV) || mAckReceived || mNakReceived;
}
bool Gps::sendAndWaitForAck(UBX_MSG ubxMsgId, const uint8_t *buffer, size_t size, const uint16_t timeoutMs) {
const int tries = 2;
auto start = millis();
bool result = false;
for (int i = 0; i < tries; i++) {
handle();
auto const loopStart = millis();
mNakReceived = false;
mAckReceived = false;
mLastAckMsgId = 0;
sendUbx(ubxMsgId, buffer, size);
mSerial.flush();
handle();
while (mLastAckMsgId != (uint16_t) ubxMsgId
&& millis() - loopStart < timeoutMs) {
if (!handle()) {
delay(1);
}
}
if (mAckReceived || mNakReceived) {
result = mAckReceived;
break;
}
log_w("Retry to send 0x%04x after %dms.", ubxMsgId, millis() - loopStart);
}
if (result) {
log_d("Success in sending. 0x%04x took %dms", ubxMsgId, millis() - start);
} else {
log_e("Failed to send. 0x%04x NAK: %d after %dms", ubxMsgId, mNakReceived, millis() - start);
}
return result;
}
#ifdef UBX_M10
bool Gps::sendCfgAndWaitForAck(enum UBX_CFG_LAYER layer, UBX_CFG_KEY_ID keyId, uint32_t value, const uint16_t timeoutMs) {
const int tries = 2;
auto start = millis();
bool result = false;
for (int i = 0; i < tries; i++) {
handle();
auto const loopStart = millis();
mNakReceived = false;
mAckReceived = false;
mLastAckMsgId = 0;
sendUbxCfg(layer, keyId, value);
mSerial.flush();
handle();
while (mLastAckMsgId != (uint16_t) UBX_MSG::CFG_VALSET && millis() - loopStart < timeoutMs) {
if (!handle()) {
delay(1);
}
}
if (mAckReceived || mNakReceived) {
result = mAckReceived;
break;
}
log_w("Retry to send cfg 0x%08x after %dms.", keyId, millis() - loopStart);
}
if (result) {
log_d("Success in sending cfg. 0x%08x took %dms", keyId, millis() - start);
} else {
log_e("Failed to send cfg. 0x%08x NAK: %d after %dms", keyId, mNakReceived, millis() - start);
}
return result;
}
#endif
/* Will delay for the given number of ms and handle GPS if needed. */
void Gps::handle(uint32_t milliSeconds) {
const auto end = millis() + milliSeconds;
while (end > millis()) {
if (!handle()) {
delay(1);
}
}
}
bool Gps::handle() {
auto handleStart = millis();
auto messageStarted = mMessageStarted;
auto lastCallDelayMs = handleStart - messageStarted;
const auto bytesAvailable = mSerial.available();
if (bytesAvailable > 0 && lastCallDelayMs > 600) { // we would get only old data
addStatisticsMessage(String("readGPSData(clear: ") + String(bytesAvailable)
+ " bytes in buffer, lastCall " + String(lastCallDelayMs)
+ "ms ago, at " + TimeUtils::dateTimeToString() + ")");
mMessageStarted = handleStart;
for (int i = 0; i < bytesAvailable; i++) {
mSerial.read();
}
handleStart = millis();
} else if (bytesAvailable > 250) {
addStatisticsMessage(String("readGPSData(av: ") + String(bytesAvailable)
+ " bytes in buffer, lastCall " + String(lastCallDelayMs)
+ "ms ago, at " + TimeUtils::dateTimeToString() + ")");
}
boolean gotGpsData = false;
int bytesProcessed = 0;
int data;
#ifdef GPS_TRANSPARENT_UART
// Redicrect data to GPS
while((data = Serial.read()) >= 0)
mSerial.write(data);
#endif
while ((data = mSerial.read()) >= 0) {
bytesProcessed++;
#ifdef GPS_TRANSPARENT_UART
// Redicrect data from GPS
Serial.write(data);
#endif
#ifdef GPS_LOW_LEVEL_DEBUGGING
log_w("GPS in: 0x%02x", data);
#endif
if (encode(data)) {
gotGpsData = true;
if (bytesProcessed > 2048) {
log_e("break after %d bytes", bytesProcessed);
break;
}
}
}
auto between = handleStart - messageStarted;
// ~150ms is needed if we write to SD
if (between > 160 && bytesProcessed > 0 || bytesProcessed > 1024) {
addStatisticsMessage(String("readGPSData(longDelay: ") + String(between)
+ "ms received " + String(bytesProcessed) + "(" + String(bytesAvailable) + ") in " + String(millis() - handleStart) + "ms)");
}
if (mSerial.available() == 0) {
mMessageStarted = millis(); // buffer empty next message might already start now
}
// TODO: Add dead device detection re-init if no data for 60 seconds...
return gotGpsData;
}
bool Gps::waitForData(const uint16_t timeoutMs) {
if (mSerial.available() > 0) {
return true;
}
auto end = millis() + timeoutMs;
while (mSerial.available() <= 0 && millis() < end) {
delay(1);
}
return mSerial.available() > 0;
}
static const String STATIC_MSG_PREFIX[] = {
"DBG: San Vel ", "DBG: San Pos ", "DBG: San Alt ", "NTC: ANTSTATUS=", "readGPSData", "TIMEGPS set:"
};
void Gps::addStatisticsMessage(String newMessage) {
int prefix = -1;
for (int i = 0; i < (sizeof(STATIC_MSG_PREFIX)/sizeof(*STATIC_MSG_PREFIX)); i++) {
if (newMessage.startsWith(STATIC_MSG_PREFIX[i])) {
prefix = i;
}
}
for (int i = 0; i < mMessages.size(); i++) {
if (mMessages[i] == newMessage) {
newMessage.clear();
break;
}
if (prefix >= 0 && mMessages[i].startsWith(STATIC_MSG_PREFIX[prefix])) {
log_i("Update: %s", newMessage.c_str());
mMessages[i] = newMessage;
newMessage.clear();
break;
}
}
if (!newMessage.isEmpty()) {
mMessages.push_back(newMessage);
log_i("New: %s", newMessage.c_str());
}
newMessage.clear();
if (mMessages.size() > 20) {
mMessages.erase(mMessages.cbegin());
}
}
bool Gps::isInsidePrivacyArea() {
// quite accurate haversine formula
// consider using simplified flat earth calculation to save time
// TODO: Config must not be read from the globals here!
const double lon = mCurrentGpsRecord.getLongitude();
const double lat = mCurrentGpsRecord.getLatitude();
for (auto pa : config.privacyAreas) {
double distance = haversine(
lat, lon, pa.transformedLatitude, pa.transformedLongitude);
if (distance < pa.radius) {
return true;
}
}
return false;
}
double Gps::haversine(double lat1, double lon1, double lat2, double lon2) {
// https://www.geeksforgeeks.org/haversine-formula-to-find-distance-between-two-points-on-a-sphere/
// distance between latitudes and longitudes
double dLat = (lat2 - lat1) * M_PI / 180.0;
double dLon = (lon2 - lon1) * M_PI / 180.0;
// convert to radians
lat1 = (lat1) * M_PI / 180.0;
lat2 = (lat2) * M_PI / 180.0;
// apply formulae
double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
double rad = 6371000;
double c = 2 * asin(sqrt(a));
return rad * c;
}
void Gps::randomOffset(PrivacyArea &p) {
randomSeed(analogRead(0));
// Offset in degree and distance
int offsetAngle = random(0, 360);
int offsetDistance = random(p.radius / 10.0, p.radius / 10.0 * 9.0);
//Offset in m
int dLatM = sin(offsetAngle / 180.0 * M_PI ) * offsetDistance;
int dLongM = cos(offsetAngle / 180.0 * M_PI ) * offsetDistance;
#ifdef DEVELOP
Serial.print(F("offsetAngle = "));
Serial.println(String(offsetAngle));
Serial.print(F("offsetDistance = "));
Serial.println(String(offsetDistance));
Serial.print(F("dLatM = "));
Serial.println(String(dLatM));
Serial.print(F("dLongM = "));
Serial.println(String(dLongM));
#endif
//Earth’s radius, sphere
double R = 6378137.0;
//Coordinate offsets in radians
double dLat = dLatM / R;
double dLon = dLongM / (R * cos(M_PI * p.latitude / 180.0));
#ifdef DEVELOP
Serial.print(F("dLat = "));
Serial.println(String(dLat, 5));
Serial.print(F("dLong = "));
Serial.println(String(dLon, 5));
#endif
//OffsetPosition, decimal degrees
p.transformedLatitude = p.latitude + dLat * 180.0 / M_PI;
p.transformedLongitude = p.longitude + dLon * 180.0 / M_PI ;
#ifdef DEVELOP
Serial.print(F("p.transformedLatitude = "));
Serial.println(String(p.transformedLatitude, 5));
Serial.print(F("p.transformedLongitude = "));
Serial.println(String(p.transformedLongitude, 5));
#endif
}
PrivacyArea Gps::newPrivacyArea(double latitude, double longitude, int radius) {
PrivacyArea newPrivacyArea;
newPrivacyArea.latitude = latitude;
newPrivacyArea.longitude = longitude;
newPrivacyArea.radius = radius;
randomOffset(newPrivacyArea);
return newPrivacyArea;
}
bool Gps::hasFix(DisplayDevice *display) const {
bool result = false;
if (mCurrentGpsRecord.hasValidFix() && mLastTimeTimeSet) {
log_d("Got location...");
display->showTextOnGrid(2, 4, "Got location");
result = true;
}
return result;
}
int32_t Gps::getValidMessageCount() const {
return mValidMessagesReceived;
}
int32_t Gps::getMessagesWithFailedCrcCount() const {
return mMessagesWithFailedCrcReceived;
}
void Gps::showWaitStatus(DisplayDevice const * display) const {
static bool clear = false;
if (!is_neo6() && !clear) {
obsDisplay->clear();
clear = true;
}
String satellitesString[2];
if (mValidMessagesReceived == 0) { // could not get any valid char from GPS module
satellitesString[0] = "OFF?";
} else if (mLastTimeTimeSet == 0) {
satellitesString[0] = "aGain:" + String(mLastGain);
satellitesString[1] = String(mCurrentGpsRecord.mSatellitesUsed) + "sats SN:" + String(mLastNoiseLevel);
} else {
satellitesString[0] = String(hw()).substring(1) + TimeUtils::timeToString();
satellitesString[1] = String(mCurrentGpsRecord.mSatellitesUsed) + "sats SN:" + String(mLastNoiseLevel);
}
obsDisplay->showTextOnGrid(2, display->currentLine() - 1, satellitesString[0]);
obsDisplay->showTextOnGrid(2, display->currentLine(), satellitesString[1]);
if (!is_neo6()){
obsDisplay->showTextOnGrid(0, 1, String(hw())+" GPS");
obsDisplay->showTextOnGrid(2, 1, "HDOP: " + getHdopAsString() + "D");
obsDisplay->showTextOnGrid(0, 2, "Jam: " + String(mLastJamInd));
obsDisplay->showTextOnGrid(2, 2, "Msgs: " + String(mValidMessagesReceived));
obsDisplay->showTextOnGrid(2, 3, "Fix: " + String(mCurrentGpsRecord.mFixStatus) + "D");
obsDisplay->showTextOnGrid(0, 3, "lat,lon:");
obsDisplay->showTextOnGrid(0, 4, String(mCurrentGpsRecord.mLatitude));
obsDisplay->showTextOnGrid(0, 5, String(mCurrentGpsRecord.mLongitude));
}
}
bool Gps::moduleIsAlive() const {
return mValidMessagesReceived > 0;
}
uint8_t Gps::getValidSatellites() const {
return mCurrentGpsRecord.mSatellitesUsed;
}
double Gps::getSpeed() const {
return (double) mCurrentGpsRecord.mSpeed * (60.0 * 60.0) / 100.0 / 1000.0;
}
String Gps::getHdopAsString() const {
return mCurrentGpsRecord.getHdopString();
}
String Gps::getMessages() const {
String theGpsMessage = "";
for (const String& msg : mMessages) {
theGpsMessage += " // ";
theGpsMessage += msg;
}
return theGpsMessage;
}
String Gps::popMessage() {
String theGpsMessage = "";
if (mMessages.size() > 0) {
theGpsMessage = mMessages[0];
mMessages.erase(mMessages.begin());
}
return theGpsMessage;
}
String Gps::getMessage(uint16_t idx) const {
String theGpsMessage = "";
if (mMessages.size() > idx) {
theGpsMessage = mMessages[idx];
}
return theGpsMessage;
}
String Gps::getMessagesHtml() const {
String theGpsMessage = "";
for (const String& msg : mMessages) {
theGpsMessage += "<br/>";
theGpsMessage += ObsUtils::encodeForXmlText(msg);
}
return theGpsMessage;
}
/* This is the last received uptime info, this might
* lag behind only updated with statistic messages.
*/
uint32_t Gps::getUptime() const {
return mGpsUptime;
}
/* Read data as received form the GPS module. */
bool Gps::encode(uint8_t data) {
bool result = false;
// TODO: Detect delay while inside a message
checkForCharThatCausesMessageReset(data);
if (mReceiverState == GPS_NULL) {
mGpsBufferBytePos = 0;
}
mGpsBuffer.u1Data[mGpsBufferBytePos++] = data;
switch (mReceiverState) {
case GPS_NULL:
if (data == 0xB5) {
mReceiverState = UBX_SYNC;
mUbxChA = 0;
mUbxChB = 0;
} else if (data == '$') {
mReceiverState = NMEA_START;
mNmeaChk = 0;
} else {
if (data != 0) {
log_w("Unexpected GPS char in state null: %02x %c", data, data);
mUnexpectedCharReceivedCount++;
}
}
break;
case UBX_SYNC:
if (data == 0x62) {
mReceiverState = UBX_SYNC1;
} else {
log_w("Unexpected GPS char in state ubx sync: %02x", data);
mUnexpectedCharReceivedCount++;
mReceiverState = GPS_NULL;
}
break;
case UBX_SYNC1:
mUbxChA += data;
mUbxChB += mUbxChA;
if (mGpsBufferBytePos == 6) {
mGpsPayloadLength = mGpsBuffer.ubxHeader.length;
if (mGpsPayloadLength + 6 > MAX_MESSAGE_LENGTH) {
log_w("Message claims to be %d (0x%04x) bytes long. Will ignore it, reset.",
mGpsPayloadLength, mGpsPayloadLength);
mReceiverState = GPS_NULL;
} else {
mReceiverState = UBX_PAYLOAD;
log_v("Expecting UBX Payload: %d bytes", mGpsPayloadLength);
}
}
break;
case UBX_PAYLOAD:
mUbxChA += data;
mUbxChB += mUbxChA;
if (mGpsBufferBytePos == 6 + mGpsPayloadLength) {
mReceiverState = UBX_CHECKSUM;
}
break;
case UBX_CHECKSUM:
if (mUbxChA != data) {
mMessagesWithFailedCrcReceived++;
log_w("UBX CK_A error: %02x != %02x after %d bytes for 0x%04x",
mUbxChA, data, mGpsBufferBytePos, mGpsBuffer.ubxHeader.ubxMsgId);
mReceiverState = GPS_NULL;
} else {
mReceiverState = UBX_CHECKSUM1;
}