-
Notifications
You must be signed in to change notification settings - Fork 3
/
gps_thread.cpp
executable file
·880 lines (756 loc) · 25.9 KB
/
gps_thread.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
/*******************************************************************************
*
* 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
\brief
*/
/*******************************************************************************
* $Id: gps_thread.cpp 64761 2013-01-11 15:30:35Z michael.ammann $
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <assert.h>
#include "ubx_log.h"
#include "std_types.h"
#include "std_lang_def.h"
#include "std_macros.h"
#include "ubx_moduleIf.h"
#include "ubx_xtraIf.h"
#include "ubx_timer.h"
#include "parserbuffer.h"
#include "protocolubx.h"
#include "protocolnmea.h"
#include "protocolunknown.h"
#include "ubxgpsstate.h"
#include "gps_thread.h"
#include "ubx_localDb.h"
#ifdef SUPL_ENABLED
#include "ubx_rilIf.h"
#include "ubx_agpsIf.h"
#include "ubx_niIf.h"
#include "suplSMmanager.h"
#include <openssl/hmac.h>
#include "openssl/ssl.h"
#include <openssl/err.h>
#include <openssl/engine.h>
#include <openssl/conf.h>
#endif
////////////////////////////////////////////////////////////////////////////////
// Definitions & Types
#define MAX_UDP_PACKET_LEN 16384 //!< Dimension of the temporary buffer for reading a complete UDP packet
#define MIN_INTERVAL 200 //!< Minimum interval time (in ms) receiver is capable of
// Debugging
#ifdef SUPL_ENABLED
//#define NI_TEST
#endif
///////////////////////////////////////////////////////////////////////////////
// Local functions
static void requestStartEventHandler(void* pContext);
static void requestStopEventHandler(void* pContext);
static void reportStatus(const ControlThreadInfo* pState);
///////////////////////////////////////////////////////////////////////////////
// Local Data
static CSerialPort s_ser; //!< Hardware interface class instance(serial port / usb file handle)
#if defined UDP_SERVER_PORT
static CUdpServer s_udp; //!< UPD server class instance
#endif
static GpsControlEventInterface s_eventHandler = //!< Gps control event interface implementation
{
requestStart_cb: requestStartEventHandler, //!< 'Start' event handler
requestStop_cb: requestStopEventHandler //!< 'Stop' event handler
};
///////////////////////////////////////////////////////////////////////////////
// Golbal Data
#ifndef UNDEBUG
pthread_t g_gpsDrvMainThread = 0; // Thread debugging
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Control support
//! Signals to any waiting threads the last command has completed
/*!
\param pControlThreadInfo : Pointer to main thread data
\param result : Last command result to make available to interested parties
*/
static void signal_cmd_complete(ControlThreadInfo* pControlThreadInfo, int result)
{
pControlThreadInfo->cmdResult = result;
pthread_mutex_lock(&pControlThreadInfo->threadCmdCompleteMutex);
pthread_cond_signal(&pControlThreadInfo->threadCmdCompleteCond);
pthread_mutex_unlock(&pControlThreadInfo->threadCmdCompleteMutex);
}
static void engineStop(ControlThreadInfo* pControlThreadInfo, bool si)
{
if (si)
{
CMyDatabase::getInstance()->decPublish();
}
pthread_mutex_lock(&pControlThreadInfo->threadDataAccessMutex);
LOGV("%s: (Begin) Client count %d", __FUNCTION__, pControlThreadInfo->clientCount);
if (pControlThreadInfo->clientCount > 0)
{
pControlThreadInfo->clientCount--;
if (pControlThreadInfo->clientCount == 0)
{
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->onPrepareShutdown();
pUbxGps->unlock();
pControlThreadInfo->gpsState = GPS_STOPPING;
pControlThreadInfo->stoppingTimeoutMs = getMonotonicMsCounter() + pUbxGps->getStoppingTimeoutMs();
CMyDatabase::getInstance()->resetPublish();
}
}
if (s_ser.isFdOpen())
{
reportStatus(pControlThreadInfo);
}
LOGV("%s: (End) Client count %d", __FUNCTION__, pControlThreadInfo->clientCount);
pthread_mutex_unlock(&pControlThreadInfo->threadDataAccessMutex);
// Do NOT signal command complete
// This is send after response from device or timeout
}
static void handle_init(ControlThreadInfo* pControlThreadInfo)
{
LOGV("%s (%u): Init state.", __FUNCTION__, (unsigned int) pthread_self());
pControlThreadInfo->gpsState = GPS_STOPPED;
signal_cmd_complete(pControlThreadInfo, 1);
}
static void handle_stopped(ControlThreadInfo* pControlThreadInfo)
{
pthread_mutex_lock(&pControlThreadInfo->threadDataAccessMutex);
LOGV("%s: (Begin)", __FUNCTION__);
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->onShutDown();
pUbxGps->unlock();
pControlThreadInfo->gpsState = GPS_STOPPED;
reportStatus(pControlThreadInfo);
LOGV("%s: (End)", __FUNCTION__);
pthread_mutex_unlock(&pControlThreadInfo->threadDataAccessMutex);
}
static void engineStart(ControlThreadInfo* pControlThreadInfo, bool si)
{
pthread_mutex_lock(&pControlThreadInfo->threadDataAccessMutex);
LOGV("%s: (Begin) Client count %d", __FUNCTION__, pControlThreadInfo->clientCount);
assert(pControlThreadInfo->clientCount >= 0);
pControlThreadInfo->clientCount++;
if (pControlThreadInfo->clientCount == 1)
{
// Reset database as it will be out of date
CMyDatabase::getInstance()->Reset();
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->onStartup();
// agps / assist now online
pUbxGps->checkAgpsDownload();
pUbxGps->unlock();
// request time from the ntp server
#if (PLATFORM_SDK_VERSION >= 14 /* =4.0 */)
CGpsIf::requestUtcTime();
#endif
/* inside the thread we already check alp file expiry
CXtraIf::requestDownload()
LOGE("%s : No AGPS xtra Callbacks", __FUNCTION__);
*/
pControlThreadInfo->gpsState = GPS_STARTED;
pUbxGps->clearReceiverShutdownAck();
#ifdef NI_TEST
CNiIf::request(5000, NotificationType_notificationAndVerficationAllowedNA);
#endif
#ifdef SUPL_ENABLED
if (si)
{
GpsPositionMode posMode = CGpsIf::getInstance()->getMode();
bool suplStarted = false;
if (((posMode == GPS_POSITION_MODE_MS_BASED) || (posMode == GPS_POSITION_MODE_MS_ASSISTED)) &&
(!suplActiveSessions()))
{
suplStarted = suplStartSetInitiatedAction();
}
if ((posMode != GPS_POSITION_MODE_MS_ASSISTED) || (!suplStarted))
{
CMyDatabase::getInstance()->incPublish();
}
}
#else
CMyDatabase::getInstance()->incPublish();
#endif
}
if (s_ser.isFdOpen())
{
reportStatus(pControlThreadInfo);
}
LOGV("%s: (End) Client count %d", __FUNCTION__, pControlThreadInfo->clientCount);
pthread_mutex_unlock(&pControlThreadInfo->threadDataAccessMutex);
}
static bool handle_cmd(ControlThreadInfo* pControlThreadInfo, U1 cmd)
{
bool ret = false;
switch(cmd)
{
case CMD_START_SI:
engineStart(pControlThreadInfo, true);
break;
case CMD_STOP_SI:
engineStop(pControlThreadInfo, true);
break;
case CMD_START_NI:
engineStart(pControlThreadInfo, false);
break;
case CMD_STOP_NI:
engineStop(pControlThreadInfo, false);
break;
#ifndef ANDROID_BUILD
case CMD_EXIT:
ret = true;
break;
#endif
default:
LOGE("%s : Unexpected command %i", __FUNCTION__, cmd);
break;
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////
//! Handle the device shut down process
/*! During the 'stopping' / device shutdown state/phase, this function checks
to see if all the device acknowledgements have been received or the shutdown
timeout has expired. If either of these conditions are true, the gps is put
into the 'stopped' state.
\param pControlThreadInfo : Pointer to main control thread data
*/
static void handle_device_shutdown(ControlThreadInfo* pControlThreadInfo)
{
int timeOut = (getMonotonicMsCounter() > pControlThreadInfo->stoppingTimeoutMs);
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
if (pUbxGps->getReceiverShutdownAck() || timeOut)
{
LOGD("%s : All aiding data received %i timeout %i",
__FUNCTION__,
pUbxGps->getReceiverShutdownAck(),
timeOut);
handle_stopped(pControlThreadInfo);
}
}
static void reportStatus(const ControlThreadInfo* pState)
{
#ifdef SUPL_ENABLED
if ((pState->clientCount > 0) &&
(pState->clientCount == suplCountSessions(true)))
{
// Only NI sessions. Don't report engine activity
CGpsIf::gpsStatus(GPS_STATUS_ENGINE_OFF);
return;
}
#endif
switch (pState->gpsState)
{
case GPS_STARTED:
CGpsIf::gpsStatus(GPS_STATUS_SESSION_BEGIN);
break;
case GPS_STOPPING:
CGpsIf::gpsStatus(GPS_STATUS_SESSION_END);
break;
case GPS_STOPPED:
CGpsIf::gpsStatus(GPS_STATUS_ENGINE_OFF);
break;
default:
// Shouldn't happen
assert(0);
break;
}
}
static bool handleCmdInput(ControlThreadInfo* pState, fd_set* pRfds)
{
bool finish = false;
if(FD_ISSET(pState->cmdPipes[0], pRfds))
{
// Command received
U1 cmd;
if (read(pState->cmdPipes[0], &cmd, 1) == -1)
{
LOGE("%s : Cmd pipe read failure (%i)", __FUNCTION__, errno);
}
else
{
LOGV("%s (%u): Cmd received (%i)", __FUNCTION__, (unsigned int) pthread_self(), cmd);
if (handle_cmd(pState, cmd))
{
#ifndef ANDROID_BUILD
LOGV("%s : Exit thread cmd received", __FUNCTION__);
finish = true;
#endif
}
}
}
return finish;
//lint -e{818} suppress "could be declared as pointing to const"
}
#if defined UDP_SERVER_PORT
static void handleUdpInput(fd_set &rfds)
{
if (s_udp.fdIsSet(rfds))
{
char tmpbuf[MAX_UDP_PACKET_LEN];
int len = s_udp.recvPort(tmpbuf, sizeof(tmpbuf));
// LOGV("%s: Received something over UDP! %d", __FUNCTION__, len);
if (len > 0)
{
// UBX or PUBX data - forward to GPS
if (s_ser.writeSerial(tmpbuf,(unsigned int) len) != len)
{
LOGE("unable to write %i to a master",len);
}
}
}
}
#endif
static void connectReceiver(const ControlThreadInfo* pState, fd_set& rfds, int& rMaxFd)
{
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
LOGV("%s: Open/Reopen the serial port", __FUNCTION__);
/* try to open/reopen the serial port for the GPS listener */
if (!s_ser.openSerial(pUbxGps->getSerialDevice(), pUbxGps->getBaudRateDefault(), 1))
{
// Device not present (unplugged)
CGpsIf::gpsStatus(GPS_STATUS_ENGINE_OFF);
LOGE("Failing to reopen the serial port");
}
else
{
// Serial port opened/reopened - Baud rate needs to be set
pUbxGps->setBaudRate();
s_ser.fdSet(rfds, rMaxFd);
pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
if (pState->gpsState == GPS_STARTED)
{
LOGV("%s: Start receiver ", __FUNCTION__);
pUbxGps->onInit();
}
else
{
LOGV("%s: Init receiver ", __FUNCTION__);
pUbxGps->onInit();
}
pUbxGps->unlock();
// Report appropriate status
reportStatus(pState);
}
}
//--------------------------------------------------------------------------------
static void releaseGpsThreadResources(ControlThreadInfo* pControlThreadInfo)
{
s_ser.closeSerial();
#if defined UDP_SERVER_PORT
s_udp.closeUdp();
#endif
if (pControlThreadInfo->cmdPipes[0] != -1)
close(pControlThreadInfo->cmdPipes[0]);
pControlThreadInfo->cmdPipes[0] = -1;
if (pControlThreadInfo->cmdPipes[1] != -1)
close(pControlThreadInfo->cmdPipes[1]);
pControlThreadInfo->cmdPipes[1] = -1;
}
///////////////////////////////////////////////////////////////////////////////
//! Main gps driver control thread
/*!
\param pThreadData : Pointer to thread data
*/
void ubx_thread(void *pThreadData)
{
ControlThreadInfo* pState = (ControlThreadInfo*) pThreadData;
assert(g_gpsDrvMainThread == 0);
#ifndef UNDEBUG
g_gpsDrvMainThread = pthread_self(); // For debugging threads
#endif
time_t now = time(NULL);
CMyDatabase* pDatabase = CMyDatabase::getInstance();
#if defined UDP_SERVER_PORT
time_t timeoutPts = now; //!< for virtual serial status check
#endif
time_t timeoutLastValidMessage = now; //!< timeout for serial port
time_t timeoutLastXtraRequest = 0;
pDatabase->setGpsState(pState);
#ifdef SUPL_ENABLED
suplInit();
#endif
CProtocolUBX protocolUBX;
CProtocolNMEA protocolNmea;
CProtocolUnknown protocolUnknown;
CParserBuffer parser; // declare after protocols, so destructor called before protocol destructors
// setup parser buffer
parser.Register(&protocolUBX);
parser.Register(&protocolNmea);
parser.RegisterUnknown(&protocolUnknown);
LOGV("%s (%u): Gps background thread started", __FUNCTION__, (unsigned int) pthread_self());
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
#ifdef SUPL_ENABLED
suplRegisterEventCallbacks(&s_eventHandler, pState);
OpenSSL_add_all_algorithms();
SSL_library_init();
LOGV("%s: SSL initialised", __FUNCTION__);
#endif
pUbxGps->setSerial(&s_ser);
#if defined UDP_SERVER_PORT
pUbxGps->setUdp(&s_udp);
#endif
#if defined UDP_SERVER_PORT
if ((s_udp.openLocalPort(pUbxGps->getUdpPort())) < 0)
{
LOGE("unable to open local port");
LOGE("Exiting the thread");
releaseGpsThreadResources(pState);
signal_cmd_complete(pState, 0); // Signal init fail
return;
}
#endif
if (pipe(pState->cmdPipes) == -1)
{
LOGE("%s : Could not create cmd pipes (%i)", __FUNCTION__, errno);
releaseGpsThreadResources(pState);
signal_cmd_complete(pState, 0); // Signal init fail
return;
}
handle_init(pState); // also turn off the device when the thread starts
// and complete (signal init handler function)
for (;;)
{
fd_set rfds;
int maxFd = 0;
/* Initialize the select mask */
//lint -e{866} suppress "Unusual use of '' in argument to sizeof"
FD_ZERO(&rfds);
if (!s_ser.fdSet(rfds, maxFd)) // Add the gps device
{
// Serial channel to receiver not open
connectReceiver(pState, rfds, maxFd);
}
FD_SET(pState->cmdPipes[0], &rfds); // Add cmd queue pipe
if (pState->cmdPipes[0]+1 > maxFd)
maxFd = pState->cmdPipes[0]+1;
#if defined UDP_SERVER_PORT
s_udp.fdSet(rfds, maxFd); // Add UDP port connection
#endif
#ifdef SUPL_ENABLED
suplAddUplListeners(&rfds, &maxFd); // Add Supl session sockets
#endif
/* make the select */
struct timeval tv; /* and setup the timeout to 1.0 seconds */
tv.tv_sec = 1;
tv.tv_usec = 0;
int res = select(maxFd, &rfds, NULL, NULL, &tv);
now = time(NULL);
#if defined UDP_SERVER_PORT
if ((now - timeoutPts) >= 1)
{
/* Check UDP connections */
s_udp.checkPort(0);
/* update pseudoterminal timeout */
timeoutPts = now;
}
#endif
if (res > 0)
{
if (s_ser.fdIsSet(rfds))
{
// There is some input in the serial port
// fill the parser with new data
unsigned char *ptr = parser.GetPointer();
unsigned int space = (unsigned int) parser.GetSpace();
int iSize = s_ser.readSerial(ptr, space);
if (iSize)
{
int iMsg;
unsigned char* pMsg;
CProtocol* pProtocol;
// we read it so update the size
parser.Append(iSize);
// Parse ...
while (parser.Parse(pProtocol, pMsg, iMsg))
{
#if defined UDP_SERVER_PORT
/* put the UBX token */
s_udp.sendPort(pMsg, iMsg);
#endif
// redirecting
if (pProtocol == &protocolUBX)
{
timeoutLastValidMessage = now;
//LOGV("MSG UBX %02X-%02X-%02X-%02X-%02X-%02X (size %d)\n", pMsg[2], pMsg[3], pMsg[4], pMsg[5], pMsg[6], pMsg[7], iMsg);
pUbxGps->lock();
pUbxGps->onNewUbxMsg(pState->gpsState, pMsg, (unsigned int) iMsg);
pUbxGps->unlock();
}
else if (pProtocol == &protocolNmea)
{
timeoutLastValidMessage = now;
#if (PLATFORM_SDK_VERSION > 8 /* >2.2 */)
if ((CGpsIf::getInstance()->m_callbacks.nmea_cb) &&
(getMonotonicMsCounter() >= pDatabase->getNextReportEpoch()))
{
#if 1
struct timeval tv1;
gettimeofday(&tv1, NULL);
GpsUtcTime gpsUtcTime = (long) (tv1.tv_sec * 1000);
gpsUtcTime += (tv1.tv_usec / 1000);
#else
GpsUtcTime gpsUtcTime = pDatabase->GetGpsUtcTime();
#endif
CGpsIf::getInstance()->m_callbacks.nmea_cb(gpsUtcTime, (const char*)pMsg, iMsg);
}
#endif
//LOGV("MSG %*.*s\n", iMsg-2, iMsg-2, pMsg);
}
else
{
LOGV("%s: MSG UNKNOWN size %d\n", __FUNCTION__, iMsg);
}
// PRINTF("size %5d ", iMsg);
// ... and Process
pProtocol->Process(pMsg, iMsg, pDatabase);
parser.Remove(iMsg);
}
parser.Compact();
}
else
{
LOGE( "%s: read error %d", __FUNCTION__, iSize);
s_ser.closeSerial();
}
// check if we have not received usefull message and may need to resync the baudrate
int twiceRate = (2 * pUbxGps->getRate() / 1000);
int validMsgThreshold = twiceRate < 1 ? 1 : twiceRate;
int baudRate = pUbxGps->getBaudRate();
if (((now - timeoutLastValidMessage) > validMsgThreshold) &&
(baudRate != pUbxGps->getBaudRateDefault()))
{
LOGV("%s : Resetting serial baud rate - diff (%li) threshold (%i)", __FUNCTION__,
(now - timeoutLastValidMessage),
twiceRate);
// switch to the original default baudrate (on init this is not needed)
s_ser.setbaudrate(pUbxGps->getBaudRateDefault());
usleep(50000);
// reconfigure the baud rate
pUbxGps->setBaudRate();
timeoutLastValidMessage = now;
}
}
#if defined UDP_SERVER_PORT
/* UDP PORT READ HANDLING */
handleUdpInput(rfds);
#endif /* UDP_SERVER_PORT */
#ifdef SUPL_ENABLED
suplReadUplSock(&rfds); // Check and process any incoming SUPL data
#endif
if (handleCmdInput(pState, &rfds))
{
break; // Will only happen when using test harness
}
}
else
{
// LOGV("%s : No input timeout", __FUNCTION__);
}
#ifdef SUPL_ENABLED
suplCheckPendingActions(); // Check for any actions on existing SUPL sessions
#endif
if (pState->gpsState == GPS_STOPPING)
{
handle_device_shutdown(pState);
}
else if (pState->gpsState == GPS_STARTED)
{
// Request a new ALP file if it seems outdated
pUbxGps->lock();
bool ok = pUbxGps->checkAlpFile();
pUbxGps->unlock();
if (!ok && ((now - timeoutLastXtraRequest) >= 60/*one minute*/))
{
CXtraIf::requestDownload();
timeoutLastXtraRequest = now;
}
}
}
// Should never get too.
#ifndef ANDROID_BUILD
suplDeinit();
ERR_remove_state(0);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
ENGINE_cleanup();
CONF_modules_unload(1);
CONF_modules_free();
sk_SSL_COMP_free (SSL_COMP_get_compression_methods());
LOGV("%s : Left main loop", __FUNCTION__);
releaseGpsThreadResources(pState);
LOGV("%s : Thread exiting", __FUNCTION__);
#endif
return;
}
///////////////////////////////////////////////////////////////////////////////
//! Injects a time into the receiver
/*!
\param timeUtcGps : Utc time
\param timeReference : Time reference
\param uncertainty : Uncertaincy
*/
void gps_state_inject_time(GpsUtcTime timeUtcGps, int64_t timeReference, int uncertainty)
{
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->putTime(timeUtcGps, timeReference, uncertainty);
pUbxGps->writeUbxAidIni();// Send AID-INI command
pUbxGps->unlock();
}
///////////////////////////////////////////////////////////////////////////////
//! Injects a location into the receiver
/*!
\param latitude : Latitude part of location
\param longitude : Longitude part of location
\param accuracy : Accuracy of location
*/
void gps_state_inject_location(double latitude, double longitude, float accuracy)
{
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->putPos(latitude, longitude, accuracy);
pUbxGps->writeUbxAidIni();
pUbxGps->unlock();
}
///////////////////////////////////////////////////////////////////////////////
//! Deletes aiding data in the receiver
/*!
\param flags : Flags indicating which data to delete
*/
void gps_state_delete_aiding_data(GpsAidingData flags)
{
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->deleteAidData(flags);
pUbxGps->writeUbxCfgRst(0x02/*reset gps only*/, flags);
pUbxGps->unlock();
}
///////////////////////////////////////////////////////////////////////////////
//! Sets the interval for the driver to report to the framework
/*!
\param min_interval : Reporting interval in ms
*/
void gps_state_set_interval(uint32_t min_interval)
{
int64_t nextReportEpochMs = 0; // default - no driver intervention
int timeInterval = 0;
if (min_interval < MIN_INTERVAL)
{
// Below minimun, set to receiver minimum, with no driver intervention
min_interval = MIN_INTERVAL;
}
else if ((min_interval >= MIN_INTERVAL) && (min_interval <= 2000))
{
// Receiver can cope with these values.
}
else
{
// Too fast for receiver, so driver will intervene to extend
LOGW("%s : Interval (%i) too big - Driver will intervene", __FUNCTION__, min_interval);
timeInterval = (int) min_interval;
nextReportEpochMs = getMonotonicMsCounter();
min_interval = 1000;
}
CMyDatabase* pDatabase = CMyDatabase::getInstance();
pDatabase->setEpochInterval(timeInterval, nextReportEpochMs);
CUbxGpsState* pUbxGps = CUbxGpsState::getInstance();
pUbxGps->lock();
pUbxGps->putRate((int) min_interval);
pUbxGps->writeUbxCfgRate();
pUbxGps->unlock();
}
///////////////////////////////////////////////////////////////////////////////
//! Initialises the main thread's control data structure
/*!
\param pControlThreadInfo : Pointer to main thread data
*/
void controlThreadInfoInit(ControlThreadInfo* pControlThreadInfo)
{
memset(pControlThreadInfo, 0, sizeof(ControlThreadInfo));
pControlThreadInfo->cmdPipes[0] = -1;
pControlThreadInfo->cmdPipes[1] = -1;
pControlThreadInfo->gpsState = GPS_UNKNOWN;
pthread_mutex_init(&pControlThreadInfo->threadCmdCompleteMutex, NULL);
pthread_cond_init(&pControlThreadInfo->threadCmdCompleteCond, NULL);
pthread_mutex_init(&pControlThreadInfo->threadDataAccessMutex, NULL);
}
///////////////////////////////////////////////////////////////////////////////
//! Releases any resources in the main thread's control data
/*!
\param pControlThreadInfo : Pointer to main thread data
*/
void controlThreadInfoRelease(ControlThreadInfo* pControlThreadInfo)
{
pthread_mutex_destroy(&pControlThreadInfo->threadCmdCompleteMutex);
pthread_cond_destroy(&pControlThreadInfo->threadCmdCompleteCond);
pthread_mutex_destroy(&pControlThreadInfo->threadDataAccessMutex);
}
///////////////////////////////////////////////////////////////////////////////
//! Sends a command to the main thread
/*!
\param pControlThreadInfo : Pointer to main thread data
\param cmd : Command to send to main thread
*/
bool controlThreadInfoSendCmd(ControlThreadInfo* pControlThreadInfo, THREAD_CMDS cmd)
{
U1 c = cmd;
if (write(pControlThreadInfo->cmdPipes[1], &c, 1) == -1)
{
LOGE("%s : Could not write to cmd pipe (%i)", __FUNCTION__, errno);
return false;
}
return true;
//lint -e{818} remove "could be declared as pointing to const"
}
///////////////////////////////////////////////////////////////////////////////
//! Implimentation of a requestStart interface function on GpsControlEventInterface
/*!
\param pContext : Pointer to the interface context
*/
static void requestStartEventHandler(void* pContext)
{
LOGV("%s: Called", __FUNCTION__);
controlThreadInfoSendCmd((ControlThreadInfo *) pContext, CMD_START_NI);
}
///////////////////////////////////////////////////////////////////////////////
//! Implimentation of a requestStop interface function on GpsControlEventInterface
/*!
\param pContext : Pointer to the interface context
*/
static void requestStopEventHandler(void* pContext)
{
LOGV("%s: Called", __FUNCTION__);
//engineStop((ControlThreadInfo *) pContext);
controlThreadInfoSendCmd((ControlThreadInfo *) pContext, CMD_STOP_NI);
}