Add opt-in low power Sensor dog tracking
Acquire fresh GPS and validated UTC, check an authenticated owner Companion, and apply saved lost-status cadence with bounded awake windows. Persist request tags, routes, and six-hour flood reservations; preserve the four-day cutoff across sleep and restart. Keep Dispatcher recovery active after a failed radio wake, honor denied flood retries after lost TxDone, and qualify GPS ownership and clock corrections. Add executable regression tests and nRF52/ESP32 Sensor build jobs. Validation: six firmware builds, 1829 native test cases, sanitized tracker/storage/GPS/sleep/recovery tests, and strict documentation build. Bluetooth Find My advertising and automatic Room mailbox polling remain separate work.
This commit is contained in:
1 parent
90b12f6fa3
commit
1f1a499482
43 files changed
+4684
-17
No files matched your search
@@ -224,6 +224,9 @@ bool Dispatcher::startOutboundTransmit() {
|
||||
|
||||
bool Dispatcher::scheduleOutboundRadioRetry() {
|
||||
if (outbound == NULL || outbound_radio_retry_used || outbound_cancellation != OutboundCancellation::None) return false;
|
||||
// A lost TxDone may follow a real transmission, so a denied flood must not
|
||||
// spend its reserved airtime again during radio recovery.
|
||||
if (outbound->isRouteFlood() && outbound->flood_retry_policy == FLOOD_RETRY_POLICY_DENY) return false;
|
||||
|
||||
outbound_radio_retry_used = true;
|
||||
outbound_radio_retry_pending = true;
|
||||
|
||||
@@ -119,6 +119,11 @@ public:
|
||||
virtual void idle() { }
|
||||
virtual void startRecv() { }
|
||||
|
||||
// A tracker may stop RF reception between explicit check-in windows. The
|
||||
// dispatcher must be made unavailable while asleep so watchdog recovery
|
||||
// cannot restart RX. Unsupported transports decline without changing state.
|
||||
virtual bool setTrackerSleep(bool sleeping) { (void)sleeping; return false; }
|
||||
|
||||
// Recover a radio whose MCU driver is still running but whose RF state has
|
||||
// stopped making progress. hard=false is a safe receive/AGC re-arm;
|
||||
// hard=true may reset only the radio peripheral. The default remains useful
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#include "SensorManager.h"
|
||||
#include <math.h>
|
||||
|
||||
#if ENV_INCLUDE_GPS
|
||||
static const uint32_t GPS_TRACKER_MAX_ACQUIRE_MS = 120000UL;
|
||||
#endif
|
||||
|
||||
bool SensorManager::getCachedGpsPosition(double& latitude, double& longitude) const {
|
||||
latitude = longitude = 0;
|
||||
#if ENV_INCLUDE_GPS
|
||||
@@ -17,6 +21,82 @@ bool SensorManager::getCachedGpsPosition(double& latitude, double& longitude) co
|
||||
#endif
|
||||
}
|
||||
|
||||
void SensorManager::setTrackerGpsModeEnabled(bool enabled) {
|
||||
#if ENV_INCLUDE_GPS
|
||||
if (gps_tracker_enabled == enabled) return;
|
||||
// Leave an interrupted window through the same hardware stop/start hooks so
|
||||
// the normal provider power cycle is rearmed when a saved GPS-on preference
|
||||
// resumes. In particular, GPS-off must not leave the receiver running.
|
||||
if (!enabled && gps_transport_available && telemetryGpsDetected() && telemetryGpsActive()) {
|
||||
telemetryGpsStop();
|
||||
}
|
||||
gps_tracker_enabled = enabled;
|
||||
gps_tracker_fix_ready = false;
|
||||
const unsigned long now = millis();
|
||||
cancelGpsTelemetryDemand(now);
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr) {
|
||||
location->endFreshTimeSync();
|
||||
// The provider's normal clock/power cycle must not wake GPS while the
|
||||
// tracker is idle. The normal preference is restored when mode ends.
|
||||
location->setGPSPowerSaving(!enabled && powersaving_enabled && gps_user_enabled);
|
||||
}
|
||||
if (enabled) {
|
||||
maybeStopGpsForTelemetry(now);
|
||||
} else if (gps_transport_available && telemetryGpsDetected() && gps_user_enabled) {
|
||||
if (!telemetryGpsActive()) telemetryGpsStart();
|
||||
} else if (gps_location_access_available) {
|
||||
gps_next_cache_update_at = 0;
|
||||
}
|
||||
#else
|
||||
(void)enabled;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool SensorManager::beginTrackerGpsAcquisition() {
|
||||
#if ENV_INCLUDE_GPS
|
||||
if (!gps_tracker_enabled || !gps_transport_available || !telemetryGpsDetected()) return false;
|
||||
if (gps_acquiring) return true; // A repeated request must not extend its bound.
|
||||
gps_tracker_fix_ready = false;
|
||||
gps_hold_until = 0;
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location == nullptr || !location->clearPositionFix()) return false;
|
||||
gps_tracker_sync_generation = location->getTimeSyncGeneration();
|
||||
location->beginFreshTimeSync();
|
||||
if (location->getGPSPowerSaving()) location->setGPSPowerSaving(false);
|
||||
beginGpsTelemetryAcquisition(millis());
|
||||
return gps_acquiring;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool SensorManager::isTrackerGpsAcquisitionPending() const {
|
||||
#if ENV_INCLUDE_GPS
|
||||
return gps_tracker_enabled && gps_acquiring;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool SensorManager::takeTrackerGpsPosition(double& latitude, double& longitude) {
|
||||
latitude = longitude = 0;
|
||||
#if ENV_INCLUDE_GPS
|
||||
const unsigned long now = millis();
|
||||
if (gps_tracker_enabled && gps_acquiring
|
||||
&& static_cast<uint32_t>(now - gps_acquire_started_at) >= GPS_TRACKER_MAX_ACQUIRE_MS)
|
||||
finishGpsTelemetryAcquisition(now, false);
|
||||
if (!gps_tracker_enabled || gps_acquiring || !gps_tracker_fix_ready) return false;
|
||||
gps_tracker_fix_ready = false;
|
||||
if (static_cast<uint32_t>(now - gps_stable_started_at) >= GPS_TRACKER_MAX_ACQUIRE_MS) return false;
|
||||
latitude = gps_cache_lat;
|
||||
longitude = gps_cache_lon;
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ENV_INCLUDE_GPS
|
||||
#ifndef GPS_TELEMETRY_CACHE_INTERVAL_SEC
|
||||
#define GPS_TELEMETRY_CACHE_INTERVAL_SEC (2UL * 60UL * 60UL)
|
||||
@@ -66,7 +146,7 @@ void SensorManager::updateGpsTelemetryCache(float lat, float lon, float altitude
|
||||
}
|
||||
|
||||
void SensorManager::maybeStopGpsForTelemetry(unsigned long now) {
|
||||
if (gps_transport_available && telemetryGpsActive() && !gps_user_enabled
|
||||
if (gps_transport_available && telemetryGpsActive() && (gps_tracker_enabled || !gps_user_enabled)
|
||||
&& !gps_acquiring && !gpsTelemetryHoldActive(now)) {
|
||||
telemetryGpsStop();
|
||||
gps_next_cache_update_at = now + GPS_TELEMETRY_CACHE_INTERVAL_SEC * 1000UL;
|
||||
@@ -114,6 +194,13 @@ void SensorManager::finishGpsTelemetryAcquisition(unsigned long now, bool use_we
|
||||
now);
|
||||
}
|
||||
gps_acquiring = false;
|
||||
if (gps_tracker_enabled) {
|
||||
// Keep a fresh position acquired before a clock-sync timeout. Its one-shot
|
||||
// result expires relative to completion, not the first position sample.
|
||||
gps_stable_started_at = now;
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr) location->endFreshTimeSync();
|
||||
}
|
||||
gps_next_cache_update_at = now + GPS_TELEMETRY_CACHE_INTERVAL_SEC * 1000UL;
|
||||
maybeStopGpsForTelemetry(now);
|
||||
}
|
||||
@@ -123,6 +210,13 @@ bool SensorManager::queryGpsTelemetry(uint8_t requester_permissions, CayenneLPP&
|
||||
|| !telemetryGpsDetected()) return false;
|
||||
|
||||
unsigned long now = millis();
|
||||
if (gps_tracker_enabled) {
|
||||
// Ordinary telemetry can observe the cache, but may not create a two-hour
|
||||
// hold or acquire GPS outside the tracker's scheduled window.
|
||||
if (!gpsTelemetryCacheFresh(now)) return false;
|
||||
telemetry.addGPS(TELEM_CHANNEL_SELF, gps_cache_lat, gps_cache_lon, gps_cache_altitude);
|
||||
return true;
|
||||
}
|
||||
if (!gps_transport_available) {
|
||||
// A bridge may temporarily own the GPS UART. Authorized callers can still
|
||||
// receive the last good fix while it is inside the normal freshness bound,
|
||||
@@ -155,6 +249,21 @@ bool SensorManager::queryGpsTelemetry(uint8_t requester_permissions, CayenneLPP&
|
||||
|
||||
void SensorManager::processGpsTelemetryFix(float lat, float lon, float altitude, unsigned long now) {
|
||||
if (!gps_transport_available) return;
|
||||
if (gps_tracker_enabled) {
|
||||
if (!gps_acquiring) return;
|
||||
if (static_cast<uint32_t>(now - gps_acquire_started_at) >= GPS_TRACKER_MAX_ACQUIRE_MS) {
|
||||
finishGpsTelemetryAcquisition(now, false);
|
||||
return;
|
||||
}
|
||||
if (!isfinite(lat) || !isfinite(lon) || lat < -90.0f || lat > 90.0f
|
||||
|| lon < -180.0f || lon > 180.0f || (lat == 0 && lon == 0)) return;
|
||||
updateGpsTelemetryCache(lat, lon, altitude, now);
|
||||
gps_tracker_fix_ready = true;
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr && location->getTimeSyncGeneration() != gps_tracker_sync_generation)
|
||||
finishGpsTelemetryAcquisition(now, false);
|
||||
return;
|
||||
}
|
||||
if (!gps_acquiring) {
|
||||
if (gps_user_enabled || gpsTelemetryHoldActive(now)) {
|
||||
updateGpsTelemetryCache(lat, lon, altitude, now);
|
||||
@@ -196,6 +305,28 @@ void SensorManager::loopGpsTelemetry(unsigned long now) {
|
||||
// Expire the validity bit even while a bridge owns the UART. A stale fix
|
||||
// must not become fresh again when the 32-bit millis counter cycles.
|
||||
if (gps_cache_valid && !gpsTelemetryCacheFresh(now)) gps_cache_valid = false;
|
||||
if (gps_tracker_enabled) {
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr && location->getGPSPowerSaving()) location->setGPSPowerSaving(false);
|
||||
if (!gps_transport_available) return;
|
||||
if (gps_acquiring
|
||||
&& static_cast<uint32_t>(now - gps_acquire_started_at) >= GPS_TRACKER_MAX_ACQUIRE_MS) {
|
||||
finishGpsTelemetryAcquisition(now, false);
|
||||
}
|
||||
if (gps_acquiring && telemetryGpsActive() && location != nullptr && location->isValid()) {
|
||||
// Tracker freshness is independent of the saved telemetry gps_interval.
|
||||
// Derived managers have already polled this provider in their previous
|
||||
// loop; clearPositionFix() made any retained pre-window sample invalid.
|
||||
processGpsTelemetryFix(static_cast<float>(location->getLatitude()) / 1000000.0f,
|
||||
static_cast<float>(location->getLongitude()) / 1000000.0f,
|
||||
static_cast<float>(location->getAltitude()) / 1000.0f, now);
|
||||
}
|
||||
if (gps_acquiring && gps_tracker_fix_ready && location != nullptr
|
||||
&& location->getTimeSyncGeneration() != gps_tracker_sync_generation)
|
||||
finishGpsTelemetryAcquisition(now, false);
|
||||
maybeStopGpsForTelemetry(now);
|
||||
return;
|
||||
}
|
||||
if (!gps_transport_available) return;
|
||||
if (!gps_user_enabled && !gpsTelemetryHoldActive(now) && !gps_acquiring) {
|
||||
maybeStopGpsForTelemetry(now);
|
||||
@@ -213,6 +344,12 @@ void SensorManager::loopGpsTelemetry(unsigned long now) {
|
||||
void SensorManager::setGpsTelemetryUserEnabled(bool enabled) {
|
||||
gps_user_enabled = enabled;
|
||||
unsigned long now = millis();
|
||||
if (gps_tracker_enabled) {
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr && location->getGPSPowerSaving()) location->setGPSPowerSaving(false);
|
||||
maybeStopGpsForTelemetry(now);
|
||||
return;
|
||||
}
|
||||
if (enabled) {
|
||||
if (gps_transport_available && telemetryGpsDetected()
|
||||
&& !telemetryGpsActive()) telemetryGpsStart();
|
||||
@@ -227,10 +364,13 @@ void SensorManager::setGpsTelemetryTransportAvailable(bool available) {
|
||||
|
||||
gps_transport_available = available;
|
||||
if (!available) {
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr) location->endFreshTimeSync();
|
||||
// The UART is no longer ours. Cancel both the short acquisition and the
|
||||
// two-hour remote-query hold so neither can silently reclaim it from a
|
||||
// bridge. Preserve the user's preference and last good cache.
|
||||
gps_acquiring = false;
|
||||
gps_tracker_fix_ready = false;
|
||||
gps_acquire_has_fix = false;
|
||||
gps_hold_until = 0;
|
||||
gps_acquire_started_at = 0;
|
||||
@@ -244,7 +384,7 @@ void SensorManager::setGpsTelemetryTransportAvailable(bool available) {
|
||||
}
|
||||
|
||||
gps_next_cache_update_at = 0;
|
||||
if (gps_user_enabled && telemetryGpsDetected() && !telemetryGpsActive()) {
|
||||
if (!gps_tracker_enabled && gps_user_enabled && telemetryGpsDetected() && !telemetryGpsActive()) {
|
||||
telemetryGpsStart();
|
||||
}
|
||||
}
|
||||
@@ -255,6 +395,7 @@ void SensorManager::resetGpsTelemetryTransportState() {
|
||||
// new probe has established which provider, if any, is present.
|
||||
gps_transport_available = true;
|
||||
gps_acquiring = false;
|
||||
gps_tracker_fix_ready = false;
|
||||
gps_acquire_has_fix = false;
|
||||
gps_hold_until = 0;
|
||||
gps_acquire_started_at = 0;
|
||||
@@ -276,7 +417,7 @@ void SensorManager::setTelemetryLocationAccessAvailable(bool available) {
|
||||
gps_location_access_available = available;
|
||||
if (available) {
|
||||
gps_next_cache_update_at = 0;
|
||||
} else if (gps_acquiring && !gps_user_enabled && !gpsTelemetryHoldActive(now)) {
|
||||
} else if (!gps_tracker_enabled && gps_acquiring && !gps_user_enabled && !gpsTelemetryHoldActive(now)) {
|
||||
gps_acquiring = false;
|
||||
maybeStopGpsForTelemetry(now);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ class SensorManager {
|
||||
unsigned long gps_acquire_started_at = 0;
|
||||
unsigned long gps_stable_started_at = 0;
|
||||
uint32_t gps_update_interval_sec = 0;
|
||||
bool gps_tracker_enabled = false;
|
||||
bool gps_tracker_fix_ready = false;
|
||||
uint32_t gps_tracker_sync_generation = 0;
|
||||
|
||||
bool gpsTelemetryHoldActive(unsigned long now) const;
|
||||
bool gpsTelemetryCacheFresh(unsigned long now) const;
|
||||
@@ -58,10 +61,12 @@ protected:
|
||||
void setGpsTelemetryTransportAvailable(bool available);
|
||||
void resetGpsTelemetryTransportState();
|
||||
bool isGpsTelemetryUserEnabled() const { return gps_user_enabled; }
|
||||
bool isTrackerGpsModeEnabled() const { return gps_tracker_enabled; }
|
||||
bool isGpsTelemetryTransportAvailable() const {
|
||||
return gps_transport_available;
|
||||
}
|
||||
bool gpsTelemetryReceiverRequired(unsigned long now) const {
|
||||
if (gps_tracker_enabled) return gps_acquiring;
|
||||
return gps_acquiring || gpsTelemetryHoldActive(now);
|
||||
}
|
||||
bool setGpsUpdateIntervalValue(const char* value) {
|
||||
@@ -112,12 +117,18 @@ public:
|
||||
// Read the existing fresh cache without acquiring GPS, changing power, or
|
||||
// taking a UART. Sleeping/off receivers may retain a recent valid fix.
|
||||
bool getCachedGpsPosition(double& latitude, double& longitude) const;
|
||||
// Runtime tracker ownership leaves the saved manual GPS preference intact.
|
||||
// Each acquisition needs a new fix and validated clock sync, bounded to 120s.
|
||||
void setTrackerGpsModeEnabled(bool enabled);
|
||||
bool beginTrackerGpsAcquisition();
|
||||
bool isTrackerGpsAcquisitionPending() const;
|
||||
bool takeTrackerGpsPosition(double& latitude, double& longitude);
|
||||
bool requestGpsTelemetryTimeSync(uint64_t min_interval_secs) {
|
||||
#if ENV_INCLUDE_GPS
|
||||
// A denied request must not consume the provider's throttle or reclaim a
|
||||
// bridge-owned UART. Shared GPS rails make isEnabled() an unsafe substitute
|
||||
// for the manager's established transport ownership.
|
||||
if (!gps_transport_available || !telemetryGpsDetected()) return false;
|
||||
if (gps_tracker_enabled || !gps_transport_available || !telemetryGpsDetected()) return false;
|
||||
LocationProvider* location = getLocationProvider();
|
||||
if (location != nullptr && location->getTimeSyncIntervalHours() != 0) {
|
||||
min_interval_secs = static_cast<uint64_t>(location->getTimeSyncIntervalHours()) * 3600UL;
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include "FilePresence.h"
|
||||
#include "TrackerRoutePolicy.h"
|
||||
|
||||
namespace mesh {
|
||||
namespace tracker {
|
||||
|
||||
static constexpr size_t kPathCapacity = 64;
|
||||
static constexpr uint8_t kUnknownPath = 0xff;
|
||||
static constexpr uint32_t kReplyWindowSeconds = 20;
|
||||
static constexpr uint32_t kGpsAcquireSeconds = 120;
|
||||
static constexpr size_t kTrackerImageSize = 160;
|
||||
static const char kTrackerBank0Path[] = "/tracker.0";
|
||||
static const char kTrackerBank1Path[] = "/tracker.1";
|
||||
static const char kTrackerTempPath[] = "/tracker.tmp";
|
||||
|
||||
struct TrackerRecord {
|
||||
bool enabled = false;
|
||||
uint8_t owner[32] = {};
|
||||
uint32_t normal_interval = 1800;
|
||||
uint32_t lost_interval = 60;
|
||||
RouteState route;
|
||||
uint8_t path_len = kUnknownPath;
|
||||
uint8_t path[kPathCapacity] = {};
|
||||
uint8_t last_lost = 0; // 0 unknown, 1 no, 2 yes
|
||||
uint32_t last_request_tag = 0; // Persisted nonce floor, bounded near RTC time.
|
||||
uint32_t generation = 0;
|
||||
};
|
||||
|
||||
enum class StoreResult : uint8_t { Success, NotFound, Invalid, Unavailable, Conflict };
|
||||
|
||||
inline size_t trackerPathByteLength(uint8_t encoded_length) {
|
||||
return static_cast<size_t>(encoded_length & 63) * ((encoded_length >> 6) + 1);
|
||||
}
|
||||
|
||||
inline bool isValidTrackerRecord(const TrackerRecord& record) {
|
||||
uint8_t owner_bits = 0;
|
||||
for (size_t index = 0; index < sizeof(record.owner); ++index) owner_bits |= record.owner[index];
|
||||
if (!owner_bits || record.normal_interval < 60 || record.normal_interval > 86400
|
||||
|| record.lost_interval < 60 || record.lost_interval > 86400
|
||||
|| record.last_lost > 2 || !isValidRouteState(record.route)) return false;
|
||||
if (record.last_request_tag && (!record.route.latest_observed
|
||||
|| uint64_t(record.last_request_tag) > uint64_t(record.route.latest_observed) + 300)) return false;
|
||||
// Match Packet::isValidPathLen: four-byte hashes are reserved, not supported.
|
||||
return record.path_len == kUnknownPath || ((record.path_len >> 6) != 3
|
||||
&& trackerPathByteLength(record.path_len) <= kPathCapacity);
|
||||
}
|
||||
|
||||
namespace tracker_store_detail {
|
||||
inline void failClosed(TrackerRecord& record) {
|
||||
record = TrackerRecord();
|
||||
record.route = route_detail::failClosed();
|
||||
}
|
||||
|
||||
inline bool encode(const TrackerRecord& record, uint8_t* image) {
|
||||
if (!image || !record.generation || !isValidTrackerRecord(record)) return false;
|
||||
memset(image, 0, kTrackerImageSize);
|
||||
image[0] = 'S'; image[1] = 'T'; image[2] = 'R'; image[3] = 1;
|
||||
route_detail::put32(image + 4, record.generation);
|
||||
image[8] = record.enabled ? 1 : 0;
|
||||
image[9] = record.last_lost;
|
||||
image[10] = record.path_len;
|
||||
route_detail::put32(image + 12, record.normal_interval);
|
||||
route_detail::put32(image + 16, record.lost_interval);
|
||||
memcpy(image + 20, record.owner, sizeof(record.owner));
|
||||
if (!encodeRouteState(record.route, image + 52, kRouteStateImageSize)) return false;
|
||||
if (record.path_len != kUnknownPath) memcpy(image + 84, record.path, trackerPathByteLength(record.path_len));
|
||||
route_detail::put32(image + 148, record.last_request_tag);
|
||||
route_detail::put32(image + 156, route_detail::crc(image, 156));
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool decode(const uint8_t* image, TrackerRecord& record) {
|
||||
if (!image || image[0] != 'S' || image[1] != 'T' || image[2] != 'R' || image[3] != 1
|
||||
|| !route_detail::get32(image + 4) || image[8] > 1 || image[11]
|
||||
|| route_detail::get32(image + 156) != route_detail::crc(image, 156)) return false;
|
||||
TrackerRecord decoded;
|
||||
decoded.generation = route_detail::get32(image + 4);
|
||||
decoded.enabled = image[8] != 0;
|
||||
decoded.last_lost = image[9];
|
||||
decoded.path_len = image[10];
|
||||
decoded.normal_interval = route_detail::get32(image + 12);
|
||||
decoded.lost_interval = route_detail::get32(image + 16);
|
||||
decoded.last_request_tag = route_detail::get32(image + 148);
|
||||
memcpy(decoded.owner, image + 20, sizeof(decoded.owner));
|
||||
if (!decodeRouteState(image + 52, kRouteStateImageSize, decoded.route)
|
||||
|| !isValidTrackerRecord(decoded)) return false;
|
||||
const size_t path_bytes = decoded.path_len == kUnknownPath ? 0 : trackerPathByteLength(decoded.path_len);
|
||||
memcpy(decoded.path, image + 84, path_bytes);
|
||||
for (size_t index = 84 + path_bytes; index < 148; ++index) if (image[index]) return false;
|
||||
for (size_t index = 152; index < 156; ++index) if (image[index]) return false;
|
||||
record = decoded;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
bool readImage(Filesystem* fs, const char* path, TrackerRecord& record,
|
||||
const uint8_t* expected = nullptr) {
|
||||
#if defined(RP2040_PLATFORM)
|
||||
auto file = fs->open(path, "r");
|
||||
#else
|
||||
auto file = fs->open(path);
|
||||
#endif
|
||||
if (!file) return false;
|
||||
uint8_t image[kTrackerImageSize];
|
||||
bool okay = !file.isDirectory() && file.size() == sizeof(image);
|
||||
if (okay) okay = static_cast<size_t>(file.read(image, sizeof(image))) == sizeof(image);
|
||||
file.close();
|
||||
return okay && (!expected || memcmp(image, expected, sizeof(image)) == 0) && decode(image, record);
|
||||
}
|
||||
|
||||
// A bad present bank is never treated as an absent store or replaced. Temps
|
||||
// are uncommitted and ignored. A power cut during publication leaves the older
|
||||
// active bank intact; the inactive bank is removed only after verifying temp.
|
||||
template <typename Filesystem>
|
||||
StoreResult inspect(Filesystem* fs, TrackerRecord& record, uint8_t& active_bank) {
|
||||
record = TrackerRecord();
|
||||
active_bank = 0xff;
|
||||
bool present[2];
|
||||
if (!fs || !filePresence(fs, kTrackerBank0Path, present[0])
|
||||
|| !filePresence(fs, kTrackerBank1Path, present[1])) {
|
||||
failClosed(record);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
if (!present[0] && !present[1]) return StoreResult::NotFound;
|
||||
const char* paths[2] = { kTrackerBank0Path, kTrackerBank1Path };
|
||||
for (uint8_t bank = 0; bank < 2; ++bank) {
|
||||
if (!present[bank]) continue;
|
||||
TrackerRecord read;
|
||||
if (!readImage(fs, paths[bank], read) || ((read.generation - 1) & 1) != bank) {
|
||||
failClosed(record);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
if (active_bank != 0xff) {
|
||||
const uint32_t high = read.generation > record.generation ? read.generation : record.generation;
|
||||
const uint32_t low = read.generation < record.generation ? read.generation : record.generation;
|
||||
if (high - low != 1) {
|
||||
failClosed(record);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
}
|
||||
if (read.generation > record.generation) {
|
||||
record = read;
|
||||
active_bank = bank;
|
||||
}
|
||||
}
|
||||
return StoreResult::Success;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
bool removeArtifact(Filesystem* fs, const char* path) {
|
||||
bool present;
|
||||
if (!filePresence(fs, path, present)) return false;
|
||||
if (!present) return true;
|
||||
fs->remove(path);
|
||||
return filePresence(fs, path, present) && !present;
|
||||
}
|
||||
} // namespace tracker_store_detail
|
||||
|
||||
template <typename Filesystem>
|
||||
StoreResult loadTracker(Filesystem* fs, TrackerRecord& record) {
|
||||
uint8_t bank;
|
||||
return tracker_store_detail::inspect(fs, record, bank);
|
||||
}
|
||||
|
||||
// Single writer, main-loop owned, durable filesystems only. generation is a
|
||||
// compare-and-swap token: refresh after a conflict or ambiguous failed save.
|
||||
// No radio transmission is permitted unless its reservation save succeeds.
|
||||
template <typename Filesystem>
|
||||
StoreResult saveTracker(Filesystem* fs, TrackerRecord& record) {
|
||||
if (!fs) return StoreResult::Unavailable;
|
||||
if (!isValidTrackerRecord(record)) return StoreResult::Invalid;
|
||||
TrackerRecord current;
|
||||
uint8_t bank;
|
||||
const StoreResult loaded = tracker_store_detail::inspect(fs, current, bank);
|
||||
if (loaded != StoreResult::Success && loaded != StoreResult::NotFound) return loaded;
|
||||
if (record.generation != current.generation) return StoreResult::Conflict;
|
||||
if (record.last_request_tag < current.last_request_tag) return StoreResult::Invalid;
|
||||
if (current.generation == UINT32_MAX) return StoreResult::Unavailable;
|
||||
TrackerRecord proposed = record;
|
||||
proposed.generation = current.generation + 1;
|
||||
uint8_t image[kTrackerImageSize];
|
||||
if (!tracker_store_detail::encode(proposed, image)
|
||||
|| !tracker_store_detail::removeArtifact(fs, kTrackerTempPath)) return StoreResult::Unavailable;
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
auto file = fs->open(kTrackerTempPath, FILE_O_WRITE);
|
||||
#elif defined(ESP32_PLATFORM)
|
||||
auto file = fs->open(kTrackerTempPath, "w", true);
|
||||
#else
|
||||
auto file = fs->open(kTrackerTempPath, "w");
|
||||
#endif
|
||||
if (!file) return StoreResult::Unavailable;
|
||||
if (file.isDirectory()) {
|
||||
file.close();
|
||||
tracker_store_detail::removeArtifact(fs, kTrackerTempPath);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
const bool written = file.write(image, sizeof(image)) == sizeof(image);
|
||||
file.flush();
|
||||
file.close();
|
||||
if (!written || !tracker_store_detail::readImage(fs, kTrackerTempPath, current, image)) {
|
||||
tracker_store_detail::removeArtifact(fs, kTrackerTempPath);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
const char* destination = ((proposed.generation - 1) & 1) ? kTrackerBank1Path : kTrackerBank0Path;
|
||||
if (!tracker_store_detail::removeArtifact(fs, destination)
|
||||
|| !fs->rename(kTrackerTempPath, destination)) {
|
||||
tracker_store_detail::removeArtifact(fs, kTrackerTempPath);
|
||||
return StoreResult::Unavailable;
|
||||
}
|
||||
if (!tracker_store_detail::readImage(fs, destination, current, image)) return StoreResult::Unavailable;
|
||||
record.generation = proposed.generation;
|
||||
return StoreResult::Success;
|
||||
}
|
||||
|
||||
} // namespace tracker
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,120 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace tracker {
|
||||
|
||||
// Encrypted PAYLOAD_TYPE_REQ/RESPONSE packets carry the usual four-byte tag.
|
||||
// Only the configured full peer identity may answer a client's pending tag.
|
||||
static constexpr uint8_t RequestType = 0x0c;
|
||||
static constexpr uint8_t Version = 1;
|
||||
static constexpr size_t TagLength = 4;
|
||||
static constexpr size_t RequestLength = 13;
|
||||
static constexpr size_t ResponseLength = 9;
|
||||
static constexpr size_t CipherBlockLength = 16;
|
||||
|
||||
enum Status : uint8_t { Unknown = 0, Safe = 1, Lost = 2 };
|
||||
enum RequestFlags : uint8_t { FreshGps = 1, GpsAttemptFailed = 2 };
|
||||
|
||||
struct StatusRequest {
|
||||
uint8_t flags = 0;
|
||||
int32_t latitude = 0; // degrees * 1e7
|
||||
int32_t longitude = 0; // degrees * 1e7
|
||||
uint16_t battery_mv = 0;
|
||||
};
|
||||
|
||||
inline uint32_t get32(const uint8_t* bytes) {
|
||||
uint32_t value = 0;
|
||||
for (size_t i = 0; i < 4; ++i) value |= uint32_t(bytes[i]) << (8 * i);
|
||||
return value;
|
||||
}
|
||||
|
||||
inline void put32(uint8_t* bytes, uint32_t value) {
|
||||
for (size_t i = 0; i < 4; ++i) bytes[i] = uint8_t(value >> (8 * i));
|
||||
}
|
||||
|
||||
inline int32_t getSigned32(const uint8_t* bytes) {
|
||||
const uint32_t value = get32(bytes);
|
||||
// Avoid implementation-defined conversion when the sign bit is set.
|
||||
return value <= UINT32_C(0x7fffffff) ? int32_t(value)
|
||||
: -1 - int32_t(UINT32_MAX - value);
|
||||
}
|
||||
|
||||
inline bool validStatusRequest(const StatusRequest& request) {
|
||||
if (request.flags > GpsAttemptFailed) return false;
|
||||
if (!(request.flags & FreshGps)) {
|
||||
return request.latitude == 0 && request.longitude == 0;
|
||||
}
|
||||
return request.latitude >= -900000000 && request.latitude <= 900000000
|
||||
&& request.longitude >= -1800000000 && request.longitude <= 1800000000;
|
||||
}
|
||||
|
||||
inline bool zeroPadded(const uint8_t* bytes, size_t length, size_t logical,
|
||||
size_t padded) {
|
||||
if (bytes == NULL || (length != logical && length != padded)) return false;
|
||||
for (size_t i = logical; i < length; ++i) {
|
||||
if (bytes[i] != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The callback has removed the tag. The seventeen-byte plaintext occupies two
|
||||
// cipher blocks, leaving a twenty-eight-byte body including zero padding.
|
||||
inline bool parseStatusRequest(const uint8_t* bytes, size_t length,
|
||||
StatusRequest& request) {
|
||||
if (!zeroPadded(bytes, length, RequestLength,
|
||||
2 * CipherBlockLength - TagLength)
|
||||
|| bytes[0] != RequestType || bytes[1] != Version) return false;
|
||||
StatusRequest value;
|
||||
value.flags = bytes[2];
|
||||
value.latitude = getSigned32(bytes + 3);
|
||||
value.longitude = getSigned32(bytes + 7);
|
||||
value.battery_mv = uint16_t(bytes[11]) | (uint16_t(bytes[12]) << 8);
|
||||
if (!validStatusRequest(value)) return false;
|
||||
request = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline size_t makeStatusRequest(const StatusRequest& request, uint8_t* bytes,
|
||||
size_t capacity) {
|
||||
if (bytes == NULL || capacity < RequestLength || !validStatusRequest(request))
|
||||
return 0;
|
||||
bytes[0] = RequestType;
|
||||
bytes[1] = Version;
|
||||
bytes[2] = request.flags;
|
||||
put32(bytes + 3, uint32_t(request.latitude));
|
||||
put32(bytes + 7, uint32_t(request.longitude));
|
||||
bytes[11] = uint8_t(request.battery_mv);
|
||||
bytes[12] = uint8_t(request.battery_mv >> 8);
|
||||
return RequestLength;
|
||||
}
|
||||
|
||||
inline size_t makeStatusResponse(uint32_t tag, uint8_t status,
|
||||
uint16_t stayawake_seconds, uint8_t* bytes,
|
||||
size_t capacity) {
|
||||
if (bytes == NULL || capacity < ResponseLength || status > Lost) return 0;
|
||||
put32(bytes, tag);
|
||||
bytes[4] = RequestType;
|
||||
bytes[5] = Version;
|
||||
bytes[6] = status;
|
||||
bytes[7] = uint8_t(stayawake_seconds);
|
||||
bytes[8] = uint8_t(stayawake_seconds >> 8);
|
||||
return ResponseLength;
|
||||
}
|
||||
|
||||
inline bool parseStatusResponse(const uint8_t* bytes, size_t length,
|
||||
uint32_t expected_tag, uint8_t& status,
|
||||
uint16_t& stayawake_seconds) {
|
||||
if (!zeroPadded(bytes, length, ResponseLength, CipherBlockLength)
|
||||
|| bytes[4] != RequestType || bytes[5] != Version || bytes[6] > Lost)
|
||||
return false;
|
||||
if (get32(bytes) != expected_tag) return false;
|
||||
status = bytes[6];
|
||||
stayawake_seconds = uint16_t(bytes[7]) | (uint16_t(bytes[8]) << 8);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace tracker
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,186 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace tracker {
|
||||
|
||||
static constexpr uint32_t kFloodIntervalSeconds = UINT32_C(21600);
|
||||
static constexpr uint32_t kOutageCutoffSeconds = UINT32_C(345600);
|
||||
static constexpr size_t kRouteStateImageSize = 32;
|
||||
static constexpr uint8_t kOutageActive = 1;
|
||||
static constexpr uint8_t kFloodLocked = 2;
|
||||
static constexpr uint8_t kClockFault = 4;
|
||||
|
||||
// RTC seconds, never millis(). Zero denotes an unknown timestamp. Persist with
|
||||
// encodeRouteState, rather than copying this compiler-dependent struct layout.
|
||||
struct RouteState {
|
||||
uint32_t outage_since = 0;
|
||||
uint32_t last_target_reply = 0;
|
||||
uint32_t last_repeater = 0;
|
||||
uint32_t last_flood = 0;
|
||||
uint32_t latest_observed = 0;
|
||||
uint8_t flags = 0;
|
||||
};
|
||||
|
||||
enum class RouteDecision : uint8_t {
|
||||
Direct, Wait, Flood, Locked, InvalidClock, InvalidState
|
||||
};
|
||||
|
||||
namespace route_detail {
|
||||
inline uint32_t crcByte(uint32_t crc, uint8_t value) {
|
||||
crc ^= value;
|
||||
for (uint8_t bit = 0; bit < 8; ++bit) {
|
||||
crc = (crc >> 1) ^ ((crc & 1) ? UINT32_C(0xedb88320) : 0);
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
inline uint32_t crc(const uint8_t* data, size_t length) {
|
||||
uint32_t value = UINT32_C(0xffffffff);
|
||||
for (size_t index = 0; index < length; ++index) value = crcByte(value, data[index]);
|
||||
return value ^ UINT32_C(0xffffffff);
|
||||
}
|
||||
inline void put32(uint8_t* data, uint32_t value) {
|
||||
for (uint8_t index = 0; index < 4; ++index) data[index] = static_cast<uint8_t>(value >> (index * 8));
|
||||
}
|
||||
inline uint32_t get32(const uint8_t* data) {
|
||||
uint32_t value = 0;
|
||||
for (uint8_t index = 0; index < 4; ++index) value |= static_cast<uint32_t>(data[index]) << (index * 8);
|
||||
return value;
|
||||
}
|
||||
inline RouteState failClosed() {
|
||||
RouteState state;
|
||||
state.flags = kClockFault;
|
||||
return state;
|
||||
}
|
||||
} // namespace route_detail
|
||||
|
||||
inline bool isValidRouteState(const RouteState& state) {
|
||||
if (state.flags & ~(kOutageActive | kFloodLocked | kClockFault)) return false;
|
||||
const bool active = (state.flags & kOutageActive) != 0;
|
||||
if (active != (state.outage_since != 0) || ((state.flags & kFloodLocked) && !active)) return false;
|
||||
if (state.outage_since > state.latest_observed || state.last_target_reply > state.latest_observed
|
||||
|| state.last_repeater > state.latest_observed || state.last_flood > state.latest_observed) return false;
|
||||
if (active && state.last_target_reply > state.outage_since) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace route_detail {
|
||||
// Invalid input never wraps a timestamp or silently resets an outage. A clock
|
||||
// fault is sticky until an authenticated target reply at a valid later time.
|
||||
inline bool observe(const RouteState& current, uint64_t now, RouteState& candidate) {
|
||||
candidate = current;
|
||||
if (!isValidRouteState(current)) {
|
||||
candidate = failClosed();
|
||||
return false;
|
||||
}
|
||||
if (now == 0 || now > UINT32_MAX || now < current.latest_observed) {
|
||||
candidate.flags |= kClockFault;
|
||||
return false;
|
||||
}
|
||||
candidate.latest_observed = static_cast<uint32_t>(now);
|
||||
if ((candidate.flags & kOutageActive)
|
||||
&& candidate.latest_observed - candidate.outage_since >= kOutageCutoffSeconds) {
|
||||
candidate.flags |= kFloodLocked;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
inline void startOutage(RouteState& state) {
|
||||
if (!(state.flags & kOutageActive)) {
|
||||
state.flags |= kOutageActive;
|
||||
state.outage_since = state.latest_observed;
|
||||
}
|
||||
}
|
||||
inline bool elapsed(uint32_t now, uint32_t anchor, uint32_t interval) {
|
||||
return anchor == 0 || (now >= anchor && now - anchor >= interval);
|
||||
}
|
||||
} // namespace route_detail
|
||||
|
||||
// Planning does not authorize transmission. Persist every changed candidate,
|
||||
// and reserve/persist a flood before transmitting it. During an outage, eligible
|
||||
// recovery floods take precedence over a retained path that has stopped working.
|
||||
inline RouteDecision planRoute(const RouteState& current, uint64_t now,
|
||||
bool has_direct_path, RouteState& candidate) {
|
||||
if (!isValidRouteState(current)) {
|
||||
candidate = route_detail::failClosed();
|
||||
return RouteDecision::InvalidState;
|
||||
}
|
||||
if (!route_detail::observe(current, now, candidate)) return RouteDecision::InvalidClock;
|
||||
if (!has_direct_path) route_detail::startOutage(candidate);
|
||||
if (candidate.flags & kClockFault) return has_direct_path ? RouteDecision::Direct : RouteDecision::InvalidClock;
|
||||
if (candidate.flags & kFloodLocked) return has_direct_path ? RouteDecision::Direct : RouteDecision::Locked;
|
||||
if (candidate.flags & kOutageActive) {
|
||||
const uint32_t time = candidate.latest_observed;
|
||||
if (route_detail::elapsed(time, candidate.outage_since, kFloodIntervalSeconds)
|
||||
&& route_detail::elapsed(time, candidate.last_repeater, kFloodIntervalSeconds)
|
||||
&& route_detail::elapsed(time, candidate.last_flood, kFloodIntervalSeconds)) return RouteDecision::Flood;
|
||||
}
|
||||
return has_direct_path ? RouteDecision::Direct : RouteDecision::Wait;
|
||||
}
|
||||
|
||||
inline bool noteFailure(const RouteState& current, uint64_t now, RouteState& candidate) {
|
||||
if (!route_detail::observe(current, now, candidate)) return false;
|
||||
route_detail::startOutage(candidate);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool noteRepeater(const RouteState& current, uint64_t now, RouteState& candidate) {
|
||||
if (!route_detail::observe(current, now, candidate)) return false;
|
||||
candidate.last_repeater = candidate.latest_observed;
|
||||
return true;
|
||||
}
|
||||
|
||||
// The caller must first authenticate the configured target and establish that
|
||||
// this is its direct DM response or matching direct ACK. Repeater adverts, room
|
||||
// messages and unrelated ACKs cannot call this function.
|
||||
inline bool noteAuthenticatedReply(const RouteState& current, uint64_t now, RouteState& candidate) {
|
||||
if (!route_detail::observe(current, now, candidate)) return false;
|
||||
candidate.last_target_reply = candidate.latest_observed;
|
||||
candidate.outage_since = 0;
|
||||
candidate.flags = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Save this reservation successfully BEFORE sending. A failed save means no
|
||||
// transmission; a reboot after saving conservatively spends this flood slot.
|
||||
inline bool reserveFlood(const RouteState& current, uint64_t now, RouteState& reserved) {
|
||||
if (planRoute(current, now, false, reserved) != RouteDecision::Flood) return false;
|
||||
reserved.last_flood = reserved.latest_observed;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool encodeRouteState(const RouteState& state, uint8_t* image, size_t size) {
|
||||
if (!image || size != kRouteStateImageSize || !isValidRouteState(state)) return false;
|
||||
memset(image, 0, size);
|
||||
image[0] = 'T'; image[1] = 'R'; image[2] = 'P'; image[3] = 1;
|
||||
image[4] = state.flags;
|
||||
route_detail::put32(image + 8, state.outage_since);
|
||||
route_detail::put32(image + 12, state.last_target_reply);
|
||||
route_detail::put32(image + 16, state.last_repeater);
|
||||
route_detail::put32(image + 20, state.last_flood);
|
||||
route_detail::put32(image + 24, state.latest_observed);
|
||||
route_detail::put32(image + 28, route_detail::crc(image, 28));
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool decodeRouteState(const uint8_t* image, size_t size, RouteState& state) {
|
||||
state = route_detail::failClosed();
|
||||
if (!image || size != kRouteStateImageSize || image[0] != 'T' || image[1] != 'R'
|
||||
|| image[2] != 'P' || image[3] != 1 || image[5] || image[6] || image[7]
|
||||
|| route_detail::get32(image + 28) != route_detail::crc(image, 28)) return false;
|
||||
RouteState decoded;
|
||||
decoded.flags = image[4];
|
||||
decoded.outage_since = route_detail::get32(image + 8);
|
||||
decoded.last_target_reply = route_detail::get32(image + 12);
|
||||
decoded.last_repeater = route_detail::get32(image + 16);
|
||||
decoded.last_flood = route_detail::get32(image + 20);
|
||||
decoded.latest_observed = route_detail::get32(image + 24);
|
||||
if (!isValidRouteState(decoded)) return false;
|
||||
state = decoded;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace tracker
|
||||
} // namespace mesh
|
||||
@@ -671,6 +671,19 @@ void RadioLibWrapper::idle() {
|
||||
state = STATE_IDLE; // need another startReceive()
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::setTrackerSleep(bool sleeping) {
|
||||
if (_cw_active || (state & 0x0f) == STATE_TX_WAIT) return false;
|
||||
if (sleeping && isPacketPendingOrReceiving()) return false;
|
||||
if (_radio->standby() != RADIOLIB_ERR_NONE) return false;
|
||||
_rx_ps_armed = false;
|
||||
_rx_hold_continuous = false;
|
||||
state = STATE_IDLE;
|
||||
// PhysicalLayer's no-argument sleep retains configuration on SX126x and
|
||||
// LR11x0. The board's powerOff() intentionally uses cold sleep on some
|
||||
// radios and must not be used for a scheduled tracker wake.
|
||||
return !sleeping || _radio->sleep() == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::triggerNoiseFloorCalibrate(int threshold) {
|
||||
_threshold = threshold;
|
||||
// The Dispatcher calls this every two seconds. Repeatedly recalibrating a
|
||||
|
||||
@@ -356,6 +356,7 @@ public:
|
||||
void resetAGC() override;
|
||||
|
||||
void loop() override;
|
||||
bool setTrackerSleep(bool sleeping) override;
|
||||
bool recoverRadio(bool hard) override;
|
||||
|
||||
uint32_t getPacketsRecv() const { return n_recv; }
|
||||
|
||||
@@ -419,6 +419,7 @@ class RAK12500LocationProvider : public LocationProvider {
|
||||
int _sats = 0;
|
||||
long _epoch = 0;
|
||||
bool _fix = false;
|
||||
bool _fresh_position_requested = false;
|
||||
mesh::RTCClock* _clock = NULL;
|
||||
unsigned long _next_time_check = 0;
|
||||
unsigned long _last_time_sync = 0;
|
||||
@@ -436,6 +437,13 @@ public:
|
||||
long getAltitude() override { return _alt; }
|
||||
long satellitesCount() override { return _sats; }
|
||||
bool isValid() override { return _fix; }
|
||||
bool clearPositionFix() override {
|
||||
_fix = false;
|
||||
_fresh_position_requested = true;
|
||||
_next_time_check = 0;
|
||||
ublox_GNSS.flushPVT();
|
||||
return true;
|
||||
}
|
||||
long getTimestamp() override { return _epoch; }
|
||||
void sendSentence(const char * sentence) override { }
|
||||
void reset() override {
|
||||
@@ -448,6 +456,8 @@ public:
|
||||
_sats = 0;
|
||||
_epoch = 0;
|
||||
_fix = false;
|
||||
_fresh_position_requested = false;
|
||||
_fresh_time_sync_required = false;
|
||||
_next_time_check = 0;
|
||||
_last_time_sync = 0;
|
||||
_valid_time_samples = 0;
|
||||
@@ -463,6 +473,18 @@ public:
|
||||
if ((int32_t)(now - _next_time_check) >= 0) {
|
||||
_next_time_check = now + 1000;
|
||||
|
||||
if (_fresh_position_requested || _fresh_time_sync_required) {
|
||||
// The library's scalar getters can return retained data even when
|
||||
// their implicit PVT poll fails. Require a successfully received PVT
|
||||
// before exposing a position for this tracker acquisition.
|
||||
ublox_GNSS.flushPVT();
|
||||
if (!ublox_GNSS.getPVT(8)) {
|
||||
_fix = false;
|
||||
_valid_time_samples = 0;
|
||||
return;
|
||||
}
|
||||
_fresh_position_requested = false;
|
||||
}
|
||||
if (ublox_GNSS.getGnssFixOk(8)) {
|
||||
_fix = true;
|
||||
_lat = ublox_GNSS.getLatitude(2) / 10;
|
||||
@@ -1156,6 +1178,10 @@ void EnvironmentSensorManager::setPowerSavingEnabled(bool enabled) {
|
||||
|
||||
#if ENV_INCLUDE_GPS
|
||||
if (!gps_detected) return;
|
||||
if (isTrackerGpsModeEnabled()) {
|
||||
_location->setGPSPowerSaving(false);
|
||||
return;
|
||||
}
|
||||
bool gps_user_enabled = isGpsTelemetryUserEnabled();
|
||||
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
|
||||
if (serialGPSFlag) {
|
||||
|
||||
@@ -29,9 +29,13 @@ protected:
|
||||
uint32_t _last_time_sync_applied_ms = 0;
|
||||
bool _time_sync_request_seen = false;
|
||||
bool _time_sync_applied_seen = false;
|
||||
bool _fresh_time_sync_required = false;
|
||||
uint32_t _time_sync_generation = 0;
|
||||
|
||||
void markTimeSyncApplied() {
|
||||
_time_sync_applied = true;
|
||||
++_time_sync_generation;
|
||||
_fresh_time_sync_required = false;
|
||||
_last_time_sync_applied_ms = static_cast<uint32_t>(millis());
|
||||
_time_sync_applied_seen = true;
|
||||
}
|
||||
@@ -63,6 +67,14 @@ public:
|
||||
else (void)requestTimeSync(static_cast<uint64_t>(_gps_sync_interval_hours) * 3600UL);
|
||||
}
|
||||
virtual void syncTime() { _time_sync_needed = true; }
|
||||
// A bounded tracker window needs new validated samples even when an older
|
||||
// clock sync is still waiting to be consumed by another component.
|
||||
virtual void beginFreshTimeSync() {
|
||||
_fresh_time_sync_required = true;
|
||||
syncTime();
|
||||
}
|
||||
void endFreshTimeSync() { _fresh_time_sync_required = false; }
|
||||
uint32_t getTimeSyncGeneration() const { return _time_sync_generation; }
|
||||
virtual bool waitingTimeSync() { return _time_sync_needed; }
|
||||
// Telemetry requests share an in-progress acquisition and rate-limit new
|
||||
// ones using monotonic time, not an RTC which GPS/manual sync may correct.
|
||||
@@ -147,6 +159,10 @@ public:
|
||||
virtual long getAltitude() = 0;
|
||||
virtual long satellitesCount() = 0;
|
||||
virtual bool isValid() = 0;
|
||||
// Invalidate a previous position without resetting receiver ephemeris or
|
||||
// clock policy. Call before starting a bounded fresh acquisition. Unknown
|
||||
// providers fail closed rather than presenting retained data as new.
|
||||
virtual bool clearPositionFix() { return false; }
|
||||
virtual long getTimestamp() = 0;
|
||||
virtual void sendSentence(const char * sentence);
|
||||
virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; }
|
||||
|
||||
@@ -79,6 +79,7 @@ class MicroNMEALocationProvider : public LocationProvider {
|
||||
bool _uart_seen = false;
|
||||
bool _nmea_seen = false;
|
||||
bool _fix_seen = false;
|
||||
bool _fresh_clock_sample = false;
|
||||
|
||||
static uint32_t ageMs(unsigned long timestamp) {
|
||||
return (uint32_t)(millis() - timestamp);
|
||||
@@ -170,6 +171,12 @@ public :
|
||||
}
|
||||
|
||||
void syncTime() override { nmea.clear(); LocationProvider::syncTime(); }
|
||||
void beginFreshTimeSync() override {
|
||||
time_valid = 0;
|
||||
_fresh_clock_sample = false;
|
||||
next_check = millis();
|
||||
LocationProvider::beginFreshTimeSync();
|
||||
}
|
||||
mesh::RTCClock* getRTCClock() override { return _clock; }
|
||||
long getLatitude() override { return nmea.getLatitude(); }
|
||||
long getLongitude() override { return nmea.getLongitude(); }
|
||||
@@ -180,6 +187,17 @@ public :
|
||||
}
|
||||
long satellitesCount() override { return nmea.getNumSatellites(); }
|
||||
bool isValid() override { return nmea.isValid(); }
|
||||
bool clearPositionFix() override {
|
||||
nmea.clear();
|
||||
// Discard only bytes already queued before the acquisition begins.
|
||||
// Snapshot the count so a noisy live UART cannot make this unbounded.
|
||||
int buffered = _gps_serial->available();
|
||||
if (buffered < 0 || buffered > 1024) return false;
|
||||
while (buffered-- > 0) {
|
||||
if (_gps_serial->read() < 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
long getTimestamp() override {
|
||||
const uint16_t year = nmea.getYear();
|
||||
@@ -256,6 +274,7 @@ public :
|
||||
(strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) {
|
||||
_last_fix_ms = millis();
|
||||
_fix_seen = true;
|
||||
_fresh_clock_sample = true;
|
||||
}
|
||||
} else {
|
||||
_nmea_checksum_bad++;
|
||||
@@ -274,11 +293,13 @@ public :
|
||||
_time_sync_needed = true;
|
||||
}
|
||||
const long timestamp = getTimestamp();
|
||||
if (isValid() && satellitesCount() >= 5 && timestamp > 0) {
|
||||
if (isValid() && satellitesCount() >= 5 && timestamp > 0
|
||||
&& (!_fresh_time_sync_required || _fresh_clock_sample)) {
|
||||
time_valid++;
|
||||
} else {
|
||||
time_valid = 0;
|
||||
}
|
||||
_fresh_clock_sample = false;
|
||||
if (_time_sync_needed && time_valid > 2) {
|
||||
if (_clock != NULL) {
|
||||
_clock->setCurrentTime(timestamp);
|
||||
|
||||
Reference in new issue
Block a user