feat: integrate R8 observer and companion updates
This commit is contained in:
1 parent
89c12d416e
commit
da61c48e7b
54 files changed
+5471
-158
No files matched your search
+120
-2
@@ -15,6 +15,7 @@
|
||||
#include <ctype.h>
|
||||
#include <Utils.h>
|
||||
#include <math.h>
|
||||
#include <new>
|
||||
#include <stddef.h>
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
@@ -72,6 +73,7 @@ static void resetToUf2Bootloader() {
|
||||
#include "MQTTDefaults.h"
|
||||
#include "MQTTPrefsAtomicStore.h"
|
||||
#include "MQTTPrefsCodec.h"
|
||||
#include "MQTTPrefsJsonImport.h"
|
||||
#include "MQTTPrefsRecovery.h"
|
||||
#endif
|
||||
|
||||
@@ -1613,7 +1615,10 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
|
||||
// Observer builds use a verified temp/backup transaction for common prefs.
|
||||
// Radio and bridge changes must never leave a truncated boot-time image.
|
||||
if (plan.common) saveCommonPrefsImageAtomically(fs);
|
||||
if (plan.observer) saveMQTTPrefs(fs);
|
||||
if (plan.observer) {
|
||||
_observer_save_result_known = true;
|
||||
_observer_save_succeeded = saveMQTTPrefs(fs);
|
||||
}
|
||||
return;
|
||||
#else
|
||||
// Observer-only saves are a no-op on roles with no observer preference image.
|
||||
@@ -1781,6 +1786,37 @@ static File openMqttPrefsRead(FILESYSTEM* fs, const char* path = "/mqtt_prefs")
|
||||
#endif
|
||||
}
|
||||
|
||||
static bool mqttJsonImportPresetValid(const char* preset) {
|
||||
return findMQTTPreset(preset) != nullptr;
|
||||
}
|
||||
|
||||
static MQTTPrefsJsonImport::Result loadMqttJsonImport(
|
||||
FILESYSTEM* fs, const MQTTPrefs& defaults, MQTTPrefs* candidate) {
|
||||
File file = openMqttPrefsRead(fs, "/mqtt.json");
|
||||
if (!file) return MQTTPrefsJsonImport::Result::InvalidSyntax;
|
||||
if (file.size() > MQTTPrefsJsonImport::kMaximumFileSize) {
|
||||
file.close();
|
||||
return MQTTPrefsJsonImport::Result::TooLarge;
|
||||
}
|
||||
const MQTTPrefsJsonImport::Result result =
|
||||
MQTTPrefsJsonImport::decode(
|
||||
file, defaults, candidate, mqttJsonImportPresetValid);
|
||||
file.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
static const char* mqttJsonImportResultName(MQTTPrefsJsonImport::Result result) {
|
||||
switch (result) {
|
||||
case MQTTPrefsJsonImport::Result::Loaded: return "loaded";
|
||||
case MQTTPrefsJsonImport::Result::LoadedWithRepairs: return "loaded with repairs";
|
||||
case MQTTPrefsJsonImport::Result::InvalidSyntax: return "invalid ConfigSerializer syntax";
|
||||
case MQTTPrefsJsonImport::Result::InvalidSchema: return "invalid v1 schema";
|
||||
case MQTTPrefsJsonImport::Result::UnsupportedVersion: return "unsupported version";
|
||||
case MQTTPrefsJsonImport::Result::TooLarge: return "file too large";
|
||||
}
|
||||
return "unknown error";
|
||||
}
|
||||
|
||||
static MQTTPrefsRecovery::FileState mqttPrefsFileState(FILESYSTEM* fs, const char* path) {
|
||||
if (!fs->exists(path)) return MQTTPrefsRecovery::FileState::Missing;
|
||||
File file = openMqttPrefsRead(fs, path);
|
||||
@@ -2127,6 +2163,72 @@ void CommonCLI::loadMQTTPrefs(
|
||||
// A failed recovery leaves the artifacts untouched and blocks this boot from
|
||||
// replacing them with defaults through a later CLI save.
|
||||
_mqtt_prefs_hold = recoverMqttPrefsFiles(fs);
|
||||
|
||||
// `/mqtt.json` was the authoritative observer-firmware-dev format. Import it
|
||||
// exactly once, but only when binary recovery found no primary or recovery
|
||||
// artifact at all. A valid, default-valued, corrupt, unreadable, or future
|
||||
// binary image always wins because neither format carries a generation that
|
||||
// could prove the JSON is newer.
|
||||
const MQTTPrefsJsonImport::Decision json_import =
|
||||
MQTTPrefsJsonImport::select(
|
||||
_mqtt_prefs_hold,
|
||||
fs->exists("/mqtt_prefs"), fs->exists("/mqtt_prefs.tmp"),
|
||||
fs->exists("/mqtt_prefs.bak"), fs->exists("/mqtt.json"),
|
||||
fs->exists("/mqtt.json.tmp"), fs->exists("/mqtt.json.bak"));
|
||||
if (json_import == MQTTPrefsJsonImport::Decision::HoldJsonArtifacts) {
|
||||
_mqtt_prefs_hold = true;
|
||||
_legacy_tail.valid = false;
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"MQTT: unresolved /mqtt.json transaction files; defaults active and all sources preserved");
|
||||
return;
|
||||
}
|
||||
if (json_import == MQTTPrefsJsonImport::Decision::ImportPrimary) {
|
||||
MQTTPrefs* candidate = new (std::nothrow) MQTTPrefs;
|
||||
if (candidate == nullptr) {
|
||||
_mqtt_prefs_hold = true;
|
||||
_legacy_tail.valid = false;
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"MQTT: no memory to import /mqtt.json; defaults active and source preserved");
|
||||
return;
|
||||
}
|
||||
setMQTTPrefsDefaults(candidate);
|
||||
const MQTTPrefsJsonImport::Result result =
|
||||
loadMqttJsonImport(fs, _mqtt_prefs, candidate);
|
||||
if (!MQTTPrefsJsonImport::loaded(result)) {
|
||||
delete candidate;
|
||||
_mqtt_prefs_hold = true;
|
||||
_legacy_tail.valid = false;
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"MQTT: /mqtt.json import refused (%s); defaults active and source preserved",
|
||||
mqttJsonImportResultName(result));
|
||||
return;
|
||||
}
|
||||
|
||||
_mqtt_prefs = *candidate;
|
||||
delete candidate;
|
||||
legacy_upgrade->requireMqttRewrite();
|
||||
if (saveMQTTPrefs(fs)) {
|
||||
legacy_upgrade->recordMqttSave(true);
|
||||
// JSON contains the full observer group. Returning prevents a stale
|
||||
// /com_prefs observer tail from being overlaid after the committed import.
|
||||
_legacy_tail.valid = false;
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"MQTT: imported /mqtt.json v1 into atomic /mqtt_prefs (%s); JSON preserved",
|
||||
mqttJsonImportResultName(result));
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not expose a partially imported runtime state after a failed publish.
|
||||
// The JSON remains untouched, and binary recovery owns any completed temp.
|
||||
setMQTTPrefsDefaults(&_mqtt_prefs);
|
||||
_mqtt_prefs_hold = true;
|
||||
_legacy_tail.valid = false;
|
||||
legacy_upgrade->recordMqttSave(false);
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"MQTT: /mqtt.json decoded but binary commit failed; defaults active and sources preserved");
|
||||
return;
|
||||
}
|
||||
|
||||
bool has_observer_fields = false;
|
||||
bool mqtt_rewrite_pending = false;
|
||||
bool migrated_legacy_mqtt = false;
|
||||
@@ -2290,6 +2392,15 @@ void CommonCLI::loadMQTTPrefs(
|
||||
MESH_DEBUG_PRINTLN("MQTT: invalid neighbors interval reset to %u hours",
|
||||
(unsigned)MQTT_NEIGHBORS_DEFAULT_INTERVAL_HOURS);
|
||||
}
|
||||
if (MQTTPrefsCodec::repairDisplayPrefs(&_mqtt_prefs)) {
|
||||
// Old payloads retain valid defaults because the object was defaulted before
|
||||
// their shorter prefix was copied. This branch repairs only a full/newer
|
||||
// payload carrying invalid display values.
|
||||
if (!_mqtt_prefs_hold) {
|
||||
mqtt_rewrite_pending = true;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("MQTT: invalid display preferences reset to defaults");
|
||||
}
|
||||
_legacy_tail.valid = false;
|
||||
|
||||
if (mqtt_rewrite_pending) {
|
||||
@@ -2355,8 +2466,15 @@ void CommonCLI::savePrefs(PrefsSaveRouting::Scope scope) {
|
||||
_prefs->clearDirty();
|
||||
}
|
||||
|
||||
void CommonCLI::saveObserverPrefs() {
|
||||
bool CommonCLI::saveObserverPrefs() {
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
_observer_save_result_known = false;
|
||||
_observer_save_succeeded = false;
|
||||
_callbacks->savePrefs(PrefsSaveRouting::Scope::Observer);
|
||||
return _observer_save_result_known && _observer_save_succeeded;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
|
||||
|
||||
@@ -725,13 +725,18 @@ class CommonCLI {
|
||||
// /mqtt_prefs is newer, corrupt, or temporarily unreadable. The in-memory prefs
|
||||
// run on defaults and saveMQTTPrefs() must not overwrite the source file.
|
||||
bool _mqtt_prefs_hold = false;
|
||||
// CommonCLICallbacks::savePrefs() has a stable void ABI. Observer setters use
|
||||
// these synchronous result latches to learn whether the callback's nested
|
||||
// CommonCLI::savePrefs(fs, Observer) transaction actually committed.
|
||||
bool _observer_save_result_known = false;
|
||||
bool _observer_save_succeeded = false;
|
||||
#endif
|
||||
bool _com_prefs_needs_upgrade = false; // old-format legacy prefs detected; rewrite once after load
|
||||
|
||||
mesh::RTCClock* getRTCClock() { return _rtc; }
|
||||
void savePrefs(
|
||||
PrefsSaveRouting::Scope scope = PrefsSaveRouting::Scope::Common);
|
||||
void saveObserverPrefs();
|
||||
bool saveObserverPrefs();
|
||||
void loadPrefsInt(FILESYSTEM* _fs, const char* filename);
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
bool recoverCommonPrefsFiles(FILESYSTEM* fs);
|
||||
|
||||
@@ -218,6 +218,44 @@ bool CommonCLI::handleObserverSetCmd(uint32_t sender_timestamp, const char* conf
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (strncmp(config, "display.timeout ", 16) == 0) {
|
||||
uint16_t seconds = 0;
|
||||
if (!observerParseBoundedUint16(config + 16, DISPLAY_TIMEOUT_MAX_SECS,
|
||||
&seconds)) {
|
||||
sprintf(reply, "Error: display.timeout must be 0-%u seconds",
|
||||
(unsigned)DISPLAY_TIMEOUT_MAX_SECS);
|
||||
} else {
|
||||
const uint16_t previous = _mqtt_prefs.display_timeout_secs;
|
||||
_mqtt_prefs.display_timeout_secs = seconds;
|
||||
if (!saveObserverPrefs()) {
|
||||
_mqtt_prefs.display_timeout_secs = previous;
|
||||
strcpy(reply, "Error: display.timeout save failed");
|
||||
} else if (seconds == 0) {
|
||||
strcpy(reply, "OK - display stays on");
|
||||
} else {
|
||||
sprintf(reply, "OK - display off after %u s", (unsigned)seconds);
|
||||
}
|
||||
}
|
||||
} else if (strcmp(config, "display.timeout") == 0) {
|
||||
strcpy(reply, "Error: missing display.timeout seconds");
|
||||
} else if (strncmp(config, "display.flip ", 13) == 0) {
|
||||
uint8_t flipped = 0;
|
||||
if (!observerParseDisplayFlip(config + 13, &flipped)) {
|
||||
strcpy(reply, "Error: display.flip must be 0/1 (or off/on)");
|
||||
} else {
|
||||
const uint8_t previous = _mqtt_prefs.display_flip;
|
||||
_mqtt_prefs.display_flip = flipped;
|
||||
if (!saveObserverPrefs()) {
|
||||
_mqtt_prefs.display_flip = previous;
|
||||
strcpy(reply, "Error: display.flip save failed");
|
||||
} else {
|
||||
strcpy(reply, flipped
|
||||
? "OK - display.flip on (applies on supported display)"
|
||||
: "OK - display.flip off (applies on supported display)");
|
||||
}
|
||||
}
|
||||
} else if (strcmp(config, "display.flip") == 0) {
|
||||
strcpy(reply, "Error: missing display.flip state");
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
} else if (strcmp(config, "mqtt.origin") == 0) {
|
||||
_mqtt_prefs.mqtt_origin[0] = '\0';
|
||||
@@ -837,6 +875,10 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
|
||||
strcpy(reply, _mqtt_prefs.snmp_enabled ? "> on" : "> off");
|
||||
} else if (memcmp(config, "radio.watchdog", 14) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)_mqtt_prefs.radio_watchdog_minutes);
|
||||
} else if (strcmp(config, "display.timeout") == 0) {
|
||||
sprintf(reply, "> %u", (unsigned)_mqtt_prefs.display_timeout_secs);
|
||||
} else if (strcmp(config, "display.flip") == 0) {
|
||||
strcpy(reply, _mqtt_prefs.display_flip ? "> on" : "> off");
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
} else if (memcmp(config, "mqtt.origin", 11) == 0) {
|
||||
char effective_origin[32];
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace companion {
|
||||
|
||||
static constexpr uint8_t kRunCliCommand = 0x42;
|
||||
|
||||
// Original aliases predate upstream's command-66 allocation. The later block
|
||||
// was shipped briefly before this fork standardized new clients on framed CLI.
|
||||
static constexpr uint8_t kOriginalGetFemRxGain = 0x42;
|
||||
static constexpr uint8_t kOriginalSetFemRxGain = 0x43;
|
||||
static constexpr uint8_t kOriginalGetRadioRxGain = 0x44;
|
||||
static constexpr uint8_t kOriginalSetRadioRxGain = 0x45;
|
||||
static constexpr uint8_t kOriginalGetWiFiPowerSave = 0x46;
|
||||
static constexpr uint8_t kOriginalSetWiFiPowerSave = 0x47;
|
||||
static constexpr uint8_t kOriginalGetBluetoothName = 0x48;
|
||||
static constexpr uint8_t kOriginalSetBluetoothName = 0x49;
|
||||
|
||||
static constexpr uint8_t kDeprecatedGetFemRxGain = 0x78;
|
||||
static constexpr uint8_t kDeprecatedSetFemRxGain = 0x79;
|
||||
static constexpr uint8_t kDeprecatedGetRadioRxGain = 0x7A;
|
||||
static constexpr uint8_t kDeprecatedSetRadioRxGain = 0x7B;
|
||||
static constexpr uint8_t kDeprecatedGetWiFiPowerSave = 0x7C;
|
||||
static constexpr uint8_t kDeprecatedSetWiFiPowerSave = 0x7D;
|
||||
static constexpr uint8_t kDeprecatedGetBluetoothName = 0x7E;
|
||||
static constexpr uint8_t kDeprecatedSetBluetoothName = 0x7F;
|
||||
|
||||
inline bool isRunCliFrame(uint8_t command, size_t frame_len) {
|
||||
return command == kRunCliCommand && frame_len >= 2;
|
||||
}
|
||||
|
||||
inline bool isFemRxGainGet(uint8_t command) {
|
||||
return command == kOriginalGetFemRxGain || command == kDeprecatedGetFemRxGain;
|
||||
}
|
||||
inline bool isFemRxGainSet(uint8_t command) {
|
||||
return command == kOriginalSetFemRxGain || command == kDeprecatedSetFemRxGain;
|
||||
}
|
||||
inline bool isRadioRxGainGet(uint8_t command) {
|
||||
return command == kOriginalGetRadioRxGain || command == kDeprecatedGetRadioRxGain;
|
||||
}
|
||||
inline bool isRadioRxGainSet(uint8_t command) {
|
||||
return command == kOriginalSetRadioRxGain || command == kDeprecatedSetRadioRxGain;
|
||||
}
|
||||
inline bool isWiFiPowerSaveGet(uint8_t command) {
|
||||
return command == kOriginalGetWiFiPowerSave || command == kDeprecatedGetWiFiPowerSave;
|
||||
}
|
||||
inline bool isWiFiPowerSaveSet(uint8_t command) {
|
||||
return command == kOriginalSetWiFiPowerSave || command == kDeprecatedSetWiFiPowerSave;
|
||||
}
|
||||
inline bool isBluetoothNameGet(uint8_t command) {
|
||||
return command == kOriginalGetBluetoothName || command == kDeprecatedGetBluetoothName;
|
||||
}
|
||||
inline bool isBluetoothNameSet(uint8_t command) {
|
||||
return command == kOriginalSetBluetoothName || command == kDeprecatedSetBluetoothName;
|
||||
}
|
||||
|
||||
} // namespace companion
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "MQTTPrefsStorage.h"
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
|
||||
// The ESP32 Companion setup portal stores a raw MQTTPrefs blob in NVS rather
|
||||
// than the observer's versioned /mqtt_prefs file. Display preferences are not
|
||||
// used by Companion firmware, so keep writing the last pre-display boundary:
|
||||
// older firmware can then read a record saved by a newer image after rollback.
|
||||
namespace CompanionMqttPrefsNvs {
|
||||
|
||||
static constexpr size_t kWriteSize = MQTT_PREFS_V1_PRE_DISPLAY_PAYLOAD_SIZE;
|
||||
// A short-lived development image wrote the compiler-padded runtime struct.
|
||||
// Freeze that exact deployed shape: using sizeof(MQTTPrefs) here would stop
|
||||
// recognizing its records the next time an append-only field grows the struct.
|
||||
static constexpr size_t kRecoverySize = 2880;
|
||||
static_assert(sizeof(MQTTPrefs) >= kRecoverySize,
|
||||
"MQTTPrefs no longer contains the recoverable NVS prefix");
|
||||
|
||||
inline bool accepts(uint16_t version, size_t length) {
|
||||
return version == MQTT_PREFS_VERSION
|
||||
&& (length == kWriteSize || length == kRecoverySize);
|
||||
}
|
||||
|
||||
} // namespace CompanionMqttPrefsNvs
|
||||
|
||||
#endif
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "CompanionMqttSetupPortal.h"
|
||||
#include "CompanionMqttPrefsNvs.h"
|
||||
|
||||
#if defined(ESP32_PLATFORM) && defined(WIFI_SSID) && defined(WITH_MQTT_BRIDGE)
|
||||
|
||||
@@ -582,52 +583,67 @@ bool CompanionMqttSetupPortal::loadStoredConfig(MQTTPrefs& prefs) {
|
||||
if (!nvs.begin(NVS_NAMESPACE, true)) return false;
|
||||
const uint16_t version = nvs.getUShort(NVS_VERSION_KEY, 0);
|
||||
const size_t length = nvs.getBytesLength(NVS_PREFS_KEY);
|
||||
const bool shape_ok = version == MQTT_PREFS_VERSION && length == sizeof(MQTTPrefs);
|
||||
const size_t read = shape_ok ? nvs.getBytes(NVS_PREFS_KEY, &prefs, sizeof(prefs)) : 0;
|
||||
// Companion stores this struct directly rather than using the observer's
|
||||
// versioned file header. Accept the previously shipped pre-display size and
|
||||
// default its append-only display tail so adding observer UI preferences
|
||||
// cannot discard an existing Companion MQTT setup after an update.
|
||||
const bool shape_ok = CompanionMqttPrefsNvs::accepts(version, length);
|
||||
MQTTPrefs loaded;
|
||||
applyMQTTDefaults(&loaded);
|
||||
const size_t read = shape_ok ? nvs.getBytes(NVS_PREFS_KEY, &loaded, length) : 0;
|
||||
nvs.end();
|
||||
if (read != sizeof(prefs)) return false;
|
||||
if (!shape_ok || read != length) return false;
|
||||
|
||||
if (!storedStringsAreValid(prefs)
|
||||
|| prefs.mqtt_status_enabled > 1
|
||||
|| prefs.mqtt_packets_enabled > 1
|
||||
|| prefs.mqtt_raw_enabled > 1
|
||||
|| prefs.mqtt_rx_enabled > 1
|
||||
|| prefs.mqtt_tx_enabled > 2
|
||||
|| prefs.wifi_power_save > 2) {
|
||||
if (!storedStringsAreValid(loaded)
|
||||
|| loaded.mqtt_status_enabled > 1
|
||||
|| loaded.mqtt_packets_enabled > 1
|
||||
|| loaded.mqtt_raw_enabled > 1
|
||||
|| loaded.mqtt_rx_enabled > 1
|
||||
|| loaded.mqtt_tx_enabled > 2
|
||||
|| loaded.wifi_power_save > 2
|
||||
|| loaded.display_timeout_secs > DISPLAY_TIMEOUT_MAX_SECS
|
||||
|| loaded.display_flip > 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* preset = prefs.mqtt_slot_preset[0];
|
||||
const char* preset = loaded.mqtt_slot_preset[0];
|
||||
const bool custom = strcmp(preset, MQTT_PRESET_CUSTOM) == 0;
|
||||
const MQTTPresetDef* preset_def = custom ? nullptr : findMQTTPreset(preset);
|
||||
if (!preset[0] || (!custom && !preset_def)) return false;
|
||||
if (custom) {
|
||||
const char* host = prefs.mqtt_slot_host[0];
|
||||
const char* host = loaded.mqtt_slot_host[0];
|
||||
if (!host[0]
|
||||
|| (prefs.mqtt_slot_port[0] == 0 && strstr(host, "://") == nullptr)
|
||||
|| (!prefs.mqtt_slot_topic[0][0] && !isThreeLetterCode(prefs.mqtt_iata))) {
|
||||
|| (loaded.mqtt_slot_port[0] == 0 && strstr(host, "://") == nullptr)
|
||||
|| (!loaded.mqtt_slot_topic[0][0] && !isThreeLetterCode(loaded.mqtt_iata))) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (preset_def->topic_style == MQTT_TOPIC_MESHCORE
|
||||
&& !isThreeLetterCode(prefs.mqtt_iata)) return false;
|
||||
&& !isThreeLetterCode(loaded.mqtt_iata)) return false;
|
||||
if (preset_def->topic_style == MQTT_TOPIC_MESHRANK
|
||||
&& !prefs.mqtt_slot_token[0][0]) return false;
|
||||
&& !loaded.mqtt_slot_token[0][0]) return false;
|
||||
if (mqttPresetNeedsSlotCredentials(preset_def)
|
||||
&& (!prefs.mqtt_slot_username[0][0] || !prefs.mqtt_slot_password[0][0])) {
|
||||
&& (!loaded.mqtt_slot_username[0][0] || !loaded.mqtt_slot_password[0][0])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
prefs = loaded;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CompanionMqttSetupPortal::saveStoredConfig(const MQTTPrefs& prefs) {
|
||||
Preferences nvs;
|
||||
if (!nvs.begin(NVS_NAMESPACE, false)) return false;
|
||||
const size_t written = nvs.putBytes(NVS_PREFS_KEY, &prefs, sizeof(prefs));
|
||||
// Companion does not consume the appended observer display tail. Keeping
|
||||
// this record at the pre-display boundary makes a firmware rollback retain
|
||||
// the MQTT setup. loadStoredConfig() still accepts the briefly written 2880
|
||||
// byte runtime shape so development images remain recoverable.
|
||||
const size_t written = nvs.putBytes(
|
||||
NVS_PREFS_KEY, &prefs, CompanionMqttPrefsNvs::kWriteSize);
|
||||
const size_t version_written = nvs.putUShort(NVS_VERSION_KEY, MQTT_PREFS_VERSION);
|
||||
nvs.end();
|
||||
return written == sizeof(prefs) && version_written == sizeof(uint16_t);
|
||||
return written == CompanionMqttPrefsNvs::kWriteSize
|
||||
&& version_written == sizeof(uint16_t);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -22,9 +22,12 @@ bool ConfigSerializer::saveSerial(Stream& s) {
|
||||
static bool is_whitespace(char c) {
|
||||
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
|
||||
}
|
||||
static bool is_key_char(char c) {
|
||||
static bool is_key_start_char(char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
|
||||
}
|
||||
static bool is_key_char(char c) {
|
||||
return is_key_start_char(c) || (c >= '0' && c <= '9');
|
||||
}
|
||||
static bool is_value_char(char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '-' || c == '.';
|
||||
}
|
||||
@@ -58,13 +61,12 @@ static double parse_fixed_decimal(const char* text) {
|
||||
}
|
||||
|
||||
#define EXPECT_OPEN_BRACE 0
|
||||
#define EXPECT_KEY 1
|
||||
#define EXPECT_VAL_OR_OBJ 2
|
||||
#define EXPECT_STRING_VAL 3
|
||||
#define EXPECT_STRING_ESCAPE 4
|
||||
#define EXPECT_COMMA_OR_CLOSE 5
|
||||
#define EXPECT_COMMA_OR_KEY 6
|
||||
#define EXPECT_COMMA_OR_KEY_OR_CLOSE 7
|
||||
#define EXPECT_KEY_OR_CLOSE 1
|
||||
#define EXPECT_KEY 2
|
||||
#define EXPECT_VAL_OR_OBJ 3
|
||||
#define EXPECT_STRING_VAL 4
|
||||
#define EXPECT_STRING_ESCAPE 5
|
||||
#define EXPECT_COMMA_OR_CLOSE 6
|
||||
|
||||
int ConfigSerializer::Context::readNext() {
|
||||
char c;
|
||||
@@ -79,33 +81,50 @@ int ConfigSerializer::Context::readNext() {
|
||||
c = (char)n;
|
||||
}
|
||||
|
||||
if (rd_root_complete) {
|
||||
return is_whitespace(c) ? TOK_WHITESPACE : TOK_ERROR;
|
||||
}
|
||||
|
||||
switch (rd_mode) {
|
||||
case EXPECT_OPEN_BRACE:
|
||||
if (c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; }
|
||||
if (c == '{') { rd_mode = EXPECT_KEY_OR_CLOSE; return TOK_START_OBJ; }
|
||||
if (is_whitespace(c)) return TOK_WHITESPACE;
|
||||
return TOK_ERROR;
|
||||
|
||||
case EXPECT_COMMA_OR_KEY_OR_CLOSE:
|
||||
if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; }
|
||||
case EXPECT_COMMA_OR_KEY:
|
||||
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
|
||||
case EXPECT_KEY:
|
||||
case EXPECT_KEY_OR_CLOSE:
|
||||
// Empty objects are valid and are emitted by serializers such as the
|
||||
// dynamic `custom` preferences object before it has any entries.
|
||||
if (rd_len == 0 && c == '}') {
|
||||
rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE;
|
||||
rd_mode = EXPECT_COMMA_OR_CLOSE;
|
||||
return TOK_END_OBJ;
|
||||
}
|
||||
// A non-empty object follows the same key grammar, but only this state
|
||||
// (entered directly after '{') permits an immediate closing brace.
|
||||
// fall through
|
||||
case EXPECT_KEY:
|
||||
if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; }
|
||||
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
|
||||
if (rd_len < CONFIG_MAX_KEYLEN-1 && is_key_char(c)) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
|
||||
if (rd_len < CONFIG_MAX_KEYLEN-1 &&
|
||||
((rd_len == 0 && is_key_start_char(c)) ||
|
||||
(rd_len > 0 && is_key_char(c)))) {
|
||||
rd_buf[rd_len++] = c;
|
||||
return TOK_WHITESPACE;
|
||||
}
|
||||
return TOK_ERROR;
|
||||
|
||||
case EXPECT_VAL_OR_OBJ:
|
||||
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
|
||||
if (rd_len == 0 && c == '"') { rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; }
|
||||
if (rd_len == 0 && c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; }
|
||||
if (is_value_char(c) && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
|
||||
if (rd_len == 0 && c == '"') {
|
||||
rd_token_quoted = true;
|
||||
rd_mode = EXPECT_STRING_VAL;
|
||||
return TOK_WHITESPACE;
|
||||
}
|
||||
if (rd_len == 0 && c == '{') { rd_mode = EXPECT_KEY_OR_CLOSE; return TOK_START_OBJ; }
|
||||
if (is_value_char(c) && rd_len < CONFIG_MAX_TOKEN_LEN-1) {
|
||||
if (rd_len == 0) rd_token_quoted = false;
|
||||
rd_buf[rd_len++] = c;
|
||||
return TOK_WHITESPACE;
|
||||
}
|
||||
if (rd_len > 0 && (c == ',' || c == '}' || is_whitespace(c))) { pending = c; rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; }
|
||||
return TOK_ERROR;
|
||||
|
||||
@@ -118,12 +137,13 @@ int ConfigSerializer::Context::readNext() {
|
||||
case EXPECT_STRING_VAL:
|
||||
if (c == '"') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; }
|
||||
if (c == '\\') { rd_mode = EXPECT_STRING_ESCAPE; return TOK_WHITESPACE; }
|
||||
if (c == '\0') return TOK_ERROR; // never silently truncate a persisted string
|
||||
if (rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
|
||||
return TOK_ERROR;
|
||||
|
||||
case EXPECT_COMMA_OR_CLOSE:
|
||||
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
|
||||
if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; }
|
||||
if (c == '}') { rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_END_OBJ; }
|
||||
if (is_whitespace(c)) return TOK_WHITESPACE;
|
||||
return TOK_ERROR;
|
||||
}
|
||||
@@ -141,9 +161,19 @@ bool ConfigSerializer::loadSerial(Stream& s) {
|
||||
if (next_tok == TOK_KEY) {
|
||||
context.setKey(sp, context.getToken());
|
||||
} else if (next_tok == TOK_VALUE) {
|
||||
context.setValueEvent(sp, false);
|
||||
_depth = 1; // re-run the structure() hierarchy again (looking for specific key, at specific depth)
|
||||
structure();
|
||||
} else if (next_tok == TOK_START_OBJ) {
|
||||
// The root has no key. For every nested object, rerun the schema at the
|
||||
// parent depth so known scalar fields can reject an object value and
|
||||
// known object fields can confirm their expected shape.
|
||||
if (sp > 0) {
|
||||
context.setValueEvent(sp, true);
|
||||
_depth = 1;
|
||||
structure();
|
||||
if (!context.success) break;
|
||||
}
|
||||
if (sp < CONFIG_MAX_DEPTH - 1) {
|
||||
sp++;
|
||||
} else {
|
||||
@@ -154,6 +184,7 @@ bool ConfigSerializer::loadSerial(Stream& s) {
|
||||
} else if (next_tok == TOK_END_OBJ) {
|
||||
if (sp > 0) {
|
||||
sp--;
|
||||
if (sp == 0) context.markRootComplete();
|
||||
} else {
|
||||
//Serial.printf("Error: too many closing '}'"); // TODO: debug logging
|
||||
context.success = false;
|
||||
@@ -161,8 +192,8 @@ bool ConfigSerializer::loadSerial(Stream& s) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sp != 0 || next_tok == TOK_ERROR) {
|
||||
context.success = false; // unmatched { }, or other parse error
|
||||
if (sp != 0 || !context.rootComplete() || next_tok == TOK_ERROR) {
|
||||
context.success = false; // missing/unmatched root object, or other parse error
|
||||
}
|
||||
_context = NULL;
|
||||
return context.success;
|
||||
@@ -357,9 +388,115 @@ void ConfigSerializer::def(const char* key, ConfigSerializer& sub_obj) {
|
||||
if (_context->file()->print("}") != 1) _context->success = false; // failure detect
|
||||
} else {
|
||||
if (_context->keyMatch(_depth, key)) {
|
||||
if (_context->objectStart() && _context->valueDepth() == _depth) {
|
||||
return; // the object itself; descendant values recurse below
|
||||
}
|
||||
if (_context->valueDepth() <= _depth) {
|
||||
_context->success = false; // known object supplied as a scalar
|
||||
return;
|
||||
}
|
||||
sub_obj._context = _context; // inherit the Context
|
||||
sub_obj._depth = _depth + 1;
|
||||
sub_obj.structure(); // recurse into sub object
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ConfigSerializer::defStrict(const char* key, char* value, size_t max_len,
|
||||
bool& seen) {
|
||||
if (_context->op() == OP::WRITE) {
|
||||
def(key, value, max_len);
|
||||
return true;
|
||||
}
|
||||
if (!_context->keyMatch(_depth, key)) return false;
|
||||
if (seen || max_len == 0 || _context->objectStart() ||
|
||||
_context->valueDepth() != _depth || !_context->tokenQuoted()) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
seen = true;
|
||||
const char* token = _context->getToken();
|
||||
const size_t len = strlen(token);
|
||||
if (len >= max_len) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
memcpy(value, token, len + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigSerializer::defStrict(const char* key, int32_t& value, bool& seen) {
|
||||
if (_context->op() == OP::WRITE) {
|
||||
def(key, value);
|
||||
return true;
|
||||
}
|
||||
if (!_context->keyMatch(_depth, key)) return false;
|
||||
if (seen || _context->objectStart() || _context->valueDepth() != _depth ||
|
||||
_context->tokenQuoted()) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
seen = true;
|
||||
|
||||
const char* token = _context->getToken();
|
||||
bool negative = false;
|
||||
if (*token == '-') {
|
||||
negative = true;
|
||||
++token;
|
||||
}
|
||||
if (*token < '0' || *token > '9') {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Accumulate the magnitude as unsigned so INT32_MIN remains representable.
|
||||
const uint32_t limit = negative ? 2147483648UL : 2147483647UL;
|
||||
uint32_t magnitude = 0;
|
||||
do {
|
||||
const uint32_t digit = static_cast<uint32_t>(*token++ - '0');
|
||||
if (magnitude > (limit - digit) / 10U) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
magnitude = magnitude * 10U + digit;
|
||||
} while (*token >= '0' && *token <= '9');
|
||||
|
||||
if (*token != '\0') {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
if (negative && magnitude == 2147483648UL) {
|
||||
value = INT32_MIN;
|
||||
} else {
|
||||
value = negative ? -static_cast<int32_t>(magnitude)
|
||||
: static_cast<int32_t>(magnitude);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigSerializer::defStrict(const char* key, ConfigSerializer& sub_obj,
|
||||
bool& seen) {
|
||||
if (_context->op() == OP::WRITE) {
|
||||
def(key, sub_obj);
|
||||
return true;
|
||||
}
|
||||
if (!_context->keyMatch(_depth, key)) return false;
|
||||
|
||||
if (_context->objectStart() && _context->valueDepth() == _depth) {
|
||||
if (seen) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
seen = true;
|
||||
return true;
|
||||
}
|
||||
if (!seen || _context->valueDepth() <= _depth) {
|
||||
_context->success = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
sub_obj._context = _context;
|
||||
sub_obj._depth = _depth + 1;
|
||||
sub_obj.structure();
|
||||
return true;
|
||||
}
|
||||
@@ -27,17 +27,39 @@ protected:
|
||||
OP _op;
|
||||
uint8_t rd_len;
|
||||
uint8_t rd_mode;
|
||||
uint8_t rd_value_depth;
|
||||
char pending;
|
||||
bool rd_token_quoted;
|
||||
bool rd_object_start;
|
||||
bool rd_root_complete;
|
||||
char rd_buf[CONFIG_MAX_TOKEN_LEN];
|
||||
char _keys[CONFIG_MAX_DEPTH][CONFIG_MAX_KEYLEN];
|
||||
|
||||
public:
|
||||
bool success = true;
|
||||
Context(Stream* f, OP op) : _f(f), _op(op) { rd_buf[rd_len = 0] = 0; rd_mode = 0; pending = 0; }
|
||||
Context(Stream* f, OP op) : _f(f), _op(op) {
|
||||
rd_buf[rd_len = 0] = 0;
|
||||
rd_mode = 0;
|
||||
rd_value_depth = 0;
|
||||
pending = 0;
|
||||
rd_token_quoted = false;
|
||||
rd_object_start = false;
|
||||
rd_root_complete = false;
|
||||
memset(_keys, 0, sizeof(_keys));
|
||||
}
|
||||
OP op() const { return _op; }
|
||||
Stream* file() const { return _f; }
|
||||
int readNext();
|
||||
const char* getToken() const { return rd_buf; }
|
||||
bool tokenQuoted() const { return rd_token_quoted; }
|
||||
uint8_t valueDepth() const { return rd_value_depth; }
|
||||
bool objectStart() const { return rd_object_start; }
|
||||
bool rootComplete() const { return rd_root_complete; }
|
||||
void markRootComplete() { rd_root_complete = true; }
|
||||
void setValueEvent(uint8_t depth, bool object_start) {
|
||||
rd_value_depth = depth;
|
||||
rd_object_start = object_start;
|
||||
}
|
||||
bool keyMatch(int8_t depth, const char* key) { return strcmp(key, _keys[depth]) == 0; }
|
||||
void setKey(uint8_t depth, const char* key) { strcpy(_keys[depth], key); }
|
||||
const char* getKey(uint8_t depth) { return _keys[depth]; }
|
||||
@@ -63,6 +85,71 @@ protected:
|
||||
void def(const char* key, bool& value);
|
||||
void def(const char* key, ConfigSerializer& sub_obj);
|
||||
|
||||
// Strict read helpers for externally editable schemas. Unlike the legacy
|
||||
// overloads, these reject duplicate keys, truncated strings, malformed
|
||||
// integers, integer overflow, and scalar/object type mismatches.
|
||||
bool defStrict(const char* key, char* value, size_t max_len, bool& seen);
|
||||
bool defStrict(const char* key, int32_t& value, bool& seen);
|
||||
bool defStrict(const char* key, ConfigSerializer& sub_obj, bool& seen);
|
||||
|
||||
// Keep literal schema keys inside the tokenizer's visible-key limit. Dynamic
|
||||
// serializers can continue using the pointer overloads above.
|
||||
template <size_t N> static void checkKey(const char (&)[N]) {
|
||||
static_assert(N <= CONFIG_MAX_KEYLEN,
|
||||
"ConfigSerializer key exceeds the visible-key limit");
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], char* value, size_t max_len) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value, max_len);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], void* value, size_t len) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value, len);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], int32_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], int16_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], int8_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], uint32_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], uint16_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], uint8_t& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], float& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], double& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], bool& value) {
|
||||
checkKey(key); def(static_cast<const char*>(key), value);
|
||||
}
|
||||
template <size_t N> void def(const char (&key)[N], ConfigSerializer& sub_obj) {
|
||||
checkKey(key); def(static_cast<const char*>(key), sub_obj);
|
||||
}
|
||||
template <size_t N>
|
||||
bool defStrict(const char (&key)[N], char* value, size_t max_len, bool& seen) {
|
||||
checkKey(key);
|
||||
return defStrict(static_cast<const char*>(key), value, max_len, seen);
|
||||
}
|
||||
template <size_t N>
|
||||
bool defStrict(const char (&key)[N], int32_t& value, bool& seen) {
|
||||
checkKey(key);
|
||||
return defStrict(static_cast<const char*>(key), value, seen);
|
||||
}
|
||||
template <size_t N>
|
||||
bool defStrict(const char (&key)[N], ConfigSerializer& sub_obj, bool& seen) {
|
||||
checkKey(key);
|
||||
return defStrict(static_cast<const char*>(key), sub_obj, seen);
|
||||
}
|
||||
|
||||
virtual void structure() = 0;
|
||||
|
||||
void markDirty() { _dirty = true; }
|
||||
|
||||
@@ -111,6 +111,11 @@ static inline void applyMQTTDefaults(MQTTPrefs* prefs) {
|
||||
// (not 0) so an in-lineage upgrade from a pre-neighbors payload is sane.
|
||||
prefs->mqtt_neighbors_enabled = 0;
|
||||
prefs->mqtt_neighbors_interval = MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS;
|
||||
|
||||
// Runtime observer display defaults. These remain implicit in compact
|
||||
// pre-display payloads and are serialized only after either value changes.
|
||||
prefs->display_timeout_secs = DISPLAY_TIMEOUT_DEFAULT_SECS;
|
||||
prefs->display_flip = 0;
|
||||
}
|
||||
|
||||
#endif // WITH_MQTT_BRIDGE
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Pure, dependency-free validators for the observer's CLI/web configuration
|
||||
@@ -58,3 +59,33 @@ static inline bool mqttNtpHostnameValid(const char* host) {
|
||||
static inline bool mqttValueFits(const char* s, size_t bufsize) {
|
||||
return s != NULL && bufsize > 0 && strlen(s) < bufsize;
|
||||
}
|
||||
|
||||
// Strict decimal parser for bounded observer settings. Unlike atoi(), this
|
||||
// rejects missing values, signs, whitespace, trailing text, and overflow.
|
||||
static inline bool observerParseBoundedUint16(const char* text, uint16_t maximum,
|
||||
uint16_t* result) {
|
||||
if (text == NULL || result == NULL || *text == '\0') return false;
|
||||
uint32_t value = 0;
|
||||
for (const char* p = text; *p != '\0'; ++p) {
|
||||
if (*p < '0' || *p > '9') return false;
|
||||
value = value * 10u + static_cast<uint32_t>(*p - '0');
|
||||
if (value > maximum) return false;
|
||||
}
|
||||
*result = static_cast<uint16_t>(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
// `display.flip` accepts only complete, lower-case tokens so a typo cannot
|
||||
// silently change persisted panel orientation.
|
||||
static inline bool observerParseDisplayFlip(const char* text, uint8_t* result) {
|
||||
if (text == NULL || result == NULL) return false;
|
||||
if (strcmp(text, "0") == 0 || strcmp(text, "off") == 0) {
|
||||
*result = 0;
|
||||
return true;
|
||||
}
|
||||
if (strcmp(text, "1") == 0 || strcmp(text, "on") == 0) {
|
||||
*result = 1;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -39,25 +39,43 @@ struct DecodePlan {
|
||||
static const size_t kV1PreObserverPayloadSize = MQTT_PREFS_V1_PRE_OBSERVER_PAYLOAD_SIZE;
|
||||
static const size_t kV1PreNeighborsPayloadSize = MQTT_PREFS_V1_PRE_NEIGHBORS_PAYLOAD_SIZE;
|
||||
static const size_t kV1PreFilterPayloadSize = MQTT_PREFS_V1_PRE_FILTER_PAYLOAD_SIZE;
|
||||
static const size_t kV1PreDisplayPayloadSize = MQTT_PREFS_V1_PRE_DISPLAY_PAYLOAD_SIZE;
|
||||
static const size_t kV1BaselinePayloadSize = MQTT_PREFS_V1_FULL_PAYLOAD_SIZE;
|
||||
static const size_t kEncodedSize = sizeof(MQTTPrefsHeader) + kV1BaselinePayloadSize;
|
||||
|
||||
// Shortest payload length that still round-trips this configuration.
|
||||
//
|
||||
// The packet-filter tail is the only optional part of the current layout, and
|
||||
// its default (all types) is exactly what a pre-filter decoder supplies for a
|
||||
// missing tail. So a device whose filters are all default keeps writing the
|
||||
// 2864-byte payload that pre-filter firmware can still read. That matters
|
||||
// because /mqtt_prefs also carries the WiFi credentials: an unrecognised
|
||||
// longer payload sends older firmware to defaults with no network, and it
|
||||
// refuses to overwrite the file, so the node cannot be recovered over the air.
|
||||
// Touching any filter opts that node into the longer payload -- a deliberate,
|
||||
// operator-initiated trade rather than a side effect of upgrading.
|
||||
// The packet-filter and display tails are optional. Their defaults are exactly
|
||||
// what a decoder supplies when the corresponding tail is missing, so merely
|
||||
// upgrading does not lengthen the file. That matters because /mqtt_prefs also
|
||||
// carries WiFi credentials: old firmware that cannot read a longer payload can
|
||||
// otherwise lose its network configuration after a downgrade. Changing a
|
||||
// filter or display control deliberately opts the node into the required tail.
|
||||
inline size_t payloadLenFor(const MQTTPrefs& prefs) {
|
||||
if (prefs.display_timeout_secs != DISPLAY_TIMEOUT_DEFAULT_SECS ||
|
||||
prefs.display_flip != 0) {
|
||||
return kV1BaselinePayloadSize;
|
||||
}
|
||||
return MQTTPacketFilter::allMasksDefault(prefs.mqtt_slot_packet_filter,
|
||||
MQTT_PREFS_SLOT_COUNT)
|
||||
? kV1PreFilterPayloadSize
|
||||
: kV1BaselinePayloadSize;
|
||||
: kV1PreDisplayPayloadSize;
|
||||
}
|
||||
|
||||
// Clamp the display tail after loading. Returns true when a persisted value was
|
||||
// repaired and should be rewritten (unless the source file is being held).
|
||||
inline bool repairDisplayPrefs(MQTTPrefs* prefs) {
|
||||
if (prefs == nullptr) return false;
|
||||
bool repaired = false;
|
||||
if (prefs->display_timeout_secs > DISPLAY_TIMEOUT_MAX_SECS) {
|
||||
prefs->display_timeout_secs = DISPLAY_TIMEOUT_DEFAULT_SECS;
|
||||
repaired = true;
|
||||
}
|
||||
if (prefs->display_flip > 1) {
|
||||
prefs->display_flip = 0;
|
||||
repaired = true;
|
||||
}
|
||||
return repaired;
|
||||
}
|
||||
|
||||
inline MQTTPrefsHeader makeHeader(size_t payload_len) {
|
||||
@@ -138,6 +156,11 @@ inline DecodePlan classify(const uint8_t* prefix, size_t prefix_read, size_t fil
|
||||
if (header.payload_len == kV1BaselinePayloadSize) {
|
||||
return {Source::Current, false, false, true, kV1BaselinePayloadSize};
|
||||
}
|
||||
if (header.payload_len == kV1PreDisplayPayloadSize) {
|
||||
// Written before runtime display controls. Defaults supply timeout and
|
||||
// flip while preserving the packet-filter tail.
|
||||
return {Source::Current, false, false, true, kV1PreDisplayPayloadSize};
|
||||
}
|
||||
if (header.payload_len == kV1PreFilterPayloadSize) {
|
||||
// Written before the per-slot packet-filter tail. Defaults supply an
|
||||
// all-types mask for every slot.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "MQTTPrefsSerializer.h"
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
|
||||
// Conservative one-way import policy for observer-firmware-dev's historical
|
||||
// `/mqtt.json` v1. Despite its name, that file uses ConfigSerializer notation
|
||||
// (unquoted keys), so decoding must use the source firmware's grammar rather
|
||||
// than a general-purpose RFC JSON parser.
|
||||
namespace MQTTPrefsJsonImport {
|
||||
|
||||
static const size_t kMaximumFileSize = 16384;
|
||||
|
||||
enum class Decision : uint8_t {
|
||||
BinaryAuthoritative,
|
||||
NoJsonSource,
|
||||
ImportPrimary,
|
||||
HoldJsonArtifacts,
|
||||
};
|
||||
|
||||
// No generation is shared by the two formats. Any binary primary or recovery
|
||||
// artifact therefore owns the configuration name, even if it later proves
|
||||
// corrupt, future, or default-valued. Likewise, unresolved JSON transaction
|
||||
// artifacts are preserved rather than guessed at.
|
||||
inline Decision select(bool binary_hold, bool binary_primary,
|
||||
bool binary_temp, bool binary_backup,
|
||||
bool json_primary, bool json_temp, bool json_backup) {
|
||||
if (binary_hold || binary_primary || binary_temp || binary_backup) {
|
||||
return Decision::BinaryAuthoritative;
|
||||
}
|
||||
if (json_temp || json_backup) return Decision::HoldJsonArtifacts;
|
||||
return json_primary ? Decision::ImportPrimary : Decision::NoJsonSource;
|
||||
}
|
||||
|
||||
enum class Result : uint8_t {
|
||||
Loaded,
|
||||
LoadedWithRepairs,
|
||||
InvalidSyntax,
|
||||
InvalidSchema,
|
||||
UnsupportedVersion,
|
||||
TooLarge,
|
||||
};
|
||||
|
||||
inline bool loaded(Result result) {
|
||||
return result == Result::Loaded || result == Result::LoadedWithRepairs;
|
||||
}
|
||||
|
||||
// `candidate` must start with this build's defaults and must not alias the live
|
||||
// runtime object. Strict parsing may touch it before a late error; the caller
|
||||
// commits it only after this function reports Loaded/LoadedWithRepairs.
|
||||
inline Result decode(Stream& source, const MQTTPrefs& repair_defaults,
|
||||
MQTTPrefs* candidate,
|
||||
MQTTPrefsPresetValidator preset_valid) {
|
||||
if (candidate == nullptr) return Result::InvalidSchema;
|
||||
MQTTPrefsSerializer serializer(candidate, &repair_defaults, preset_valid);
|
||||
const bool parsed = serializer.loadSerial(source);
|
||||
|
||||
// Version is format-mandated as the first root property. If a future writer
|
||||
// uses new grammar later in the file, preserve it as opaque even though this
|
||||
// parser stops at that unknown construct.
|
||||
if (serializer.hasFutureVersion()) return Result::UnsupportedVersion;
|
||||
if (!parsed) return Result::InvalidSyntax;
|
||||
|
||||
bool repaired = false;
|
||||
if (!serializer.apply(&repaired)) return Result::InvalidSchema;
|
||||
return repaired ? Result::LoadedWithRepairs : Result::Loaded;
|
||||
}
|
||||
|
||||
} // namespace MQTTPrefsJsonImport
|
||||
|
||||
#endif // WITH_MQTT_BRIDGE
|
||||
@@ -0,0 +1,447 @@
|
||||
#pragma once
|
||||
|
||||
#include <helpers/ConfigSerializer.h>
|
||||
#include <helpers/MQTTObserverValidation.h>
|
||||
#include <helpers/MQTTPrefsStorage.h>
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
|
||||
static const int32_t MQTT_PREFS_JSON_FORMAT_VERSION = 1;
|
||||
typedef bool (*MQTTPrefsPresetValidator)(const char* preset);
|
||||
|
||||
// Format invariant inherited from observer-firmware-dev: `version` is the
|
||||
// first root property. Recognizing it before any later unknown grammar lets the
|
||||
// importer preserve a future file as opaque rather than misclassifying it as a
|
||||
// corrupt v1 source.
|
||||
|
||||
// ConfigSerializer adapter for the observer preference POD. Keeping the
|
||||
// serializer separate avoids making the runtime object layout part of the JSON
|
||||
// format and adds no permanent per-slot serializer state to CommonCLI.
|
||||
class MQTTPrefsSerializer : public ConfigSerializer {
|
||||
|
||||
class WifiPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _power_save, _default_power_save;
|
||||
bool _seen_ssid = false, _seen_password = false, _seen_power_save = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("ssid", _prefs->wifi_ssid, sizeof(_prefs->wifi_ssid), _seen_ssid);
|
||||
defStrict("password", _prefs->wifi_password, sizeof(_prefs->wifi_password), _seen_password);
|
||||
defStrict("power_save", _power_save, _seen_power_save);
|
||||
}
|
||||
public:
|
||||
WifiPrefs(MQTTPrefs* prefs, const MQTTPrefs* defaults)
|
||||
: _prefs(prefs), _power_save(prefs->wifi_power_save),
|
||||
_default_power_save(defaults->wifi_power_save) {
|
||||
if (_default_power_save < 0 || _default_power_save > 2) {
|
||||
_default_power_save = 1;
|
||||
}
|
||||
}
|
||||
bool apply(bool* repaired) {
|
||||
if (_power_save < 0 || _power_save > 2) {
|
||||
_power_save = _default_power_save;
|
||||
*repaired = true;
|
||||
}
|
||||
_prefs->wifi_power_save = static_cast<uint8_t>(_power_save);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
class TimePrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _utc_offset, _default_utc_offset;
|
||||
char _default_ntp_server[sizeof(MQTTPrefs::mqtt_ntp_server)];
|
||||
bool _seen_timezone = false, _seen_utc_offset = false, _seen_ntp_server = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("timezone", _prefs->timezone_string, sizeof(_prefs->timezone_string), _seen_timezone);
|
||||
defStrict("utc_offset", _utc_offset, _seen_utc_offset);
|
||||
defStrict("ntp_server", _prefs->mqtt_ntp_server, sizeof(_prefs->mqtt_ntp_server), _seen_ntp_server);
|
||||
}
|
||||
public:
|
||||
TimePrefs(MQTTPrefs* prefs, const MQTTPrefs* defaults)
|
||||
: _prefs(prefs), _utc_offset(prefs->timezone_offset),
|
||||
_default_utc_offset(defaults->timezone_offset) {
|
||||
if (_default_utc_offset < -12 || _default_utc_offset > 14) {
|
||||
_default_utc_offset = 0;
|
||||
}
|
||||
memcpy(_default_ntp_server, defaults->mqtt_ntp_server, sizeof(_default_ntp_server));
|
||||
if (_default_ntp_server[0] != '\0' &&
|
||||
!mqttNtpHostnameValid(_default_ntp_server)) {
|
||||
_default_ntp_server[0] = '\0';
|
||||
}
|
||||
}
|
||||
bool apply(bool* repaired) {
|
||||
if (_utc_offset < -12 || _utc_offset > 14) {
|
||||
_utc_offset = _default_utc_offset;
|
||||
*repaired = true;
|
||||
}
|
||||
if (_prefs->mqtt_ntp_server[0] != '\0' &&
|
||||
!mqttNtpHostnameValid(_prefs->mqtt_ntp_server)) {
|
||||
memcpy(_prefs->mqtt_ntp_server, _default_ntp_server, sizeof(_default_ntp_server));
|
||||
*repaired = true;
|
||||
}
|
||||
_prefs->timezone_offset = static_cast<int8_t>(_utc_offset);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
class StatusPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _enabled, _interval_ms;
|
||||
bool _seen_enabled = false, _seen_interval = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("enabled", _enabled, _seen_enabled);
|
||||
defStrict("interval_ms", _interval_ms, _seen_interval);
|
||||
}
|
||||
public:
|
||||
explicit StatusPrefs(MQTTPrefs* prefs)
|
||||
: _prefs(prefs), _enabled(prefs->mqtt_status_enabled),
|
||||
_interval_ms(static_cast<int32_t>(prefs->mqtt_status_interval)) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_enabled < 0 || _enabled > 1) { _enabled = 1; *repaired = true; }
|
||||
if (_interval_ms < 60000 || _interval_ms > 3600000) {
|
||||
_interval_ms = 300000;
|
||||
*repaired = true;
|
||||
}
|
||||
_prefs->mqtt_status_enabled = static_cast<uint8_t>(_enabled);
|
||||
_prefs->mqtt_status_interval = static_cast<uint32_t>(_interval_ms);
|
||||
}
|
||||
};
|
||||
|
||||
class NeighborPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _enabled, _interval_ms;
|
||||
bool _seen_enabled = false, _seen_interval = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("enabled", _enabled, _seen_enabled);
|
||||
defStrict("interval_ms", _interval_ms, _seen_interval);
|
||||
}
|
||||
public:
|
||||
explicit NeighborPrefs(MQTTPrefs* prefs)
|
||||
: _prefs(prefs), _enabled(prefs->mqtt_neighbors_enabled),
|
||||
_interval_ms(static_cast<int32_t>(prefs->mqtt_neighbors_interval)) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_enabled < 0 || _enabled > 1) { _enabled = 0; *repaired = true; }
|
||||
if (_interval_ms < static_cast<int32_t>(MQTT_NEIGHBORS_MIN_INTERVAL_MS) ||
|
||||
_interval_ms > static_cast<int32_t>(MQTT_NEIGHBORS_MAX_INTERVAL_MS)) {
|
||||
_interval_ms = static_cast<int32_t>(MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS);
|
||||
*repaired = true;
|
||||
}
|
||||
_prefs->mqtt_neighbors_enabled = static_cast<uint8_t>(_enabled);
|
||||
_prefs->mqtt_neighbors_interval = static_cast<uint32_t>(_interval_ms);
|
||||
}
|
||||
};
|
||||
|
||||
class OwnerPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
bool _seen_public_key = false, _seen_email = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("public_key", _prefs->mqtt_owner_public_key,
|
||||
sizeof(_prefs->mqtt_owner_public_key), _seen_public_key);
|
||||
defStrict("email", _prefs->mqtt_email, sizeof(_prefs->mqtt_email), _seen_email);
|
||||
}
|
||||
public:
|
||||
explicit OwnerPrefs(MQTTPrefs* prefs) : _prefs(prefs) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_prefs->mqtt_owner_public_key[0] != '\0' &&
|
||||
!mqttOwnerKeyValid(_prefs->mqtt_owner_public_key)) {
|
||||
_prefs->mqtt_owner_public_key[0] = '\0';
|
||||
*repaired = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class SlotPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int _index;
|
||||
int32_t _port, _filter;
|
||||
MQTTPrefsPresetValidator _preset_valid;
|
||||
bool _seen_preset = false, _seen_host = false, _seen_port = false;
|
||||
bool _seen_username = false, _seen_password = false, _seen_token = false;
|
||||
bool _seen_topic = false, _seen_audience = false, _seen_filter = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("preset", _prefs->mqtt_slot_preset[_index],
|
||||
sizeof(_prefs->mqtt_slot_preset[_index]), _seen_preset);
|
||||
defStrict("host", _prefs->mqtt_slot_host[_index],
|
||||
sizeof(_prefs->mqtt_slot_host[_index]), _seen_host);
|
||||
defStrict("port", _port, _seen_port);
|
||||
defStrict("username", _prefs->mqtt_slot_username[_index],
|
||||
sizeof(_prefs->mqtt_slot_username[_index]), _seen_username);
|
||||
defStrict("password", _prefs->mqtt_slot_password[_index],
|
||||
sizeof(_prefs->mqtt_slot_password[_index]), _seen_password);
|
||||
defStrict("token", _prefs->mqtt_slot_token[_index],
|
||||
sizeof(_prefs->mqtt_slot_token[_index]), _seen_token);
|
||||
defStrict("topic", _prefs->mqtt_slot_topic[_index],
|
||||
sizeof(_prefs->mqtt_slot_topic[_index]), _seen_topic);
|
||||
defStrict("audience", _prefs->mqtt_slot_audience[_index],
|
||||
sizeof(_prefs->mqtt_slot_audience[_index]), _seen_audience);
|
||||
defStrict("packet_filter", _filter, _seen_filter);
|
||||
}
|
||||
public:
|
||||
SlotPrefs(MQTTPrefs* prefs, int index, MQTTPrefsPresetValidator preset_valid)
|
||||
: _prefs(prefs), _index(index), _port(prefs->mqtt_slot_port[index]),
|
||||
_filter(prefs->mqtt_slot_packet_filter[index]),
|
||||
_preset_valid(preset_valid) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_port < 0 || _port > 65535) { _port = 0; *repaired = true; }
|
||||
if (_filter < 0 || _filter > 65535) { _filter = 0xffff; *repaired = true; }
|
||||
const char* preset = _prefs->mqtt_slot_preset[_index];
|
||||
if (strcmp(preset, "none") != 0 && strcmp(preset, "custom") != 0 &&
|
||||
(_preset_valid == nullptr || !_preset_valid(preset))) {
|
||||
strcpy(_prefs->mqtt_slot_preset[_index], "none");
|
||||
*repaired = true;
|
||||
}
|
||||
_prefs->mqtt_slot_port[_index] = static_cast<uint16_t>(_port);
|
||||
_prefs->mqtt_slot_packet_filter[_index] = static_cast<uint16_t>(_filter);
|
||||
}
|
||||
};
|
||||
|
||||
class MqttPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _packets_enabled, _raw_enabled, _tx_enabled, _rx_enabled;
|
||||
char _default_iata[sizeof(MQTTPrefs::mqtt_iata)];
|
||||
bool _seen_origin = false, _seen_iata = false, _seen_packets = false;
|
||||
bool _seen_raw = false, _seen_tx = false, _seen_rx = false;
|
||||
bool _seen_status = false, _seen_neighbors = false, _seen_owner = false;
|
||||
bool _seen_slot1 = false, _seen_slot2 = false, _seen_slot3 = false;
|
||||
bool _seen_slot4 = false, _seen_slot5 = false, _seen_slot6 = false;
|
||||
StatusPrefs _status;
|
||||
NeighborPrefs _neighbors;
|
||||
OwnerPrefs _owner;
|
||||
static_assert(MQTT_PREFS_SLOT_COUNT == 6,
|
||||
"MQTTPrefsSerializer slot members and keys must be updated");
|
||||
SlotPrefs _slot1, _slot2, _slot3, _slot4, _slot5, _slot6;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("origin", _prefs->mqtt_origin, sizeof(_prefs->mqtt_origin), _seen_origin);
|
||||
defStrict("iata", _prefs->mqtt_iata, sizeof(_prefs->mqtt_iata), _seen_iata);
|
||||
defStrict("packets_enabled", _packets_enabled, _seen_packets);
|
||||
defStrict("raw_enabled", _raw_enabled, _seen_raw);
|
||||
defStrict("tx_enabled", _tx_enabled, _seen_tx);
|
||||
defStrict("rx_enabled", _rx_enabled, _seen_rx);
|
||||
defStrict("status", _status, _seen_status);
|
||||
defStrict("neighbors", _neighbors, _seen_neighbors);
|
||||
defStrict("owner", _owner, _seen_owner);
|
||||
defStrict("slot1", _slot1, _seen_slot1);
|
||||
defStrict("slot2", _slot2, _seen_slot2);
|
||||
defStrict("slot3", _slot3, _seen_slot3);
|
||||
defStrict("slot4", _slot4, _seen_slot4);
|
||||
defStrict("slot5", _slot5, _seen_slot5);
|
||||
defStrict("slot6", _slot6, _seen_slot6);
|
||||
}
|
||||
public:
|
||||
MqttPrefs(MQTTPrefs* prefs, const MQTTPrefs* defaults,
|
||||
MQTTPrefsPresetValidator preset_valid)
|
||||
: _prefs(prefs), _packets_enabled(prefs->mqtt_packets_enabled),
|
||||
_raw_enabled(prefs->mqtt_raw_enabled), _tx_enabled(prefs->mqtt_tx_enabled),
|
||||
_rx_enabled(prefs->mqtt_rx_enabled), _status(prefs), _neighbors(prefs),
|
||||
_owner(prefs), _slot1(prefs, 0, preset_valid),
|
||||
_slot2(prefs, 1, preset_valid), _slot3(prefs, 2, preset_valid),
|
||||
_slot4(prefs, 3, preset_valid), _slot5(prefs, 4, preset_valid),
|
||||
_slot6(prefs, 5, preset_valid) {
|
||||
memcpy(_default_iata, defaults->mqtt_iata, sizeof(_default_iata));
|
||||
if (_default_iata[0] != '\0' && !mqttIataValid(_default_iata)) {
|
||||
_default_iata[0] = '\0';
|
||||
}
|
||||
for (char* p = _default_iata; *p; ++p) {
|
||||
if (*p >= 'a' && *p <= 'z') *p = static_cast<char>(*p - ('a' - 'A'));
|
||||
}
|
||||
}
|
||||
void apply(bool* repaired) {
|
||||
if (_packets_enabled < 0 || _packets_enabled > 1) { _packets_enabled = 1; *repaired = true; }
|
||||
if (_raw_enabled < 0 || _raw_enabled > 1) { _raw_enabled = 0; *repaired = true; }
|
||||
if (_tx_enabled < 0 || _tx_enabled > 2) { _tx_enabled = 2; *repaired = true; }
|
||||
if (_rx_enabled < 0 || _rx_enabled > 1) { _rx_enabled = 1; *repaired = true; }
|
||||
_prefs->mqtt_packets_enabled = static_cast<uint8_t>(_packets_enabled);
|
||||
_prefs->mqtt_raw_enabled = static_cast<uint8_t>(_raw_enabled);
|
||||
_prefs->mqtt_tx_enabled = static_cast<uint8_t>(_tx_enabled);
|
||||
_prefs->mqtt_rx_enabled = static_cast<uint8_t>(_rx_enabled);
|
||||
if (_prefs->mqtt_iata[0] != '\0') {
|
||||
if (!mqttIataValid(_prefs->mqtt_iata)) {
|
||||
memcpy(_prefs->mqtt_iata, _default_iata, sizeof(_default_iata));
|
||||
*repaired = true;
|
||||
} else {
|
||||
for (char* p = _prefs->mqtt_iata; *p; ++p) {
|
||||
if (*p >= 'a' && *p <= 'z') {
|
||||
*p = static_cast<char>(*p - ('a' - 'A'));
|
||||
*repaired = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_status.apply(repaired);
|
||||
_neighbors.apply(repaired);
|
||||
_owner.apply(repaired);
|
||||
_slot1.apply(repaired); _slot2.apply(repaired); _slot3.apply(repaired);
|
||||
_slot4.apply(repaired); _slot5.apply(repaired); _slot6.apply(repaired);
|
||||
}
|
||||
};
|
||||
|
||||
class SnmpPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _enabled;
|
||||
bool _seen_enabled = false, _seen_community = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("enabled", _enabled, _seen_enabled);
|
||||
defStrict("community", _prefs->snmp_community,
|
||||
sizeof(_prefs->snmp_community), _seen_community);
|
||||
}
|
||||
public:
|
||||
explicit SnmpPrefs(MQTTPrefs* prefs) : _prefs(prefs), _enabled(prefs->snmp_enabled) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_enabled < 0 || _enabled > 1) { _enabled = 0; *repaired = true; }
|
||||
_prefs->snmp_enabled = static_cast<uint8_t>(_enabled);
|
||||
}
|
||||
};
|
||||
|
||||
class RadioPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _watchdog_min;
|
||||
bool _seen_watchdog = false;
|
||||
protected:
|
||||
void structure() override { defStrict("watchdog_min", _watchdog_min, _seen_watchdog); }
|
||||
public:
|
||||
explicit RadioPrefs(MQTTPrefs* prefs)
|
||||
: _prefs(prefs), _watchdog_min(prefs->radio_watchdog_minutes) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_watchdog_min < 0 || _watchdog_min > 120) { _watchdog_min = 5; *repaired = true; }
|
||||
_prefs->radio_watchdog_minutes = static_cast<uint8_t>(_watchdog_min);
|
||||
}
|
||||
};
|
||||
|
||||
class AlertPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _enabled, _wifi_minutes, _mqtt_minutes, _rate_limit_min;
|
||||
bool _seen_enabled = false, _seen_psk = false, _seen_wifi = false;
|
||||
bool _seen_mqtt = false, _seen_rate = false, _seen_hashtag = false, _seen_region = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("enabled", _enabled, _seen_enabled);
|
||||
defStrict("psk_hex", _prefs->alert_psk_hex, sizeof(_prefs->alert_psk_hex), _seen_psk);
|
||||
defStrict("wifi_minutes", _wifi_minutes, _seen_wifi);
|
||||
defStrict("mqtt_minutes", _mqtt_minutes, _seen_mqtt);
|
||||
defStrict("rate_limit_min", _rate_limit_min, _seen_rate);
|
||||
defStrict("hashtag", _prefs->alert_hashtag, sizeof(_prefs->alert_hashtag), _seen_hashtag);
|
||||
defStrict("region", _prefs->alert_region, sizeof(_prefs->alert_region), _seen_region);
|
||||
}
|
||||
public:
|
||||
explicit AlertPrefs(MQTTPrefs* prefs)
|
||||
: _prefs(prefs), _enabled(prefs->alert_enabled),
|
||||
_wifi_minutes(prefs->alert_wifi_minutes), _mqtt_minutes(prefs->alert_mqtt_minutes),
|
||||
_rate_limit_min(prefs->alert_min_interval_min) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_enabled < 0 || _enabled > 1) { _enabled = 0; *repaired = true; }
|
||||
if (_wifi_minutes < 0 || _wifi_minutes > 1440) { _wifi_minutes = 30; *repaired = true; }
|
||||
if (_mqtt_minutes < 0 || _mqtt_minutes > 10080) { _mqtt_minutes = 240; *repaired = true; }
|
||||
if (_rate_limit_min < 60 || _rate_limit_min > 10080) { _rate_limit_min = 60; *repaired = true; }
|
||||
if (_prefs->alert_psk_hex[0] != '\0') {
|
||||
const size_t len = strlen(_prefs->alert_psk_hex);
|
||||
bool valid_hex = len == 32;
|
||||
for (size_t i = 0; valid_hex && i < len; ++i) {
|
||||
const char c = _prefs->alert_psk_hex[i];
|
||||
valid_hex = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
|
||||
(c >= 'a' && c <= 'f');
|
||||
}
|
||||
if (!valid_hex) {
|
||||
_prefs->alert_psk_hex[0] = '\0';
|
||||
_prefs->alert_hashtag[0] = '\0';
|
||||
*repaired = true;
|
||||
}
|
||||
}
|
||||
_prefs->alert_enabled = static_cast<uint8_t>(_enabled);
|
||||
_prefs->alert_wifi_minutes = static_cast<uint16_t>(_wifi_minutes);
|
||||
_prefs->alert_mqtt_minutes = static_cast<uint16_t>(_mqtt_minutes);
|
||||
_prefs->alert_min_interval_min = static_cast<uint16_t>(_rate_limit_min);
|
||||
}
|
||||
};
|
||||
|
||||
class DisplayPrefs : public ConfigSerializer {
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _timeout_s, _flip;
|
||||
bool _seen_timeout = false, _seen_flip = false;
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("timeout_s", _timeout_s, _seen_timeout);
|
||||
defStrict("flip", _flip, _seen_flip);
|
||||
}
|
||||
public:
|
||||
explicit DisplayPrefs(MQTTPrefs* prefs)
|
||||
: _prefs(prefs), _timeout_s(prefs->display_timeout_secs), _flip(prefs->display_flip) {}
|
||||
void apply(bool* repaired) {
|
||||
if (_timeout_s < 0 || _timeout_s > DISPLAY_TIMEOUT_MAX_SECS) {
|
||||
_timeout_s = DISPLAY_TIMEOUT_DEFAULT_SECS;
|
||||
*repaired = true;
|
||||
}
|
||||
if (_flip < 0 || _flip > 1) { _flip = 0; *repaired = true; }
|
||||
_prefs->display_timeout_secs = static_cast<uint16_t>(_timeout_s);
|
||||
_prefs->display_flip = static_cast<uint8_t>(_flip);
|
||||
}
|
||||
};
|
||||
|
||||
MQTTPrefs* _prefs;
|
||||
int32_t _version = MQTT_PREFS_JSON_FORMAT_VERSION;
|
||||
bool _seen_version = false;
|
||||
bool _seen_wifi = false, _seen_time = false, _seen_mqtt = false;
|
||||
bool _seen_snmp = false, _seen_radio = false, _seen_alert = false;
|
||||
bool _seen_display = false;
|
||||
WifiPrefs _wifi;
|
||||
TimePrefs _time;
|
||||
MqttPrefs _mqtt;
|
||||
SnmpPrefs _snmp;
|
||||
RadioPrefs _radio;
|
||||
AlertPrefs _alert;
|
||||
DisplayPrefs _display;
|
||||
|
||||
protected:
|
||||
void structure() override {
|
||||
defStrict("version", _version, _seen_version); // must stay first; see above
|
||||
defStrict("wifi", _wifi, _seen_wifi);
|
||||
defStrict("time", _time, _seen_time);
|
||||
defStrict("mqtt", _mqtt, _seen_mqtt);
|
||||
defStrict("snmp", _snmp, _seen_snmp);
|
||||
defStrict("radio", _radio, _seen_radio);
|
||||
defStrict("alert", _alert, _seen_alert);
|
||||
defStrict("display", _display, _seen_display);
|
||||
}
|
||||
|
||||
public:
|
||||
explicit MQTTPrefsSerializer(
|
||||
MQTTPrefs* prefs, const MQTTPrefs* repair_defaults = nullptr,
|
||||
MQTTPrefsPresetValidator preset_valid = nullptr)
|
||||
: _prefs(prefs), _wifi(prefs, repair_defaults ? repair_defaults : prefs),
|
||||
_time(prefs, repair_defaults ? repair_defaults : prefs),
|
||||
_mqtt(prefs, repair_defaults ? repair_defaults : prefs, preset_valid), _snmp(prefs),
|
||||
_radio(prefs), _alert(prefs), _display(prefs) {}
|
||||
|
||||
bool hasSupportedVersion() const {
|
||||
return _seen_version && _version == MQTT_PREFS_JSON_FORMAT_VERSION;
|
||||
}
|
||||
bool hasFutureVersion() const {
|
||||
return _seen_version && _version > MQTT_PREFS_JSON_FORMAT_VERSION;
|
||||
}
|
||||
|
||||
bool normalize(bool* repaired) {
|
||||
if (repaired == nullptr) return false;
|
||||
*repaired = false;
|
||||
_wifi.apply(repaired);
|
||||
_time.apply(repaired);
|
||||
_mqtt.apply(repaired);
|
||||
_snmp.apply(repaired);
|
||||
_radio.apply(repaired);
|
||||
_alert.apply(repaired);
|
||||
_display.apply(repaired);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool apply(bool* repaired) {
|
||||
return hasSupportedVersion() && normalize(repaired);
|
||||
}
|
||||
};
|
||||
|
||||
#endif // WITH_MQTT_BRIDGE
|
||||
@@ -122,6 +122,13 @@ struct MQTTPrefs {
|
||||
// for both packets and raw MQTT topics. Appended so older v1 payloads load
|
||||
// with the default all-types masks intact.
|
||||
uint16_t mqtt_slot_packet_filter[MQTT_PREFS_SLOT_COUNT];
|
||||
|
||||
// Runtime display controls. These are an append-only v1 tail: older payloads
|
||||
// stop before them and retain the defaults below. The serialized payload ends
|
||||
// after display_flip at byte 2879; the compiler's final alignment byte is not
|
||||
// part of the on-flash format.
|
||||
uint16_t display_timeout_secs;
|
||||
uint8_t display_flip;
|
||||
};
|
||||
|
||||
// Neighbor discovery is scheduled with the wrap-safe millis() helpers, whose
|
||||
@@ -134,7 +141,10 @@ static const uint32_t MQTT_NEIGHBORS_MIN_INTERVAL_MS = MQTT_NEIGHBORS_MIN_INTERV
|
||||
static const uint32_t MQTT_NEIGHBORS_MAX_INTERVAL_MS = MQTT_NEIGHBORS_MAX_INTERVAL_HOURS * 3600000UL;
|
||||
static const uint32_t MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS = MQTT_NEIGHBORS_DEFAULT_INTERVAL_HOURS * 3600000UL;
|
||||
|
||||
// Version-1 has four payload layouts this firmware can decode. Never infer a
|
||||
static const uint16_t DISPLAY_TIMEOUT_DEFAULT_SECS = 60;
|
||||
static const uint16_t DISPLAY_TIMEOUT_MAX_SECS = 3600;
|
||||
|
||||
// Version-1 has five payload layouts this firmware can decode. Never infer a
|
||||
// compatible payload from an arbitrary SHORTER size: raw prefs have no
|
||||
// checksum, so a short length has to match a boundary that was really shipped.
|
||||
//
|
||||
@@ -146,16 +156,19 @@ static const uint32_t MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS = MQTT_NEIGHBORS_DEFAUL
|
||||
// - PRE_OBSERVER (2736): stops before the observer tail (snmp_*/alert_*).
|
||||
// - PRE_NEIGHBORS (2860): full observer tail, no neighbors fields yet.
|
||||
// - PRE_FILTER (2864): neighbors tail, no per-slot packet filters.
|
||||
// - FULL (2876): current baseline, with six uint16_t filter masks.
|
||||
// - PRE_DISPLAY (2876): six filter masks, no runtime display controls.
|
||||
// - FULL (2879): timeout plus flip, excluding final struct padding.
|
||||
//
|
||||
// FULL is the maximum written, not the default: MQTTPrefsCodec::payloadLenFor()
|
||||
// keeps emitting PRE_FILTER while every slot holds the all-types default, so a
|
||||
// node that never touches a filter stays readable by pre-filter firmware. See
|
||||
// the rollback note there -- /mqtt_prefs also carries the WiFi credentials.
|
||||
// keeps emitting PRE_FILTER while every slot and display control has its
|
||||
// default. A non-default filter writes PRE_DISPLAY; a non-default display
|
||||
// control writes FULL. See the rollback note there -- /mqtt_prefs also carries
|
||||
// the WiFi credentials.
|
||||
static const size_t MQTT_PREFS_V1_PRE_OBSERVER_PAYLOAD_SIZE = 2736;
|
||||
static const size_t MQTT_PREFS_V1_PRE_NEIGHBORS_PAYLOAD_SIZE = 2860;
|
||||
static const size_t MQTT_PREFS_V1_PRE_FILTER_PAYLOAD_SIZE = 2864;
|
||||
static const size_t MQTT_PREFS_V1_FULL_PAYLOAD_SIZE = 2876;
|
||||
static const size_t MQTT_PREFS_V1_PRE_DISPLAY_PAYLOAD_SIZE = 2876;
|
||||
static const size_t MQTT_PREFS_V1_FULL_PAYLOAD_SIZE = 2879;
|
||||
|
||||
// /mqtt_prefs starts with a self-describing 8-byte header. Headerless files
|
||||
// are deployed legacy layouts and continue to be distinguished by size.
|
||||
@@ -274,8 +287,8 @@ static const size_t LEGACY6_AUDIENCE_RX_SIZE = 2840;
|
||||
static_assert(sizeof(MQTTPrefsHeader) == 8, "versioned /mqtt_prefs header must stay 8 bytes");
|
||||
static_assert(offsetof(MQTTPrefs, snmp_enabled) == MQTT_PREFS_V1_PRE_OBSERVER_PAYLOAD_SIZE,
|
||||
"v1 pre-observer /mqtt_prefs boundary changed");
|
||||
static_assert(sizeof(MQTTPrefs) == MQTT_PREFS_V1_FULL_PAYLOAD_SIZE,
|
||||
"v1 /mqtt_prefs payload layout changed");
|
||||
static_assert(sizeof(MQTTPrefs) == 2880,
|
||||
"runtime MQTTPrefs layout or final alignment changed");
|
||||
// Lock the neighbors tail to the flex neighbors build's layout so a /mqtt_prefs
|
||||
// written by either firmware is byte-for-byte interchangeable. The enable flag
|
||||
// lands in the old struct's zeroed trailing padding (offset 2857), and the
|
||||
@@ -287,6 +300,11 @@ static_assert(offsetof(MQTTPrefs, mqtt_neighbors_interval) == MQTT_PREFS_V1_PRE_
|
||||
"neighbors interval offset must equal the pre-neighbors payload size");
|
||||
static_assert(offsetof(MQTTPrefs, mqtt_slot_packet_filter) == MQTT_PREFS_V1_PRE_FILTER_PAYLOAD_SIZE,
|
||||
"packet filters must begin at the pre-filter payload boundary");
|
||||
static_assert(offsetof(MQTTPrefs, display_timeout_secs) == MQTT_PREFS_V1_PRE_DISPLAY_PAYLOAD_SIZE,
|
||||
"display timeout must begin at the pre-display payload boundary");
|
||||
static_assert(offsetof(MQTTPrefs, display_flip) + sizeof(MQTTPrefs::display_flip) ==
|
||||
MQTT_PREFS_V1_FULL_PAYLOAD_SIZE,
|
||||
"serialized display tail must end immediately after display_flip");
|
||||
static_assert(sizeof(OldMQTTPrefs) == 472, "frozen pre-slot /mqtt_prefs layout changed");
|
||||
static_assert(sizeof(PreWifiPowerOldMQTTPrefs) == 472, "frozen pre-WiFi-power /mqtt_prefs layout changed");
|
||||
static_assert(offsetof(OldMQTTPrefs, wifi_power_save) == 144,
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Fixed-memory rolling window of RF receive activity, bucketed by minute.
|
||||
//
|
||||
// Pure logic: no Arduino, radio, display or role headers. Callers supply a
|
||||
// millisecond counter and the per-packet values.
|
||||
//
|
||||
// The caller's 32-bit millis() is extended to a monotonic 64-bit clock on entry
|
||||
// (see tick()), so nothing downstream has a rollover case. Unsigned-subtraction
|
||||
// tricks are not enough here: they only survive a single wrap crossing, while an
|
||||
// always-on observer accumulates uptime past 2^32 ms (~49.7 days), at which
|
||||
// point a 32-bit tracker age would collapse back to a small value and the
|
||||
// window would re-enter warm-up and divide 20 minutes of traffic by seconds.
|
||||
|
||||
#define RADIO_ACTIVITY_BUCKETS 20
|
||||
#define RADIO_ACTIVITY_BUCKET_MS 60000UL
|
||||
|
||||
// Beyond this, "time since last packet" stops being reported rather than shown
|
||||
// as a stale or (after a 49-day rollover) nonsensical age.
|
||||
#define RADIO_ACTIVITY_MAX_AGE_MS (100UL * RADIO_ACTIVITY_BUCKET_MS)
|
||||
|
||||
// How far a timestamp may run behind the previous one and still count as an
|
||||
// out-of-order reading rather than a very long forward gap.
|
||||
#define RADIO_ACTIVITY_BACKSTEP_TOLERANCE_MS 5000UL
|
||||
|
||||
struct RadioActivitySnapshot {
|
||||
uint32_t packets;
|
||||
uint32_t wire_bytes;
|
||||
uint32_t airtime_ms;
|
||||
int32_t snr_q4_sum;
|
||||
int32_t rssi_sum;
|
||||
|
||||
// Span the totals actually cover: 19 whole minutes plus the elapsed part of
|
||||
// the current one, so it tops out just under 20 minutes and never claims
|
||||
// coverage the ring does not have.
|
||||
uint32_t window_ms;
|
||||
uint32_t tracking_ms; // how long the tracker has been running
|
||||
|
||||
uint32_t last_packet_age_ms;
|
||||
bool has_last_packet; // false until the first packet, and once stale
|
||||
|
||||
uint16_t peak_per_min;
|
||||
uint16_t buckets[RADIO_ACTIVITY_BUCKETS]; // [0] oldest .. [N-1] current minute
|
||||
|
||||
bool isEmpty() const { return packets == 0; }
|
||||
|
||||
bool isWarmingUp() const {
|
||||
return tracking_ms < (uint32_t)RADIO_ACTIVITY_BUCKETS * RADIO_ACTIVITY_BUCKET_MS;
|
||||
}
|
||||
uint32_t warmupMinutes() const { return tracking_ms / RADIO_ACTIVITY_BUCKET_MS; }
|
||||
|
||||
// Derived values, in integer fixed point so host tests are exact and the
|
||||
// formatting path stays off the FPU. All are zero when the window is empty.
|
||||
uint32_t packetsPerMinuteX10() const {
|
||||
if (window_ms == 0) return 0;
|
||||
return (uint32_t)(((uint64_t)packets * RADIO_ACTIVITY_BUCKET_MS * 10) / window_ms);
|
||||
}
|
||||
uint32_t bytesPerSecondX10() const {
|
||||
if (window_ms == 0) return 0;
|
||||
return (uint32_t)(((uint64_t)wire_bytes * 1000 * 10) / window_ms);
|
||||
}
|
||||
uint32_t avgBytesPerPacket() const {
|
||||
if (packets == 0) return 0;
|
||||
return (wire_bytes + packets / 2) / packets;
|
||||
}
|
||||
// Receive airtime as tenths of a percent of the window.
|
||||
uint32_t airtimePercentX10() const {
|
||||
if (window_ms == 0) return 0;
|
||||
return (uint32_t)(((uint64_t)airtime_ms * 1000) / window_ms);
|
||||
}
|
||||
// Average SNR in tenths of a dB (sums are quarter-dB units).
|
||||
int32_t avgSnrX10() const {
|
||||
if (packets == 0) return 0;
|
||||
return (snr_q4_sum * 10) / ((int32_t)packets * 4);
|
||||
}
|
||||
int32_t avgRssi() const {
|
||||
if (packets == 0) return 0;
|
||||
return rssi_sum / (int32_t)packets;
|
||||
}
|
||||
};
|
||||
|
||||
class RadioActivityWindow {
|
||||
public:
|
||||
RadioActivityWindow() { reset(0); }
|
||||
|
||||
void reset(uint32_t now_ms) {
|
||||
memset(_buckets, 0, sizeof(_buckets));
|
||||
_head = 0;
|
||||
_now_ms = 0;
|
||||
_last_input_ms = now_ms;
|
||||
_bucket_start_ms = 0;
|
||||
_tracking_since_ms = 0;
|
||||
_last_packet_ms = 0;
|
||||
_ever_received = false;
|
||||
}
|
||||
|
||||
void recordPacket(uint32_t now_ms, uint16_t wire_bytes, uint32_t airtime_ms, int8_t snr_q4,
|
||||
int16_t rssi_dbm) {
|
||||
advance(now_ms);
|
||||
|
||||
Bucket& b = _buckets[_head];
|
||||
// Saturated: drop the event whole so the bucket's averages stay consistent
|
||||
// with its packet count. Unreachable at any real LoRa packet rate.
|
||||
if (b.packets == 0xFFFF) return;
|
||||
|
||||
b.packets++;
|
||||
b.wire_bytes += wire_bytes;
|
||||
b.airtime_ms += airtime_ms;
|
||||
b.snr_q4_sum += snr_q4;
|
||||
b.rssi_sum += rssi_dbm;
|
||||
|
||||
_last_packet_ms = _now_ms;
|
||||
_ever_received = true;
|
||||
}
|
||||
|
||||
void snapshot(uint32_t now_ms, RadioActivitySnapshot* out) {
|
||||
advance(now_ms);
|
||||
memset(out, 0, sizeof(*out));
|
||||
|
||||
for (int i = 0; i < RADIO_ACTIVITY_BUCKETS; i++) {
|
||||
const Bucket& b = _buckets[(_head + 1 + i) % RADIO_ACTIVITY_BUCKETS];
|
||||
out->buckets[i] = b.packets;
|
||||
out->packets += b.packets;
|
||||
out->wire_bytes += b.wire_bytes;
|
||||
out->airtime_ms += b.airtime_ms;
|
||||
out->snr_q4_sum += b.snr_q4_sum;
|
||||
out->rssi_sum += b.rssi_sum;
|
||||
if (b.packets > out->peak_per_min) out->peak_per_min = b.packets;
|
||||
}
|
||||
|
||||
uint64_t elapsed_in_current = _now_ms - _bucket_start_ms; // < BUCKET_MS after advance()
|
||||
uint64_t max_span =
|
||||
(uint64_t)(RADIO_ACTIVITY_BUCKETS - 1) * RADIO_ACTIVITY_BUCKET_MS + elapsed_in_current;
|
||||
uint64_t tracking = _now_ms - _tracking_since_ms;
|
||||
const uint64_t full_span = (uint64_t)RADIO_ACTIVITY_BUCKETS * RADIO_ACTIVITY_BUCKET_MS;
|
||||
|
||||
// Clamped, so the 32-bit snapshot fields stay in range on a long-lived node.
|
||||
// Past full_span the exact tracker age is not needed: the window is warm.
|
||||
out->tracking_ms = (uint32_t)(tracking < full_span ? tracking : full_span);
|
||||
out->window_ms = (uint32_t)(tracking < max_span ? tracking : max_span);
|
||||
|
||||
if (_ever_received) {
|
||||
uint64_t age = _now_ms - _last_packet_ms;
|
||||
if (age <= RADIO_ACTIVITY_MAX_AGE_MS) {
|
||||
out->last_packet_age_ms = (uint32_t)age;
|
||||
out->has_last_packet = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
struct Bucket {
|
||||
uint32_t wire_bytes;
|
||||
uint32_t airtime_ms;
|
||||
int32_t snr_q4_sum;
|
||||
int32_t rssi_sum;
|
||||
uint16_t packets;
|
||||
uint16_t _reserved;
|
||||
};
|
||||
|
||||
Bucket _buckets[RADIO_ACTIVITY_BUCKETS];
|
||||
uint64_t _now_ms; // monotonic clock, extended from the caller's
|
||||
uint64_t _bucket_start_ms; // start of the current (newest) minute
|
||||
uint64_t _tracking_since_ms;
|
||||
uint64_t _last_packet_ms;
|
||||
uint32_t _last_input_ms; // last 32-bit value the caller handed in
|
||||
uint8_t _head; // ring index of the current minute
|
||||
bool _ever_received;
|
||||
|
||||
// Accumulates the unsigned delta since the previous call, which is correct
|
||||
// across one millis() wrap.
|
||||
//
|
||||
// A delta past the halfway mark is ambiguous: it is either a slightly stale
|
||||
// reading or a genuine gap of more than ~24.8 days. recordPacket() and
|
||||
// snapshot() sample millis() microseconds apart, so a real stale reading is
|
||||
// tiny - anything larger is treated as the long gap it is, which matters
|
||||
// because rejecting it outright would freeze the ring and leave a
|
||||
// month-old packet looking recently received.
|
||||
void tick(uint32_t now_ms) {
|
||||
uint32_t delta = now_ms - _last_input_ms;
|
||||
if (delta > 0x80000000u &&
|
||||
(uint32_t)(_last_input_ms - now_ms) <= RADIO_ACTIVITY_BACKSTEP_TOLERANCE_MS) {
|
||||
return; // out-of-order reading: no time has passed
|
||||
}
|
||||
_now_ms += delta;
|
||||
_last_input_ms = now_ms;
|
||||
}
|
||||
|
||||
// Retires expired buckets lazily, advancing the boundary by whole BUCKET_MS
|
||||
// steps so the minute phase is preserved across gaps.
|
||||
void advance(uint32_t now_ms) {
|
||||
tick(now_ms);
|
||||
|
||||
uint64_t elapsed = _now_ms - _bucket_start_ms;
|
||||
if (elapsed < RADIO_ACTIVITY_BUCKET_MS) return;
|
||||
|
||||
uint64_t steps = elapsed / RADIO_ACTIVITY_BUCKET_MS;
|
||||
_bucket_start_ms += steps * RADIO_ACTIVITY_BUCKET_MS;
|
||||
|
||||
if (steps >= RADIO_ACTIVITY_BUCKETS) {
|
||||
memset(_buckets, 0, sizeof(_buckets));
|
||||
_head = 0;
|
||||
_tracking_since_ms = _bucket_start_ms;
|
||||
return;
|
||||
}
|
||||
|
||||
for (uint64_t i = 0; i < steps; i++) {
|
||||
_head = (uint8_t)((_head + 1) % RADIO_ACTIVITY_BUCKETS);
|
||||
memset(&_buckets[_head], 0, sizeof(Bucket));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static_assert(sizeof(RadioActivityWindow) <= 1024, "RadioActivityWindow must stay under 1 KiB");
|
||||
@@ -0,0 +1,126 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
|
||||
#include "TouchTapDetector.h"
|
||||
|
||||
// Minimal polled driver for the CHSC6X capacitive touch controller on the
|
||||
// Heltec V4 R8 Expansion Kit V2 panel.
|
||||
//
|
||||
// Only "is a finger down" is needed to toggle the display, so no coordinates
|
||||
// and no calibration are read. TP_INT is not used: on this board it is an
|
||||
// optional link (R13) on GPIO 43, which is also U0TXD - see HeltecV4R8Board.cpp
|
||||
// for the verified pin map.
|
||||
|
||||
#ifndef CHSC6X_I2C_ADDR
|
||||
#define CHSC6X_I2C_ADDR 0x2E
|
||||
#endif
|
||||
|
||||
#define CHSC6X_READ_LEN 5
|
||||
|
||||
class CHSC6XTouch {
|
||||
public:
|
||||
// Probes the bus for diagnostics only. The result must NOT gate polling: this
|
||||
// controller NACKs its address whenever it has nothing to report, so a single
|
||||
// idle probe at boot is indistinguishable from absent hardware. checkTap()
|
||||
// keeps polling either way, and a NACK there costs one quiet, fast bus cycle.
|
||||
bool begin(TwoWire& wire = Wire) {
|
||||
_wire = &wire;
|
||||
_wire->beginTransmission((uint8_t)CHSC6X_I2C_ADDR);
|
||||
_present = (_wire->endTransmission() == 0);
|
||||
_detector.reset(millis());
|
||||
|
||||
#if defined(DISPLAY_TOUCH_DEBUG) && defined(PIN_TOUCH_INT)
|
||||
pinMode(PIN_TOUCH_INT, INPUT_PULLUP);
|
||||
#endif
|
||||
|
||||
if (_present) {
|
||||
Serial.printf("Touch: CHSC6X found at 0x%02X\n", CHSC6X_I2C_ADDR);
|
||||
} else {
|
||||
// Report what is actually on the bus, so an unexpected controller or
|
||||
// address can be identified from a normal boot log.
|
||||
Serial.printf("Touch: idle or absent at 0x%02X; I2C bus currently answers:",
|
||||
CHSC6X_I2C_ADDR);
|
||||
for (uint8_t addr = 8; addr < 0x78; addr++) {
|
||||
_wire->beginTransmission(addr);
|
||||
if (_wire->endTransmission() == 0) Serial.printf(" 0x%02X", addr);
|
||||
}
|
||||
Serial.println();
|
||||
}
|
||||
return _present;
|
||||
}
|
||||
|
||||
bool isPresent() const { return _present; }
|
||||
|
||||
// True exactly once per new touch.
|
||||
bool checkTap(uint32_t now_ms) {
|
||||
bool pressed = readPressed();
|
||||
if (pressed && !_present) {
|
||||
_present = true; // answered late; the boot probe caught it mid-idle
|
||||
Serial.println("Touch: CHSC6X responding");
|
||||
}
|
||||
return _detector.update(now_ms, pressed);
|
||||
}
|
||||
|
||||
private:
|
||||
TwoWire* _wire = NULL;
|
||||
bool _present = false;
|
||||
TouchTapDetector _detector;
|
||||
|
||||
bool readPressed() {
|
||||
// Probe the address first. This controller NACKs while it has nothing to
|
||||
// report, and going straight to requestFrom() turns that into a logged bus
|
||||
// error every poll plus, once the bus wedges, a ~1 s timeout stall in the
|
||||
// UI loop. endTransmission() reports the same NACK quietly and cheaply.
|
||||
_wire->beginTransmission((uint8_t)CHSC6X_I2C_ADDR);
|
||||
if (_wire->endTransmission() != 0) return false;
|
||||
|
||||
uint8_t got = _wire->requestFrom((uint8_t)CHSC6X_I2C_ADDR, (uint8_t)CHSC6X_READ_LEN);
|
||||
uint8_t buf[CHSC6X_READ_LEN];
|
||||
for (uint8_t i = 0; i < CHSC6X_READ_LEN; i++) {
|
||||
buf[i] = i < got ? (uint8_t)_wire->read() : 0xFF;
|
||||
}
|
||||
while (_wire->available()) _wire->read(); // drain a short read
|
||||
|
||||
if (got != CHSC6X_READ_LEN) {
|
||||
logRaw(got, NULL);
|
||||
return false;
|
||||
}
|
||||
logRaw(got, buf);
|
||||
|
||||
// Measured on the Expansion Kit V2 panel: byte 0 reads 0x00 while idle and
|
||||
// 0x1F while a finger is down - not the 0x01 point count the reference
|
||||
// CHSC6X drivers document, so testing for a count of 1 never fires. A
|
||||
// partly-failed read leaves 0xFF, which must not register as a press.
|
||||
return buf[0] != 0x00 && buf[0] != 0xFF;
|
||||
}
|
||||
|
||||
#ifdef DISPLAY_TOUCH_DEBUG
|
||||
int16_t _logged = -1;
|
||||
uint8_t _log_budget = 5; // always show the first few frames, then on change
|
||||
|
||||
// Mostly logs on change, so a normal boot stays quiet - but the opening
|
||||
// frames are unconditional so an idle read that never changes is still
|
||||
// visible in the log.
|
||||
void logRaw(uint8_t got, const uint8_t* buf) {
|
||||
int16_t key = buf ? (int16_t)buf[0] : (int16_t)(-2 - (int16_t)got);
|
||||
if (key == _logged && _log_budget == 0) return;
|
||||
if (_log_budget > 0) _log_budget--;
|
||||
_logged = key;
|
||||
|
||||
if (!buf) {
|
||||
Serial.printf("Touch: short read (%u of %u bytes)\n", got, CHSC6X_READ_LEN);
|
||||
return;
|
||||
}
|
||||
Serial.printf("Touch: raw %02X %02X %02X %02X %02X", buf[0], buf[1], buf[2], buf[3], buf[4]);
|
||||
#ifdef PIN_TOUCH_INT
|
||||
// Pulled up, so an unfitted R13 sits steady HIGH and a wired INT pulses LOW.
|
||||
Serial.printf(" INT=%d", digitalRead(PIN_TOUCH_INT));
|
||||
#endif
|
||||
Serial.println();
|
||||
}
|
||||
#else
|
||||
void logRaw(uint8_t, const uint8_t*) {}
|
||||
#endif
|
||||
};
|
||||
@@ -36,6 +36,10 @@ public:
|
||||
(void)degrees;
|
||||
return false;
|
||||
}
|
||||
// Rotate 180 degrees relative to the display's compiled orientation. This is
|
||||
// intentionally separate from absolute rotation: fixed portrait/landscape
|
||||
// layouts can be flipped without changing their geometry.
|
||||
virtual void setFlipped(bool flipped) { (void)flipped; }
|
||||
virtual bool isEink() { return false; } // default to non-eink, override in eink drivers
|
||||
virtual void forceFullRefresh() {} // next refresh will be full for eink
|
||||
virtual void turnOn() = 0;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace DisplayFrameSignature {
|
||||
|
||||
static constexpr uint32_t INITIAL = 2166136261u;
|
||||
|
||||
inline uint32_t append(uint32_t signature, const char *text) {
|
||||
if (text) {
|
||||
while (*text) {
|
||||
signature ^= static_cast<uint8_t>(*text++);
|
||||
signature *= 16777619u;
|
||||
}
|
||||
}
|
||||
|
||||
// Separate adjacent fields so { "ab", "c" } differs from { "a", "bc" }.
|
||||
signature ^= 0xFFu;
|
||||
signature *= 16777619u;
|
||||
return signature;
|
||||
}
|
||||
|
||||
} // namespace DisplayFrameSignature
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace DisplayViewport {
|
||||
|
||||
struct Geometry {
|
||||
int16_t logical_width;
|
||||
int16_t logical_height;
|
||||
int16_t physical_width;
|
||||
int16_t physical_height;
|
||||
|
||||
int16_t mapX(int16_t x) const {
|
||||
return static_cast<int16_t>((static_cast<int32_t>(x) * physical_width) / logical_width);
|
||||
}
|
||||
|
||||
int16_t mapY(int16_t y) const {
|
||||
return static_cast<int16_t>((static_cast<int32_t>(y) * physical_height) / logical_height);
|
||||
}
|
||||
|
||||
uint16_t spanX(int16_t x, int16_t width) const { return static_cast<uint16_t>(mapX(x + width) - mapX(x)); }
|
||||
|
||||
uint16_t spanY(int16_t y, int16_t height) const {
|
||||
return static_cast<uint16_t>(mapY(y + height) - mapY(y));
|
||||
}
|
||||
|
||||
uint16_t logicalWidthForPhysical(uint16_t width) const {
|
||||
return static_cast<uint16_t>((static_cast<uint32_t>(width) * logical_width + physical_width - 1) /
|
||||
physical_width);
|
||||
}
|
||||
};
|
||||
|
||||
inline uint8_t selectTextScale(uint16_t width_at_scale_one, uint8_t preferred_scale, uint8_t minimum_scale,
|
||||
uint16_t available_width) {
|
||||
if (static_cast<uint32_t>(width_at_scale_one) * preferred_scale <= available_width) {
|
||||
return preferred_scale;
|
||||
}
|
||||
return minimum_scale;
|
||||
}
|
||||
|
||||
} // namespace DisplayViewport
|
||||
@@ -0,0 +1,527 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "../RadioActivityWindow.h"
|
||||
#include "DisplayDriver.h"
|
||||
#include "DisplayFrameSignature.h"
|
||||
|
||||
// Observer analytics dashboard for the Heltec V4 R8 TFT targets.
|
||||
//
|
||||
// Fork-owned and self-contained: the role UITasks only pick a layout, hand over
|
||||
// a Context plus a snapshot, and ask for a full frame or a single changed row.
|
||||
// Everything here is host-buildable against DisplayDriver, so the layout, the
|
||||
// formatting and the redraw policy are all covered by test_observer_dashboard.
|
||||
|
||||
namespace ObserverDashboard {
|
||||
|
||||
// ---------------------------------------------------------------- palette ---
|
||||
// Kept local to the dashboard. applyDarkPalette() retunes the shared UIColor
|
||||
// slots at runtime, which is why no display driver needs editing for the theme.
|
||||
|
||||
constexpr ColorVal rgb565(uint8_t r, uint8_t g, uint8_t b) {
|
||||
return (ColorVal)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
|
||||
}
|
||||
|
||||
constexpr ColorVal BG = rgb565(10, 12, 16);
|
||||
constexpr ColorVal HEADER_BG = rgb565(18, 38, 74);
|
||||
constexpr ColorVal HEADER_SUB = rgb565(130, 170, 214);
|
||||
constexpr ColorVal TEXT = rgb565(232, 238, 246);
|
||||
constexpr ColorVal MUTED = rgb565(122, 134, 150);
|
||||
constexpr ColorVal ACCENT = rgb565(64, 176, 240);
|
||||
constexpr ColorVal BAR = rgb565(38, 116, 168);
|
||||
constexpr ColorVal BAR_NOW = rgb565(96, 208, 255);
|
||||
constexpr ColorVal GRID = rgb565(38, 46, 60);
|
||||
constexpr ColorVal GOOD = rgb565(72, 208, 136);
|
||||
constexpr ColorVal WARN = rgb565(248, 176, 72);
|
||||
|
||||
// Retunes the shared colour slots so every screen this UITask draws - boot,
|
||||
// setup portal, reboot, power-off and the dashboard - is coherently dark.
|
||||
inline void applyDarkPalette() {
|
||||
UIColor::window_bkg = BG;
|
||||
UIColor::title_bkg = HEADER_BG;
|
||||
UIColor::title_txt = TEXT;
|
||||
UIColor::primary_txt = TEXT;
|
||||
UIColor::secondary_txt = MUTED;
|
||||
UIColor::warning_txt = WARN;
|
||||
UIColor::popup_bkg = HEADER_BG;
|
||||
UIColor::popup_txt = TEXT;
|
||||
UIColor::corp_blue = ACCENT;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- layout ---
|
||||
// Logical 128x64 coordinates, as the shared DisplayDriver API expects. The two
|
||||
// orientations need separate row pitches: a text row is a fixed 16 physical
|
||||
// pixels, which is 3.2 logical units in portrait (y scale 5) but 4.27 in
|
||||
// landscape (y scale 3.75), so one shared grid would overlap in landscape.
|
||||
|
||||
struct Layout {
|
||||
int16_t margin_x;
|
||||
int16_t right_x; // right edge of the content column (exclusive)
|
||||
int16_t header_h;
|
||||
int16_t header_text_y;
|
||||
int16_t header_sub_y; // second header row for the role label; -1 = same row
|
||||
int16_t radio_y;
|
||||
int16_t window_y;
|
||||
int16_t headline_y;
|
||||
int16_t headline_h;
|
||||
int16_t rate_y;
|
||||
int16_t graph_y;
|
||||
int16_t graph_h; // includes the one-unit baseline at the bottom
|
||||
int16_t rf_y;
|
||||
int16_t status_y;
|
||||
int16_t text_h; // logical height of one size-1 text row
|
||||
int16_t max_chars; // size-1 characters that fit between the margins
|
||||
int16_t max_chars_big; // size-2 characters that fit
|
||||
};
|
||||
|
||||
// 240x320 panel: x scale 1.875, y scale 5, 12x16 glyphs (24x32 at size 2).
|
||||
constexpr Layout portraitLayout() {
|
||||
return Layout{
|
||||
/*margin_x*/ 4, /*right_x*/ 124,
|
||||
/*header_h*/ 9, /*header_text_y*/ 1, /*header_sub_y*/ 5,
|
||||
/*radio_y*/ 11,
|
||||
/*window_y*/ 16,
|
||||
/*headline_y*/ 21, /*headline_h*/ 7,
|
||||
/*rate_y*/ 29,
|
||||
/*graph_y*/ 34, /*graph_h*/ 16,
|
||||
/*rf_y*/ 52,
|
||||
/*status_y*/ 57,
|
||||
/*text_h*/ 4,
|
||||
/*max_chars*/ 18, /*max_chars_big*/ 9};
|
||||
}
|
||||
|
||||
// 320x240 panel: x scale 2.5, y scale 3.75, 12x16 glyphs (30x40 at size 2).
|
||||
constexpr Layout landscapeLayout() {
|
||||
return Layout{
|
||||
/*margin_x*/ 4, /*right_x*/ 124,
|
||||
/*header_h*/ 7, /*header_text_y*/ 1, /*header_sub_y*/ -1,
|
||||
/*radio_y*/ 9,
|
||||
/*window_y*/ 14,
|
||||
/*headline_y*/ 19, /*headline_h*/ 12,
|
||||
/*rate_y*/ 31,
|
||||
/*graph_y*/ 36, /*graph_h*/ 12,
|
||||
/*rf_y*/ 50,
|
||||
/*status_y*/ 56,
|
||||
/*text_h*/ 5,
|
||||
/*max_chars*/ 25, /*max_chars_big*/ 10};
|
||||
}
|
||||
|
||||
inline const Layout& activeLayout() {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
static const Layout layout = portraitLayout();
|
||||
#else
|
||||
static const Layout layout = landscapeLayout();
|
||||
#endif
|
||||
return layout;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- formatting ---
|
||||
// Every value is formatted from integers. Arguments are widened explicitly so
|
||||
// the same code is correct on a 32-bit target and on a 64-bit host.
|
||||
|
||||
inline void formatCompactCount(char* out, size_t n, uint32_t v) {
|
||||
if (v < 10000) {
|
||||
snprintf(out, n, "%lu", (unsigned long)v);
|
||||
} else if (v < 100000) {
|
||||
snprintf(out, n, "%lu.%luk", (unsigned long)(v / 1000), (unsigned long)((v % 1000) / 100));
|
||||
} else if (v < 1000000) {
|
||||
snprintf(out, n, "%luk", (unsigned long)(v / 1000));
|
||||
} else if (v < 100000000) {
|
||||
snprintf(out, n, "%lu.%luM", (unsigned long)(v / 1000000),
|
||||
(unsigned long)((v % 1000000) / 100000));
|
||||
} else {
|
||||
snprintf(out, n, "%luM", (unsigned long)(v / 1000000));
|
||||
}
|
||||
}
|
||||
|
||||
inline void formatCompactBytes(char* out, size_t n, uint32_t v) {
|
||||
if (v < 1024) {
|
||||
snprintf(out, n, "%lu B", (unsigned long)v);
|
||||
return;
|
||||
}
|
||||
if (v < 1048576UL) {
|
||||
uint32_t tenths = (uint32_t)(((uint64_t)v * 10) / 1024);
|
||||
if (tenths < 1000) {
|
||||
snprintf(out, n, "%lu.%lu KB", (unsigned long)(tenths / 10), (unsigned long)(tenths % 10));
|
||||
} else {
|
||||
snprintf(out, n, "%lu KB", (unsigned long)(tenths / 10));
|
||||
}
|
||||
return;
|
||||
}
|
||||
uint32_t tenths = (uint32_t)(((uint64_t)v * 10) / 1048576UL);
|
||||
if (tenths < 1000) {
|
||||
snprintf(out, n, "%lu.%lu MB", (unsigned long)(tenths / 10), (unsigned long)(tenths % 10));
|
||||
} else {
|
||||
snprintf(out, n, "%lu MB", (unsigned long)(tenths / 10));
|
||||
}
|
||||
}
|
||||
|
||||
// One decimal below 100, whole numbers above, so the field cannot grow wide.
|
||||
inline void formatTenths(char* out, size_t n, uint32_t tenths) {
|
||||
if (tenths < 1000) {
|
||||
snprintf(out, n, "%lu.%lu", (unsigned long)(tenths / 10), (unsigned long)(tenths % 10));
|
||||
} else {
|
||||
formatCompactCount(out, n, tenths / 10);
|
||||
}
|
||||
}
|
||||
|
||||
inline void formatSignedTenths(char* out, size_t n, int32_t tenths) {
|
||||
const char* sign = tenths < 0 ? "-" : "+";
|
||||
uint32_t mag = (uint32_t)(tenths < 0 ? -tenths : tenths);
|
||||
snprintf(out, n, "%s%lu.%lu", sign, (unsigned long)(mag / 10), (unsigned long)(mag % 10));
|
||||
}
|
||||
|
||||
// Quantised to the 5 s activity cadence so the string is stable within a tick
|
||||
// and cannot make the status row repaint more often than the panel updates.
|
||||
inline uint32_t quantizeAgeSecs(uint32_t age_ms) { return (age_ms / 5000) * 5; }
|
||||
|
||||
inline void formatAge(char* out, size_t n, uint32_t age_ms, bool valid) {
|
||||
if (!valid) {
|
||||
snprintf(out, n, "--");
|
||||
return;
|
||||
}
|
||||
uint32_t secs = quantizeAgeSecs(age_ms);
|
||||
if (secs < 5) {
|
||||
snprintf(out, n, "now");
|
||||
} else if (secs < 60) {
|
||||
snprintf(out, n, "%lus", (unsigned long)secs);
|
||||
} else if (secs < 3600) {
|
||||
snprintf(out, n, "%lum", (unsigned long)(secs / 60));
|
||||
} else if (secs < 86400) {
|
||||
snprintf(out, n, "%luh", (unsigned long)(secs / 3600));
|
||||
} else {
|
||||
snprintf(out, n, "%lud", (unsigned long)(secs / 86400));
|
||||
}
|
||||
}
|
||||
|
||||
// "910.525 SF7 BW62.5" / "869.618 SF8 BW250" - a trailing ".0" on the
|
||||
// bandwidth would push the widest case past the content column.
|
||||
inline void formatRadioStrip(char* out, size_t n, float freq, uint8_t sf, float bw) {
|
||||
int32_t tenths = (int32_t)(bw * 10.0f + 0.5f);
|
||||
char bw_str[24];
|
||||
if (tenths % 10 == 0) {
|
||||
snprintf(bw_str, sizeof(bw_str), "%ld", (long)(tenths / 10));
|
||||
} else {
|
||||
snprintf(bw_str, sizeof(bw_str), "%ld.%ld", (long)(tenths / 10), (long)(tenths % 10));
|
||||
}
|
||||
snprintf(out, n, "%.3f SF%u BW%s", (double)freq, (unsigned)sf, bw_str);
|
||||
}
|
||||
|
||||
// Trims to a character budget rather than a measured width. The font is fixed
|
||||
// width, so the budget is exact - and DisplayDriver::drawTextEllipsized() must
|
||||
// not be used here: it trims against getTextWidth(), which reports an
|
||||
// over-long string at the portrait driver's *fallback* scale and so stops
|
||||
// trimming while the string is still too wide to draw at full size.
|
||||
inline void fitToChars(char* out, size_t n, const char* src, int max_chars) {
|
||||
if (max_chars < 0) max_chars = 0;
|
||||
if ((size_t)max_chars > n - 1) max_chars = (int)(n - 1);
|
||||
|
||||
size_t len = src ? strlen(src) : 0;
|
||||
if (len <= (size_t)max_chars) {
|
||||
memcpy(out, src ? src : "", len);
|
||||
out[len] = 0;
|
||||
return;
|
||||
}
|
||||
if (max_chars <= 3) {
|
||||
memcpy(out, src, (size_t)max_chars);
|
||||
out[max_chars] = 0;
|
||||
return;
|
||||
}
|
||||
memcpy(out, src, (size_t)max_chars - 3);
|
||||
memcpy(out + max_chars - 3, "...", 4);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- row content --
|
||||
|
||||
enum Row { ROW_WINDOW = 0, ROW_HEADLINE, ROW_RATE, ROW_GRAPH, ROW_RF, ROW_STATUS, ROW_COUNT };
|
||||
|
||||
struct Context {
|
||||
const char* node_name;
|
||||
const char* role_label; // "REPEATER" / "ROOM SERVER"
|
||||
float freq;
|
||||
uint8_t sf;
|
||||
float bw;
|
||||
bool link_up;
|
||||
};
|
||||
|
||||
struct RowText {
|
||||
char left[24];
|
||||
char right[24];
|
||||
ColorVal left_color;
|
||||
ColorVal right_color;
|
||||
};
|
||||
|
||||
inline void composeRow(Row row, const Context& ctx, const RadioActivitySnapshot& s, RowText* out) {
|
||||
out->left[0] = out->right[0] = 0;
|
||||
out->left_color = TEXT;
|
||||
out->right_color = MUTED;
|
||||
|
||||
// All compact helpers fit inside 15 visible characters. Keeping this
|
||||
// intermediate bound tighter than RowText also lets the compiler prove that
|
||||
// adding row labels cannot truncate the destination.
|
||||
char scratch[16];
|
||||
switch (row) {
|
||||
case ROW_WINDOW:
|
||||
if (s.isWarmingUp()) {
|
||||
snprintf(out->left, sizeof(out->left), "LIVE %lum", (unsigned long)s.warmupMinutes());
|
||||
} else {
|
||||
snprintf(out->left, sizeof(out->left), "LAST 20m");
|
||||
}
|
||||
out->left_color = MUTED;
|
||||
if (s.peak_per_min > 0) {
|
||||
formatCompactCount(scratch, sizeof(scratch), s.peak_per_min);
|
||||
snprintf(out->right, sizeof(out->right), "max %s/m", scratch);
|
||||
}
|
||||
break;
|
||||
|
||||
case ROW_HEADLINE:
|
||||
if (s.isEmpty()) {
|
||||
snprintf(out->left, sizeof(out->left), "No RF yet");
|
||||
out->left_color = MUTED;
|
||||
} else {
|
||||
formatCompactCount(scratch, sizeof(scratch), s.packets);
|
||||
snprintf(out->left, sizeof(out->left), "%s pkt", scratch);
|
||||
out->left_color = BAR_NOW;
|
||||
}
|
||||
break;
|
||||
|
||||
case ROW_RATE:
|
||||
formatCompactBytes(out->left, sizeof(out->left), s.wire_bytes);
|
||||
formatTenths(scratch, sizeof(scratch), s.packetsPerMinuteX10());
|
||||
snprintf(out->right, sizeof(out->right), "%s/min", scratch);
|
||||
if (s.isEmpty()) {
|
||||
out->left_color = MUTED;
|
||||
}
|
||||
break;
|
||||
|
||||
case ROW_RF:
|
||||
if (s.isEmpty()) {
|
||||
snprintf(out->left, sizeof(out->left), "SNR --");
|
||||
out->left_color = MUTED;
|
||||
} else {
|
||||
int32_t snr = s.avgSnrX10();
|
||||
formatSignedTenths(scratch, sizeof(scratch), snr);
|
||||
snprintf(out->left, sizeof(out->left), "SNR %s", scratch);
|
||||
out->left_color = snr >= 0 ? GOOD : (snr >= -70 ? TEXT : WARN);
|
||||
}
|
||||
{
|
||||
uint32_t air = s.airtimePercentX10();
|
||||
formatTenths(scratch, sizeof(scratch), air);
|
||||
snprintf(out->right, sizeof(out->right), "AIR %s%%", scratch);
|
||||
out->right_color = air >= 100 ? WARN : MUTED;
|
||||
}
|
||||
break;
|
||||
|
||||
case ROW_STATUS:
|
||||
formatAge(scratch, sizeof(scratch), s.last_packet_age_ms, s.has_last_packet);
|
||||
snprintf(out->left, sizeof(out->left), "RX %s", scratch);
|
||||
out->left_color = s.has_last_packet ? TEXT : MUTED;
|
||||
snprintf(out->right, sizeof(out->right), ctx.link_up ? "WiFi OK" : "WiFi --");
|
||||
out->right_color = ctx.link_up ? GOOD : WARN;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
inline int16_t rowY(const Layout& l, Row row) {
|
||||
switch (row) {
|
||||
case ROW_WINDOW: return l.window_y;
|
||||
case ROW_HEADLINE: return l.headline_y;
|
||||
case ROW_RATE: return l.rate_y;
|
||||
case ROW_GRAPH: return l.graph_y;
|
||||
case ROW_RF: return l.rf_y;
|
||||
default: return l.status_y;
|
||||
}
|
||||
}
|
||||
|
||||
inline int16_t rowH(const Layout& l, Row row) {
|
||||
if (row == ROW_HEADLINE) return l.headline_h;
|
||||
if (row == ROW_GRAPH) return l.graph_h;
|
||||
return l.text_h;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- the graph --
|
||||
|
||||
// Bar heights in logical units, oldest first. Any minute with traffic rounds up
|
||||
// to at least one unit; empty minutes stay empty.
|
||||
inline void barHeights(const Layout& l, const RadioActivitySnapshot& s,
|
||||
uint8_t out[RADIO_ACTIVITY_BUCKETS]) {
|
||||
uint16_t scale = s.peak_per_min > 0 ? s.peak_per_min : 1;
|
||||
int16_t max_h = l.graph_h - 1; // the last unit is the baseline
|
||||
for (int i = 0; i < RADIO_ACTIVITY_BUCKETS; i++) {
|
||||
uint32_t v = s.buckets[i];
|
||||
out[i] = v == 0 ? 0 : (uint8_t)((v * max_h + scale - 1) / scale);
|
||||
}
|
||||
}
|
||||
|
||||
inline int16_t barSlot(const Layout& l) {
|
||||
return (int16_t)((l.right_x - l.margin_x) / RADIO_ACTIVITY_BUCKETS);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- signatures ---
|
||||
// One signature per row, computed from exactly what is drawn, so a repaint
|
||||
// happens only where the pixels actually differ.
|
||||
|
||||
inline uint32_t rowSignature(const Layout& l, Row row, const Context& ctx,
|
||||
const RadioActivitySnapshot& s) {
|
||||
uint32_t sig = DisplayFrameSignature::INITIAL;
|
||||
if (row == ROW_GRAPH) {
|
||||
uint8_t h[RADIO_ACTIVITY_BUCKETS];
|
||||
barHeights(l, s, h);
|
||||
char buf[4 * RADIO_ACTIVITY_BUCKETS];
|
||||
size_t p = 0;
|
||||
for (int i = 0; i < RADIO_ACTIVITY_BUCKETS && p + 4 < sizeof(buf); i++) {
|
||||
p += (size_t)snprintf(buf + p, sizeof(buf) - p, "%u,", (unsigned)h[i]);
|
||||
}
|
||||
return DisplayFrameSignature::append(sig, buf);
|
||||
}
|
||||
|
||||
RowText t;
|
||||
composeRow(row, ctx, s, &t);
|
||||
sig = DisplayFrameSignature::append(sig, t.left);
|
||||
return DisplayFrameSignature::append(sig, t.right);
|
||||
}
|
||||
|
||||
inline void allRowSignatures(const Layout& l, const Context& ctx, const RadioActivitySnapshot& s,
|
||||
uint32_t out[ROW_COUNT]) {
|
||||
for (int r = 0; r < ROW_COUNT; r++) out[r] = rowSignature(l, (Row)r, ctx, s);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ render --
|
||||
|
||||
// Right-hand text is measured and placed first, then the left text is
|
||||
// ellipsized into whatever column is left, so the two can never collide.
|
||||
//
|
||||
// The right edge gets a one-unit gutter: getTextWidth() converts physical
|
||||
// glyph widths back to logical units and rounds, so anchoring flush at right_x
|
||||
// can land a pixel past it.
|
||||
inline void drawPair(DisplayDriver& d, const Layout& l, int16_t y, const RowText& t,
|
||||
int max_chars) {
|
||||
int right_len = (int)strlen(t.right);
|
||||
if (right_len > 0) {
|
||||
int16_t rw = (int16_t)d.getTextWidth(t.right);
|
||||
d.setColor(t.right_color);
|
||||
d.setCursor((int16_t)(l.right_x - rw - 1), y);
|
||||
d.print(t.right);
|
||||
}
|
||||
|
||||
int budget = max_chars - (right_len > 0 ? right_len + 1 : 0);
|
||||
if (t.left[0] && budget > 0) {
|
||||
char fitted[32];
|
||||
fitToChars(fitted, sizeof(fitted), t.left, budget);
|
||||
d.setColor(t.left_color);
|
||||
d.setCursor(l.margin_x, y);
|
||||
d.print(fitted);
|
||||
}
|
||||
}
|
||||
|
||||
inline void clearRow(DisplayDriver& d, const Layout& l, Row row) {
|
||||
d.setColor(BG);
|
||||
d.fillRect(l.margin_x, rowY(l, row), l.right_x - l.margin_x, rowH(l, row));
|
||||
}
|
||||
|
||||
inline void drawGraph(DisplayDriver& d, const Layout& l, const RadioActivitySnapshot& s) {
|
||||
int16_t base_y = (int16_t)(l.graph_y + l.graph_h - 1);
|
||||
d.setColor(GRID);
|
||||
d.fillRect(l.margin_x, base_y, l.right_x - l.margin_x, 1);
|
||||
|
||||
uint8_t h[RADIO_ACTIVITY_BUCKETS];
|
||||
barHeights(l, s, h);
|
||||
int16_t slot = barSlot(l);
|
||||
for (int i = 0; i < RADIO_ACTIVITY_BUCKETS; i++) {
|
||||
if (h[i] == 0) continue;
|
||||
d.setColor(i == RADIO_ACTIVITY_BUCKETS - 1 ? BAR_NOW : BAR);
|
||||
d.fillRect((int16_t)(l.margin_x + i * slot), (int16_t)(base_y - h[i]), (int16_t)(slot - 1),
|
||||
h[i]);
|
||||
}
|
||||
}
|
||||
|
||||
inline void drawRow(DisplayDriver& d, const Layout& l, Row row, const Context& ctx,
|
||||
const RadioActivitySnapshot& s, bool clear_first) {
|
||||
if (clear_first) clearRow(d, l, row);
|
||||
|
||||
if (row == ROW_GRAPH) {
|
||||
drawGraph(d, l, s);
|
||||
return;
|
||||
}
|
||||
|
||||
RowText t;
|
||||
composeRow(row, ctx, s, &t);
|
||||
d.setTextSize(row == ROW_HEADLINE ? 2 : 1);
|
||||
drawPair(d, l, rowY(l, row), t, row == ROW_HEADLINE ? l.max_chars_big : l.max_chars);
|
||||
if (row == ROW_HEADLINE) d.setTextSize(1);
|
||||
}
|
||||
|
||||
inline void drawHeader(DisplayDriver& d, const Layout& l, const Context& ctx) {
|
||||
d.setColor(HEADER_BG);
|
||||
d.fillRect(0, 0, 128, l.header_h);
|
||||
d.setTextSize(1);
|
||||
|
||||
RowText t{};
|
||||
t.left_color = TEXT;
|
||||
t.right_color = HEADER_SUB;
|
||||
snprintf(t.left, sizeof(t.left), "%s", ctx.node_name ? ctx.node_name : "");
|
||||
snprintf(t.right, sizeof(t.right), "%s", ctx.role_label ? ctx.role_label : "");
|
||||
|
||||
if (l.header_sub_y < 0) {
|
||||
drawPair(d, l, l.header_text_y, t, l.max_chars); // both fit on one line
|
||||
return;
|
||||
}
|
||||
|
||||
// Narrow panel: the node name keeps the whole width and the role drops to a
|
||||
// second line, rather than the name being ellipsized down to a few letters.
|
||||
RowText name{};
|
||||
name.left_color = t.left_color;
|
||||
memcpy(name.left, t.left, sizeof(name.left));
|
||||
drawPair(d, l, l.header_text_y, name, l.max_chars);
|
||||
|
||||
RowText role{};
|
||||
role.left_color = t.right_color;
|
||||
memcpy(role.left, t.right, sizeof(role.left));
|
||||
drawPair(d, l, l.header_sub_y, role, l.max_chars);
|
||||
}
|
||||
|
||||
inline void drawRadioStrip(DisplayDriver& d, const Layout& l, const Context& ctx) {
|
||||
char tmp[32];
|
||||
formatRadioStrip(tmp, sizeof(tmp), ctx.freq, ctx.sf, ctx.bw);
|
||||
char fitted[32];
|
||||
fitToChars(fitted, sizeof(fitted), tmp, l.max_chars);
|
||||
d.setTextSize(1);
|
||||
d.setColor(MUTED);
|
||||
d.setCursor(l.margin_x, l.radio_y);
|
||||
d.print(fitted);
|
||||
}
|
||||
|
||||
// Complete repaint. The caller has already run startFrame(), which clears to
|
||||
// UIColor::window_bkg - the dark background applyDarkPalette() installed.
|
||||
inline void drawFull(DisplayDriver& d, const Layout& l, const Context& ctx,
|
||||
const RadioActivitySnapshot& s) {
|
||||
drawHeader(d, l, ctx);
|
||||
drawRadioStrip(d, l, ctx);
|
||||
for (int r = 0; r < ROW_COUNT; r++) drawRow(d, l, (Row)r, ctx, s, false);
|
||||
}
|
||||
|
||||
// Repaints only the rows whose signature moved. Never touches the header, the
|
||||
// radio strip, or anything outside the analytics rows, so no startFrame() and
|
||||
// no whole-screen clear is involved.
|
||||
inline bool drawChangedRows(DisplayDriver& d, const Layout& l, const Context& ctx,
|
||||
const RadioActivitySnapshot& s, uint32_t signatures[ROW_COUNT]) {
|
||||
uint32_t fresh[ROW_COUNT];
|
||||
allRowSignatures(l, ctx, s, fresh);
|
||||
|
||||
bool drew = false;
|
||||
for (int r = 0; r < ROW_COUNT; r++) {
|
||||
if (fresh[r] == signatures[r]) continue;
|
||||
drawRow(d, l, (Row)r, ctx, s, true);
|
||||
signatures[r] = fresh[r];
|
||||
drew = true;
|
||||
}
|
||||
return drew;
|
||||
}
|
||||
|
||||
} // namespace ObserverDashboard
|
||||
@@ -25,10 +25,20 @@ bool SSD1306Display::begin() {
|
||||
const bool started = display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS,
|
||||
true, false)
|
||||
&& i2c_probe(Wire, DISPLAY_ADDRESS);
|
||||
if (started) setRotationDegrees(0);
|
||||
if (started) {
|
||||
_panel_ready = true;
|
||||
applyRotation();
|
||||
}
|
||||
return started;
|
||||
}
|
||||
|
||||
void SSD1306Display::applyRotation() {
|
||||
display.setRotation((_base_rotation + (_flipped ? 2 : 0)) & 3);
|
||||
setDimensions(display.width(), display.height());
|
||||
display.clearDisplay();
|
||||
display.display();
|
||||
}
|
||||
|
||||
bool SSD1306Display::setRotationDegrees(uint16_t degrees) {
|
||||
uint8_t rotation;
|
||||
switch (degrees) {
|
||||
@@ -45,13 +55,17 @@ bool SSD1306Display::setRotationDegrees(uint16_t degrees) {
|
||||
default: return false;
|
||||
}
|
||||
|
||||
display.setRotation(rotation);
|
||||
setDimensions(display.width(), display.height());
|
||||
display.clearDisplay();
|
||||
display.display();
|
||||
_base_rotation = rotation;
|
||||
if (_panel_ready) applyRotation();
|
||||
return true;
|
||||
}
|
||||
|
||||
void SSD1306Display::setFlipped(bool flipped) {
|
||||
if (_flipped == flipped) return;
|
||||
_flipped = flipped;
|
||||
if (_panel_ready) applyRotation();
|
||||
}
|
||||
|
||||
void SSD1306Display::turnOn() {
|
||||
if (!_isOn) {
|
||||
if (_peripher_power) _peripher_power->claim();
|
||||
@@ -69,6 +83,7 @@ void SSD1306Display::turnOff() {
|
||||
digitalWrite(PIN_OLED_RESET, LOW);
|
||||
#endif
|
||||
_peripher_power->release();
|
||||
_panel_ready = false;
|
||||
}
|
||||
_isOn = false;
|
||||
}
|
||||
|
||||
@@ -18,10 +18,18 @@
|
||||
class SSD1306Display : public DisplayDriver {
|
||||
Adafruit_SSD1306 display;
|
||||
bool _isOn;
|
||||
bool _panel_ready = false;
|
||||
bool _flipped = false;
|
||||
#ifdef DISPLAY_ROTATION
|
||||
uint8_t _base_rotation = DISPLAY_ROTATION & 3;
|
||||
#else
|
||||
uint8_t _base_rotation = 0;
|
||||
#endif
|
||||
uint8_t _color;
|
||||
RefCountedDigitalPin* _peripher_power;
|
||||
|
||||
bool i2c_probe(TwoWire& wire, uint8_t addr);
|
||||
void applyRotation();
|
||||
public:
|
||||
SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(128, 64),
|
||||
display(128, 64, &Wire, PIN_OLED_RESET),
|
||||
@@ -34,6 +42,7 @@ public:
|
||||
bool isOn() override { return _isOn; }
|
||||
bool supportsRotation() const override { return true; }
|
||||
bool setRotationDegrees(uint16_t degrees) override;
|
||||
void setFlipped(bool flipped) override;
|
||||
void turnOn() override;
|
||||
void turnOff() override;
|
||||
void clear() override;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#include "ST7789LCDDisplay.h"
|
||||
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
#include "DisplayViewport.h"
|
||||
#endif
|
||||
|
||||
#ifndef PIN_TFT_MISO
|
||||
#define PIN_TFT_MISO -1
|
||||
#endif
|
||||
@@ -19,6 +23,29 @@
|
||||
#define DISPLAY_WIDTH 240
|
||||
#define DISPLAY_HEIGHT 320
|
||||
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
#ifndef ST7789_PORTRAIT_TEXT_SCALE
|
||||
#define ST7789_PORTRAIT_TEXT_SCALE 2
|
||||
#endif
|
||||
|
||||
static DisplayViewport::Geometry portraitViewport(int16_t physical_width, int16_t physical_height) {
|
||||
return {128, 64, physical_width, physical_height};
|
||||
}
|
||||
#endif
|
||||
|
||||
// The compiled orientation, optionally turned 180 degrees by `display.flip`.
|
||||
// Adding 2 keeps portrait portrait and landscape landscape, so the viewport
|
||||
// geometry below never has to change with it.
|
||||
uint8_t ST7789LCDDisplay::effectiveRotation() const {
|
||||
return (uint8_t)((DISPLAY_ROTATION + (_flipped ? 2 : 0)) & 3);
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::setFlipped(bool flipped) {
|
||||
if (_flipped == flipped) return;
|
||||
_flipped = flipped;
|
||||
if (_panel_ready) display.setRotation(effectiveRotation());
|
||||
}
|
||||
|
||||
bool ST7789LCDDisplay::i2c_probe(TwoWire& wire, uint8_t addr) {
|
||||
return true;
|
||||
}
|
||||
@@ -36,6 +63,22 @@ ColorVal UIColor::corp_blue = 0x001A;
|
||||
|
||||
bool ST7789LCDDisplay::begin() {
|
||||
if (!_isOn) {
|
||||
#ifdef HELTEC_V4_R8_TFT
|
||||
// turnOff() leaves this panel configured and powered - its reset line is
|
||||
// shared with the touch controller, so it is never parked low - which makes
|
||||
// waking just a backlight switch. Re-running the init below would re-enter
|
||||
// SPI setup and pulse GPIO 21, resetting the touch controller on every wake
|
||||
// and stalling the UI loop for ~500 ms of reset delays.
|
||||
if (_panel_ready) {
|
||||
if (_peripher_power) _peripher_power->claim();
|
||||
if (PIN_TFT_LEDA_CTL != -1) {
|
||||
digitalWrite(PIN_TFT_LEDA_CTL, PIN_TFT_LEDA_CTL_ACTIVE);
|
||||
}
|
||||
_isOn = true;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_peripher_power) {
|
||||
_peripher_power->claim();
|
||||
#ifdef HELTEC_V4_R8_TFT
|
||||
@@ -58,13 +101,19 @@ bool ST7789LCDDisplay::begin() {
|
||||
#endif
|
||||
|
||||
display.init(DISPLAY_WIDTH, DISPLAY_HEIGHT);
|
||||
display.setRotation(DISPLAY_ROTATION);
|
||||
display.setRotation(effectiveRotation());
|
||||
|
||||
display.setSPISpeed(40e6);
|
||||
|
||||
display.fillScreen(ST77XX_BLACK);
|
||||
display.setTextColor(ST77XX_WHITE);
|
||||
display.setTextSize(2 * DISPLAY_SCALE_X);
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
_logical_text_size = 1;
|
||||
display.setTextSize(ST7789_PORTRAIT_TEXT_SCALE);
|
||||
display.setTextWrap(false);
|
||||
#else
|
||||
display.setTextSize(2 * DISPLAY_SCALE_X);
|
||||
#endif
|
||||
display.cp437(true); // Use full 256 char 'Code Page 437' font
|
||||
|
||||
#ifdef HELTEC_V4_R8_TFT
|
||||
@@ -73,6 +122,7 @@ bool ST7789LCDDisplay::begin() {
|
||||
}
|
||||
#endif
|
||||
|
||||
_panel_ready = true;
|
||||
_isOn = true;
|
||||
}
|
||||
|
||||
@@ -92,13 +142,18 @@ void ST7789LCDDisplay::turnOff() {
|
||||
digitalWrite(PIN_TFT_LEDA_CTL, HIGH);
|
||||
#endif
|
||||
}
|
||||
#ifndef HELTEC_V4_R8_TFT
|
||||
if (PIN_TFT_RST != -1) {
|
||||
digitalWrite(PIN_TFT_RST, LOW);
|
||||
}
|
||||
#ifndef HELTEC_V4_R8_TFT
|
||||
if (PIN_TFT_LEDA_CTL != -1) {
|
||||
digitalWrite(PIN_TFT_LEDA_CTL, LOW);
|
||||
}
|
||||
#else
|
||||
// On the V4 R8 Expansion Kit this reset line is shared with the touch
|
||||
// panel's TP_RST, so parking it low would hold the touch controller in
|
||||
// reset for as long as the display is off. Killing the backlight is what
|
||||
// "off" means for this LCD anyway.
|
||||
#endif
|
||||
_isOn = false;
|
||||
|
||||
@@ -113,12 +168,22 @@ void ST7789LCDDisplay::clear() {
|
||||
void ST7789LCDDisplay::startFrame(ColorVal bkg) {
|
||||
display.fillScreen(bkg);
|
||||
display.setTextColor(_color = UIColor::primary_txt);
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
_logical_text_size = 1;
|
||||
display.setTextSize(ST7789_PORTRAIT_TEXT_SCALE);
|
||||
#else
|
||||
display.setTextSize(1 * DISPLAY_SCALE_X); // This one affects size of Please wait... message
|
||||
#endif
|
||||
display.cp437(true); // Use full 256 char 'Code Page 437' font
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::setTextSize(int sz) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
_logical_text_size = sz > 0 ? static_cast<uint8_t>(sz) : 1;
|
||||
display.setTextSize(_logical_text_size * ST7789_PORTRAIT_TEXT_SCALE);
|
||||
#else
|
||||
display.setTextSize(sz * DISPLAY_SCALE_X);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::setColor(ColorVal c) {
|
||||
@@ -126,24 +191,70 @@ void ST7789LCDDisplay::setColor(ColorVal c) {
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::setCursor(int x, int y) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
DisplayViewport::Geometry viewport = portraitViewport(display.width(), display.height());
|
||||
display.setCursor(viewport.mapX(x), viewport.mapY(y));
|
||||
#else
|
||||
display.setCursor(x * DISPLAY_SCALE_X, y * DISPLAY_SCALE_Y);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::print(const char* str) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
int16_t cursor_x = display.getCursorX();
|
||||
if (cursor_x < 0) {
|
||||
cursor_x = 0;
|
||||
display.setCursor(cursor_x, display.getCursorY());
|
||||
}
|
||||
if (cursor_x >= display.width()) return;
|
||||
|
||||
printFitted(str, static_cast<uint16_t>(display.width() - cursor_x));
|
||||
#else
|
||||
display.print(str);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::fillRect(int x, int y, int w, int h) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
DisplayViewport::Geometry viewport = portraitViewport(display.width(), display.height());
|
||||
display.fillRect(viewport.mapX(x), viewport.mapY(y), viewport.spanX(x, w), viewport.spanY(y, h), _color);
|
||||
#else
|
||||
display.fillRect(x * DISPLAY_SCALE_X, y * DISPLAY_SCALE_Y, w * DISPLAY_SCALE_X, h * DISPLAY_SCALE_Y, _color);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::drawRect(int x, int y, int w, int h) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
DisplayViewport::Geometry viewport = portraitViewport(display.width(), display.height());
|
||||
display.drawRect(viewport.mapX(x), viewport.mapY(y), viewport.spanX(x, w), viewport.spanY(y, h), _color);
|
||||
#else
|
||||
display.drawRect(x * DISPLAY_SCALE_X, y * DISPLAY_SCALE_Y, w * DISPLAY_SCALE_X, h * DISPLAY_SCALE_Y, _color);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::drawXbm(int x, int y, const uint8_t* bits, int w, int h) {
|
||||
uint8_t byteWidth = (w + 7) / 8;
|
||||
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
DisplayViewport::Geometry viewport = portraitViewport(display.width(), display.height());
|
||||
int16_t physical_y = viewport.mapY(y);
|
||||
|
||||
for (int j = 0; j < h; j++) {
|
||||
// Scale both bitmap axes from the logical X ratio so logo pixels stay square.
|
||||
int16_t y0 = physical_y + viewport.mapX(j);
|
||||
int16_t y1 = physical_y + viewport.mapX(j + 1);
|
||||
for (int i = 0; i < w; i++) {
|
||||
uint8_t byte = bits[j * byteWidth + i / 8];
|
||||
bool pixelOn = byte & (0x80 >> (i & 7));
|
||||
|
||||
if (pixelOn) {
|
||||
int16_t x0 = viewport.mapX(x + i);
|
||||
int16_t x1 = viewport.mapX(x + i + 1);
|
||||
display.fillRect(x0, y0, x1 - x0, y1 - y0, _color);
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (int j = 0; j < h; j++) {
|
||||
for (int i = 0; i < w; i++) {
|
||||
uint8_t byte = bits[j * byteWidth + i / 8];
|
||||
@@ -158,16 +269,74 @@ void ST7789LCDDisplay::drawXbm(int x, int y, const uint8_t* bits, int w, int h)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
uint16_t ST7789LCDDisplay::getTextWidth(const char* str) {
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
uint8_t physical_scale = selectTextScale(str, display.width());
|
||||
uint16_t physical_width = measureTextWidth(str, physical_scale);
|
||||
if (physical_width > display.width()) physical_width = display.width();
|
||||
|
||||
DisplayViewport::Geometry viewport = portraitViewport(display.width(), display.height());
|
||||
return viewport.logicalWidthForPhysical(physical_width);
|
||||
#else
|
||||
int16_t x1, y1;
|
||||
uint16_t w, h;
|
||||
display.getTextBounds(str, 0, 0, &x1, &y1, &w, &h);
|
||||
|
||||
return w / DISPLAY_SCALE_X;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
uint16_t ST7789LCDDisplay::measureTextWidth(const char* str, uint8_t physical_scale) {
|
||||
int16_t x1, y1;
|
||||
uint16_t w, h;
|
||||
display.setTextSize(physical_scale);
|
||||
display.getTextBounds(str, 0, 0, &x1, &y1, &w, &h);
|
||||
return w;
|
||||
}
|
||||
|
||||
uint8_t ST7789LCDDisplay::selectTextScale(const char* str, uint16_t available_width) {
|
||||
uint16_t width_at_scale_one = measureTextWidth(str, 1);
|
||||
uint8_t preferred_scale = _logical_text_size * ST7789_PORTRAIT_TEXT_SCALE;
|
||||
return DisplayViewport::selectTextScale(width_at_scale_one, preferred_scale, _logical_text_size,
|
||||
available_width);
|
||||
}
|
||||
|
||||
void ST7789LCDDisplay::printFitted(const char* str, uint16_t available_width) {
|
||||
if (!str || available_width == 0) return;
|
||||
|
||||
uint8_t physical_scale = selectTextScale(str, available_width);
|
||||
if (measureTextWidth(str, physical_scale) <= available_width) {
|
||||
display.print(str);
|
||||
return;
|
||||
}
|
||||
|
||||
static const char* ellipsis = "...";
|
||||
uint16_t ellipsis_width = measureTextWidth(ellipsis, physical_scale);
|
||||
if (ellipsis_width > available_width) return;
|
||||
|
||||
char fitted[256];
|
||||
size_t len = strlen(str);
|
||||
if (len > sizeof(fitted) - 4) len = sizeof(fitted) - 4;
|
||||
memcpy(fitted, str, len);
|
||||
fitted[len] = 0;
|
||||
|
||||
while (len > 0 && measureTextWidth(fitted, physical_scale) + ellipsis_width > available_width) {
|
||||
--len;
|
||||
while (len > 0 && (static_cast<uint8_t>(fitted[len]) & 0xC0) == 0x80)
|
||||
--len;
|
||||
fitted[len] = 0;
|
||||
}
|
||||
|
||||
memcpy(fitted + len, ellipsis, 4);
|
||||
display.setTextSize(physical_scale);
|
||||
display.print(fitted);
|
||||
}
|
||||
#endif
|
||||
|
||||
void ST7789LCDDisplay::endFrame() {
|
||||
// display.display();
|
||||
}
|
||||
@@ -13,9 +13,20 @@ class ST7789LCDDisplay : public DisplayDriver {
|
||||
#endif
|
||||
Adafruit_ST7789 display;
|
||||
bool _isOn;
|
||||
bool _panel_ready = false; // panel has been configured at least once
|
||||
bool _flipped = false;
|
||||
uint16_t _color;
|
||||
RefCountedDigitalPin* _peripher_power;
|
||||
|
||||
#ifdef ST7789_PORTRAIT_PROFILE
|
||||
uint8_t _logical_text_size = 1;
|
||||
|
||||
uint16_t measureTextWidth(const char* str, uint8_t physical_scale);
|
||||
uint8_t selectTextScale(const char* str, uint16_t available_width);
|
||||
void printFitted(const char* str, uint16_t available_width);
|
||||
#endif
|
||||
|
||||
uint8_t effectiveRotation() const;
|
||||
bool i2c_probe(TwoWire& wire, uint8_t addr);
|
||||
public:
|
||||
#ifdef USE_PIN_TFT
|
||||
@@ -48,6 +59,7 @@ public:
|
||||
void turnOff() override;
|
||||
void clear() override;
|
||||
void startFrame(ColorVal bkg = UIColor::window_bkg) override;
|
||||
void setFlipped(bool flipped) override;
|
||||
void setTextSize(int sz) override;
|
||||
void setColor(ColorVal c) override;
|
||||
void setCursor(int x, int y) override;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// Debounced rising-edge detector for a polled touch panel.
|
||||
//
|
||||
// Pure logic: no Arduino, no I2C. The caller polls the panel and hands over a
|
||||
// raw "finger down" reading; this decides when that counts as a new tap. All
|
||||
// elapsed-time comparisons are unsigned subtractions, so millis() rollover is
|
||||
// a non-event.
|
||||
|
||||
// Must exceed the caller's poll interval, or a state change is confirmed by the
|
||||
// very next sample and the debounce does nothing. At the 50 ms touch poll this
|
||||
// requires two consecutive consistent reads, so one NACK or short read during a
|
||||
// continuous touch cannot fake a release (and therefore a second tap).
|
||||
#ifndef TOUCH_TAP_DEBOUNCE_MS
|
||||
#define TOUCH_TAP_DEBOUNCE_MS 80
|
||||
#endif
|
||||
|
||||
// Ignores a second tap arriving this soon after an accepted one, so a bouncy
|
||||
// panel or a slightly long press cannot toggle the display twice.
|
||||
#ifndef TOUCH_TAP_MIN_GAP_MS
|
||||
#define TOUCH_TAP_MIN_GAP_MS 400
|
||||
#endif
|
||||
|
||||
class TouchTapDetector {
|
||||
public:
|
||||
TouchTapDetector() { reset(0); }
|
||||
|
||||
void reset(uint32_t now_ms = 0) {
|
||||
_raw = false;
|
||||
_stable = false;
|
||||
_changed_at = now_ms;
|
||||
_last_tap = now_ms;
|
||||
_tapped_before = false;
|
||||
}
|
||||
|
||||
// Returns true exactly once per accepted finger-down.
|
||||
bool update(uint32_t now_ms, bool pressed) {
|
||||
if (pressed != _raw) { // reading moved; restart the settling window
|
||||
_raw = pressed;
|
||||
_changed_at = now_ms;
|
||||
return false;
|
||||
}
|
||||
if (now_ms - _changed_at < TOUCH_TAP_DEBOUNCE_MS) return false; // not settled
|
||||
if (_raw == _stable) return false; // nothing new
|
||||
|
||||
_stable = _raw;
|
||||
if (!_stable) return false; // this is the release, not a tap
|
||||
|
||||
if (_tapped_before && (now_ms - _last_tap) < TOUCH_TAP_MIN_GAP_MS) return false;
|
||||
_last_tap = now_ms;
|
||||
_tapped_before = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isTouched() const { return _stable; }
|
||||
|
||||
private:
|
||||
uint32_t _changed_at;
|
||||
uint32_t _last_tap;
|
||||
bool _raw;
|
||||
bool _stable;
|
||||
bool _tapped_before;
|
||||
};
|
||||
Reference in new issue
Block a user