firmware/src/gps/GPS.cpp

64 lines
1.6 KiB
C++
Raw Normal View History

2020-02-06 15:39:21 +00:00
#include "GPS.h"
#include "configuration.h"
#include "time.h"
#include <assert.h>
#include <sys/time.h>
2020-02-06 15:39:21 +00:00
#ifdef GPS_RX_PIN
2020-05-04 18:15:05 +00:00
HardwareSerial _serial_gps_real(GPS_SERIAL_NUM);
HardwareSerial &GPS::_serial_gps = _serial_gps_real;
#else
// Assume NRF52
2020-05-04 18:15:05 +00:00
HardwareSerial &GPS::_serial_gps = Serial1;
#endif
2020-02-20 04:02:57 +00:00
2020-04-05 02:16:30 +00:00
bool timeSetFromGPS; // We try to set our time from GPS each time we wake from sleep
2020-02-06 15:39:21 +00:00
2020-05-04 18:15:05 +00:00
GPS *gps;
// stuff that really should be in in the instance instead...
static uint32_t
timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
static uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
2020-05-04 18:15:05 +00:00
void readFromRTC()
2020-02-06 15:39:21 +00:00
{
struct timeval tv; /* btw settimeofday() is helpfull here too*/
if (!gettimeofday(&tv, NULL)) {
uint32_t now = millis();
2020-02-20 04:02:57 +00:00
DEBUG_MSG("Read RTC time as %ld (cur millis %u) valid=%d\n", tv.tv_sec, now, timeSetFromGPS);
timeStartMsec = now;
2020-02-19 18:53:09 +00:00
zeroOffsetSecs = tv.tv_sec;
}
}
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
2020-05-04 18:15:05 +00:00
void perhapsSetRTC(const struct timeval *tv)
2020-02-19 18:53:09 +00:00
{
if (!timeSetFromGPS) {
2020-02-19 18:53:09 +00:00
timeSetFromGPS = true;
DEBUG_MSG("Setting RTC %ld secs\n", tv->tv_sec);
#ifndef NO_ESP32
2020-02-19 18:53:09 +00:00
settimeofday(tv, NULL);
#else
2020-04-30 20:50:40 +00:00
DEBUG_MSG("ERROR TIME SETTING NOT IMPLEMENTED!\n");
#endif
2020-02-19 18:53:09 +00:00
readFromRTC();
}
2020-02-06 15:39:21 +00:00
}
2020-02-20 02:51:17 +00:00
#include <time.h>
2020-05-04 18:15:05 +00:00
uint32_t getTime()
2020-02-21 16:41:36 +00:00
{
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
}
2020-05-04 18:15:05 +00:00
uint32_t getValidTime()
2020-02-21 16:41:36 +00:00
{
return timeSetFromGPS ? getTime() : 0;
}