-
Notifications
You must be signed in to change notification settings - Fork 3
/
ubxgpsstate.cpp
executable file
·1863 lines (1652 loc) · 60.7 KB
/
ubxgpsstate.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
/*******************************************************************************
*
* Copyright (C) u-blox AG
* u-blox AG, Thalwil, Switzerland
*
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR U-BLOX MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
*******************************************************************************
*
* Project: PE_ANS
*
******************************************************************************/
/*!
\file State Managment for UBX gps receiver
\brief
This class contain the state managment for the u-blox gps receiver.
It handles sending of commands to the receiver, collection and sending of
aiding information.
It has implemented the folwing feature:
- Time and Position Injection with UBX-AID-INI
- Local Aiding of Ephemeris, Almanac, Ionossphere, UTC data and Health
- AssistNow Autonomous Aiding
- AssistNow Offline (Server based, not Flash based)
- Configuration of the receiver (e.g Rate, Baudrate, Messages)
*/
/*******************************************************************************
* $Id: ubxgpsstate.cpp 64945 2013-01-17 10:41:30Z jon.bowern $
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <cutils/properties.h>
#include <string.h>
#include <pthread.h>
#ifndef ANDROID_BUILD
// Needed for Linux build
#include <malloc.h>
#include <string.h>
#define _LIBS_CUTILS_UIO_H
#endif
#include "std_types.h"
#include "ubx_messageDef.h"
#include "ubx_timer.h"
#include "ubx_log.h"
#include "ubx_cfg.h"
#include "ubxgpsstate.h"
#include "protocolubx.h"
#ifdef SUPL_ENABLED
#include "ubx_agpsIf.h"
#endif
///////////////////////////////////////////////////////////////////////////////
// Types & Definitions
#define AIDING_DATA_FILE "/data/aiding.ubx"
#define SERPORT_DEFAULT "/dev/ttyO3"
#define SERPORT_BAUDRATE_DEFAULT 9600
#define SHUTDOWN_TIMEOUT_DEFAULT 5 //!< 5 seconds
#define XTRA_POLL_INTERVAL_DEFUALT 20 //!< 20 hours
#ifdef SUPL_ENABLED
#define MSA_RESPONSE_DELAY_DEFAULT 10 //!< Default timeout (in seconds) to response with psedo ranges for MSA session
#define NI_UI_TIMEOUT_DEFAULT 120 //!< Default timeout (in seconds) to display NI Notify/verify dialog
#define NI_RESPONSE_TIMEOUT 75 //!< Default timeout (in seconds) to respond to an NI request
#endif
///////////////////////////////////////////////////////////////////////////////
// Static data
static CUbxGpsState s_ubxGpsState;
///////////////////////////////////////////////////////////////////////////////
//! Constructor
CUbxGpsState::CUbxGpsState()
{
memset(&m_Db, 0, sizeof(m_Db));
m_Db.dbAssistChanged = false;
m_Db.dbAssistCleared = true;
m_Db.rateMs = 1000;
CCfg cfg;
cfg.load("/system/etc/u-blox.conf");
m_pSerialDevice = strdup( cfg.get("SERIAL_DEVICE", SERPORT_DEFAULT) );
m_baudRate = cfg.get("BAUDRATE" , SERPORT_BAUDRATE_DEFAULT);
m_baudRateDef = cfg.get("BAUDRATE_DEF" , SERPORT_BAUDRATE_DEFAULT);
m_pAlpTempFile = strdup( cfg.get("ALP_TEMP" , AIDING_DATA_FILE) );
m_stoppingTimeoutMs = cfg.get("STOP_TIMEOUT", SHUTDOWN_TIMEOUT_DEFAULT) * 1000;
m_xtraPollInterval = cfg.get("XTRA_POLL_INTERVAL", XTRA_POLL_INTERVAL_DEFUALT) * 60 * 60 * 1000;
m_persistence = cfg.get("PERSISTENCE", 1);
m_receiverShutdownAck = false;
#ifdef SUPL_ENABLED
m_almanacRequest = (bool) cfg.get("SUPL_ALMANAC_REQUEST", false);
m_utcModelRequest = (bool) cfg.get("SUPL_UTC_MODEL_REQUEST", false);
m_ionosphericModelRequest = (bool) cfg.get("SUPL_IONOSPHERIC_MODEL_REQUEST", false);
m_dgpsCorrectionsRequest = (bool) cfg.get("SUPL_DGPS_CORRECTIONS_REQUEST", false);
m_refLocRequest = (bool) cfg.get("SUPL_REF_LOC_REQUEST", false);
m_refTimeRequest = (bool) cfg.get("SUPL_REF_TIME_REQUEST", false);
m_acquisitionAssistRequest = (bool) cfg.get("SUPL_AQUISITION_ASSIST_REQUEST", false);
m_realTimeIntegrityRequest = (bool) cfg.get("SUPL_TIME_INTEGRITY_REQUEST", false);
m_navigationModelRequest = (bool) cfg.get("SUPL_NAVIGATIONAL_MODEL_REQUEST", false);
m_fakePhone = (bool) cfg.get("SUPL_FAKE_PHONE_CONNECTION", false);
m_niUiTimeout = cfg.get("SUPL_NI_UI_TIMEOUT", NI_UI_TIMEOUT_DEFAULT);
m_niResponseTimeout = cfg.get("SUPL_NI_RESPONSE_TIMEOUT", NI_RESPONSE_TIMEOUT);
CAgpsIf::getInstance()->setCertificateFileName(cfg.get("SUPL_CACERT", (const char*)NULL));
m_logSuplMessages = (bool) cfg.get("SUPL_LOG_MESSAGES", false);
m_cmccLogActive = (bool) cfg.get("SUPL_CMCC_LOGGING", false);
m_suplMsgToFile = (bool) cfg.get("SUPL_MSG_TO_FILE", false);
#endif
m_pSer = NULL;
#if defined UDP_SERVER_PORT
m_pUdpServer = NULL;
m_udpPort = cfg.get("UDP_SERVER_PORT", UDP_SERVER_PORT);
#endif
m_agpsThreadParam.server = strdup( cfg.get("UBX_HOST", "") );
m_agpsThreadParam.port = cfg.get("UBX_PORT", 46434);
char brand[PROPERTY_VALUE_MAX];
char model[PROPERTY_VALUE_MAX];
char serial[PROPERTY_VALUE_MAX];
property_get("ro.product.brand", brand, "");
property_get("ro.product.model", model, "");
property_get("ro.product.serial", serial, "");
if (strcmp(serial,"")==0)
snprintf(m_agpsThreadParam.request, MAX_REQUEST, "and=%s.%s", brand, model);
else
snprintf(m_agpsThreadParam.request, MAX_REQUEST, "and=%s.%s.%s", brand, model, serial);
m_agpsThreadParam.request[MAX_REQUEST-1] = '\0';
m_agpsThreadParam.active = false;
m_agpsThreadParam.timeoutLastRequest = getMonotonicMsCounter() - (60 * 120 * 1000);
pthread_mutex_init(&m_ubxStateMutex, NULL);
}
///////////////////////////////////////////////////////////////////////////////
// Destructor
CUbxGpsState::~CUbxGpsState()
{
// write back the data to the file
//lint -e{1551} remove Function may throw exception
deleteAidData(GPS_DELETE_ALL); // this frees all the buffers
if (m_pSerialDevice) free(m_pSerialDevice);
if (m_pAlpTempFile) free(m_pAlpTempFile);
if (m_agpsThreadParam.server) free(m_agpsThreadParam.server);
m_pSer = NULL; // Never allocated in this class, so do not need to free
m_pUdpServer = NULL; // Never allocated in this class, so do not need to free
pthread_mutex_destroy(&m_ubxStateMutex);
}
CUbxGpsState* CUbxGpsState::getInstance()
{
return &s_ubxGpsState;
}
/*******************************************************************************
* Thread safety
*******************************************************************************/
void CUbxGpsState::lock(void)
{
pthread_mutex_lock(&m_ubxStateMutex);
}
void CUbxGpsState::unlock(void)
{
pthread_mutex_unlock(&m_ubxStateMutex);
}
/*******************************************************************************
* STARTUP on SHUTDOWN
*******************************************************************************/
//! on Statup Sequence
/*! Exectute the sequence needed to restart the receiver, this includes the following steps.
- powering up the gps (optional)
- restore the local aiding to a file
- enableing gps receiver
- configure the receiver
- do all the aiding
*/
void CUbxGpsState::onStartup(void)
{
LOGGPS(0x00000000, "#gps start");
// Switch power on to the gps device
if(powerOn())
{
setBaudRate();
}
// load any previous aiding data
loadAiding();
// turn on the gps, we assume that the gps is turned off
writeUbxCfgRst(0x09/*gps start*/, 0);
// Wait 50 msec before sending the rest...
usleep(50000);
// Configuration
// ---------------------------------------
// set the desired navigation rate
writeUbxCfgRate();
// enable additional messages and protocols this gives accuracies
writeUbxCfgMsg(0xF0, 0x07); // enable NMEA-GST message
writeUbxCfgMsg(0x01, 0x30); // enable UBX-NAV-SVINFO message
writeUbxCfgMsg(0x01, 0x06); // enable UBX-NAV-SOL message
writeUbxCfgMsg(0x01, 0x07); // enable UBX-NAV-PVT message
// enable all the adining information
writeUbxCfgMsg(0x0B, 0x30); // enable UBX-AID-ALM message
writeUbxCfgMsg(0x0B, 0x31); // enable UBX-AID-EPH message
writeUbxCfgMsg(0x0B, 0x32); // enable UBX-AID-ALP message
writeUbxCfgMsg(0x0B, 0x33); // enable UBX-AID-AOP message
#ifdef SUPL_ENABLED
writeUbxCfgMsg(0x02, 0x12); // enable UBX-RXM-MEAS message for SUPL MS-Assist
#endif
// Aiding
// ---------------------------------------
// do time and position aiding
writeUbxAidIni();
// eventually push the alp header to the device such that it that we have a file
writeUbxAlpHeader();
// send all the aiding data available here
sendAidData(true, true, true, true);
// finally enable aop (might already be enabled by the aiding above
writeUbxNavX5AopEnable();
}
//! on Prepare Shutdown Sequence
/*! Exectute the sequence needed to initiate the shutdown, this includes the following steps.
- polling of local aiding data
- turning off the gps
*/
void CUbxGpsState::onPrepareShutdown()
{
// Send stop gps msg
// As this msg is sent after aiding data polling msgs, then the ack for this msgs
// should appear after the responsing aiding msgs, and hence signify that shutdown
// is complete.
writeUbxCfgRst(0x08/*gps stop*/, 0);
}
//! on Shutdown Sequence
/*! Exectute the sequence needed to finalize the shutdown, this includes the following steps.
- save the local aiding to a file
- powering down the gps (optional)
\param state GPS state variable
*/
void CUbxGpsState::onShutDown()
{
// save aiding data
saveAiding();
// Switch power off to the gps device
powerOff();
LOGGPS(0x00000001, "#gps stop");
}
//! on Initialise Sequence
/*! Exectute the sequence needed to initialise the device, this includes the following steps.
- turning off the gps
- powering down the gps (optional)
\param state GPS state variable
*/
void CUbxGpsState::onInit(void)
{
// Make sure gps receiver is stopped
writeUbxCfgRst(0x08/*gps stop*/, 0);
// and make sure receiever is powered off (optional)
powerOff();
}
/*******************************************************************************
* MEASUREMENT RATE CONFIGURATION
*******************************************************************************/
//! set the mesurement rate
/*! put the requested measurement rate into our local configuration db,
the gps receiver can be switched of while we a receiveing such a request
\param rateMs the mesaurement requested configuration
*/
void CUbxGpsState::putRate(int rateMs)
{
LOGV("Put Rate rate=%d", rateMs);
m_Db.rateMs = rateMs;
}
//! send measurement rate to the receiver
/*! configure the measurement rate of the receiver
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::writeUbxCfgRate()
{
// Send CFG-RATE command
GPS_UBX_CFG_RATE_t Payload;
Payload.measRate = (U2) m_Db.rateMs;
Payload.navRate = 1;
Payload.timeRef = 1;
LOGV("Send CFG-RATE rate=%d", Payload.measRate);
return writeUbx(0x06, 0x08, &Payload, sizeof(Payload));
}
//! Set the baud rate for the receiver and the host's serial port
/*!
*/
void CUbxGpsState::setBaudRate()
{
if (m_pSer == NULL)
{
LOGW("%s: invalid serial port handler", __FUNCTION__);
return;
}
int baudRate = getBaudRate();
if (baudRate != getBaudRateDefault())
{
// reconfigure the baud rate
usleep(100000);
m_pSer->setbaudrate(getBaudRateDefault());
usleep(100000);
writeUbxCfgPort(1 /* UART1 */, baudRate);
usleep(100000); // 1/10 second
m_pSer->setbaudrate(baudRate);
}
}
/*******************************************************************************
* LOCAL AIDING: EPH,HUI,ALM,AOP
*******************************************************************************/
//! send local aiding data to the receiver
/*! send the local adining data to the receiver
\param bEph set to true if Ephemeris shall be aided
\param bAop set to true if AssistNow Autonomous shall be aided
\param bAlm set to true if Almanac shall be aided
\param bHui set to true if Health/UTC/Ionosphere shall be aided
*/
void CUbxGpsState::sendAidData(bool bEph, bool bAop, bool bAlm, bool bHui)
{
BUF_t* p = NULL;
if (bEph)
{
for (int svix = 0; svix < NUM_GPS_SVS; svix ++)
{
p = &m_Db.sv[svix].eph;
if ((p->p != NULL) && (p->i>0))
{
if ((m_pSer != NULL) && (m_pSer->writeSerial(p->p,p->i) == (int)p->i))
{
// LOGV("Send Eph G%d size %d", svix+1, p->i);
}
#if defined UDP_SERVER_PORT
if (m_pUdpServer != NULL)
{
m_pUdpServer->sendPort(p->p,(int) p->i);
}
#endif
}
}
}
if (bAop)
{
for (int svix = 0; svix < NUM_GPS_SVS; svix ++)
{
p = &m_Db.sv[svix].aop;
if ((p->p != NULL) && (p->i>0))
{
if ((m_pSer != NULL) && (m_pSer->writeSerial(p->p,p->i) == (int)p->i))
{
// LOGV("Send Aop G%d size %d", svix+1, p->i);
}
#if defined UDP_SERVER_PORT
if (m_pUdpServer != NULL)
{
m_pUdpServer->sendPort(p->p,(int) p->i);
}
#endif
}
}
}
if (bAlm)
{
for (int svix = 0; svix < NUM_GPS_SVS; svix ++)
{
p = &m_Db.sv[svix].alm;
if ((p->p != NULL) && (p->i>0))
{
if ((m_pSer != NULL) && (m_pSer->writeSerial(p->p,p->i) == (int)p->i))
{
// LOGV("Send Alm G%d size %d", svix+1, p->i);
}
#if defined UDP_SERVER_PORT
if (m_pUdpServer != NULL)
{
m_pUdpServer->sendPort(p->p,(int) p->i);
}
#endif
}
}
}
if (bHui)
{
p = &m_Db.hui;
if ((p->p != NULL) && (p->i>0))
{
if ((m_pSer != NULL) && (m_pSer->writeSerial(p->p,p->i) == (int)p->i))
{
// LOGV("Send Hui size %d", p->i);
}
#if defined UDP_SERVER_PORT
if (m_pUdpServer != NULL)
{
m_pUdpServer->sendPort(p->p,(int) p->i);
}
#endif
}
}
}
//! poll local aiding data from the receiver
/*! request the local adining data from the receiver
\param bEph set to true if Ephemeris shall be polled
\param bAop set to true if AssistNow Autonomous shall be polled
\param bAlm set to true if Almanac shall be polled
\param bHui set to true if Health/UTC/Ionosphere shall be polled
*/
void CUbxGpsState::pollAidData(bool bEph, bool bAop, bool bAlm, bool bHui)
{
if (bEph) writeUbx(0x0B, 0x31, NULL, 0);
if (bAop) writeUbx(0x0B, 0x33, NULL, 0);
if (bAlm) writeUbx(0x0B, 0x30, NULL, 0);
if (bHui) writeUbx(0x0B, 0x02, NULL, 0);
}
//! handle new messages from the receiver
/*! This is the main routine which is called whenever a new UBX message was received in the parser.
\param pMsg the pointer to the complete message (includes frameing and payload)
\param iMsg the size of the complete message (includes frameing and payload)
*/
//lint -e{661,662}
void CUbxGpsState::onNewUbxMsg(GPS_THREAD_STATES state, const unsigned char* pMsg, unsigned int iMsg)
{
unsigned char clsId;
unsigned char msgId;
if (iMsg < 4)
return;
clsId = pMsg[2];
msgId = pMsg[3];
//LOGV("%s : Received %x %x %x %x %x %x", __FUNCTION__, pMsg[2], pMsg[3], pMsg[4], pMsg[5], pMsg[6], pMsg[7]);
if ((clsId == 0x0B) && (iMsg >= 9))
{
// save the aiding data in a local database
if (0x02 == msgId)
{
// Health / UTC / Ionosphere paramters
if (replaceBuf(&m_Db.hui, pMsg, iMsg))
{
m_Db.dbAssistChanged = true;
LOGV("Got new Hui");
}
}
else if (0x01 == msgId)
{
onNewUbxAidIni(pMsg, iMsg);
}
else if ((0x32 == msgId) && (state != -1))
{
// AssistNow Offline
onNewUbxAlpMsg(pMsg,iMsg);
}
else
{
unsigned int svix = pMsg[6] - 1;
if ((0x30 == msgId) && (iMsg > 16) && (svix < NUM_GPS_SVS))
{
// Almanac
if (replaceBuf(&m_Db.sv[svix].alm, pMsg, iMsg))
{
m_Db.dbAssistChanged = true;
LOGV("Got Alm G%d", svix+1);
}
}
else if ((0x31 == msgId) && (iMsg > 16) && (svix < NUM_GPS_SVS))
{
// Ephemeris parameters
if (replaceBuf(&m_Db.sv[svix].eph, pMsg, iMsg))
{
m_Db.dbAssistChanged = true;
LOGV("Got Eph G%d", svix+1);
}
}
else if ((0x33 == msgId) && (iMsg > 9) && (svix < NUM_GPS_SVS))
{
// AssistNow Offline parameters
if (replaceBuf(&m_Db.sv[svix].aop, pMsg, iMsg))
{
m_Db.dbAssistChanged = true;
LOGV("Got Aop G%d", svix+1);
}
}
}
}
else if ((clsId == 0x05) && (msgId == 0x01) && (iMsg == 10))
{
time_t now = time(NULL);
char* s = ctime(&now);
s[strlen(s)-1] = '\0';
// ACK-ACK received
if ((pMsg[6] == 0x06) && (pMsg[7] == 0x04))
{
// Acknowledging last CFG-RST
LOGV("%s : Ack of last CFG-RST state %i (%s) - ", __FUNCTION__, state, s);
if (state == GPS_STOPPING)
{
m_receiverShutdownAck = true;
LOGV("%s : Ack of last CFG-RST - Stopping sequence can now complete", __FUNCTION__);
}
}
else
{
LOGV("%s : Ack received %02X-%02X (%s)", __FUNCTION__, pMsg[6], pMsg[7], s);
}
}
}
//! delete local aiding in the local database
/*! Delete the local aiding data in our database, this may also free the buffers.
It does not send a message to the receiver to clear the receivers nvs data,
this has to be done separately,
\param flags the things to clear, see gps.h for a definition
*/
void CUbxGpsState::deleteAidData(GpsAidingData flags)
{
if (flags & GPS_DELETE_POSITION)
memset(&m_Db.pos, 0, sizeof(m_Db.pos));
if (flags & GPS_DELETE_TIME)
memset(&m_Db.time, 0, sizeof(m_Db.time));
for (int svix = 0; svix < NUM_GPS_SVS; svix ++)
{
if (flags & GPS_DELETE_EPHEMERIS)
{
freeBuf(&m_Db.sv[svix].eph);
//LOGV("Clr Eph G%d", svix+1);
}
if (flags & GPS_DELETE_SADATA)
{
freeBuf(&m_Db.sv[svix].aop);
//LOGV("Clr Aop G%d", svix+1);
}
if (flags & GPS_DELETE_ALMANAC)
{
freeBuf(&m_Db.sv[svix].alm);
//LOGV("Clr Alm G%d", svix+1);
}
}
if (flags & (GPS_DELETE_IONO|GPS_DELETE_UTC|GPS_DELETE_HEALTH))
{
freeBuf(&m_Db.hui);
//LOGV("Clr Hui");
}
if (flags & (GPS_DELETE_SVDIR|GPS_DELETE_SVSTEER))
{
freeBuf(&m_Db.alp.file);
//LOGV("Clr Apl");
}
m_Db.dbAssistChanged = true;
}
//! Enable AOP in the receiver
/*! Send a UBX-CFG-NAVX5 message to the receiver to enable the AssistNow Autonomous Feature.
\param state GPS state variable
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::writeUbxNavX5AopEnable()
{
GPS_UBX_CFG_NAV5X_t Payload;
memset(&Payload, 0, sizeof(Payload));
Payload.mask1 = 0x4000; // config AOP
Payload.aopFlags = 0x01; // enable AOP
Payload.aopOrbMaxError = 0; // use default
return writeUbx(0x06, 0x23, &Payload, sizeof(Payload));
}
/*******************************************************************************
* LOCAL AIDING: TIME POSITION
*******************************************************************************/
//! Helper function to return a reference time
/*! this function has to be used to calculate aging of of the NTP (inject_time)
return the current refrence time.
*/
int64_t CUbxGpsState::currentRefTimeMs(void)
{
return getMonotonicMsCounter();
}
//! put time information into the local database.
/*! Put the time information received from a SNTP request into the local database.
This data is then used by #writeUbxAidIni to achieve time transfer from the network
to the device.
\param timeUtcMs The current utc time in milliseconds as define in gps.h
\param timeRefMs the reference time in milliseconds of the SNTP request use together with #currentRefTimeMs to age the timeUtcMs
\param accMs The time accuracy in milliseconds of this information (half the rount trip time).
*/
void CUbxGpsState::putTime(GpsUtcTime timeUtcMs, int64_t timeRefMs, int accMs)
{
time_t tUtc = (long) (timeUtcMs/1000);
char s[20];
struct tm t;
strftime(s, 20, "%Y.%m.%d %H:%M:%S", gmtime_r(&tUtc, &t));
LOGV("Got Utc %s.%03d Ref %lli Now %lli Acc %.3f ms", s, (int)(timeUtcMs%1000), timeRefMs, currentRefTimeMs(), accMs*0.001);
m_Db.time.timeUtcMs = timeUtcMs;
m_Db.time.timeRefMs = timeRefMs;
m_Db.time.accMs = accMs;
m_Db.dbAssistChanged = true;
}
//! put the position information into the local database
/*! Put the position information received from Android into the local database.
This data is then used by #writeUbxAidIni to achieve position aiding from the network
The function also recored the time of reception so that it could be aged.
\param latDeg the Latitude in Degrees
\param latDeg the Longitude in Degrees
\param accM the accuracy in meters of this information
*/
void CUbxGpsState::putPos(double latDeg, double lonDeg, float accM)
{
LOGV("Got Lat %.6f Lon %.6f Acc %f", latDeg, lonDeg, (double)accM);
m_Db.pos.latDeg = latDeg;
m_Db.pos.lonDeg = lonDeg;
m_Db.pos.accM = (int) accM;
m_Db.pos.timeRefMs = currentRefTimeMs();
m_Db.dbAssistChanged = true;
}
//! do send position and time aiding to the receiver
/*! Send a UBX-AID-INI message to the receiver. This implemenation of the message
support the following aiding:
- position
- time
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::writeUbxAidIni()
{
GPS_UBX_AID_INI_U5__t Payload;
memset(&Payload, 0, sizeof(Payload));
int64_t timeNowMs = currentRefTimeMs();
// position aiding
if (m_Db.pos.accM > 0)
{
Payload.ecefXOrLat = (I4)(m_Db.pos.latDeg * 1e7); // deg -> deg*1e-7
Payload.ecefYOrLon = (I4)(m_Db.pos.lonDeg * 1e7); // deg -> deg*1e-7
Payload.posAcc = (U4)(m_Db.pos.accM * 1e2); // m -> cm
Payload.flags |= GPS_UBX_AID_INI_U5__FLAGS_POS_MASK |
GPS_UBX_AID_INI_U5__FLAGS_LLA_MASK |
GPS_UBX_AID_INI_U5__FLAGS_ALTINV_MASK;
LOGV("Send Ini Lat %d Lon %d Acc %dcm", Payload.ecefXOrLat, Payload.ecefYOrLon, Payload.posAcc );
}
// time aiding
if (m_Db.time.accMs > 0)
{
int64_t timeUtcMs = m_Db.time.timeUtcMs;
int64_t ageMs = (timeNowMs - m_Db.time.timeRefMs);
int64_t accNs = (int64_t) ((MSTIME_ACC_COMM + (int64_t) m_Db.time.accMs) * (int64_t) 1000000); // about 1 us / second aging
accNs += ageMs;
const int64_t oneMinuteNs = 60LL * 1000000000LL;
const int oneWeekMs = 1000 * 60 *60 * 24 * 7;
const int leapSecMs = 1000 * 16; // leap second 22.10.2012 is 16 seconds
int64_t timeGpsMs = timeUtcMs + ageMs + leapSecMs;
// subtract offset between gps and utc time
timeGpsMs -= 315964800000LL; // which is mkgmtime(1980,1,6,0,0,0,0)*1000
if (accNs < oneMinuteNs)
{
Payload.wn = (U2) (timeGpsMs / oneWeekMs);
Payload.tow = (unsigned int) (timeGpsMs % (int64_t) oneWeekMs);
Payload.towNs = 0;
// Payload.tAccMs = (accNs / 1000000);
// Payload.tAccNs = (accNs % 1000000);
/* Use not so precise accuracy, it would help when next leap second will arrive... */
Payload.tAccMs = 2000;
Payload.tAccNs = 0;
Payload.flags |= GPS_UBX_AID_INI_U5__FLAGS_TIME_MASK;
}
time_t tUtc = (long) (timeUtcMs/1000);
char s[20];
struct tm t;
strftime(s, 20, "%Y.%m.%d %H:%M:%S", gmtime_r(&tUtc, &t));
LOGV("Send Ini UTC %s.%03d GPS %d:%09d Acc %d.%06dms Age %dms ", s, (int)(timeUtcMs%1000), Payload.wn, Payload.tow,
(int)Payload.tAccMs, (int)Payload.tAccNs, (int)ageMs);
}
// only need to do something if the is at least one part of the information available
if (Payload.flags != 0)
{
return writeUbx(0x0B, 0x01, &Payload, sizeof(Payload));
}
return false;
}
//! handle a aid ini message
/*! Parse a UBX-AID-INI message to the receiver. This implemenation of the message
support the following aiding:
- position
- time
\param pMsg the pointer to the complete message (includes frameing and payload)
\param iMsg the size of the complete message (includes frameing and payload)
\return true if sucessfull, false otherwise
*/
//lint -e{661,662,670}
bool CUbxGpsState::onNewUbxAidIni(const unsigned char* pMsg, unsigned int iMsg) const
{
GPS_UBX_AID_INI_U5__t Payload;
if (iMsg != 8+sizeof(Payload))
return false;
memcpy(&Payload, &pMsg[6], sizeof(Payload));
// position aiding
if (Payload.flags & GPS_UBX_AID_INI_U5__FLAGS_POS_MASK)
{
if (!(Payload.flags & GPS_UBX_AID_INI_U5__FLAGS_LLA_MASK))
{
//convertXYZtoLLH
}
/* Payload.flags |= GPS_UBX_AID_INI_U5__FLAGS_POS_MASK |
GPS_UBX_AID_INI_U5__FLAGS_LLA_MASK |
GPS_UBX_AID_INI_U5__FLAGS_ALTINV_MASK;*/
LOGV("Got Ini XYZ %d/%d/%d Acc %dcm", Payload.ecefXOrLat, Payload.ecefYOrLon, Payload.ecefZOrAlt, Payload.posAcc );
}
// time aiding
if (Payload.flags & GPS_UBX_AID_INI_U5__FLAGS_TIME_MASK)
{
double tow = Payload.tow + 1e-6 * Payload.towNs;
double acc = Payload.tAccMs + 1e-6 * Payload.tAccNs;
LOGV("Got Ini Time %d:%16.9f Acc %10.6fms", Payload.wn, 1e-3 * tow, acc);
}
// only need to do something if the is at least one part of the information available
return true;
}
/*******************************************************************************
* ASSISTNOW OFFLINE / ALMANAC PLUS
*******************************************************************************/
// Struture of the Assistnow Offline / Almanac Plus data
typedef struct {
U4 magic; // magic word must be 0x015062b5
U2 reserved0[32];
U2 size; // size of full file, incl. header, in units of 4 bytes
U2 reserved1;
U4 reserved2;
U4 p_tow; // Start of prediction Time of week
U2 p_wno; // Start of prediction Weeknumber
U2 duration; // Nominal/Typical duration of predictions, in units of 10 minutes.
} ALP_FILE_HEADER_t;
//! handle new Assistnow Offline / Almanac Plus messages from the receiver
/*! This is the main routine which is called whenever a new UBX_AID-ALP message was received in the parser.
\param pMsg the pointer to the complete message (includes frameing and payload)
\param iMsg the size of the complete message (includes frameing and payload)
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::onNewUbxAlpMsg(const unsigned char* pMsg, unsigned int iMsg)
{
GPS_UBX_AID_ALPSRV_CLI_t cli;
((void)(iMsg));
//!todo Size of the message is not verified!
if ((m_Db.alp.file.p != NULL) && (m_Db.alp.file.i > 0))
{
memcpy(&cli, &pMsg[6], sizeof(cli));
if (cli.idSize >= sizeof(cli))
{
unsigned int size = (unsigned int)cli.size << 1;
unsigned int offset = (unsigned int)cli.ofs << 1;
// LOGV("Got Alp Request idsize %d type %d ofs %d size %d fileId %d", cli.idSize, cli.type, cli.ofs, cli.size, cli.fileId);
if ( (size > 0) && (offset < m_Db.alp.file.i) )
{
if (offset + size >= m_Db.alp.file.i) // if we exceed the file size
size = m_Db.alp.file.i - offset; // then truncate
if (cli.type == 0xFF)
{
if (m_Db.alp.fileId == cli.fileId)
{
LOGV("Update Alp fileId %d offset %d size %d", cli.fileId, offset, size);
memcpy(&m_Db.alp.file.p[offset], &pMsg[6+cli.idSize], size);
m_Db.dbAssistChanged = true;
return true;
}
else
{
LOGE("Update Alp failed fileId %d does not match %d offset %d size %d", cli.fileId, m_Db.alp.fileId, offset, size);
return writeUbxAlpHeader();
}
}
}
else
{
LOGE("Request Alp out of range fileId %d offset %d size %d", cli.fileId, offset, size);
return writeUbxAlpHeader();
}
GPS_UBX_AID_ALPSRV_SRV_t srv;
memset(&srv, 0, sizeof(srv));
memcpy(&srv, &pMsg[6], cli.idSize);
srv.fileId = m_Db.alp.fileId;
srv.dataSize = (U2) size;
// LOGV("Send Alp Answer idsize %d type %d ofs %d size %d fileId %d datasize %d, %02X %02X %08X",
// srv.idSize, srv.type, srv.ofs, srv.size, srv.fileId,
// srv.dataSize, srv.id1, srv.id2, srv.id3);
return writeUbx(0x0B, 0x32, &srv, srv.idSize, &m_Db.alp.file.p[offset], (int) size);
}
}
return false;
}
//! put the Assistnow Offline / Alamanac Plus data into the local database
/*! Put the Assistnow Offline / Alamanac Plus data into the local database and check / validate
the content. Very simple check on the header are done. And if of the file ist saved in the db.
The time of reception is recorded to later check if a a file update shal be requested.
\param pData The pointer to the complete ALP file
\param iData The size of the complete ALP file
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::putAlpFile(const unsigned char* pData, unsigned int iData)
{
if (iData < (int)sizeof(ALP_FILE_HEADER_t))
LOGE("Alp size %d too small", iData);
else
{
ALP_FILE_HEADER_t head;
memcpy(&head, pData, sizeof(head));
if (head.magic != 0x015062b5)
LOGE("Alp magic bad %08X", head.magic);
else if (head.size*4 != iData)
LOGE("Alp size bad %d != %d", head.size*4, iData);
else if (replaceBuf(&m_Db.alp.file, pData, iData))
{
m_Db.alp.fileId ++;
m_Db.alp.timeRefMs = currentRefTimeMs();
m_Db.dbAssistChanged = true;
LOGV("Got Alp file %d size %d at", m_Db.alp.fileId, iData);
LOGV("Info Alp time %d:%06d dur %.3fdays\n", head.p_wno, head.p_tow, (head.duration * 10.0) / (60.0 * 24.0));
return true;
}
}
return false;
}
//! check if the new Assistnow Offline / Alamanac Plus file shall be requested.
/*! check if the new Assistnow Offline / Alamanac Plus file shall be requested.
A very simple timeout after reception is used to request a new file.
\note the duration of the data in the current file may exceed this timeout.
But we want to keep the data uptodate to acheive best accuracy.
\return true if the file is not yet old, false if it is old or not available
*/
bool CUbxGpsState::checkAlpFile(void) const
{
if (!m_Db.alp.file.p || (m_Db.alp.file.i < sizeof(ALP_FILE_HEADER_t)))
return false; // No ALP file present, so ALP can be requested
int64_t timeNowMs = currentRefTimeMs();
return (timeNowMs - m_Db.alp.timeRefMs) < m_xtraPollInterval;
}
//! Push the Assistnow Offline / Alamanac Plus header to the device.
/*! Push the Assistnow Offline / Alamanac Plus header to the device.
This function is used at startup to push the knowledge of the file / file id to the receiver.
\return true if sucessfull, false otherwise
*/
bool CUbxGpsState::writeUbxAlpHeader()
{
if (!m_Db.alp.file.p || (m_Db.alp.file.i < sizeof(ALP_FILE_HEADER_t)))
return false;
GPS_UBX_AID_ALPSRV_SRV_t srv;
memset(&srv, 0, sizeof(srv));
srv.idSize = sizeof(srv);
srv.type = 1; // header need to be type 1
srv.ofs = 0; // It was 0 >> 1; but do not why...
srv.size = sizeof(ALP_FILE_HEADER_t) >> 1;
srv.fileId = m_Db.alp.fileId;
srv.dataSize = sizeof(ALP_FILE_HEADER_t);
LOGV("Send Alp Header idsize %d type %d ofs %d size %d fileId %d datasize %d, %02X %02X %04X",
srv.idSize, srv.type, srv.ofs, srv.size, srv.fileId,
srv.dataSize, srv.id1, srv.id2, srv.id3);
return writeUbx(0x0B, 0x32, &srv, srv.idSize, &m_Db.alp.file.p[0], sizeof(ALP_FILE_HEADER_t));
}
/*******************************************************************************
* ASSIST NOW ONLINE
*******************************************************************************/
void CUbxGpsState::checkAgpsDownload(void)
{
// Check the Agps (AssistNow Online) thread is not running...
LOGV("CUbxGpsState::%s : Checking Agps (Online) server", __FUNCTION__);
if ((m_agpsThreadParam.server != NULL) && (*m_agpsThreadParam.server != '\0'))
{
if (!m_agpsThreadParam.active)
{
int64_t deltaTime = getMonotonicMsCounter() - m_agpsThreadParam.timeoutLastRequest;
LOGV("CUbxGpsState::%s : Agps delta timeout is %lld", __FUNCTION__, deltaTime);
if (deltaTime >= (60 * 100*1000)) /* Timeout of 100 minutes */
{
LOGV("CUbxGpsState::%s : Request AssistNow online", __FUNCTION__);
m_agpsThreadParam.active = true;
if (pthread_create( &m_agpsThreadParam.thread, NULL,
CUbxGpsState::agpsDownloadThread, &m_agpsThreadParam) == 0)
m_agpsThreadParam.active = false;
}
else
{
LOGV("CUbxGpsState::%s : Assistance data old less than 100 minutes", __FUNCTION__);
}
}
else
{
LOGV("CUbxGpsState::%s : Agps thread still active!", __FUNCTION__);
}
}
else
{
LOGV("CUbxGpsState::%s : Agps (Online) server not defined", __FUNCTION__);
}
}
//! request aiding iformation from a Assist Now Server / Poxy Server
void* CUbxGpsState::agpsDownloadThread(void *pThreadData)
{
AGPS_THREAD_DATA_t* data = (AGPS_THREAD_DATA_t*) pThreadData;
// get the ip address
struct sockaddr_in server;
memset( &server, 0, sizeof (server));
unsigned long addr = inet_addr(data->server);
if (addr != INADDR_NONE) // numeric IP address
memcpy((char *)&server.sin_addr, &addr, sizeof(addr));
else
{
// get by host name
struct hostent* host_info = gethostbyname(data->server);
if (host_info != NULL)