From 3b1e34efa13f4ee3813426b39b9ad636e9e23ffa Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Sat, 26 Nov 2022 20:50:00 +0100 Subject: [PATCH 001/119] Refrain from transmitting if duty cycle exceeded --- src/airtime.cpp | 14 ++++++++++++++ src/airtime.h | 2 ++ src/mesh/NodeDB.cpp | 1 + src/mesh/Router.cpp | 13 +++++++++++++ 4 files changed, 30 insertions(+) diff --git a/src/airtime.cpp b/src/airtime.cpp index fed4ef8aa..1c2fb3233 100644 --- a/src/airtime.cpp +++ b/src/airtime.cpp @@ -117,6 +117,20 @@ float AirTime::utilizationTXPercent() return (float(sum) / float(MS_IN_HOUR)) * 100; } +// Get the amount of minutes we have to be silent before we can send again +uint8_t AirTime::getSilentMinutes(float txPercent, float dutyCycle) +{ + float newTxPercent = txPercent; + for (int8_t i = MINUTES_IN_HOUR-1; i >= 0; --i) { + newTxPercent -= ((float)this->utilizationTX[i] / (MS_IN_MINUTE * MINUTES_IN_HOUR / 100)); + if (newTxPercent < dutyCycle) + return MINUTES_IN_HOUR-1-i; + } + + return MINUTES_IN_HOUR; +} + + AirTime::AirTime() : concurrency::OSThread("AirTime"),airtimes({}) { } diff --git a/src/airtime.h b/src/airtime.h index f6b9bdcb5..3f38f39f8 100644 --- a/src/airtime.h +++ b/src/airtime.h @@ -29,6 +29,7 @@ #define PERIODS_TO_LOG 8 #define MINUTES_IN_HOUR 60 #define SECONDS_IN_MINUTE 60 +#define MS_IN_MINUTE (SECONDS_IN_MINUTE * 1000) #define MS_IN_HOUR (MINUTES_IN_HOUR * SECONDS_IN_MINUTE * 1000) @@ -57,6 +58,7 @@ class AirTime : private concurrency::OSThread uint32_t getSecondsPerPeriod(); uint32_t getSecondsSinceBoot(); uint32_t *airtimeReport(reportTypes reportType); + uint8_t getSilentMinutes(float txPercent, float dutyCycle); private: bool firstTime = true; diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 6b2d5bfb3..c30542def 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -162,6 +162,7 @@ void NodeDB::installDefaultConfig() config.has_network = true; config.has_bluetooth = true; config.lora.tx_enabled = true; // FIXME: maybe false in the future, and setting region to enable it. (unset region forces it off) + config.lora.override_duty_cycle = false; config.lora.region = Config_LoRaConfig_RegionCode_UNSET; config.lora.modem_preset = Config_LoRaConfig_ModemPreset_LONG_FAST; config.lora.hop_limit = HOP_RELIABLE; diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index e0746bdd9..fd69aa492 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -2,6 +2,7 @@ #include "Channels.h" #include "CryptoEngine.h" #include "NodeDB.h" +#include "MeshRadio.h" #include "RTC.h" #include "configuration.h" #include "main.h" @@ -188,6 +189,18 @@ ErrorCode Router::send(MeshPacket *p) { assert(p->to != nodeDB.getNodeNum()); // should have already been handled by sendLocal + // Abort sending if we are violating the duty cycle + if (!config.lora.override_duty_cycle && myRegion->dutyCycle != 100) { + float hourlyTxPercent = airTime->utilizationTXPercent(); + if (hourlyTxPercent > myRegion->dutyCycle) { + uint8_t silentMinutes = airTime->getSilentMinutes(hourlyTxPercent, myRegion->dutyCycle); + DEBUG_MSG("WARNING: Duty cycle limit exceeded. Aborting send for now, you can send again in %d minutes.\n", silentMinutes); + Routing_Error err = Routing_Error_DUTY_CYCLE_LIMIT; + abortSendAndNak(err, p); + return err; + } + } + // PacketId nakId = p->decoded.which_ackVariant == SubPacket_fail_id_tag ? p->decoded.ackVariant.fail_id : 0; // assert(!nakId); // I don't think we ever send 0hop naks over the wire (other than to the phone), test that assumption with // assert From 330ac3be68246a5f65e7baf6f9aaa6ced8ce7fd9 Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Sat, 26 Nov 2022 21:07:36 +0100 Subject: [PATCH 002/119] Update generated protobufs --- src/mesh/generated/apponly.pb.h | 2 +- src/mesh/generated/config.pb.h | 9 ++++++--- src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/mesh.pb.h | 4 +++- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/mesh/generated/apponly.pb.h b/src/mesh/generated/apponly.pb.h index 63f3cf3bf..e5e933873 100644 --- a/src/mesh/generated/apponly.pb.h +++ b/src/mesh/generated/apponly.pb.h @@ -54,7 +54,7 @@ extern const pb_msgdesc_t ChannelSet_msg; #define ChannelSet_fields &ChannelSet_msg /* Maximum encoded size of messages (where known) */ -#define ChannelSet_size 582 +#define ChannelSet_size 584 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/config.pb.h b/src/mesh/generated/config.pb.h index 2d6f3a1d9..cdc89664c 100644 --- a/src/mesh/generated/config.pb.h +++ b/src/mesh/generated/config.pb.h @@ -126,6 +126,7 @@ typedef struct _Config_LoRaConfig { bool tx_enabled; int8_t tx_power; uint16_t channel_num; + bool override_duty_cycle; pb_size_t ignore_incoming_count; uint32_t ignore_incoming[3]; } Config_LoRaConfig; @@ -235,7 +236,7 @@ extern "C" { #define Config_NetworkConfig_init_default {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_default} #define Config_NetworkConfig_IpV4Config_init_default {0, 0, 0, 0} #define Config_DisplayConfig_init_default {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN} -#define Config_LoRaConfig_init_default {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, {0, 0, 0}} +#define Config_LoRaConfig_init_default {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} #define Config_BluetoothConfig_init_default {0, _Config_BluetoothConfig_PairingMode_MIN, 0} #define Config_init_zero {0, {Config_DeviceConfig_init_zero}} #define Config_DeviceConfig_init_zero {_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0} @@ -244,7 +245,7 @@ extern "C" { #define Config_NetworkConfig_init_zero {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_zero} #define Config_NetworkConfig_IpV4Config_init_zero {0, 0, 0, 0} #define Config_DisplayConfig_init_zero {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN} -#define Config_LoRaConfig_init_zero {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, {0, 0, 0}} +#define Config_LoRaConfig_init_zero {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} #define Config_BluetoothConfig_init_zero {0, _Config_BluetoothConfig_PairingMode_MIN, 0} /* Field tags (for use in manual encoding/decoding) */ @@ -274,6 +275,7 @@ extern "C" { #define Config_LoRaConfig_tx_enabled_tag 9 #define Config_LoRaConfig_tx_power_tag 10 #define Config_LoRaConfig_channel_num_tag 11 +#define Config_LoRaConfig_override_duty_cycle_tag 12 #define Config_LoRaConfig_ignore_incoming_tag 103 #define Config_NetworkConfig_IpV4Config_ip_tag 1 #define Config_NetworkConfig_IpV4Config_gateway_tag 2 @@ -407,6 +409,7 @@ X(a, STATIC, SINGULAR, UINT32, hop_limit, 8) \ X(a, STATIC, SINGULAR, BOOL, tx_enabled, 9) \ X(a, STATIC, SINGULAR, INT32, tx_power, 10) \ X(a, STATIC, SINGULAR, UINT32, channel_num, 11) \ +X(a, STATIC, SINGULAR, BOOL, override_duty_cycle, 12) \ X(a, STATIC, REPEATED, UINT32, ignore_incoming, 103) #define Config_LoRaConfig_CALLBACK NULL #define Config_LoRaConfig_DEFAULT NULL @@ -443,7 +446,7 @@ extern const pb_msgdesc_t Config_BluetoothConfig_msg; #define Config_BluetoothConfig_size 10 #define Config_DeviceConfig_size 18 #define Config_DisplayConfig_size 22 -#define Config_LoRaConfig_size 68 +#define Config_LoRaConfig_size 70 #define Config_NetworkConfig_IpV4Config_size 20 #define Config_NetworkConfig_size 161 #define Config_PositionConfig_size 42 diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 054cae4db..01baddc2f 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -150,7 +150,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; #define LocalModuleConfig_fields &LocalModuleConfig_msg /* Maximum encoded size of messages (where known) */ -#define LocalConfig_size 385 +#define LocalConfig_size 387 #define LocalModuleConfig_size 361 #ifdef __cplusplus diff --git a/src/mesh/generated/mesh.pb.h b/src/mesh/generated/mesh.pb.h index 8d96960d1..f22ec6b12 100644 --- a/src/mesh/generated/mesh.pb.h +++ b/src/mesh/generated/mesh.pb.h @@ -185,9 +185,11 @@ typedef enum _Routing_Error { /* TODO: REPLACE */ Routing_Error_NO_RESPONSE = 8, /* TODO: REPLACE */ - Routing_Error_BAD_REQUEST = 32, + Routing_Error_DUTY_CYCLE_LIMIT = 9, /* The new version of the heltec WiFi_Lora_32_V2 board that has battery sensing hooked to GPIO 37. Sadly they did not update anything on the silkscreen to identify this board */ + Routing_Error_BAD_REQUEST = 32, + /* Ancient heltec WiFi_Lora_32 board */ Routing_Error_NOT_AUTHORIZED = 33 } Routing_Error; From c7681cb24d812cb7b1deb9de93cd6a7ffbcc2220 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 27 Nov 2022 14:03:50 +0100 Subject: [PATCH 003/119] update board definition, update copy/paste errors, fix SX1280. --- src/main.cpp | 26 ++++++++++++++++++- src/mesh/InterfacesTemplates.cpp | 3 --- src/mesh/RadioInterface.h | 2 ++ src/mesh/SX1280Interface.cpp | 4 --- src/mesh/SX1280Interface.h | 3 --- src/mesh/SX128xInterface.cpp | 44 +++++++++++++++++--------------- src/mesh/SX128xInterface.h | 12 ++++----- variants/tlora_v2_1_16/variant.h | 5 ---- variants/tlora_v2_1_18/variant.h | 12 ++------- 9 files changed, 59 insertions(+), 52 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 98f22ecf1..692837ad8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -387,7 +387,7 @@ void setup() } #endif -#if defined(USE_SX1280) && !defined(ARCH_PORTDUINO) +#if defined(USE_SX1280) if (!rIf) { rIf = new SX1280Interface(SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY, SPI); if (!rIf->init()) { @@ -452,6 +452,30 @@ void setup() } #endif +// check if the radio chip matches the selected region + +if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLora())){ + DEBUG_MSG("Warning: Radio chip does not support 2.4GHz LoRa. Reverting to unset.\n"); + config.lora.region = Config_LoRaConfig_RegionCode_UNSET; + nodeDB.saveToDisk(SEGMENT_CONFIG); + if(!rIf->reconfigure()) { + DEBUG_MSG("Reconfigure failed, rebooting\n"); + screen->startRebootScreen(); + rebootAtMsec = millis() + 5000; + } +} + +if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (rIf->wideLora())){ + DEBUG_MSG("Warning: Radio chip only supports 2.4GHz LoRa. Adjusting Region.\n"); + config.lora.region = Config_LoRaConfig_RegionCode_LORA_24; + nodeDB.saveToDisk(SEGMENT_CONFIG); + if(!rIf->reconfigure()) { + DEBUG_MSG("Reconfigure failed, rebooting\n"); + screen->startRebootScreen(); + rebootAtMsec = millis() + 5000; + } +} + #if HAS_WIFI || HAS_ETHERNET mqttInit(); #endif diff --git a/src/mesh/InterfacesTemplates.cpp b/src/mesh/InterfacesTemplates.cpp index 9602525b5..0d2246428 100644 --- a/src/mesh/InterfacesTemplates.cpp +++ b/src/mesh/InterfacesTemplates.cpp @@ -7,7 +7,4 @@ template class SX126xInterface; template class SX126xInterface; template class SX126xInterface; - -#if defined(RADIOLIB_GODMODE) template class SX128xInterface; -#endif \ No newline at end of file diff --git a/src/mesh/RadioInterface.h b/src/mesh/RadioInterface.h index e9f725c89..437f294a4 100644 --- a/src/mesh/RadioInterface.h +++ b/src/mesh/RadioInterface.h @@ -97,6 +97,8 @@ class RadioInterface */ virtual bool canSleep() { return true; } + virtual bool wideLora() { return false; } + /// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep. virtual bool sleep() { return true; } diff --git a/src/mesh/SX1280Interface.cpp b/src/mesh/SX1280Interface.cpp index 97a3febe3..7fc6b45e1 100644 --- a/src/mesh/SX1280Interface.cpp +++ b/src/mesh/SX1280Interface.cpp @@ -2,12 +2,8 @@ #include "SX1280Interface.h" #include "error.h" -#if defined(RADIOLIB_GODMODE) - SX1280Interface::SX1280Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi) : SX128xInterface(cs, irq, rst, busy, spi) { } - -#endif \ No newline at end of file diff --git a/src/mesh/SX1280Interface.h b/src/mesh/SX1280Interface.h index a9661501a..190ca3cf4 100644 --- a/src/mesh/SX1280Interface.h +++ b/src/mesh/SX1280Interface.h @@ -6,12 +6,9 @@ * Our adapter for SX1280 radios */ -#if defined(RADIOLIB_GODMODE) class SX1280Interface : public SX128xInterface { public: SX1280Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi); }; - -#endif \ No newline at end of file diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index 36eb0bb94..0a51d618a 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -2,8 +2,6 @@ #include "SX128xInterface.h" #include "error.h" -#if defined(RADIOLIB_GODMODE) - // Particular boards might define a different max power based on what their hardware can do #ifndef SX128X_MAX_POWER #define SX128X_MAX_POWER 13 @@ -27,11 +25,11 @@ bool SX128xInterface::init() pinMode(SX128X_POWER_EN, OUTPUT); #endif -#ifdef SX128X_RXEN // set not rx or tx mode +#if defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) // set not rx or tx mode digitalWrite(SX128X_RXEN, LOW); // Set low before becoming an output pinMode(SX128X_RXEN, OUTPUT); #endif -#ifdef SX128X_TXEN +#if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) digitalWrite(SX128X_TXEN, LOW); pinMode(SX128X_TXEN, OUTPUT); #endif @@ -46,6 +44,8 @@ bool SX128xInterface::init() limitPower(); + preambleLength = 12; // 12 is the default for this chip, 32 does not RX at all + int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength); // \todo Display actual typename of the adapter, not just `SX128x` DEBUG_MSG("SX128x init result %d\n", res); @@ -54,12 +54,6 @@ bool SX128xInterface::init() DEBUG_MSG("Bandwidth set to %f\n", bw); DEBUG_MSG("Power output set to %d\n", power); -#ifdef SX128X_TXEN - // lora.begin sets Dio2 as RF switch control, which is not true if we are manually controlling RX and TX - if (res == RADIOLIB_ERR_NONE) - res = lora.setDio2AsRfSwitch(true); -#endif - if (res == RADIOLIB_ERR_NONE) res = lora.setCRC(2); @@ -122,18 +116,28 @@ void INTERRUPT_ATTR SX128xInterface::disableInterrupt() lora.clearDio1Action(); } +template +bool SX128xInterface::wideLora() +{ + return true; +} + template void SX128xInterface::setStandby() { checkNotification(); // handle any pending interrupts before we force standby int err = lora.standby(); + + if (err != RADIOLIB_ERR_NONE) + DEBUG_MSG("SX128x standby failed with error %d\n", err); + assert(err == RADIOLIB_ERR_NONE); -#ifdef SX128X_RXEN // we have RXEN/TXEN control - turn off RX and TX power +#if defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn off RX and TX power digitalWrite(SX128X_RXEN, LOW); #endif -#ifdef SX128X_TXEN +#if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) digitalWrite(SX128X_TXEN, LOW); #endif @@ -158,10 +162,10 @@ void SX128xInterface::addReceiveMetadata(MeshPacket *mp) template void SX128xInterface::configHardwareForSend() { -#ifdef SX128X_TXEN // we have RXEN/TXEN control - turn on TX power / off RX power +#if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn on TX power / off RX power digitalWrite(SX128X_TXEN, HIGH); #endif -#ifdef SX128X_RXEN +#if defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) digitalWrite(SX128X_RXEN, LOW); #endif @@ -180,10 +184,10 @@ void SX128xInterface::startReceive() setStandby(); -#ifdef SX128X_RXEN // we have RXEN/TXEN control - turn on RX power / off TX power +#if defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn on RX power / off TX power digitalWrite(SX128X_RXEN, HIGH); #endif -#ifdef SX128X_TXEN +#if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) digitalWrite(SX128X_TXEN, LOW); #endif @@ -219,11 +223,13 @@ bool SX128xInterface::isChannelActive() template bool SX128xInterface::isActivelyReceiving() { - // return isChannelActive(); - +#ifdef RADIOLIB_GODMODE uint16_t irq = lora.getIrqStatus(); bool hasPreamble = (irq & RADIOLIB_SX128X_IRQ_HEADER_VALID); return hasPreamble; +#else + return isChannelActive(); +#endif } template @@ -248,5 +254,3 @@ bool SX128xInterface::sleep() return true; } - -#endif \ No newline at end of file diff --git a/src/mesh/SX128xInterface.h b/src/mesh/SX128xInterface.h index 9994ce850..5a6ed95f9 100644 --- a/src/mesh/SX128xInterface.h +++ b/src/mesh/SX128xInterface.h @@ -1,7 +1,5 @@ #pragma once -#if defined(RADIOLIB_GODMODE) - #include "RadioLibInterface.h" /** @@ -19,6 +17,8 @@ class SX128xInterface : public RadioLibInterface /// \return true if initialisation succeeded. virtual bool init() override; + virtual bool wideLora() override; + /// Apply any radio provisioning changes /// Make sure the Driver is properly configured before calling init(). /// \return true if initialisation succeeded. @@ -27,9 +27,11 @@ class SX128xInterface : public RadioLibInterface /// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep. virtual bool sleep() override; - protected: +#ifdef RADIOLIB_GODMODE + bool isIRQPending() override { return lora.getIrqStatus() != 0; } +#endif - float currentLimit = 140; // Higher OCP limit for SX128x PA + protected: /** * Specific module instance @@ -71,5 +73,3 @@ class SX128xInterface : public RadioLibInterface private: }; - -#endif \ No newline at end of file diff --git a/variants/tlora_v2_1_16/variant.h b/variants/tlora_v2_1_16/variant.h index a58b10b81..14175f48b 100644 --- a/variants/tlora_v2_1_16/variant.h +++ b/variants/tlora_v2_1_16/variant.h @@ -3,8 +3,6 @@ #define GPS_RX_PIN 15 // per @der_bear on the forum, 36 is incorrect for this board type and 15 is a better pick #define GPS_TX_PIN 13 -#define EXT_NOTIFY_OUT 2 // Default pin to use for Ext Notify Module. - #define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage // ratio of voltage divider = 2.0 (R42=100k, R43=100k) #define ADC_MULTIPLIER 2.11 // 2.0 + 10% for correction of display undervoltage. @@ -12,9 +10,6 @@ #define I2C_SDA 21 // I2C pins for this board #define I2C_SCL 22 -// #define RESET_OLED 16 // If defined, this pin will be used to reset the display controller. Crashes on newer ESP-IDF and not needed per schematic - -#define VEXT_ENABLE 21 // active low, powers the oled display and the lora antenna boost #define LED_PIN 25 // If defined we will blink this LED #define BUTTON_PIN 12 // If defined, this will be used for user button presses, diff --git a/variants/tlora_v2_1_18/variant.h b/variants/tlora_v2_1_18/variant.h index dd94847be..95d699767 100644 --- a/variants/tlora_v2_1_18/variant.h +++ b/variants/tlora_v2_1_18/variant.h @@ -1,9 +1,5 @@ #undef GPS_RX_PIN #undef GPS_TX_PIN -#define GPS_RX_PIN 15 // per @der_bear on the forum, 36 is incorrect for this board type and 15 is a better pick -#define GPS_TX_PIN 13 - -#define EXT_NOTIFY_OUT 2 // Default pin to use for Ext Notify Module. #define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage // ratio of voltage divider = 2.0 (R42=100k, R43=100k) @@ -20,11 +16,7 @@ #define USE_SX1280 #define LORA_RESET 23 -#define SX128X_CS 18 // FIXME - we really should define LORA_CS instead +#define SX128X_CS 18 #define SX128X_DIO1 26 -#define SX128X_DIO2 33 #define SX128X_BUSY 32 -#define SX128X_RESET LORA_RESET -#define SX128X_E22 // Not really an E22 but TTGO seems to be trying to clone that -// Internally the TTGO module hooks the SX1280-DIO2 in to control the TX/RX switch (which is the default for the sx1280interface -// code) +#define SX128X_RESET LORA_RESET \ No newline at end of file From 7ca104cef6f031df463c47cbe8b99a1ed6c817ea Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Sun, 27 Nov 2022 16:53:02 +0100 Subject: [PATCH 004/119] Override duty cycle if user is_licensed --- src/modules/AdminModule.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 7226abd0b..f599a5d75 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -186,6 +186,7 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) void AdminModule::handleSetOwner(const User &o) { int changed = 0; + bool licensed_changed = false; if (*o.long_name) { changed |= strcmp(owner.long_name, o.long_name); @@ -201,12 +202,14 @@ void AdminModule::handleSetOwner(const User &o) } if (owner.is_licensed != o.is_licensed) { changed = 1; + licensed_changed = true; owner.is_licensed = o.is_licensed; + config.lora.override_duty_cycle = owner.is_licensed; // override duty cycle for licensed operators } if (changed) { // If nothing really changed, don't broadcast on the network or write to flash service.reloadOwner(!hasOpenEditTransaction); - saveChanges(SEGMENT_DEVICESTATE); + licensed_changed ? saveChanges(SEGMENT_CONFIG | SEGMENT_DEVICESTATE) : saveChanges(SEGMENT_DEVICESTATE); } } From f3c5a01dafb282f5d9e455c5df3bc379f90b2b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Mon, 28 Nov 2022 21:58:30 +0100 Subject: [PATCH 005/119] remove a few DSR Router bits for S&F Module --- src/main.cpp | 3 --- src/mesh/ReliableRouter.cpp | 6 ++---- src/mesh/ReliableRouter.h | 6 ------ src/mesh/Router.cpp | 1 - src/sleep.cpp | 2 +- 5 files changed, 3 insertions(+), 15 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 692837ad8..c0fcaf96e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,8 +8,6 @@ #include "configuration.h" #include "error.h" #include "power.h" -// #include "rom/rtc.h" -//#include "DSRRouter.h" #include "ReliableRouter.h" // #include "debug.h" #include "FSCommon.h" @@ -217,7 +215,6 @@ void setup() fsInit(); - // router = new DSRRouter(); router = new ReliableRouter(); #ifdef I2C_SDA1 diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index 2807178b8..7933a7920 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -90,8 +90,7 @@ void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) { NodeNum ourNode = getNodeNum(); - if (p->to == ourNode) { // ignore ack/nak/want_ack packets that are not address to us (we only handle 0 hop reliability - // - not DSR routing) + if (p->to == ourNode) { // ignore ack/nak/want_ack packets that are not address to us (we only handle 0 hop reliability) if (p->want_ack) { if (MeshModule::currentReply) DEBUG_MSG("Some other module has replied to this message, no need for a 2nd ack\n"); @@ -200,8 +199,7 @@ int32_t ReliableRouter::doRetransmissions() DEBUG_MSG("Reliable send failed, returning a nak for fr=0x%x,to=0x%x,id=0x%x\n", p.packet->from, p.packet->to, p.packet->id); sendAckNak(Routing_Error_MAX_RETRANSMIT, getFrom(p.packet), p.packet->id, p.packet->channel); - // Note: we don't stop retransmission here, instead the Nak packet gets processed in sniffReceived - which - // allows the DSR version to still be able to look at the PendingPacket + // Note: we don't stop retransmission here, instead the Nak packet gets processed in sniffReceived stopRetransmission(it->first); stillValid = false; // just deleted it } else { diff --git a/src/mesh/ReliableRouter.h b/src/mesh/ReliableRouter.h index 3f89dcbd6..ff304cdd7 100644 --- a/src/mesh/ReliableRouter.h +++ b/src/mesh/ReliableRouter.h @@ -38,12 +38,6 @@ struct PendingPacket { /** Starts at NUM_RETRANSMISSIONS -1(normally 3) and counts down. Once zero it will be removed from the list */ uint8_t numRetransmissions = 0; - /** True if we have started trying to find a route - for DSR usage - * While trying to find a route we don't actually send the data packet. We just leave it here pending until - * we have a route or we've failed to find one. - */ - bool wantRoute = false; - PendingPacket() {} explicit PendingPacket(MeshPacket *p); }; diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index e0746bdd9..6b6a03a3a 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -21,7 +21,6 @@ extern "C" { * DONE: Implement basic interface and use it elsewhere in app * Add naive flooding mixin (& drop duplicate rx broadcasts), add tools for sending broadcasts with incrementing sequence #s * Add an optional adjacent node only 'send with ack' mixin. If we timeout waiting for the ack, call handleAckTimeout(packet) - * Add DSR mixin * **/ diff --git a/src/sleep.cpp b/src/sleep.cpp index 390ab7f65..39ee43ebc 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -237,7 +237,7 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more r // We want RTC peripherals to stay on esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); -#ifdef BUTTON_NEED_PULLUP +#if defined(BUTTON_PIN) && defined(BUTTON_NEED_PULLUP) gpio_pullup_en((gpio_num_t)BUTTON_PIN); #endif From 4d32f7c5ad55ef44afa4fed7078c083d842ffd00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 29 Nov 2022 11:22:18 +0100 Subject: [PATCH 006/119] WIP: audio module still does not work, but enabled for all regions where audio is permitted. --- arch/esp32/esp32.ini | 3 +- arch/esp32/esp32s3.ini | 1 + src/modules/Modules.cpp | 4 - src/modules/esp32/AudioModule.cpp | 221 +++++++++++++++----------- src/modules/esp32/AudioModule.h | 59 ++++--- variants/tlora_v2_1_18/platformio.ini | 3 - 6 files changed, 167 insertions(+), 124 deletions(-) diff --git a/arch/esp32/esp32.ini b/arch/esp32/esp32.ini index 730b78942..70654e8ec 100644 --- a/arch/esp32/esp32.ini +++ b/arch/esp32/esp32.ini @@ -33,7 +33,8 @@ lib_deps = ${environmental_base.lib_deps} https://github.com/meshtastic/esp32_https_server.git#23665b3adc080a311dcbb586ed5941b5f94d6ea2 h2zero/NimBLE-Arduino@^1.4.0 - https://github.com/lewisxhe/XPowersLib.git#84b7373faea3118b6c37954d52f98b8a337148d6 + https://github.com/lewisxhe/XPowersLib.git#84b7373faea3118b6c37954d52f98b8a337148d6 + caveman99/ESP32 Codec2@^1.0.1 lib_ignore = segger_rtt diff --git a/arch/esp32/esp32s3.ini b/arch/esp32/esp32s3.ini index 0c2d7d8f1..b05772344 100644 --- a/arch/esp32/esp32s3.ini +++ b/arch/esp32/esp32s3.ini @@ -34,6 +34,7 @@ lib_deps = https://github.com/meshtastic/esp32_https_server.git#23665b3adc080a311dcbb586ed5941b5f94d6ea2 h2zero/NimBLE-Arduino@^1.4.0 https://github.com/lewisxhe/XPowersLib.git#84b7373faea3118b6c37954d52f98b8a337148d6 + caveman99/ESP32 Codec2@^1.0.1 lib_ignore = segger_rtt diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index d24fa8f26..b97e965e1 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -19,10 +19,8 @@ #ifdef ARCH_ESP32 #include "modules/esp32/RangeTestModule.h" #include "modules/esp32/StoreForwardModule.h" -#ifdef USE_SX1280 #include "modules/esp32/AudioModule.h" #endif -#endif #if defined(ARCH_ESP32) || defined(ARCH_NRF52) #include "modules/ExternalNotificationModule.h" #if !defined(TTGO_T_ECHO) @@ -68,9 +66,7 @@ void setupModules() #endif #ifdef ARCH_ESP32 // Only run on an esp32 based device. -#ifdef USE_SX1280 new AudioModule(); -#endif new ExternalNotificationModule(); storeForwardModule = new StoreForwardModule(); diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index c37a1b2a8..0f95c306a 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -6,6 +6,8 @@ #include "Router.h" #include "FSCommon.h" +#include +#include #include /* @@ -30,7 +32,7 @@ KNOWN PROBLEMS * Until the module is initilized by the startup sequence, the amp_pin pin is in a floating - state. This may produce a bit of "noise". + radio_state. This may produce a bit of "noise". * Will not work on NRF and the Linux device targets. */ @@ -40,12 +42,20 @@ #define AUDIO_MODULE_RX_BUFFER 128 #define AUDIO_MODULE_DATA_MAX Constants_DATA_PAYLOAD_LEN -#define AUDIO_MODULE_MODE 7 // 700B -#define AUDIO_MODULE_ACK 1 +#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 -#if defined(ARCH_ESP32) && defined(USE_SX1280) +#if defined(ARCH_ESP32) AudioModule *audioModule; +Codec2Thread *codec2Thread; + +FastAudioFIFO audio_fifo; +uint16_t adc_buffer[ADC_BUFFER_SIZE] = {}; +uint16_t adc_buffer_index = 0; +portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; +int16_t speech[ADC_BUFFER_SIZE] = {}; +volatile RadioState radio_state = RadioState::tx; +adc1_channel_t mic_chan = (adc1_channel_t)0; ButterworthFilter hp_filter(240, 8000, ButterworthFilter::ButterworthFilter::Highpass, 1); @@ -55,55 +65,22 @@ int Sine1KHz_index = 0; uint8_t rx_raw_audio_value = 127; -AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { - audio_fifo.init(); +int IRAM_ATTR local_adc1_read(int channel) { + uint16_t adc_value; + SENS.sar_meas_start1.sar1_en_pad = (1 << channel); // only one channel is selected + while (SENS.sar_slave_addr1.meas_status != 0); + SENS.sar_meas_start1.meas1_start_sar = 0; + SENS.sar_meas_start1.meas1_start_sar = 1; + while (SENS.sar_meas_start1.meas1_done_sar == 0); + adc_value = SENS.sar_meas_start1.meas1_data_sar; + return adc_value; } -void AudioModule::run_codec2() +IRAM_ATTR void am_onTimer() { - if (state == State::tx) - { - for (int i = 0; i < ADC_BUFFER_SIZE; i++) - speech[i] = (int16_t)hp_filter.Update((float)speech[i]); - - codec2_encode(codec2_state, tx_encode_frame + tx_encode_frame_index, speech); - - //increment the pointer where the encoded frame must be saved - tx_encode_frame_index += 8; - - //If it is the 5th time then we have a ready trasnmission frame - if (tx_encode_frame_index == ENCODE_FRAME_SIZE) - { - tx_encode_frame_index = 0; - //Transmit it - sendPayload(); - } - } - if (state == State::rx) //Receiving - { - //Make a cycle to get each codec2 frame from the received frame - for (int i = 0; i < ENCODE_FRAME_SIZE; i += 8) - { - //Decode the codec2 frame - codec2_decode(codec2_state, output_buffer, rx_encode_frame + i); - - // Add to the audio buffer the 320 samples resulting of the decode of the codec2 frame. - for (int g = 0; g < ADC_BUFFER_SIZE; g++) - audio_fifo.put(output_buffer[g]); - } - } - state = State::standby; -} - -void AudioModule::handleInterrupt() -{ - audioModule->onTimer(); -} - -void AudioModule::onTimer() -{ - if (state == State::tx) { - adc_buffer[adc_buffer_index++] = (16 * adc1_get_raw(mic_chan)) - 32768; + portENTER_CRITICAL_ISR(&timerMux); //Enter crital code without interruptions + if (radio_state == RadioState::tx) { + adc_buffer[adc_buffer_index++] = (16 * local_adc1_read(mic_chan)) - 32768; //If you want to test with a 1KHz tone, comment the line above and descomment the three lines below @@ -113,39 +90,96 @@ void AudioModule::onTimer() if (adc_buffer_index == ADC_BUFFER_SIZE) { adc_buffer_index = 0; + DEBUG_MSG("--- memcpy\n"); memcpy((void*)speech, (void*)adc_buffer, 2 * ADC_BUFFER_SIZE); - audioModule->setIntervalFromNow(0); // process buffer immediately + // Notify codec2 task that the buffer is ready. + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + DEBUG_MSG("--- notifyFromISR\n"); + codec2Thread->notifyFromISR(&xHigherPriorityTaskWoken, RadioState::tx, true); + if (xHigherPriorityTaskWoken) + portYIELD_FROM_ISR(); } - } else if (state == State::rx) { + } else if (radio_state == RadioState::rx) { int16_t v; //Get a value from audio_fifo and convert it to 0 - 255 to play it in the ADC - //If none value is available the DAC will play the last one that was read, that's - //why the rx_raw_audio_value variable is a global one. if (audio_fifo.get(&v)) rx_raw_audio_value = (uint8_t)((v + 32768) / 256); - - //Play dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, rx_raw_audio_value); } + portEXIT_CRITICAL_ISR(&timerMux); // exit critical code +} + +Codec2Thread::Codec2Thread() : concurrency::NotifiedWorkerThread("Codec2Thread") { + if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { + DEBUG_MSG("--- Setting up codec2 in mode %u\n", moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); + codec2_state = codec2_create(moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); + codec2_set_lpc_post_filter(codec2_state, 1, 0, 0.8, 0.2); + } else { + DEBUG_MSG("--- Codec2 disabled\n"); + } +} + +AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { + audio_fifo.init(); + new Codec2Thread(); +} + +void Codec2Thread::onNotify(uint32_t notification) +{ + switch (notification) { + case RadioState::tx: + for (int i = 0; i < ADC_BUFFER_SIZE; i++) + speech[i] = (int16_t)hp_filter.Update((float)speech[i]); + + codec2_encode(codec2_state, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, speech); + + //increment the pointer where the encoded frame must be saved + audioModule->tx_encode_frame_index += 8; + + //If it is the 5th time then we have a ready trasnmission frame + if (audioModule->tx_encode_frame_index == ENCODE_FRAME_SIZE) + { + audioModule->tx_encode_frame_index = 0; + //Transmit it + audioModule->sendPayload(); + } + break; + case RadioState::rx: + //Make a cycle to get each codec2 frame from the received frame + for (int i = 0; i < ENCODE_FRAME_SIZE; i += ENCODE_CODEC2_SIZE) + { + //Decode the codec2 frame + codec2_decode(codec2_state, output_buffer, audioModule->rx_encode_frame + i); + + // Add to the audio buffer the 320 samples resulting of the decode of the codec2 frame. + for (int g = 0; g < ADC_BUFFER_SIZE; g++) + audio_fifo.put(output_buffer[g]); + } + break; + default: + assert(0); // We expected to receive a valid notification from the ISR + break; + } } int32_t AudioModule::runOnce() { - if (moduleConfig.audio.codec2_enabled) { - + if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { if (firstTime) { - - DEBUG_MSG("Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); + DEBUG_MSG("--- Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; adc1_config_width(ADC_WIDTH_12Bit); - adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); + adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); + adc1_get_raw(mic_chan); + + radio_state = RadioState::rx; // Start a timer at 8kHz to sample the ADC and play the audio on the DAC. uint32_t cpufreq = getCpuFrequencyMhz(); - switch (cpufreq){ + switch (cpufreq){ case 160: adcTimer = timerBegin(3, 1000, true); // 160 MHz / 1000 = 160KHz break; @@ -160,48 +194,44 @@ int32_t AudioModule::runOnce() adcTimer = timerBegin(3, 500, true); // 80 MHz / 500 = 160KHz break; } - timerAttachInterrupt(adcTimer, &AudioModule::handleInterrupt, true); - timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second - timerAlarmEnable(adcTimer); + DEBUG_MSG("--- Timer CPU Frequency: %u MHz\n", cpufreq); + timerAttachInterrupt(adcTimer, &am_onTimer, false); + timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second + timerAlarmEnable(adcTimer); - DEBUG_MSG("Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); - DEBUG_MSG("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + DEBUG_MSG("--- Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); + DEBUG_MSG("--- Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); // Configure PTT input - pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT_PULLUP); + pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); - state = State::rx; - - DEBUG_MSG("Setting up codec2 in mode %u\n", moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); - - codec2_state = codec2_create(moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); - codec2_set_lpc_post_filter(codec2_state, 1, 0, 0.8, 0.2); - - firstTime = 0; + firstTime = false; } else { - // Check if we have a PTT press - if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == LOW) { - // PTT pressed, recording - state = State::tx; - } - if (state != State::standby) { - run_codec2(); + // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. + if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { + if (radio_state == RadioState::rx) { + DEBUG_MSG("--- PTT pressed, switching to TX\n"); + radio_state = RadioState::tx; + } + } else { + if (radio_state == RadioState::tx) { + DEBUG_MSG("--- PTT released, switching to RX\n"); + radio_state = RadioState::rx; + } } + } - return 100; } else { - DEBUG_MSG("Audio Module Disabled\n"); - + DEBUG_MSG("--- Audio Module Disabled\n"); return INT32_MAX; } + } MeshPacket *AudioModule::allocReply() { - auto reply = allocDataPacket(); // Allocate a packet for sending - return reply; } @@ -211,7 +241,8 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) p->to = dest; p->decoded.want_response = wantReplies; - p->want_ack = AUDIO_MODULE_ACK; + p->want_ack = false; // Audio is shoot&forget. TODO: Is this really suppressing retransmissions? + p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime p->decoded.payload.size = ENCODE_FRAME_SIZE; memcpy(p->decoded.payload.bytes, tx_encode_frame, p->decoded.payload.size); @@ -221,16 +252,18 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) ProcessMessage AudioModule::handleReceived(const MeshPacket &mp) { - if (moduleConfig.audio.codec2_enabled) { + if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { auto &p = mp.decoded; if (getFrom(&mp) != nodeDB.getNodeNum()) { if (p.payload.size == ENCODE_FRAME_SIZE) { memcpy(rx_encode_frame, p.payload.bytes, p.payload.size); - state = State::rx; - audioModule->setIntervalFromNow(0); - run_codec2(); + radio_state = RadioState::rx; + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + codec2Thread->notifyFromISR(&xHigherPriorityTaskWoken, RadioState::rx, true); + if (xHigherPriorityTaskWoken) + portYIELD_FROM_ISR(); } else { - DEBUG_MSG("Invalid payload size %u != %u\n", p.payload.size, ENCODE_FRAME_SIZE); + DEBUG_MSG("--- Invalid payload size %u != %u\n", p.payload.size, ENCODE_FRAME_SIZE); } } } diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index d82af4d43..c83160cfb 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -7,38 +7,45 @@ #include #include #include -#if defined(ARCH_ESP32) && defined(USE_SX1280) +#if defined(ARCH_ESP32) #include #include #include #endif #define ADC_BUFFER_SIZE 320 // 40ms of voice in 8KHz sampling frequency -#define ENCODE_FRAME_SIZE 40 // 5 codec2 frames of 8 bytes each +#define ENCODE_CODEC2_SIZE 8 +#define ENCODE_FRAME_SIZE (ENCODE_CODEC2_SIZE * 5) // 5 codec2 frames of 8 bytes each + +class Codec2Thread : public concurrency::NotifiedWorkerThread +{ +#if defined(ARCH_ESP32) + struct CODEC2* codec2_state = NULL; + int16_t output_buffer[ADC_BUFFER_SIZE] = {}; + + public: + Codec2Thread(); + + protected: + virtual void onNotify(uint32_t notification) override; +#endif +}; class AudioModule : public SinglePortModule, private concurrency::OSThread { -#if defined(ARCH_ESP32) && defined(USE_SX1280) - bool firstTime = 1; +#if defined(ARCH_ESP32) + bool firstTime = true; hw_timer_t* adcTimer = NULL; - uint16_t adc_buffer[ADC_BUFFER_SIZE] = {}; - int16_t speech[ADC_BUFFER_SIZE] = {}; - int16_t output_buffer[ADC_BUFFER_SIZE] = {}; - unsigned char rx_encode_frame[ENCODE_FRAME_SIZE] = {}; - unsigned char tx_encode_frame[ENCODE_FRAME_SIZE] = {}; - int tx_encode_frame_index = 0; + FastAudioFIFO audio_fifo; uint16_t adc_buffer_index = 0; - adc1_channel_t mic_chan = (adc1_channel_t)0; - struct CODEC2* codec2_state = NULL; - enum State - { - standby, rx, tx - }; - volatile State state = State::tx; public: + unsigned char rx_encode_frame[ENCODE_FRAME_SIZE] = {}; + unsigned char tx_encode_frame[ENCODE_FRAME_SIZE] = {}; + int tx_encode_frame_index = 0; + AudioModule(); /** @@ -49,11 +56,7 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread protected: virtual int32_t runOnce() override; - static void handleInterrupt(); - - void onTimer(); - - void run_codec2(); + // void run_codec2(); virtual MeshPacket *allocReply() override; @@ -65,4 +68,16 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread }; extern AudioModule *audioModule; +extern Codec2Thread *codec2Thread; + +extern FastAudioFIFO audio_fifo; +extern uint16_t adc_buffer[ADC_BUFFER_SIZE]; +extern uint16_t adc_buffer_index; +extern portMUX_TYPE timerMux; +extern int16_t speech[ADC_BUFFER_SIZE]; +enum RadioState { standby, rx, tx }; +extern volatile RadioState radio_state; +extern adc1_channel_t mic_chan; + +IRAM_ATTR void am_onTimer(); diff --git a/variants/tlora_v2_1_18/platformio.ini b/variants/tlora_v2_1_18/platformio.ini index f5af98904..ac7c1a5e4 100644 --- a/variants/tlora_v2_1_18/platformio.ini +++ b/variants/tlora_v2_1_18/platformio.ini @@ -1,8 +1,5 @@ [env:tlora-v2-1-1.8] extends = esp32_base board = ttgo-lora32-v21 -lib_deps = - ${esp32_base.lib_deps} - caveman99/ESP32 Codec2@^1.0.1 build_flags = ${esp32_base.build_flags} -D TLORA_V2_1_18 -I variants/tlora_v2_1_18 -D RADIOLIB_GODMODE \ No newline at end of file From bba6bf387ec41712597b49506d6094dabdc75a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 29 Nov 2022 14:35:46 +0100 Subject: [PATCH 007/119] hopefully fix compilation errors --- src/modules/esp32/AudioModule.cpp | 16 ++++++++++++++-- src/modules/esp32/AudioModule.h | 12 ++---------- variants/heltec_v3/platformio.ini | 2 +- variants/heltec_wsl_v3/platformio.ini | 2 +- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 0f95c306a..959366dec 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -1,4 +1,6 @@ + #include "configuration.h" +#if defined(ARCH_ESP32) #include "AudioModule.h" #include "MeshService.h" #include "NodeDB.h" @@ -44,8 +46,6 @@ #define AUDIO_MODULE_DATA_MAX Constants_DATA_PAYLOAD_LEN #define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 -#if defined(ARCH_ESP32) - AudioModule *audioModule; Codec2Thread *codec2Thread; @@ -67,12 +67,21 @@ uint8_t rx_raw_audio_value = 127; int IRAM_ATTR local_adc1_read(int channel) { uint16_t adc_value; +#if CONFIG_IDF_TARGET_ESP32S3 + SENS.sar_meas1_ctrl2.sar1_en_pad = (1 << channel); // only one channel is selected + while (SENS.sar_slave_addr1.meas_status != 0); + SENS.sar_meas1_ctrl2.meas1_start_sar = 0; + SENS.sar_meas1_ctrl2.meas1_start_sar = 1; + while (SENS.sar_meas1_ctrl2.meas1_done_sar == 0); + adc_value = SENS.sar_meas1_ctrl2.meas1_data_sar; +#else SENS.sar_meas_start1.sar1_en_pad = (1 << channel); // only one channel is selected while (SENS.sar_slave_addr1.meas_status != 0); SENS.sar_meas_start1.meas1_start_sar = 0; SENS.sar_meas_start1.meas1_start_sar = 1; while (SENS.sar_meas_start1.meas1_done_sar == 0); adc_value = SENS.sar_meas_start1.meas1_data_sar; +#endif return adc_value; } @@ -106,7 +115,10 @@ IRAM_ATTR void am_onTimer() //Get a value from audio_fifo and convert it to 0 - 255 to play it in the ADC if (audio_fifo.get(&v)) rx_raw_audio_value = (uint8_t)((v + 32768) / 256); + // comment out for now, S3 does not have Hardware-DAC. Consider I2S instead. +#if !CONFIG_IDF_TARGET_ESP32S3 dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, rx_raw_audio_value); +#endif } portEXIT_CRITICAL_ISR(&timerMux); // exit critical code } diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index c83160cfb..16705a141 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -3,15 +3,14 @@ #include "SinglePortModule.h" #include "concurrency/OSThread.h" #include "configuration.h" +#if defined(ARCH_ESP32) #include "NodeDB.h" #include #include #include -#if defined(ARCH_ESP32) #include #include #include -#endif #define ADC_BUFFER_SIZE 320 // 40ms of voice in 8KHz sampling frequency #define ENCODE_CODEC2_SIZE 8 @@ -19,7 +18,6 @@ class Codec2Thread : public concurrency::NotifiedWorkerThread { -#if defined(ARCH_ESP32) struct CODEC2* codec2_state = NULL; int16_t output_buffer[ADC_BUFFER_SIZE] = {}; @@ -28,16 +26,12 @@ class Codec2Thread : public concurrency::NotifiedWorkerThread protected: virtual void onNotify(uint32_t notification) override; -#endif }; class AudioModule : public SinglePortModule, private concurrency::OSThread { -#if defined(ARCH_ESP32) bool firstTime = true; hw_timer_t* adcTimer = NULL; - - FastAudioFIFO audio_fifo; uint16_t adc_buffer_index = 0; @@ -64,13 +58,11 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread * @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; -#endif }; extern AudioModule *audioModule; extern Codec2Thread *codec2Thread; -extern FastAudioFIFO audio_fifo; extern uint16_t adc_buffer[ADC_BUFFER_SIZE]; extern uint16_t adc_buffer_index; extern portMUX_TYPE timerMux; @@ -80,4 +72,4 @@ extern volatile RadioState radio_state; extern adc1_channel_t mic_chan; IRAM_ATTR void am_onTimer(); - +#endif \ No newline at end of file diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 6cd75bed8..372f42d64 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -1,6 +1,6 @@ [env:heltec-v3] platform = https://github.com/Baptou88/platform-espressif32.git -extends = esp32_base +extends = esp32s3_base board = heltec_wifi_lora_32_V3 # Temporary: https://community.platformio.org/t/heltec-esp32-lora-v3-board-support/30406/2 platform_packages = diff --git a/variants/heltec_wsl_v3/platformio.ini b/variants/heltec_wsl_v3/platformio.ini index 8854b1a44..336e44936 100644 --- a/variants/heltec_wsl_v3/platformio.ini +++ b/variants/heltec_wsl_v3/platformio.ini @@ -1,6 +1,6 @@ [env:heltec-wsl-v3] platform = https://github.com/Baptou88/platform-espressif32.git -extends = esp32_base +extends = esp32s3_base board = heltec_wifi_lora_32_V3 # Temporary: https://community.platformio.org/t/heltec-esp32-lora-v3-board-support/30406/2 platform_packages = From 05e992ad679c3bd71ac2a0337f09544a9ce0f828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 29 Nov 2022 17:19:10 +0100 Subject: [PATCH 008/119] WIP: add digital audio. Needs a proto change, so checking in generated files for now. --- src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/module_config.pb.h | 20 ++++- src/modules/esp32/AudioModule.cpp | 110 ++++++++++++++++++-------- src/modules/esp32/AudioModule.h | 1 + 4 files changed, 95 insertions(+), 38 deletions(-) diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 01baddc2f..44d923839 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -151,7 +151,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; /* Maximum encoded size of messages (where known) */ #define LocalConfig_size 387 -#define LocalModuleConfig_size 361 +#define LocalModuleConfig_size 385 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 12018203e..3747452c7 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -67,6 +67,10 @@ typedef struct _ModuleConfig_AudioConfig { uint32_t amp_pin; uint32_t ptt_pin; ModuleConfig_AudioConfig_Audio_Baud bitrate; + uint32_t i2s_ws; + uint32_t i2s_sd; + uint32_t i2s_din; + uint32_t i2s_sck; } ModuleConfig_AudioConfig; typedef struct _ModuleConfig_CannedMessageConfig { @@ -183,7 +187,7 @@ extern "C" { /* Initializer values for message structs */ #define ModuleConfig_init_default {0, {ModuleConfig_MQTTConfig_init_default}} #define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} -#define ModuleConfig_AudioConfig_init_default {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN} +#define ModuleConfig_AudioConfig_init_default {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} @@ -192,7 +196,7 @@ extern "C" { #define ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} #define ModuleConfig_init_zero {0, {ModuleConfig_MQTTConfig_init_zero}} #define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} -#define ModuleConfig_AudioConfig_init_zero {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN} +#define ModuleConfig_AudioConfig_init_zero {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} @@ -206,6 +210,10 @@ extern "C" { #define ModuleConfig_AudioConfig_amp_pin_tag 3 #define ModuleConfig_AudioConfig_ptt_pin_tag 4 #define ModuleConfig_AudioConfig_bitrate_tag 5 +#define ModuleConfig_AudioConfig_i2s_ws_tag 6 +#define ModuleConfig_AudioConfig_i2s_sd_tag 7 +#define ModuleConfig_AudioConfig_i2s_din_tag 8 +#define ModuleConfig_AudioConfig_i2s_sck_tag 9 #define ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 #define ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 #define ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 @@ -295,7 +303,11 @@ X(a, STATIC, SINGULAR, BOOL, codec2_enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, mic_chan, 2) \ X(a, STATIC, SINGULAR, UINT32, amp_pin, 3) \ X(a, STATIC, SINGULAR, UINT32, ptt_pin, 4) \ -X(a, STATIC, SINGULAR, UENUM, bitrate, 5) +X(a, STATIC, SINGULAR, UENUM, bitrate, 5) \ +X(a, STATIC, SINGULAR, UINT32, i2s_ws, 6) \ +X(a, STATIC, SINGULAR, UINT32, i2s_sd, 7) \ +X(a, STATIC, SINGULAR, UINT32, i2s_din, 8) \ +X(a, STATIC, SINGULAR, UINT32, i2s_sck, 9) #define ModuleConfig_AudioConfig_CALLBACK NULL #define ModuleConfig_AudioConfig_DEFAULT NULL @@ -383,7 +395,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; #define ModuleConfig_CannedMessageConfig_fields &ModuleConfig_CannedMessageConfig_msg /* Maximum encoded size of messages (where known) */ -#define ModuleConfig_AudioConfig_size 22 +#define ModuleConfig_AudioConfig_size 46 #define ModuleConfig_CannedMessageConfig_size 49 #define ModuleConfig_ExternalNotificationConfig_size 22 #define ModuleConfig_MQTTConfig_size 169 diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 959366dec..0c02251b0 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -42,6 +42,14 @@ #define AAMP 14 #define PTT_PIN 39 +// #define I2S_WS 13 +// #define I2S_SD 15 +// #define I2S_SIN 2 +// #define I2S_SCK 14 + +// Use I2S Processor 0 +#define I2S_PORT I2S_NUM_0 + #define AUDIO_MODULE_RX_BUFFER 128 #define AUDIO_MODULE_DATA_MAX Constants_DATA_PAYLOAD_LEN #define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 @@ -88,7 +96,7 @@ int IRAM_ATTR local_adc1_read(int channel) { IRAM_ATTR void am_onTimer() { portENTER_CRITICAL_ISR(&timerMux); //Enter crital code without interruptions - if (radio_state == RadioState::tx) { + if ((radio_state == RadioState::tx) && (!moduleConfig.audio.i2s_sd)) { adc_buffer[adc_buffer_index++] = (16 * local_adc1_read(mic_chan)) - 32768; //If you want to test with a 1KHz tone, comment the line above and descomment the three lines below @@ -108,15 +116,15 @@ IRAM_ATTR void am_onTimer() if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR(); } - } else if (radio_state == RadioState::rx) { - + } else if ((radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din) { + // ESP32-S3 does not have DAC support +#if !defined(CONFIG_IDF_TARGET_ESP32S3) int16_t v; //Get a value from audio_fifo and convert it to 0 - 255 to play it in the ADC if (audio_fifo.get(&v)) rx_raw_audio_value = (uint8_t)((v + 32768) / 256); - // comment out for now, S3 does not have Hardware-DAC. Consider I2S instead. -#if !CONFIG_IDF_TARGET_ESP32S3 + dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, rx_raw_audio_value); #endif } @@ -180,41 +188,77 @@ int32_t AudioModule::runOnce() { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { if (firstTime) { - DEBUG_MSG("--- Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); + // if we have I2S_SD defined, take samples from digital mic. I2S_DIN means digital output to amp. + if (moduleConfig.audio.i2s_sd || moduleConfig.audio.i2s_din) { + // Set up I2S Processor configuration. This will produce 16bit samples instead of 12 from the ADC + DEBUG_MSG("--- Initializing I2S for input\n"); + i2s_config_t i2s_config = { + .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), + .sample_rate = 8000, + .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, + .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, + .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), + .intr_alloc_flags = 0, + .dma_buf_count = 8, + .dma_buf_len = ADC_BUFFER_SIZE, + .use_apll = false, + .tx_desc_auto_clear = true, + .fixed_mclk = 0 + }; + i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); - mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; - adc1_config_width(ADC_WIDTH_12Bit); - adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); - adc1_get_raw(mic_chan); + const i2s_pin_config_t pin_config = { + .bck_io_num = moduleConfig.audio.i2s_sck, + .ws_io_num = moduleConfig.audio.i2s_ws, + .data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE, + .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE + }; + i2s_set_pin(I2S_PORT, &pin_config); + + i2s_start(I2S_PORT); + } + + if (!moduleConfig.audio.i2s_sd) { + DEBUG_MSG("--- Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); + mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; + adc1_config_width(ADC_WIDTH_12Bit); + adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); + adc1_get_raw(mic_chan); + } radio_state = RadioState::rx; - // Start a timer at 8kHz to sample the ADC and play the audio on the DAC. - uint32_t cpufreq = getCpuFrequencyMhz(); - switch (cpufreq){ - case 160: - adcTimer = timerBegin(3, 1000, true); // 160 MHz / 1000 = 160KHz - break; - case 240: - adcTimer = timerBegin(3, 1500, true); // 240 MHz / 1500 = 160KHz - break; - case 320: - adcTimer = timerBegin(3, 2000, true); // 320 MHz / 2000 = 160KHz - break; - case 80: - default: - adcTimer = timerBegin(3, 500, true); // 80 MHz / 500 = 160KHz - break; + if ((!moduleConfig.audio.i2s_sd) || (!moduleConfig.audio.i2s_din)) { + // Start a timer at 8kHz to sample the ADC and play the audio on the DAC, but only if we have analogue audio to process + uint32_t cpufreq = getCpuFrequencyMhz(); + switch (cpufreq){ + case 160: + adcTimer = timerBegin(3, 1000, true); // 160 MHz / 1000 = 160KHz + break; + case 240: + adcTimer = timerBegin(3, 1500, true); // 240 MHz / 1500 = 160KHz + break; + case 320: + adcTimer = timerBegin(3, 2000, true); // 320 MHz / 2000 = 160KHz + break; + case 80: + default: + adcTimer = timerBegin(3, 500, true); // 80 MHz / 500 = 160KHz + break; + } + DEBUG_MSG("--- Timer CPU Frequency: %u MHz\n", cpufreq); + timerAttachInterrupt(adcTimer, &am_onTimer, false); + timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second + timerAlarmEnable(adcTimer); } - DEBUG_MSG("--- Timer CPU Frequency: %u MHz\n", cpufreq); - timerAttachInterrupt(adcTimer, &am_onTimer, false); - timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second - timerAlarmEnable(adcTimer); - - DEBUG_MSG("--- Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); - DEBUG_MSG("--- Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + // setup analogue DAC only if we don't use I2S for output. This is not available on ESP32-S3 +#if !defined(CONFIG_IDF_TARGET_ESP32S3) + if (moduleConfig.audio.i2s_din) + DEBUG_MSG("--- Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); +#endif // Configure PTT input + DEBUG_MSG("--- Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index 16705a141..b30e82bc2 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -6,6 +6,7 @@ #if defined(ARCH_ESP32) #include "NodeDB.h" #include +#include #include #include #include From 628028475c9831217c19e6dbb37662759aa92983 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 29 Nov 2022 17:45:57 +0100 Subject: [PATCH 009/119] fix compile --- protobufs | 2 +- src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/module_config.pb.h | 16 ++++++++-------- src/modules/esp32/AudioModule.cpp | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/protobufs b/protobufs index afa460569..2bb457de4 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit afa4605699e9ba9e2d0f0407bbc32dcd133f76af +Subproject commit 2bb457de42cd6d5c2a6e7d8a4992fc6c90e37de5 diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 44d923839..b8c8b27ef 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -151,7 +151,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; /* Maximum encoded size of messages (where known) */ #define LocalConfig_size 387 -#define LocalModuleConfig_size 385 +#define LocalModuleConfig_size 364 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 3747452c7..189eb2ca5 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -63,14 +63,14 @@ typedef enum _ModuleConfig_CannedMessageConfig_InputEventChar { /* Struct definitions */ typedef struct _ModuleConfig_AudioConfig { bool codec2_enabled; - uint32_t mic_chan; - uint32_t amp_pin; - uint32_t ptt_pin; + uint8_t mic_chan; + uint8_t amp_pin; + uint8_t ptt_pin; ModuleConfig_AudioConfig_Audio_Baud bitrate; - uint32_t i2s_ws; - uint32_t i2s_sd; - uint32_t i2s_din; - uint32_t i2s_sck; + uint8_t i2s_ws; + uint8_t i2s_sd; + uint8_t i2s_din; + uint8_t i2s_sck; } ModuleConfig_AudioConfig; typedef struct _ModuleConfig_CannedMessageConfig { @@ -395,7 +395,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; #define ModuleConfig_CannedMessageConfig_fields &ModuleConfig_CannedMessageConfig_msg /* Maximum encoded size of messages (where known) */ -#define ModuleConfig_AudioConfig_size 46 +#define ModuleConfig_AudioConfig_size 25 #define ModuleConfig_CannedMessageConfig_size 49 #define ModuleConfig_ExternalNotificationConfig_size 22 #define ModuleConfig_MQTTConfig_size 169 diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 0c02251b0..55677c0a9 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -116,7 +116,7 @@ IRAM_ATTR void am_onTimer() if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR(); } - } else if ((radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din) { + } else if ((radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din)) { // ESP32-S3 does not have DAC support #if !defined(CONFIG_IDF_TARGET_ESP32S3) int16_t v; @@ -197,7 +197,7 @@ int32_t AudioModule::runOnce() .sample_rate = 8000, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, - .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), + .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), .intr_alloc_flags = 0, .dma_buf_count = 8, .dma_buf_len = ADC_BUFFER_SIZE, From 72e17b558ce90beecf40028836652dffc45516b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 30 Nov 2022 09:52:28 +0100 Subject: [PATCH 010/119] add temp code for heap debugging. Disable -DDEBUG_HEAP for release builds. DEBUG_MSG output only for now. --- platformio.ini | 1 + src/Power.cpp | 3 +++ 2 files changed, 4 insertions(+) diff --git a/platformio.ini b/platformio.ini index dbddf7535..792f2f8b1 100644 --- a/platformio.ini +++ b/platformio.ini @@ -55,6 +55,7 @@ build_flags = -Wno-missing-field-initializers -DRADIOLIB_EXCLUDE_MORSE -DRADIOLIB_EXCLUDE_RTTY -DRADIOLIB_EXCLUDE_SSTV + -DDEBUG_HEAP monitor_speed = 115200 diff --git a/src/Power.cpp b/src/Power.cpp index af10acb5e..8da365caf 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -283,6 +283,9 @@ void Power::readPowerStatus() DEBUG_MSG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d\n", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); +#ifdef DEBUG_HEAP + DEBUG_MSG("Heap status: %d/%d bytes free\n", ESP.getFreeHeap(), ESP.getHeapSize()); +#endif // If we have a battery at all and it is less than 10% full, force deep sleep if we have more than 3 low readings in a row // Supect fluctuating voltage on the RAK4631 to force it to deep sleep even if battery is at 85% after only a few days From 7907404028a38c17b27a0a55e90b1dc06af41b2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 30 Nov 2022 09:57:10 +0100 Subject: [PATCH 011/119] start rearranging the S&F Module --- src/modules/esp32/StoreForwardModule.cpp | 273 ++++++++++++----------- src/modules/esp32/StoreForwardModule.h | 14 +- 2 files changed, 146 insertions(+), 141 deletions(-) diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index e51296824..9d1c44c18 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -16,52 +16,50 @@ StoreForwardModule *storeForwardModule; int32_t StoreForwardModule::runOnce() { - #ifdef ARCH_ESP32 + if (moduleConfig.store_forward.enabled && is_server) { + // Send out the message queue. + if (this->busy) { + // Only send packets if the channel is less than 25% utilized. + if (airTime->channelUtilizationPercent() < polite_channel_util_percent) { - if (moduleConfig.store_forward.enabled) { + // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); + storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); - if (config.device.role == Config_DeviceConfig_Role_ROUTER) { - - // Send out the message queue. - if (this->busy) { - - // Only send packets if the channel is less than 25% utilized. - if (airTime->channelUtilizationPercent() < polite_channel_util_percent) { - - // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); - storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); - - if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { - strcpy(this->routerMessage, "** S&F - Done"); - storeForwardModule->sendMessage(this->busyTo, this->routerMessage); - - // DEBUG_MSG("--- --- --- In busy loop - Done \n"); - this->packetHistoryTXQueue_index = 0; - this->busy = false; - } else { - this->packetHistoryTXQueue_index++; - } + if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { + strcpy(this->routerMessage, "** S&F - Done"); + storeForwardModule->sendMessage(this->busyTo, this->routerMessage); + // DEBUG_MSG("--- --- --- In busy loop - Done \n"); + this->packetHistoryTXQueue_index = 0; + this->busy = false; } else { - DEBUG_MSG("Channel utilization is too high. Skipping this opportunity to send and will retry later.\n"); + this->packetHistoryTXQueue_index++; } + + } else { + DEBUG_MSG("Channel utilization is too high. Retrying later.\n"); } - DEBUG_MSG("SF myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); + DEBUG_MSG("SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); - return (this->packetTimeMax); - } else { - DEBUG_MSG("Store & Forward Module - Disabled (is_router = false)\n"); + } else if (millis() - lastHeartbeat > 300000) { + lastHeartbeat = millis(); + DEBUG_MSG("Sending heartbeat\n"); + + StoreAndForward sf; + sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; + sf.has_heartbeat = true; + sf.heartbeat.period = 300; + sf.heartbeat.secondary = 0; // TODO we always have one primary router for now - return (INT32_MAX); + MeshPacket *p = allocDataProtobuf(sf); + p->to = NODENUM_BROADCAST; + p->decoded.want_response = false; + p->priority = MeshPacket_Priority_MIN; + service.sendToMesh(p); } - - } else { - DEBUG_MSG("Store & Forward Module - Disabled\n"); - - return (INT32_MAX); + return (this->packetTimeMax); } - #endif return (INT32_MAX); } @@ -76,12 +74,7 @@ void StoreForwardModule::populatePSRAM() https://learn.upesy.com/en/programmation/psram.html#psram-tab */ - DEBUG_MSG("Before PSRAM initilization:\n"); - - DEBUG_MSG(" Total heap: %d\n", ESP.getHeapSize()); - DEBUG_MSG(" Free heap: %d\n", ESP.getFreeHeap()); - DEBUG_MSG(" Total PSRAM: %d\n", ESP.getPsramSize()); - DEBUG_MSG(" Free PSRAM: %d\n", ESP.getFreePsram()); + DEBUG_MSG("Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); this->packetHistoryTXQueue = static_cast(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct))); @@ -93,19 +86,12 @@ void StoreForwardModule::populatePSRAM() this->packetHistory = static_cast(ps_calloc(numberOfPackets, sizeof(PacketHistoryStruct))); - DEBUG_MSG("After PSRAM initilization:\n"); - - DEBUG_MSG(" Total heap: %d\n", ESP.getHeapSize()); - DEBUG_MSG(" Free heap: %d\n", ESP.getFreeHeap()); - DEBUG_MSG(" Total PSRAM: %d\n", ESP.getPsramSize()); - DEBUG_MSG(" Free PSRAM: %d\n", ESP.getFreePsram()); - DEBUG_MSG("Store and Forward Stats:\n"); - DEBUG_MSG(" numberOfPackets for packetHistory - %u\n", numberOfPackets); + DEBUG_MSG("After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + DEBUG_MSG("numberOfPackets for packetHistory - %u\n", numberOfPackets); } void StoreForwardModule::historyReport() { - DEBUG_MSG("Iterating through the message history...\n"); DEBUG_MSG("Message history contains %u records\n", this->packetHistoryCurrent); } @@ -246,8 +232,8 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) DEBUG_MSG("--- S&F Received something\n"); - // The router node should not be sending messages as a client. - if (getFrom(&mp) != nodeDB.getNodeNum()) { + // The router node should not be sending messages as a client. Unless he is a ROUTER_CLIENT + if ((getFrom(&mp) != nodeDB.getNodeNum()) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { DEBUG_MSG("Packet came from - PortNum_TEXT_MESSAGE_APP\n"); @@ -264,6 +250,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) } else { storeForwardModule->historySend(1000 * 60, getFrom(&mp)); } + } else if ((p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 'm') && (p.payload.bytes[3] == 0x00)) { strlcpy(this->routerMessage, @@ -278,14 +265,12 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) } } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { + DEBUG_MSG("Packet came from an PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); } else { DEBUG_MSG("Packet came from an unknown port %u\n", mp.decoded.portnum); } } - - } else { - DEBUG_MSG("Store & Forward Module - Disabled\n"); } #endif @@ -293,92 +278,107 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) return ProcessMessage::CONTINUE; // Let others look at this message also if they want } -ProcessMessage StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p) +bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p) { if (!moduleConfig.store_forward.enabled) { // If this module is not enabled in any capacity, don't handle the packet, and allow other modules to consume - return ProcessMessage::CONTINUE; + return false; } - if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { - DEBUG_MSG("Packet came from an PortNum_TEXT_MESSAGE_APP port %u\n", mp.decoded.portnum); - return ProcessMessage::CONTINUE; - } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { - DEBUG_MSG("Packet came from an PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); - + if (mp.decoded.portnum != PortNum_STORE_FORWARD_APP) { + DEBUG_MSG("Packet came from port %u\n", mp.decoded.portnum); + return false; } else { - DEBUG_MSG("Packet came from an UNKNOWN port %u\n", mp.decoded.portnum); - return ProcessMessage::CONTINUE; - } + DEBUG_MSG("Packet came from PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); + switch (p->rr) { - case StoreAndForward_RequestResponse_CLIENT_ERROR: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_ERROR\n"); - break; + case StoreAndForward_RequestResponse_CLIENT_ERROR: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_ERROR\n"); + } + break; - case StoreAndForward_RequestResponse_CLIENT_HISTORY: - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_HISTORY\n"); + case StoreAndForward_RequestResponse_CLIENT_HISTORY: + if(is_server) { + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_HISTORY\n"); + // Send the last 60 minutes of messages. + if (this->busy) { + strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); + storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); + } else { + storeForwardModule->historySend(1000 * 60, getFrom(&mp)); + } + } + break; - // Send the last 60 minutes of messages. - if (this->busy) { - strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); - storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); - } else { - storeForwardModule->historySend(1000 * 60, getFrom(&mp)); + case StoreAndForward_RequestResponse_CLIENT_PING: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PING\n"); + } + break; + + case StoreAndForward_RequestResponse_CLIENT_PONG: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PONG\n"); + } + break; + + case StoreAndForward_RequestResponse_CLIENT_STATS: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_STATS\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_BUSY: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_ERROR: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_ERROR\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_HEARTBEAT\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_PING: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PING\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_PONG: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PONG\n"); + } + break; + + default: + assert(0); // unexpected state - FIXME, make an error code and reboot } - - break; - - case StoreAndForward_RequestResponse_CLIENT_PING: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PING\n"); - break; - - case StoreAndForward_RequestResponse_CLIENT_PONG: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PONG\n"); - break; - - case StoreAndForward_RequestResponse_CLIENT_STATS: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_STATS\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_BUSY: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_ERROR: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_ERROR\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_HEARTBEAT\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_PING: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PING\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_PONG: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PONG\n"); - break; - - default: - assert(0); // unexpected state - FIXME, make an error code and reboot } - return ProcessMessage::STOP; // There's no need for others to look at this message. + return true; // There's no need for others to look at this message. } StoreForwardModule::StoreForwardModule() - : SinglePortModule("StoreForwardModule", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("StoreForwardModule") + : concurrency::OSThread("StoreForwardModule"), ProtobufModule("StoreForward", PortNum_STORE_FORWARD_APP, &StoreAndForward_msg) { #ifdef ARCH_ESP32 @@ -397,9 +397,9 @@ StoreForwardModule::StoreForwardModule() if (moduleConfig.store_forward.enabled) { // Router - if (config.device.role == Config_DeviceConfig_Role_ROUTER) { - DEBUG_MSG("Initializing Store & Forward Module - Enabled as Router\n"); - if (ESP.getPsramSize()) { + if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + DEBUG_MSG("Initializing Store & Forward Module in Router mode\n"); + if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { // Do the startup here @@ -416,26 +416,27 @@ StoreForwardModule::StoreForwardModule() if (moduleConfig.store_forward.records) this->records = moduleConfig.store_forward.records; - // Maximum number of records to store in memory + // send heartbeat advertising? if (moduleConfig.store_forward.heartbeat) this->heartbeat = moduleConfig.store_forward.heartbeat; // Popupate PSRAM with our data structures. this->populatePSRAM(); - + is_server = true; } else { - DEBUG_MSG("Device has less than 1M of PSRAM free. Aborting startup.\n"); - DEBUG_MSG("Store & Forward Module - Aborting Startup.\n"); + DEBUG_MSG("Device has less than 1M of PSRAM free.\n"); + DEBUG_MSG("Store & Forward Module - disabling server.\n"); } - } else { DEBUG_MSG("Device doesn't have PSRAM.\n"); - DEBUG_MSG("Store & Forward Module - Aborting Startup.\n"); + DEBUG_MSG("Store & Forward Module - disabling server.\n"); } // Client - } else { - DEBUG_MSG("Initializing Store & Forward Module - Enabled as Client\n"); + } + if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + is_client = true; + DEBUG_MSG("Initializing Store & Forward Module in Client mode\n"); } } #endif diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index 2c6d6ec6e..32d3cddc9 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -1,6 +1,6 @@ #pragma once -#include "SinglePortModule.h" +#include "ProtobufModule.h" #include "concurrency/OSThread.h" #include "mesh/generated/storeforward.pb.h" @@ -18,9 +18,8 @@ struct PacketHistoryStruct { pb_size_t payload_size; }; -class StoreForwardModule : public SinglePortModule, private concurrency::OSThread +class StoreForwardModule : private concurrency::OSThread, public ProtobufModule { - // bool firstTime = 1; bool busy = 0; uint32_t busyTo = 0; char routerMessage[Constants_DATA_PAYLOAD_LEN] = {0}; @@ -34,7 +33,12 @@ class StoreForwardModule : public SinglePortModule, private concurrency::OSThrea uint32_t packetHistoryTXQueue_size = 0; uint32_t packetHistoryTXQueue_index = 0; - uint32_t packetTimeMax = 2000; + uint32_t packetTimeMax = 5000; + + unsigned long lastHeartbeat = 0; + + bool is_client = false; + bool is_server = false; public: StoreForwardModule(); @@ -78,7 +82,7 @@ class StoreForwardModule : public SinglePortModule, private concurrency::OSThrea it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; - virtual ProcessMessage handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p); + virtual bool handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p); }; From dbefa71bc8915835d69931a618b12860a48c61bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 30 Nov 2022 10:04:54 +0100 Subject: [PATCH 012/119] this define is arch specific --- arch/esp32/esp32.ini | 1 + arch/esp32/esp32s3.ini | 5 +++-- platformio.ini | 1 - 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/esp32/esp32.ini b/arch/esp32/esp32.ini index 70654e8ec..0011cc39f 100644 --- a/arch/esp32/esp32.ini +++ b/arch/esp32/esp32.ini @@ -26,6 +26,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 -DCONFIG_BT_NIMBLE_MAX_CCCDS=20 -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DDEBUG_HEAP lib_deps = ${arduino_base.lib_deps} diff --git a/arch/esp32/esp32s3.ini b/arch/esp32/esp32s3.ini index b05772344..72b176999 100644 --- a/arch/esp32/esp32s3.ini +++ b/arch/esp32/esp32s3.ini @@ -23,9 +23,10 @@ build_flags = -DMYNEWT_VAL_BLE_HS_LOG_LVL=LOG_LEVEL_CRITICAL -DAXP_DEBUG_PORT=Serial -DCONFIG_BT_NIMBLE_ENABLED - -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 + -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 -DCONFIG_BT_NIMBLE_MAX_CCCDS=20 - -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DDEBUG_HEAP lib_deps = ${arduino_base.lib_deps} diff --git a/platformio.ini b/platformio.ini index 792f2f8b1..dbddf7535 100644 --- a/platformio.ini +++ b/platformio.ini @@ -55,7 +55,6 @@ build_flags = -Wno-missing-field-initializers -DRADIOLIB_EXCLUDE_MORSE -DRADIOLIB_EXCLUDE_RTTY -DRADIOLIB_EXCLUDE_SSTV - -DDEBUG_HEAP monitor_speed = 115200 From c7529f9a3e2985a29583c85662b7f49d863a4602 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 30 Nov 2022 10:23:54 +0100 Subject: [PATCH 013/119] fix platform define here too --- arch/esp32/esp32.ini | 1 + arch/esp32/esp32s3.ini | 5 +++-- platformio.ini | 1 - 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/esp32/esp32.ini b/arch/esp32/esp32.ini index 70654e8ec..0011cc39f 100644 --- a/arch/esp32/esp32.ini +++ b/arch/esp32/esp32.ini @@ -26,6 +26,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 -DCONFIG_BT_NIMBLE_MAX_CCCDS=20 -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DDEBUG_HEAP lib_deps = ${arduino_base.lib_deps} diff --git a/arch/esp32/esp32s3.ini b/arch/esp32/esp32s3.ini index b05772344..72b176999 100644 --- a/arch/esp32/esp32s3.ini +++ b/arch/esp32/esp32s3.ini @@ -23,9 +23,10 @@ build_flags = -DMYNEWT_VAL_BLE_HS_LOG_LVL=LOG_LEVEL_CRITICAL -DAXP_DEBUG_PORT=Serial -DCONFIG_BT_NIMBLE_ENABLED - -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 + -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 -DCONFIG_BT_NIMBLE_MAX_CCCDS=20 - -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DDEBUG_HEAP lib_deps = ${arduino_base.lib_deps} diff --git a/platformio.ini b/platformio.ini index 792f2f8b1..dbddf7535 100644 --- a/platformio.ini +++ b/platformio.ini @@ -55,7 +55,6 @@ build_flags = -Wno-missing-field-initializers -DRADIOLIB_EXCLUDE_MORSE -DRADIOLIB_EXCLUDE_RTTY -DRADIOLIB_EXCLUDE_SSTV - -DDEBUG_HEAP monitor_speed = 115200 From fb898289902383541bffdd6e4b042c42510c1eea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 1 Dec 2022 17:47:04 +0100 Subject: [PATCH 014/119] Definition cleanup and AudioModule WIP --- arch/esp32/esp32s3.ini | 2 +- src/mesh/RadioInterface.h | 1 - src/mesh/RadioLibInterface.h | 3 +- src/modules/esp32/AudioModule.cpp | 102 ++++++++++++++++++++---------- src/modules/esp32/AudioModule.h | 16 +++-- src/platform/portduino/SimRadio.h | 1 - 6 files changed, 81 insertions(+), 44 deletions(-) diff --git a/arch/esp32/esp32s3.ini b/arch/esp32/esp32s3.ini index 72b176999..b276ceff9 100644 --- a/arch/esp32/esp32s3.ini +++ b/arch/esp32/esp32s3.ini @@ -35,7 +35,7 @@ lib_deps = https://github.com/meshtastic/esp32_https_server.git#23665b3adc080a311dcbb586ed5941b5f94d6ea2 h2zero/NimBLE-Arduino@^1.4.0 https://github.com/lewisxhe/XPowersLib.git#84b7373faea3118b6c37954d52f98b8a337148d6 - caveman99/ESP32 Codec2@^1.0.1 + caveman99/ESP32 Codec2@^1.0.1 lib_ignore = segger_rtt diff --git a/src/mesh/RadioInterface.h b/src/mesh/RadioInterface.h index 437f294a4..f50c0ae77 100644 --- a/src/mesh/RadioInterface.h +++ b/src/mesh/RadioInterface.h @@ -1,6 +1,5 @@ #pragma once -#include "../concurrency/NotifiedWorkerThread.h" #include "MemoryPool.h" #include "MeshTypes.h" #include "Observer.h" diff --git a/src/mesh/RadioLibInterface.h b/src/mesh/RadioLibInterface.h index f368cf83e..16495c2f4 100644 --- a/src/mesh/RadioLibInterface.h +++ b/src/mesh/RadioLibInterface.h @@ -1,10 +1,9 @@ #pragma once -#include "../concurrency/OSThread.h" +#include "concurrency/NotifiedWorkerThread.h" #include "RadioInterface.h" #include "MeshPacketQueue.h" -#define RADIOLIB_EXCLUDE_HTTP #include // ESP32 has special rules about ISR code diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 55677c0a9..7ff46bf10 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -42,6 +42,13 @@ #define AAMP 14 #define PTT_PIN 39 +#ifdef ARCH_ESP32 +// ESP32 doesn't use that flag +#define YIELD_FROM_ISR(x) portYIELD_FROM_ISR() +#else +#define YIELD_FROM_ISR(x) portYIELD_FROM_ISR(x) +#endif + // #define I2S_WS 13 // #define I2S_SD 15 // #define I2S_SIN 2 @@ -51,7 +58,6 @@ #define I2S_PORT I2S_NUM_0 #define AUDIO_MODULE_RX_BUFFER 128 -#define AUDIO_MODULE_DATA_MAX Constants_DATA_PAYLOAD_LEN #define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 AudioModule *audioModule; @@ -107,11 +113,11 @@ IRAM_ATTR void am_onTimer() if (adc_buffer_index == ADC_BUFFER_SIZE) { adc_buffer_index = 0; - DEBUG_MSG("--- memcpy\n"); + DEBUG_MSG("♪♫♪ memcpy\n"); memcpy((void*)speech, (void*)adc_buffer, 2 * ADC_BUFFER_SIZE); // Notify codec2 task that the buffer is ready. BaseType_t xHigherPriorityTaskWoken = pdFALSE; - DEBUG_MSG("--- notifyFromISR\n"); + DEBUG_MSG("♪♫♪ notifyFromISR\n"); codec2Thread->notifyFromISR(&xHigherPriorityTaskWoken, RadioState::tx, true); if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR(); @@ -133,42 +139,51 @@ IRAM_ATTR void am_onTimer() Codec2Thread::Codec2Thread() : concurrency::NotifiedWorkerThread("Codec2Thread") { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - DEBUG_MSG("--- Setting up codec2 in mode %u\n", moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); - codec2_state = codec2_create(moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE); + DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + codec2_state = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2_set_lpc_post_filter(codec2_state, 1, 0, 0.8, 0.2); + encode_codec_size = (codec2_bits_per_frame(codec2_state) + 7) / 8; + encode_frame_num = Constants_DATA_PAYLOAD_LEN / encode_codec_size; + encode_frame_size = encode_frame_num * encode_codec_size; // max 237 bytes + DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); } else { - DEBUG_MSG("--- Codec2 disabled\n"); + DEBUG_MSG("♪♫♪ Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { audio_fifo.init(); new Codec2Thread(); + //debug + moduleConfig.audio.i2s_ws = 13; + moduleConfig.audio.i2s_sd = 15; + moduleConfig.audio.i2s_din = 2; + moduleConfig.audio.i2s_sck = 14; } -void Codec2Thread::onNotify(uint32_t notification) +void IRAM_ATTR Codec2Thread::onNotify(uint32_t notification) { switch (notification) { case RadioState::tx: for (int i = 0; i < ADC_BUFFER_SIZE; i++) speech[i] = (int16_t)hp_filter.Update((float)speech[i]); - codec2_encode(codec2_state, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, speech); + codec2_encode(codec2_state, audioModule->tx_encode_frame + tx_encode_frame_index, speech); //increment the pointer where the encoded frame must be saved - audioModule->tx_encode_frame_index += 8; + tx_encode_frame_index += encode_codec_size; - //If it is the 5th time then we have a ready trasnmission frame - if (audioModule->tx_encode_frame_index == ENCODE_FRAME_SIZE) + //If it this is reached we have a ready trasnmission frame + if (tx_encode_frame_index == encode_frame_size) { - audioModule->tx_encode_frame_index = 0; + tx_encode_frame_index = 0; //Transmit it audioModule->sendPayload(); } break; case RadioState::rx: //Make a cycle to get each codec2 frame from the received frame - for (int i = 0; i < ENCODE_FRAME_SIZE; i += ENCODE_CODEC2_SIZE) + for (int i = 0; i < encode_frame_size; i += encode_codec_size) { //Decode the codec2 frame codec2_decode(codec2_state, output_buffer, audioModule->rx_encode_frame + i); @@ -187,25 +202,28 @@ void Codec2Thread::onNotify(uint32_t notification) int32_t AudioModule::runOnce() { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { + esp_err_t res; if (firstTime) { // if we have I2S_SD defined, take samples from digital mic. I2S_DIN means digital output to amp. if (moduleConfig.audio.i2s_sd || moduleConfig.audio.i2s_din) { - // Set up I2S Processor configuration. This will produce 16bit samples instead of 12 from the ADC - DEBUG_MSG("--- Initializing I2S for input\n"); + // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC + DEBUG_MSG("♪♫♪ Initializing I2S SD: %d DIN: %d WS: %d SCK:%d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), .sample_rate = 8000, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, - .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, + .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), - .intr_alloc_flags = 0, + .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = 8, - .dma_buf_len = ADC_BUFFER_SIZE, + .dma_buf_len = ADC_BUFFER_SIZE, // 320 * 2 bytes .use_apll = false, .tx_desc_auto_clear = true, .fixed_mclk = 0 }; - i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); + res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to install I2S driver: %d\n", res); const i2s_pin_config_t pin_config = { .bck_io_num = moduleConfig.audio.i2s_sck, @@ -213,13 +231,18 @@ int32_t AudioModule::runOnce() .data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE, .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE }; - i2s_set_pin(I2S_PORT, &pin_config); + res = i2s_set_pin(I2S_PORT, &pin_config); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to set I2S pin config: %d\n", res); - i2s_start(I2S_PORT); + res = i2s_start(I2S_PORT); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to start I2S: %d\n", res); } if (!moduleConfig.audio.i2s_sd) { - DEBUG_MSG("--- Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); + // Set up ADC if we don't have a digital microphone. + DEBUG_MSG("♪♫♪ Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; adc1_config_width(ADC_WIDTH_12Bit); adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); @@ -246,7 +269,7 @@ int32_t AudioModule::runOnce() adcTimer = timerBegin(3, 500, true); // 80 MHz / 500 = 160KHz break; } - DEBUG_MSG("--- Timer CPU Frequency: %u MHz\n", cpufreq); + DEBUG_MSG("♪♫♪ Timer CPU Frequency: %u MHz\n", cpufreq); timerAttachInterrupt(adcTimer, &am_onTimer, false); timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second timerAlarmEnable(adcTimer); @@ -255,10 +278,10 @@ int32_t AudioModule::runOnce() // setup analogue DAC only if we don't use I2S for output. This is not available on ESP32-S3 #if !defined(CONFIG_IDF_TARGET_ESP32S3) if (moduleConfig.audio.i2s_din) - DEBUG_MSG("--- Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); + DEBUG_MSG("♪♫♪ Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); #endif // Configure PTT input - DEBUG_MSG("--- Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + DEBUG_MSG("♪♫♪ Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; @@ -266,20 +289,35 @@ int32_t AudioModule::runOnce() // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { - DEBUG_MSG("--- PTT pressed, switching to TX\n"); + DEBUG_MSG("♪♫♪ PTT pressed, switching to TX\n"); radio_state = RadioState::tx; } } else { if (radio_state == RadioState::tx) { - DEBUG_MSG("--- PTT released, switching to RX\n"); + DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); radio_state = RadioState::rx; } } - + if ((radio_state == RadioState::tx) && moduleConfig.audio.i2s_sd) { + // Get I2S data from the microphone and place in data buffer + size_t bytesIn = 0; + res = i2s_read(I2S_PORT, &adc_buffer + adc_buffer_index, ADC_BUFFER_SIZE - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. + + if (res == ESP_OK) { + adc_buffer_index += bytesIn; + if (adc_buffer_index == ADC_BUFFER_SIZE) { + adc_buffer_index = 0; + DEBUG_MSG("♪♫♪ We have a full buffer, process it\n"); + memcpy((void*)speech, (void*)adc_buffer, 2 * ADC_BUFFER_SIZE); + // Notify codec2 task that the buffer is ready. + codec2Thread->notify(RadioState::tx, true); + } + } + } } return 100; } else { - DEBUG_MSG("--- Audio Module Disabled\n"); + DEBUG_MSG("♪♫♪ Audio Module Disabled\n"); return INT32_MAX; } @@ -300,7 +338,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) p->want_ack = false; // Audio is shoot&forget. TODO: Is this really suppressing retransmissions? p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime - p->decoded.payload.size = ENCODE_FRAME_SIZE; + p->decoded.payload.size = codec2Thread->get_encode_frame_size(); memcpy(p->decoded.payload.bytes, tx_encode_frame, p->decoded.payload.size); service.sendToMesh(p); @@ -311,7 +349,7 @@ ProcessMessage AudioModule::handleReceived(const MeshPacket &mp) if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { auto &p = mp.decoded; if (getFrom(&mp) != nodeDB.getNodeNum()) { - if (p.payload.size == ENCODE_FRAME_SIZE) { + if (p.payload.size == codec2Thread->get_encode_frame_size()) { memcpy(rx_encode_frame, p.payload.bytes, p.payload.size); radio_state = RadioState::rx; BaseType_t xHigherPriorityTaskWoken = pdFALSE; @@ -319,7 +357,7 @@ ProcessMessage AudioModule::handleReceived(const MeshPacket &mp) if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR(); } else { - DEBUG_MSG("--- Invalid payload size %u != %u\n", p.payload.size, ENCODE_FRAME_SIZE); + DEBUG_MSG("♪♫♪ Invalid payload size %u != %u\n", p.payload.size, codec2Thread->get_encode_frame_size()); } } } diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index b30e82bc2..47eba55ee 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -1,7 +1,7 @@ #pragma once #include "SinglePortModule.h" -#include "concurrency/OSThread.h" +#include "concurrency/NotifiedWorkerThread.h" #include "configuration.h" #if defined(ARCH_ESP32) #include "NodeDB.h" @@ -14,8 +14,6 @@ #include #define ADC_BUFFER_SIZE 320 // 40ms of voice in 8KHz sampling frequency -#define ENCODE_CODEC2_SIZE 8 -#define ENCODE_FRAME_SIZE (ENCODE_CODEC2_SIZE * 5) // 5 codec2 frames of 8 bytes each class Codec2Thread : public concurrency::NotifiedWorkerThread { @@ -25,7 +23,13 @@ class Codec2Thread : public concurrency::NotifiedWorkerThread public: Codec2Thread(); + int get_encode_frame_size() { return encode_frame_size; }; + protected: + int tx_encode_frame_index = 0; + int encode_codec_size = 0; + int encode_frame_num = 0; + int encode_frame_size = 0; virtual void onNotify(uint32_t notification) override; }; @@ -35,11 +39,9 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread hw_timer_t* adcTimer = NULL; uint16_t adc_buffer_index = 0; - public: - unsigned char rx_encode_frame[ENCODE_FRAME_SIZE] = {}; - unsigned char tx_encode_frame[ENCODE_FRAME_SIZE] = {}; - int tx_encode_frame_index = 0; + unsigned char rx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; + unsigned char tx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; AudioModule(); diff --git a/src/platform/portduino/SimRadio.h b/src/platform/portduino/SimRadio.h index dad419c62..a71cf22f8 100644 --- a/src/platform/portduino/SimRadio.h +++ b/src/platform/portduino/SimRadio.h @@ -4,7 +4,6 @@ #include "MeshPacketQueue.h" #include "wifi/WiFiServerAPI.h" -#define RADIOLIB_EXCLUDE_HTTP #include class SimRadio : public RadioInterface From 4b63730efb29ea748c47a30ce9641696224540a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 2 Dec 2022 00:30:31 +0100 Subject: [PATCH 015/119] Still WIP, but first working version of audio. I2S works good, analogue not so much. --- src/modules/Modules.cpp | 2 +- src/modules/esp32/AudioModule.cpp | 262 +++++++++++++++--------------- src/modules/esp32/AudioModule.h | 57 +++---- 3 files changed, 154 insertions(+), 167 deletions(-) diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index b97e965e1..b0b923863 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -66,7 +66,7 @@ void setupModules() #endif #ifdef ARCH_ESP32 // Only run on an esp32 based device. - new AudioModule(); + audioModule = new AudioModule(); new ExternalNotificationModule(); storeForwardModule = new StoreForwardModule(); diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 7ff46bf10..a47f47bd8 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -23,25 +23,36 @@ Basic Usage: 1) Enable the module by setting audio.codec2_enabled to 1. - 2) Set the pins (audio.mic_pin / audio.amp_pin) for your preferred microphone and amplifier GPIO pins. - On tbeam, recommend to use: + 2a) Set the pins for the I2S interface if you want to use digital audio. Recommended on TLora is I2S_WS 13/I2S_SD 15/I2S_SIN 2/I2S_SCK 14 + 2b) Set the pins (audio.mic_pin / audio.amp_pin) for your preferred microphone and amplifier GPIO pins if you want to use analog audio. + This is rather heavy on the CPU and not recommended. + On tbeam, best use: audio.mic_chan 6 (GPIO 34) audio.amp_pin 14 audio.ptt_pin 39 - 3) Set audio.timeout to the amount of time to wait before we consider - your voice stream as "done". - 4) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, CODEC2_1200, CODEC2_700, CODEC2_700B) + 3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, CODEC2_1200, CODEC2_700, CODEC2_700B) KNOWN PROBLEMS - * Until the module is initilized by the startup sequence, the amp_pin pin is in a floating - radio_state. This may produce a bit of "noise". - * Will not work on NRF and the Linux device targets. + * Until the module is initilized by the startup sequence, the amp_pin is in a floating + state. This may produce a bit of "noise". + * Will not work on NRF and the Linux device targets (yet?). */ #define AMIC 6 #define AAMP 14 #define PTT_PIN 39 +ButterworthFilter hp_filter(240, 8000, ButterworthFilter::ButterworthFilter::Highpass, 1); + +// Use I2S Processor 0 +#define I2S_PORT I2S_NUM_0 + +#define AUDIO_MODULE_RX_BUFFER 128 +#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 + +TaskHandle_t codec2HandlerTask; +AudioModule *audioModule; + #ifdef ARCH_ESP32 // ESP32 doesn't use that flag #define YIELD_FROM_ISR(x) portYIELD_FROM_ISR() @@ -49,36 +60,13 @@ #define YIELD_FROM_ISR(x) portYIELD_FROM_ISR(x) #endif -// #define I2S_WS 13 -// #define I2S_SD 15 -// #define I2S_SIN 2 -// #define I2S_SCK 14 - -// Use I2S Processor 0 -#define I2S_PORT I2S_NUM_0 - -#define AUDIO_MODULE_RX_BUFFER 128 -#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 - -AudioModule *audioModule; -Codec2Thread *codec2Thread; - -FastAudioFIFO audio_fifo; -uint16_t adc_buffer[ADC_BUFFER_SIZE] = {}; -uint16_t adc_buffer_index = 0; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; -int16_t speech[ADC_BUFFER_SIZE] = {}; -volatile RadioState radio_state = RadioState::tx; -adc1_channel_t mic_chan = (adc1_channel_t)0; - -ButterworthFilter hp_filter(240, 8000, ButterworthFilter::ButterworthFilter::Highpass, 1); +hw_timer_t* adcTimer = NULL; //int16_t 1KHz sine test tone int16_t Sine1KHz[8] = { -21210 , -30000, -21210, 0 , 21210 , 30000 , 21210, 0 }; int Sine1KHz_index = 0; -uint8_t rx_raw_audio_value = 127; - int IRAM_ATTR local_adc1_read(int channel) { uint16_t adc_value; #if CONFIG_IDF_TARGET_ESP32S3 @@ -102,8 +90,8 @@ int IRAM_ATTR local_adc1_read(int channel) { IRAM_ATTR void am_onTimer() { portENTER_CRITICAL_ISR(&timerMux); //Enter crital code without interruptions - if ((radio_state == RadioState::tx) && (!moduleConfig.audio.i2s_sd)) { - adc_buffer[adc_buffer_index++] = (16 * local_adc1_read(mic_chan)) - 32768; + if ((audioModule->radio_state == RadioState::tx) && (!moduleConfig.audio.i2s_sd)) { + audioModule->adc_buffer[audioModule->adc_buffer_index++] = (16 * local_adc1_read(audioModule->mic_chan)) - 32768; //If you want to test with a 1KHz tone, comment the line above and descomment the three lines below @@ -111,91 +99,90 @@ IRAM_ATTR void am_onTimer() // if (Sine1KHz_index >= 8) // Sine1KHz_index = 0; - if (adc_buffer_index == ADC_BUFFER_SIZE) { - adc_buffer_index = 0; - DEBUG_MSG("♪♫♪ memcpy\n"); - memcpy((void*)speech, (void*)adc_buffer, 2 * ADC_BUFFER_SIZE); - // Notify codec2 task that the buffer is ready. + if (audioModule->adc_buffer_index == audioModule->adc_buffer_size) { + audioModule->adc_buffer_index = 0; + memcpy((void*)audioModule->speech, (void*)audioModule->adc_buffer, 2 * audioModule->adc_buffer_size); BaseType_t xHigherPriorityTaskWoken = pdFALSE; - DEBUG_MSG("♪♫♪ notifyFromISR\n"); - codec2Thread->notifyFromISR(&xHigherPriorityTaskWoken, RadioState::tx, true); - if (xHigherPriorityTaskWoken) - portYIELD_FROM_ISR(); + vTaskNotifyGiveFromISR(codec2HandlerTask, &xHigherPriorityTaskWoken); + if (xHigherPriorityTaskWoken == pdTRUE) + YIELD_FROM_ISR(xHigherPriorityTaskWoken); } - } else if ((radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din)) { + } else if ((audioModule->radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din)) { // ESP32-S3 does not have DAC support #if !defined(CONFIG_IDF_TARGET_ESP32S3) - int16_t v; //Get a value from audio_fifo and convert it to 0 - 255 to play it in the ADC - if (audio_fifo.get(&v)) - rx_raw_audio_value = (uint8_t)((v + 32768) / 256); + if (audioModule->fifo.get(&audioModule->sample)) + audioModule->rx_raw_audio_value = (uint8_t)((audioModule->sample + 32768) / 256); - dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, rx_raw_audio_value); + dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, audioModule->rx_raw_audio_value); #endif } portEXIT_CRITICAL_ISR(&timerMux); // exit critical code } -Codec2Thread::Codec2Thread() : concurrency::NotifiedWorkerThread("Codec2Thread") { - if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); - codec2_state = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); - codec2_set_lpc_post_filter(codec2_state, 1, 0, 0.8, 0.2); - encode_codec_size = (codec2_bits_per_frame(codec2_state) + 7) / 8; - encode_frame_num = Constants_DATA_PAYLOAD_LEN / encode_codec_size; - encode_frame_size = encode_frame_num * encode_codec_size; // max 237 bytes - DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); - } else { - DEBUG_MSG("♪♫♪ Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); +void run_codec2(void* parameter) +{ + while (true) { + uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); + + if (tcount != 0) { + if (audioModule->radio_state == RadioState::tx) { + + for (int i = 0; i < audioModule->adc_buffer_size; i++) + audioModule->speech[i] = (int16_t)hp_filter.Update((float)audioModule->speech[i]); + + codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, audioModule->speech); + + //increment the pointer where the encoded frame must be saved + audioModule->tx_encode_frame_index += audioModule->encode_codec_size; + + //If it this is reached we have a ready trasnmission frame + if (audioModule->tx_encode_frame_index == audioModule->encode_frame_size) + { + //Transmit it + DEBUG_MSG("♪♫♪ Sending %d bytes\n", audioModule->encode_frame_size); + audioModule->sendPayload(); + audioModule->tx_encode_frame_index = 0; + } + } + if (audioModule->radio_state == RadioState::rx) { + //Make a cycle to get each codec2 frame from the received frame + for (int i = 0; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) + { + //Decode the codec2 frame + codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); + + if (moduleConfig.audio.i2s_din) { + size_t bytesOut = 0; + + i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(40)); + } else { + //Put the decoded audio in the fifo + for (int j = 0; j < audioModule->adc_buffer_size; j++) + audioModule->fifo.put(audioModule->output_buffer[j]); + } + } + } + } } } -AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { - audio_fifo.init(); - new Codec2Thread(); - //debug - moduleConfig.audio.i2s_ws = 13; - moduleConfig.audio.i2s_sd = 15; - moduleConfig.audio.i2s_din = 2; - moduleConfig.audio.i2s_sck = 14; -} - -void IRAM_ATTR Codec2Thread::onNotify(uint32_t notification) +AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { - switch (notification) { - case RadioState::tx: - for (int i = 0; i < ADC_BUFFER_SIZE; i++) - speech[i] = (int16_t)hp_filter.Update((float)speech[i]); - - codec2_encode(codec2_state, audioModule->tx_encode_frame + tx_encode_frame_index, speech); - - //increment the pointer where the encoded frame must be saved - tx_encode_frame_index += encode_codec_size; - - //If it this is reached we have a ready trasnmission frame - if (tx_encode_frame_index == encode_frame_size) - { - tx_encode_frame_index = 0; - //Transmit it - audioModule->sendPayload(); - } - break; - case RadioState::rx: - //Make a cycle to get each codec2 frame from the received frame - for (int i = 0; i < encode_frame_size; i += encode_codec_size) - { - //Decode the codec2 frame - codec2_decode(codec2_state, output_buffer, audioModule->rx_encode_frame + i); - - // Add to the audio buffer the 320 samples resulting of the decode of the codec2 frame. - for (int g = 0; g < ADC_BUFFER_SIZE; g++) - audio_fifo.put(output_buffer[g]); - } - break; - default: - assert(0); // We expected to receive a valid notification from the ISR - break; + if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { + fifo.init(); + DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + codec2_set_lpc_post_filter(codec2, 1, 0, 0.8, 0.2); + encode_codec_size = (codec2_bits_per_frame(codec2) + 7) / 8; + encode_frame_num = Constants_DATA_PAYLOAD_LEN / encode_codec_size; + encode_frame_size = encode_frame_num * encode_codec_size; // max 237 bytes + adc_buffer_size = codec2_samples_per_frame(codec2); + DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); + xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); + } else { + DEBUG_MSG("♪♫♪ Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -214,9 +201,9 @@ int32_t AudioModule::runOnce() .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), - .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, + .intr_alloc_flags = 0, .dma_buf_count = 8, - .dma_buf_len = ADC_BUFFER_SIZE, // 320 * 2 bytes + .dma_buf_len = adc_buffer_size, // 320 * 2 bytes .use_apll = false, .tx_desc_auto_clear = true, .fixed_mclk = 0 @@ -239,9 +226,20 @@ int32_t AudioModule::runOnce() if(res != ESP_OK) DEBUG_MSG("♪♫♪ Failed to start I2S: %d\n", res); } + + // setup analogue DAC only if we don't use I2S for output. This is not available on ESP32-S3 +#if !defined(CONFIG_IDF_TARGET_ESP32S3) + if (!moduleConfig.audio.i2s_din) + DEBUG_MSG("♪♫♪ Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); +#else + if (!moduleConfig.audio.i2s_din) { + DEBUG_MSG("♪♫♪ ESP32-S3 does not support DAC. Audio Module Disabled.\n"); + return INT32_MAX; + } +#endif if (!moduleConfig.audio.i2s_sd) { - // Set up ADC if we don't have a digital microphone. + // Set up ADC if we don't have a digital microphone. DEBUG_MSG("♪♫♪ Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; adc1_config_width(ADC_WIDTH_12Bit); @@ -249,8 +247,6 @@ int32_t AudioModule::runOnce() adc1_get_raw(mic_chan); } - radio_state = RadioState::rx; - if ((!moduleConfig.audio.i2s_sd) || (!moduleConfig.audio.i2s_din)) { // Start a timer at 8kHz to sample the ADC and play the audio on the DAC, but only if we have analogue audio to process uint32_t cpufreq = getCpuFrequencyMhz(); @@ -275,11 +271,8 @@ int32_t AudioModule::runOnce() timerAlarmEnable(adcTimer); } - // setup analogue DAC only if we don't use I2S for output. This is not available on ESP32-S3 -#if !defined(CONFIG_IDF_TARGET_ESP32S3) - if (moduleConfig.audio.i2s_din) - DEBUG_MSG("♪♫♪ Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); -#endif + radio_state = RadioState::rx; + // Configure PTT input DEBUG_MSG("♪♫♪ Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); @@ -294,23 +287,32 @@ int32_t AudioModule::runOnce() } } else { if (radio_state == RadioState::tx) { - DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); + if (tx_encode_frame_index > 0) { + // Send the incomplete frame + DEBUG_MSG("♪♫♪ Sending %d bytes (incomplete)\n", tx_encode_frame_index); + sendPayload(); + } + DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); + tx_encode_frame_index = 0; radio_state = RadioState::rx; } } if ((radio_state == RadioState::tx) && moduleConfig.audio.i2s_sd) { // Get I2S data from the microphone and place in data buffer size_t bytesIn = 0; - res = i2s_read(I2S_PORT, &adc_buffer + adc_buffer_index, ADC_BUFFER_SIZE - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. + res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. if (res == ESP_OK) { adc_buffer_index += bytesIn; - if (adc_buffer_index == ADC_BUFFER_SIZE) { + if (adc_buffer_index == adc_buffer_size) { adc_buffer_index = 0; - DEBUG_MSG("♪♫♪ We have a full buffer, process it\n"); - memcpy((void*)speech, (void*)adc_buffer, 2 * ADC_BUFFER_SIZE); - // Notify codec2 task that the buffer is ready. - codec2Thread->notify(RadioState::tx, true); + memcpy((void*)speech, (void*)adc_buffer, 2 * adc_buffer_size); + // Notify run_codec2 task that the buffer is ready. + radio_state = RadioState::tx; + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + vTaskNotifyGiveFromISR(codec2HandlerTask, &xHigherPriorityTaskWoken); + if (xHigherPriorityTaskWoken == pdTRUE) + YIELD_FROM_ISR(xHigherPriorityTaskWoken); } } } @@ -338,7 +340,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) p->want_ack = false; // Audio is shoot&forget. TODO: Is this really suppressing retransmissions? p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime - p->decoded.payload.size = codec2Thread->get_encode_frame_size(); + p->decoded.payload.size = tx_encode_frame_index; memcpy(p->decoded.payload.bytes, tx_encode_frame, p->decoded.payload.size); service.sendToMesh(p); @@ -349,16 +351,14 @@ ProcessMessage AudioModule::handleReceived(const MeshPacket &mp) if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { auto &p = mp.decoded; if (getFrom(&mp) != nodeDB.getNodeNum()) { - if (p.payload.size == codec2Thread->get_encode_frame_size()) { - memcpy(rx_encode_frame, p.payload.bytes, p.payload.size); - radio_state = RadioState::rx; - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - codec2Thread->notifyFromISR(&xHigherPriorityTaskWoken, RadioState::rx, true); - if (xHigherPriorityTaskWoken) - portYIELD_FROM_ISR(); - } else { - DEBUG_MSG("♪♫♪ Invalid payload size %u != %u\n", p.payload.size, codec2Thread->get_encode_frame_size()); - } + memcpy(rx_encode_frame, p.payload.bytes, p.payload.size); + radio_state = RadioState::rx; + rx_encode_frame_index = p.payload.size; + // Notify run_codec2 task that the buffer is ready. + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + vTaskNotifyGiveFromISR(codec2HandlerTask, &xHigherPriorityTaskWoken); + if (xHigherPriorityTaskWoken == pdTRUE) + YIELD_FROM_ISR(xHigherPriorityTaskWoken); } } diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index 47eba55ee..c81c5c310 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -7,41 +7,36 @@ #include "NodeDB.h" #include #include -#include +// #include #include #include #include #include -#define ADC_BUFFER_SIZE 320 // 40ms of voice in 8KHz sampling frequency +#define ADC_BUFFER_SIZE_MAX 320 -class Codec2Thread : public concurrency::NotifiedWorkerThread -{ - struct CODEC2* codec2_state = NULL; - int16_t output_buffer[ADC_BUFFER_SIZE] = {}; - - public: - Codec2Thread(); - - int get_encode_frame_size() { return encode_frame_size; }; - - protected: - int tx_encode_frame_index = 0; - int encode_codec_size = 0; - int encode_frame_num = 0; - int encode_frame_size = 0; - virtual void onNotify(uint32_t notification) override; -}; +enum RadioState { standby, rx, tx }; class AudioModule : public SinglePortModule, private concurrency::OSThread { - bool firstTime = true; - hw_timer_t* adcTimer = NULL; - uint16_t adc_buffer_index = 0; - public: unsigned char rx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; unsigned char tx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; + int16_t speech[ADC_BUFFER_SIZE_MAX] = {}; + int16_t output_buffer[ADC_BUFFER_SIZE_MAX] = {}; + uint16_t adc_buffer[ADC_BUFFER_SIZE_MAX] = {}; + int adc_buffer_size = 0; + uint16_t adc_buffer_index = 0; + int tx_encode_frame_index = 0; + int rx_encode_frame_index = 0; + int encode_codec_size = 0; + int encode_frame_size = 0; + volatile RadioState radio_state = RadioState::rx; + FastAudioFIFO fifo; + struct CODEC2* codec2 = NULL; + int16_t sample; + adc1_channel_t mic_chan = (adc1_channel_t)0; + uint8_t rx_raw_audio_value = 127; AudioModule(); @@ -51,9 +46,11 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread void sendPayload(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false); protected: - virtual int32_t runOnce() override; + int encode_frame_num = 0; + bool firstTime = true; - // void run_codec2(); + + virtual int32_t runOnce() override; virtual MeshPacket *allocReply() override; @@ -64,15 +61,5 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread }; extern AudioModule *audioModule; -extern Codec2Thread *codec2Thread; -extern uint16_t adc_buffer[ADC_BUFFER_SIZE]; -extern uint16_t adc_buffer_index; -extern portMUX_TYPE timerMux; -extern int16_t speech[ADC_BUFFER_SIZE]; -enum RadioState { standby, rx, tx }; -extern volatile RadioState radio_state; -extern adc1_channel_t mic_chan; - -IRAM_ATTR void am_onTimer(); #endif \ No newline at end of file From eb4f682ad1f7a9edf9b71fa161ca64831d8d8b0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 2 Dec 2022 12:20:21 +0100 Subject: [PATCH 016/119] debug print thread count. max_threads is 32 --- src/Power.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Power.cpp b/src/Power.cpp index 8da365caf..929f9a072 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -284,7 +284,7 @@ void Power::readPowerStatus() powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP - DEBUG_MSG("Heap status: %d/%d bytes free\n", ESP.getFreeHeap(), ESP.getHeapSize()); + DEBUG_MSG("Heap status: %d/%d bytes free, running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), concurrency::mainController.size(false)); #endif // If we have a battery at all and it is less than 10% full, force deep sleep if we have more than 3 low readings in a row From 470e711383b6a6a07cdb442d26ef42964a222dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 2 Dec 2022 12:58:26 +0100 Subject: [PATCH 017/119] Audio Module is finished for regression tests. --- protobufs | 2 +- src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/module_config.pb.h | 36 ++--- src/modules/esp32/AudioModule.cpp | 202 +++++--------------------- src/modules/esp32/AudioModule.h | 9 +- 5 files changed, 59 insertions(+), 192 deletions(-) diff --git a/protobufs b/protobufs index 2bb457de4..0a5959958 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 2bb457de42cd6d5c2a6e7d8a4992fc6c90e37de5 +Subproject commit 0a59599589bc77763e76302e533a4c4bfa5ec80e diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index b8c8b27ef..596bb7b9a 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -151,7 +151,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; /* Maximum encoded size of messages (where known) */ #define LocalConfig_size 387 -#define LocalModuleConfig_size 364 +#define LocalModuleConfig_size 358 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 189eb2ca5..4b2e29f17 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -63,8 +63,6 @@ typedef enum _ModuleConfig_CannedMessageConfig_InputEventChar { /* Struct definitions */ typedef struct _ModuleConfig_AudioConfig { bool codec2_enabled; - uint8_t mic_chan; - uint8_t amp_pin; uint8_t ptt_pin; ModuleConfig_AudioConfig_Audio_Baud bitrate; uint8_t i2s_ws; @@ -187,7 +185,7 @@ extern "C" { /* Initializer values for message structs */ #define ModuleConfig_init_default {0, {ModuleConfig_MQTTConfig_init_default}} #define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} -#define ModuleConfig_AudioConfig_init_default {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} +#define ModuleConfig_AudioConfig_init_default {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} @@ -196,7 +194,7 @@ extern "C" { #define ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} #define ModuleConfig_init_zero {0, {ModuleConfig_MQTTConfig_init_zero}} #define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} -#define ModuleConfig_AudioConfig_init_zero {0, 0, 0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} +#define ModuleConfig_AudioConfig_init_zero {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} @@ -206,14 +204,12 @@ extern "C" { /* Field tags (for use in manual encoding/decoding) */ #define ModuleConfig_AudioConfig_codec2_enabled_tag 1 -#define ModuleConfig_AudioConfig_mic_chan_tag 2 -#define ModuleConfig_AudioConfig_amp_pin_tag 3 -#define ModuleConfig_AudioConfig_ptt_pin_tag 4 -#define ModuleConfig_AudioConfig_bitrate_tag 5 -#define ModuleConfig_AudioConfig_i2s_ws_tag 6 -#define ModuleConfig_AudioConfig_i2s_sd_tag 7 -#define ModuleConfig_AudioConfig_i2s_din_tag 8 -#define ModuleConfig_AudioConfig_i2s_sck_tag 9 +#define ModuleConfig_AudioConfig_ptt_pin_tag 2 +#define ModuleConfig_AudioConfig_bitrate_tag 3 +#define ModuleConfig_AudioConfig_i2s_ws_tag 4 +#define ModuleConfig_AudioConfig_i2s_sd_tag 5 +#define ModuleConfig_AudioConfig_i2s_din_tag 6 +#define ModuleConfig_AudioConfig_i2s_sck_tag 7 #define ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 #define ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 #define ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 @@ -300,14 +296,12 @@ X(a, STATIC, SINGULAR, BOOL, json_enabled, 6) #define ModuleConfig_AudioConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, codec2_enabled, 1) \ -X(a, STATIC, SINGULAR, UINT32, mic_chan, 2) \ -X(a, STATIC, SINGULAR, UINT32, amp_pin, 3) \ -X(a, STATIC, SINGULAR, UINT32, ptt_pin, 4) \ -X(a, STATIC, SINGULAR, UENUM, bitrate, 5) \ -X(a, STATIC, SINGULAR, UINT32, i2s_ws, 6) \ -X(a, STATIC, SINGULAR, UINT32, i2s_sd, 7) \ -X(a, STATIC, SINGULAR, UINT32, i2s_din, 8) \ -X(a, STATIC, SINGULAR, UINT32, i2s_sck, 9) +X(a, STATIC, SINGULAR, UINT32, ptt_pin, 2) \ +X(a, STATIC, SINGULAR, UENUM, bitrate, 3) \ +X(a, STATIC, SINGULAR, UINT32, i2s_ws, 4) \ +X(a, STATIC, SINGULAR, UINT32, i2s_sd, 5) \ +X(a, STATIC, SINGULAR, UINT32, i2s_din, 6) \ +X(a, STATIC, SINGULAR, UINT32, i2s_sck, 7) #define ModuleConfig_AudioConfig_CALLBACK NULL #define ModuleConfig_AudioConfig_DEFAULT NULL @@ -395,7 +389,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; #define ModuleConfig_CannedMessageConfig_fields &ModuleConfig_CannedMessageConfig_msg /* Maximum encoded size of messages (where known) */ -#define ModuleConfig_AudioConfig_size 25 +#define ModuleConfig_AudioConfig_size 19 #define ModuleConfig_CannedMessageConfig_size 49 #define ModuleConfig_ExternalNotificationConfig_size 22 #define ModuleConfig_MQTTConfig_size 169 diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index a47f47bd8..b1433a0ae 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -8,8 +8,6 @@ #include "Router.h" #include "FSCommon.h" -#include -#include #include /* @@ -23,23 +21,14 @@ Basic Usage: 1) Enable the module by setting audio.codec2_enabled to 1. - 2a) Set the pins for the I2S interface if you want to use digital audio. Recommended on TLora is I2S_WS 13/I2S_SD 15/I2S_SIN 2/I2S_SCK 14 - 2b) Set the pins (audio.mic_pin / audio.amp_pin) for your preferred microphone and amplifier GPIO pins if you want to use analog audio. - This is rather heavy on the CPU and not recommended. - On tbeam, best use: - audio.mic_chan 6 (GPIO 34) - audio.amp_pin 14 - audio.ptt_pin 39 + 2) Set the pins for the I2S interface. Recommended on TLora is I2S_WS 13/I2S_SD 15/I2S_SIN 2/I2S_SCK 14 3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, CODEC2_1200, CODEC2_700, CODEC2_700B) KNOWN PROBLEMS - * Until the module is initilized by the startup sequence, the amp_pin is in a floating - state. This may produce a bit of "noise". + * Half Duplex * Will not work on NRF and the Linux device targets (yet?). */ -#define AMIC 6 -#define AAMP 14 #define PTT_PIN 39 ButterworthFilter hp_filter(240, 8000, ButterworthFilter::ButterworthFilter::Highpass, 1); @@ -60,67 +49,10 @@ AudioModule *audioModule; #define YIELD_FROM_ISR(x) portYIELD_FROM_ISR(x) #endif -portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; -hw_timer_t* adcTimer = NULL; - //int16_t 1KHz sine test tone int16_t Sine1KHz[8] = { -21210 , -30000, -21210, 0 , 21210 , 30000 , 21210, 0 }; int Sine1KHz_index = 0; -int IRAM_ATTR local_adc1_read(int channel) { - uint16_t adc_value; -#if CONFIG_IDF_TARGET_ESP32S3 - SENS.sar_meas1_ctrl2.sar1_en_pad = (1 << channel); // only one channel is selected - while (SENS.sar_slave_addr1.meas_status != 0); - SENS.sar_meas1_ctrl2.meas1_start_sar = 0; - SENS.sar_meas1_ctrl2.meas1_start_sar = 1; - while (SENS.sar_meas1_ctrl2.meas1_done_sar == 0); - adc_value = SENS.sar_meas1_ctrl2.meas1_data_sar; -#else - SENS.sar_meas_start1.sar1_en_pad = (1 << channel); // only one channel is selected - while (SENS.sar_slave_addr1.meas_status != 0); - SENS.sar_meas_start1.meas1_start_sar = 0; - SENS.sar_meas_start1.meas1_start_sar = 1; - while (SENS.sar_meas_start1.meas1_done_sar == 0); - adc_value = SENS.sar_meas_start1.meas1_data_sar; -#endif - return adc_value; -} - -IRAM_ATTR void am_onTimer() -{ - portENTER_CRITICAL_ISR(&timerMux); //Enter crital code without interruptions - if ((audioModule->radio_state == RadioState::tx) && (!moduleConfig.audio.i2s_sd)) { - audioModule->adc_buffer[audioModule->adc_buffer_index++] = (16 * local_adc1_read(audioModule->mic_chan)) - 32768; - - //If you want to test with a 1KHz tone, comment the line above and descomment the three lines below - - // adc_buffer[adc_buffer_index++] = Sine1KHz[Sine1KHz_index++]; - // if (Sine1KHz_index >= 8) - // Sine1KHz_index = 0; - - if (audioModule->adc_buffer_index == audioModule->adc_buffer_size) { - audioModule->adc_buffer_index = 0; - memcpy((void*)audioModule->speech, (void*)audioModule->adc_buffer, 2 * audioModule->adc_buffer_size); - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - vTaskNotifyGiveFromISR(codec2HandlerTask, &xHigherPriorityTaskWoken); - if (xHigherPriorityTaskWoken == pdTRUE) - YIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - } else if ((audioModule->radio_state == RadioState::rx) && (!moduleConfig.audio.i2s_din)) { - // ESP32-S3 does not have DAC support -#if !defined(CONFIG_IDF_TARGET_ESP32S3) - - //Get a value from audio_fifo and convert it to 0 - 255 to play it in the ADC - if (audioModule->fifo.get(&audioModule->sample)) - audioModule->rx_raw_audio_value = (uint8_t)((audioModule->sample + 32768) / 256); - - dacWrite(moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP, audioModule->rx_raw_audio_value); -#endif - } - portEXIT_CRITICAL_ISR(&timerMux); // exit critical code -} - void run_codec2(void* parameter) { while (true) { @@ -128,10 +60,12 @@ void run_codec2(void* parameter) if (tcount != 0) { if (audioModule->radio_state == RadioState::tx) { - + + // Apply the TX filter for (int i = 0; i < audioModule->adc_buffer_size; i++) audioModule->speech[i] = (int16_t)hp_filter.Update((float)audioModule->speech[i]); + // Encode the audio codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, audioModule->speech); //increment the pointer where the encoded frame must be saved @@ -141,7 +75,7 @@ void run_codec2(void* parameter) if (audioModule->tx_encode_frame_index == audioModule->encode_frame_size) { //Transmit it - DEBUG_MSG("♪♫♪ Sending %d bytes\n", audioModule->encode_frame_size); + DEBUG_MSG("♪♫♪ Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = 0; } @@ -152,16 +86,8 @@ void run_codec2(void* parameter) { //Decode the codec2 frame codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); - - if (moduleConfig.audio.i2s_din) { - size_t bytesOut = 0; - - i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(40)); - } else { - //Put the decoded audio in the fifo - for (int j = 0; j < audioModule->adc_buffer_size; j++) - audioModule->fifo.put(audioModule->output_buffer[j]); - } + size_t bytesOut = 0; + i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); } } } @@ -171,7 +97,6 @@ void run_codec2(void* parameter) AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - fifo.init(); DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2_set_lpc_post_filter(codec2, 1, 0, 0.8, 0.2); @@ -191,86 +116,39 @@ int32_t AudioModule::runOnce() if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { esp_err_t res; if (firstTime) { - // if we have I2S_SD defined, take samples from digital mic. I2S_DIN means digital output to amp. - if (moduleConfig.audio.i2s_sd || moduleConfig.audio.i2s_din) { - // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC - DEBUG_MSG("♪♫♪ Initializing I2S SD: %d DIN: %d WS: %d SCK:%d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); - i2s_config_t i2s_config = { - .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), - .sample_rate = 8000, - .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, - .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, - .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), - .intr_alloc_flags = 0, - .dma_buf_count = 8, - .dma_buf_len = adc_buffer_size, // 320 * 2 bytes - .use_apll = false, - .tx_desc_auto_clear = true, - .fixed_mclk = 0 - }; - res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); - if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to install I2S driver: %d\n", res); + // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC + DEBUG_MSG("♪♫♪ Initializing I2S SD: %d DIN: %d WS: %d SCK:%d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); + i2s_config_t i2s_config = { + .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), + .sample_rate = 8000, + .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, + .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, + .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), + .intr_alloc_flags = 0, + .dma_buf_count = 8, + .dma_buf_len = adc_buffer_size, // 320 * 2 bytes + .use_apll = false, + .tx_desc_auto_clear = true, + .fixed_mclk = 0 + }; + res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to install I2S driver: %d\n", res); - const i2s_pin_config_t pin_config = { - .bck_io_num = moduleConfig.audio.i2s_sck, - .ws_io_num = moduleConfig.audio.i2s_ws, - .data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE, - .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE - }; - res = i2s_set_pin(I2S_PORT, &pin_config); - if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to set I2S pin config: %d\n", res); + const i2s_pin_config_t pin_config = { + .bck_io_num = moduleConfig.audio.i2s_sck, + .ws_io_num = moduleConfig.audio.i2s_ws, + .data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE, + .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE + }; + res = i2s_set_pin(I2S_PORT, &pin_config); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to set I2S pin config: %d\n", res); - res = i2s_start(I2S_PORT); - if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to start I2S: %d\n", res); - } - - // setup analogue DAC only if we don't use I2S for output. This is not available on ESP32-S3 -#if !defined(CONFIG_IDF_TARGET_ESP32S3) - if (!moduleConfig.audio.i2s_din) - DEBUG_MSG("♪♫♪ Initializing DAC on Pin %u\n", moduleConfig.audio.amp_pin ? moduleConfig.audio.amp_pin : AAMP); -#else - if (!moduleConfig.audio.i2s_din) { - DEBUG_MSG("♪♫♪ ESP32-S3 does not support DAC. Audio Module Disabled.\n"); - return INT32_MAX; - } -#endif + res = i2s_start(I2S_PORT); + if(res != ESP_OK) + DEBUG_MSG("♪♫♪ Failed to start I2S: %d\n", res); - if (!moduleConfig.audio.i2s_sd) { - // Set up ADC if we don't have a digital microphone. - DEBUG_MSG("♪♫♪ Initializing ADC on Channel %u\n", moduleConfig.audio.mic_chan ? moduleConfig.audio.mic_chan : AMIC); - mic_chan = moduleConfig.audio.mic_chan ? (adc1_channel_t)(int)moduleConfig.audio.mic_chan : (adc1_channel_t)AMIC; - adc1_config_width(ADC_WIDTH_12Bit); - adc1_config_channel_atten(mic_chan, ADC_ATTEN_DB_6); - adc1_get_raw(mic_chan); - } - - if ((!moduleConfig.audio.i2s_sd) || (!moduleConfig.audio.i2s_din)) { - // Start a timer at 8kHz to sample the ADC and play the audio on the DAC, but only if we have analogue audio to process - uint32_t cpufreq = getCpuFrequencyMhz(); - switch (cpufreq){ - case 160: - adcTimer = timerBegin(3, 1000, true); // 160 MHz / 1000 = 160KHz - break; - case 240: - adcTimer = timerBegin(3, 1500, true); // 240 MHz / 1500 = 160KHz - break; - case 320: - adcTimer = timerBegin(3, 2000, true); // 320 MHz / 2000 = 160KHz - break; - case 80: - default: - adcTimer = timerBegin(3, 500, true); // 80 MHz / 500 = 160KHz - break; - } - DEBUG_MSG("♪♫♪ Timer CPU Frequency: %u MHz\n", cpufreq); - timerAttachInterrupt(adcTimer, &am_onTimer, false); - timerAlarmWrite(adcTimer, 20, true); // Interrupts when counter == 20, 8.000 times a second - timerAlarmEnable(adcTimer); - } - radio_state = RadioState::rx; // Configure PTT input @@ -289,7 +167,7 @@ int32_t AudioModule::runOnce() if (radio_state == RadioState::tx) { if (tx_encode_frame_index > 0) { // Send the incomplete frame - DEBUG_MSG("♪♫♪ Sending %d bytes (incomplete)\n", tx_encode_frame_index); + DEBUG_MSG("♪♫♪ Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); @@ -297,7 +175,7 @@ int32_t AudioModule::runOnce() radio_state = RadioState::rx; } } - if ((radio_state == RadioState::tx) && moduleConfig.audio.i2s_sd) { + if (radio_state == RadioState::tx) { // Get I2S data from the microphone and place in data buffer size_t bytesIn = 0; res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index c81c5c310..aee09a0b0 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -7,11 +7,9 @@ #include "NodeDB.h" #include #include -// #include #include #include #include -#include #define ADC_BUFFER_SIZE_MAX 320 @@ -32,11 +30,9 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread int encode_codec_size = 0; int encode_frame_size = 0; volatile RadioState radio_state = RadioState::rx; - FastAudioFIFO fifo; + struct CODEC2* codec2 = NULL; - int16_t sample; - adc1_channel_t mic_chan = (adc1_channel_t)0; - uint8_t rx_raw_audio_value = 127; + // int16_t sample; AudioModule(); @@ -49,7 +45,6 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread int encode_frame_num = 0; bool firstTime = true; - virtual int32_t runOnce() override; virtual MeshPacket *allocReply() override; From bb1a9192ebbd8d177249e1015cce31f7d72e720b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 2 Dec 2022 13:44:36 +0100 Subject: [PATCH 018/119] send a 4 byte magic header including the codec version --- src/modules/esp32/AudioModule.cpp | 25 +++++++++++-------------- src/modules/esp32/AudioModule.h | 20 +++++++++++++++++--- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index b1433a0ae..4e784e1a9 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -29,16 +29,8 @@ * Will not work on NRF and the Linux device targets (yet?). */ -#define PTT_PIN 39 - ButterworthFilter hp_filter(240, 8000, ButterworthFilter::ButterworthFilter::Highpass, 1); -// Use I2S Processor 0 -#define I2S_PORT I2S_NUM_0 - -#define AUDIO_MODULE_RX_BUFFER 128 -#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 - TaskHandle_t codec2HandlerTask; AudioModule *audioModule; @@ -55,6 +47,9 @@ int Sine1KHz_index = 0; void run_codec2(void* parameter) { + // 4 bytes of header in each frame Kennung hex c0 de c2 plus the bitrate + memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); + while (true) { uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); @@ -72,12 +67,12 @@ void run_codec2(void* parameter) audioModule->tx_encode_frame_index += audioModule->encode_codec_size; //If it this is reached we have a ready trasnmission frame - if (audioModule->tx_encode_frame_index == audioModule->encode_frame_size) + if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) { //Transmit it DEBUG_MSG("♪♫♪ Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); - audioModule->tx_encode_frame_index = 0; + audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); } } if (audioModule->radio_state == RadioState::rx) { @@ -99,10 +94,12 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); + tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; codec2_set_lpc_post_filter(codec2, 1, 0, 0.8, 0.2); encode_codec_size = (codec2_bits_per_frame(codec2) + 7) / 8; - encode_frame_num = Constants_DATA_PAYLOAD_LEN / encode_codec_size; - encode_frame_size = encode_frame_num * encode_codec_size; // max 237 bytes + encode_frame_num = (Constants_DATA_PAYLOAD_LEN - sizeof(tx_header)) / encode_codec_size; + encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes adc_buffer_size = codec2_samples_per_frame(codec2); DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); @@ -165,13 +162,13 @@ int32_t AudioModule::runOnce() } } else { if (radio_state == RadioState::tx) { - if (tx_encode_frame_index > 0) { + if (tx_encode_frame_index > sizeof(tx_header)) { // Send the incomplete frame DEBUG_MSG("♪♫♪ Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); - tx_encode_frame_index = 0; + tx_encode_frame_index = sizeof(tx_header); radio_state = RadioState::rx; } } diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index aee09a0b0..8e813ad1e 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -11,21 +11,35 @@ #include #include -#define ADC_BUFFER_SIZE_MAX 320 - enum RadioState { standby, rx, tx }; +const char c2_magic[3] = {0xc0, 0xde, 0xc2}; // Magic number for codec2 header + +struct c2_header { + char magic[3]; + char mode; +}; + +#define ADC_BUFFER_SIZE_MAX 320 +#define PTT_PIN 39 + +#define I2S_PORT I2S_NUM_0 + +#define AUDIO_MODULE_RX_BUFFER 128 +#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 + class AudioModule : public SinglePortModule, private concurrency::OSThread { public: unsigned char rx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; unsigned char tx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; + c2_header tx_header = {}; int16_t speech[ADC_BUFFER_SIZE_MAX] = {}; int16_t output_buffer[ADC_BUFFER_SIZE_MAX] = {}; uint16_t adc_buffer[ADC_BUFFER_SIZE_MAX] = {}; int adc_buffer_size = 0; uint16_t adc_buffer_index = 0; - int tx_encode_frame_index = 0; + int tx_encode_frame_index = sizeof(c2_header); // leave room for header int rx_encode_frame_index = 0; int encode_codec_size = 0; int encode_frame_size = 0; From 911083c49d8ee58dec810dd74ff2f0cf045af381 Mon Sep 17 00:00:00 2001 From: code8buster Date: Sun, 4 Dec 2022 01:57:00 -0500 Subject: [PATCH 019/119] Adds a flag to turn the GPS power rail off entirely on tbeam --- src/ButtonThread.h | 17 +++++++++++++++-- src/gps/GPS.cpp | 1 - src/gps/GPS.h | 4 +++- src/sleep.cpp | 16 ++++++++++++++++ src/sleep.h | 2 +- variants/tbeam/platformio.ini | 1 + 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 088642099..23859b8ad 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -5,6 +5,7 @@ #include "configuration.h" #include "graphics/Screen.h" #include "power.h" +#include "GPS.h" #include namespace concurrency @@ -159,9 +160,21 @@ class ButtonThread : public concurrency::OSThread static void userButtonDoublePressed() { -#if defined(USE_EINK) && defined(PIN_EINK_EN) + #if defined(USE_EINK) && defined(PIN_EINK_EN) digitalWrite(PIN_EINK_EN, digitalRead(PIN_EINK_EN) == LOW); -#endif + #endif + #if defined(GPS_POWER_TOGGLE) + if(gps->gpsPowerflag) + { + DEBUG_MSG("Flag set to false for gps power\n"); + } + else + { + DEBUG_MSG("Flag set to true to restore power\n"); + } + gps->gpsPowerflag = !(gps->gpsPowerflag); + doGPSpowersave(gps->gpsPowerflag); + #endif } static void userButtonMultiPressed() diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 54dc59cbb..2a00af475 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -276,7 +276,6 @@ bool GPS::setup() delay(10); digitalWrite(PIN_GPS_RESET, 0); #endif - setAwake(true); // Wake GPS power before doing any init bool ok = setupGPS(); diff --git a/src/gps/GPS.h b/src/gps/GPS.h index 8f04b6793..c9f0ff41b 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -77,6 +77,8 @@ class GPS : private concurrency::OSThread /// Return true if we are connected to a GPS bool isConnected() const { return hasGPS; } + bool gpsPowerflag; + /** * Restart our lock attempt - try to get and broadcast a GPS reading ASAP * called after the CPU wakes from light-sleep state @@ -128,7 +130,6 @@ class GPS : private concurrency::OSThread void setNumSatellites(uint8_t n); - private: /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs /// always returns 0 to indicate okay to sleep int prepareSleep(void *unused); @@ -136,6 +137,7 @@ class GPS : private concurrency::OSThread /// Prepare the GPS for the cpu entering deep sleep, expect to be gone for at least 100s of msecs /// always returns 0 to indicate okay to sleep int prepareDeepSleep(void *unused); + private: /** * Switch the GPS into a mode where we are actively looking for a lock, or alternatively switch GPS into a low power mode diff --git a/src/sleep.cpp b/src/sleep.cpp index 39ee43ebc..7f6735939 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -167,6 +167,22 @@ static void waitEnterSleep() notifySleep.notifyObservers(NULL); } +void doGPSpowersave(bool on) +{ + if (on) + { + DEBUG_MSG("Turning GPS back on\n"); + gps->forceWake(1); + setGPSPower(1); + } + else + { + DEBUG_MSG("Turning off GPS chip\n"); + notifySleep.notifyObservers(NULL); + setGPSPower(0); + } +} + void doDeepSleep(uint64_t msecToWake) { DEBUG_MSG("Entering deep sleep for %lu seconds\n", msecToWake / 1000); diff --git a/src/sleep.h b/src/sleep.h index 7f0592af4..f911a7cc8 100644 --- a/src/sleep.h +++ b/src/sleep.h @@ -13,7 +13,7 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t msecToWake); extern esp_sleep_source_t wakeCause; #endif void setGPSPower(bool on); - +void doGPSpowersave(bool on); // Perform power on init that we do on each wake from deep sleep void initDeepSleep(); diff --git a/variants/tbeam/platformio.ini b/variants/tbeam/platformio.ini index 578a74f7b..df526ae5b 100644 --- a/variants/tbeam/platformio.ini +++ b/variants/tbeam/platformio.ini @@ -6,4 +6,5 @@ lib_deps = ${esp32_base.lib_deps} build_flags = ${esp32_base.build_flags} -D TBEAM_V10 -I variants/tbeam + ;-DGPS_POWER_TOGGLE ;uncomment this line to allow a double press on the user button to turn off gps entirely. upload_speed = 921600 From 53da7cb0361a7bc7b165c7ce735dbfef3328b6b3 Mon Sep 17 00:00:00 2001 From: code8buster Date: Sun, 4 Dec 2022 02:38:14 -0500 Subject: [PATCH 020/119] Add initialized value to constructor --- src/gps/GPS.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gps/GPS.h b/src/gps/GPS.h index c9f0ff41b..f77d13a80 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -77,7 +77,7 @@ class GPS : private concurrency::OSThread /// Return true if we are connected to a GPS bool isConnected() const { return hasGPS; } - bool gpsPowerflag; + bool gpsPowerflag = 1; /** * Restart our lock attempt - try to get and broadcast a GPS reading ASAP From 03bfdec1e1fe33e2b62a42e4b32d053747a2ead9 Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Mon, 5 Dec 2022 20:38:06 +0100 Subject: [PATCH 021/119] TraceRouteModule --- src/mesh/FloodingRouter.cpp | 5 ++ src/mesh/FloodingRouter.h | 1 + src/modules/Modules.cpp | 2 + src/modules/TraceRouteModule.cpp | 86 ++++++++++++++++++++++++++++++++ src/modules/TraceRouteModule.h | 36 +++++++++++++ 5 files changed, 130 insertions(+) create mode 100644 src/modules/TraceRouteModule.cpp create mode 100644 src/modules/TraceRouteModule.h diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 818bacf45..925735903 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -41,6 +41,11 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) tosend->hop_limit--; // bump down the hop count + // If it is a traceRoute request, update the route that it went via me + if (p->which_payload_variant == MeshPacket_decoded_tag && traceRouteModule->wantPacket(p)) { + traceRouteModule->updateRoute(tosend); + } + printPacket("Rebroadcasting received floodmsg to neighbors", p); // Note: we are careful to resend using the original senders node id // We are careful not to call our hooked version of send() - because we don't want to check this again diff --git a/src/mesh/FloodingRouter.h b/src/mesh/FloodingRouter.h index 387b4576b..7e6271fc0 100644 --- a/src/mesh/FloodingRouter.h +++ b/src/mesh/FloodingRouter.h @@ -2,6 +2,7 @@ #include "PacketHistory.h" #include "Router.h" +#include "modules/TraceRouteModule.h" /** * This is a mixin that extends Router with the ability to do Naive Flooding (in the standard mesh protocol sense) diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index b0b923863..ece160ced 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -11,6 +11,7 @@ #include "modules/ReplyModule.h" #include "modules/RoutingModule.h" #include "modules/TextMessageModule.h" +#include "modules/TraceRouteModule.h" #include "modules/WaypointModule.h" #if HAS_TELEMETRY #include "modules/Telemetry/DeviceTelemetry.h" @@ -40,6 +41,7 @@ void setupModules() positionModule = new PositionModule(); waypointModule = new WaypointModule(); textMessageModule = new TextMessageModule(); + traceRouteModule = new TraceRouteModule(); // Note: if the rest of meshtastic doesn't need to explicitly use your module, you do not need to assign the instance // to a global variable. diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp new file mode 100644 index 000000000..1c5fd97d3 --- /dev/null +++ b/src/modules/TraceRouteModule.cpp @@ -0,0 +1,86 @@ +#include "TraceRouteModule.h" +#include "MeshService.h" +#include "FloodingRouter.h" + +TraceRouteModule *traceRouteModule; + + +bool TraceRouteModule::handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) +{ + // Only handle a response + if (mp.decoded.request_id) { + printRoute(r, mp.to, mp.from); + } + + return false; // let it be handled by RoutingModule +} + + +void TraceRouteModule::updateRoute(MeshPacket* p) +{ + auto &incoming = p->decoded; + // Only append an ID for the request (one way) + if (!incoming.request_id) { + RouteDiscovery scratch; + RouteDiscovery *updated = NULL; + memset(&scratch, 0, sizeof(scratch)); + pb_decode_from_bytes(incoming.payload.bytes, incoming.payload.size, RouteDiscovery_fields, &scratch); + updated = &scratch; + + appendMyID(updated); + printRoute(updated, p->from, NODENUM_BROADCAST); + + // Set updated route to the payload of the to be flooded packet + p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), RouteDiscovery_fields, updated); + } +} + + +void TraceRouteModule::appendMyID(RouteDiscovery* updated) +{ + // Length of route array can normally not be exceeded due to the max. hop_limit of 7 + if (updated->route_count < sizeof(updated->route)/sizeof(updated->route[0])) { + updated->route[updated->route_count] = myNodeInfo.my_node_num; + updated->route_count += 1; + } else { + DEBUG_MSG("WARNING: Route exceeded maximum hop limit, are you bridging networks?\n"); + } +} + + +void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest) +{ + DEBUG_MSG("Route traced:\n"); + DEBUG_MSG("0x%x --> ", origin); + for (uint8_t i=0; iroute_count; i++) { + DEBUG_MSG("0x%x --> ", r->route[i]); + } + if (dest != NODENUM_BROADCAST) DEBUG_MSG("0x%x\n", dest); else DEBUG_MSG("...\n"); +} + + +MeshPacket* TraceRouteModule::allocReply() +{ + assert(currentRequest); + + // Copy the payload of the current request + auto req = *currentRequest; + auto &p = req.decoded; + RouteDiscovery scratch; + RouteDiscovery *updated = NULL; + memset(&scratch, 0, sizeof(scratch)); + pb_decode_from_bytes(p.payload.bytes, p.payload.size, RouteDiscovery_fields, &scratch); + updated = &scratch; + + printRoute(updated, req.from, req.to); + + // Create a MeshPacket with this payload and set it as the reply + MeshPacket* reply = allocDataProtobuf(*updated); + + return reply; +} + + +TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, RouteDiscovery_fields) { + ourPortNum = PortNum_TRACEROUTE_APP; +} diff --git a/src/modules/TraceRouteModule.h b/src/modules/TraceRouteModule.h new file mode 100644 index 000000000..15b7a564d --- /dev/null +++ b/src/modules/TraceRouteModule.h @@ -0,0 +1,36 @@ +#pragma once +#include "ProtobufModule.h" + + +/** + * A module that traces the route to a certain destination node + */ +class TraceRouteModule : public ProtobufModule +{ + public: + TraceRouteModule(); + + // Let FloodingRouter call updateRoute upon rebroadcasting a TraceRoute request + friend class FloodingRouter; + + protected: + bool handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) override; + + virtual MeshPacket *allocReply() override; + + /* Call before rebroadcasting a RouteDiscovery payload in order to update + the route array containing the IDs of nodes this packet went through */ + void updateRoute(MeshPacket* p); + + private: + // Call to add your ID to the route array of a RouteDiscovery message + void appendMyID(RouteDiscovery *r); + + /* Call to print the route array of a RouteDiscovery message. + Set origin to where the request came from. + Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */ + void printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest); + +}; + +extern TraceRouteModule *traceRouteModule; \ No newline at end of file From 0f7e6b896481a9cf90f2488c22aa16948cae9997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 6 Dec 2022 13:55:43 +0100 Subject: [PATCH 022/119] update submodule protobufs to latest --- protobufs | 2 +- src/mesh/generated/portnums.pb.h | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/protobufs b/protobufs index 0a5959958..0dbf6e9e2 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 0a59599589bc77763e76302e533a4c4bfa5ec80e +Subproject commit 0dbf6e9e24bfcaf5a2323f1480ae57304969989b diff --git a/src/mesh/generated/portnums.pb.h b/src/mesh/generated/portnums.pb.h index ec7b7eaec..74805ed10 100644 --- a/src/mesh/generated/portnums.pb.h +++ b/src/mesh/generated/portnums.pb.h @@ -82,6 +82,9 @@ typedef enum _PortNum { Maintained by GitHub user GUVWAF. Project files at https://github.com/GUVWAF/Meshtasticator */ PortNum_SIMULATOR_APP = 69, + /* Provides a traceroute functionality to show the route a packet towards + a certain destination would take on the mesh. */ + PortNum_TRACEROUTE_APP = 70, /* Private applications should use portnums >= 256. To simplify initial development and testing you can use "PRIVATE_APP" in your code without needing to rebuild protobuf files (via [regen-protos.sh](https://github.com/meshtastic/firmware/blob/master/bin/regen-protos.sh)) */ From a00187b97fd2478e03efe910d1953cc1eaa65652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 6 Dec 2022 16:56:38 +0100 Subject: [PATCH 023/119] manual master merge --- boards/tbeam-s3-core.json | 6 +- src/Power.cpp | 8 +- src/mesh/RadioLibInterface.cpp | 1 + src/modules/SerialModule.cpp | 8 +- src/modules/esp32/StoreForwardModule.cpp | 273 ++++++++++++----------- src/modules/esp32/StoreForwardModule.h | 14 +- src/mqtt/MQTT.cpp | 22 +- 7 files changed, 181 insertions(+), 151 deletions(-) diff --git a/boards/tbeam-s3-core.json b/boards/tbeam-s3-core.json index 82d858df8..ee66650fc 100644 --- a/boards/tbeam-s3-core.json +++ b/boards/tbeam-s3-core.json @@ -1,6 +1,6 @@ { "build": { - "arduino":{ + "arduino": { "ldscript": "esp32s3_out.ld" }, "core": "esp32", @@ -8,9 +8,7 @@ "-DBOARD_HAS_PSRAM", "-DLILYGO_TBEAM_S3_CORE", "-DARDUINO_USB_CDC_ON_BOOT=1", - "-DARDUINO_USB_DFU_ON_BOOT=1", - "-DARDUINO_USB_MSC_ON_BOOT=1", - "-DARDUINO_USB_MODE=1", + "-DARDUINO_USB_MODE=0", "-DARDUINO_RUNNING_CORE=1", "-DARDUINO_EVENT_RUNNING_CORE=1" ], diff --git a/src/Power.cpp b/src/Power.cpp index 929f9a072..5a493c4fd 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -458,6 +458,9 @@ bool Power::axpChipInit() // Set constant current charging current PMU->setChargerConstantCurr(XPOWERS_AXP192_CHG_CUR_450MA); + //Set up the charging voltage + PMU->setChargeTargetVoltage(XPOWERS_AXP192_CHG_VOL_4V2); + } else if (PMU->getChipModel() == XPOWERS_AXP2101) { // t-beam s3 core @@ -510,6 +513,8 @@ bool Power::axpChipInit() //Set the constant current charging current of AXP2101, temporarily use 500mA by default PMU->setChargerConstantCurr(XPOWERS_AXP2101_CHG_CUR_500MA); + //Set up the charging voltage + PMU->setChargeTargetVoltage(XPOWERS_AXP2101_CHG_VOL_4V2); } @@ -563,9 +568,6 @@ bool Power::axpChipInit() DEBUG_MSG("=======================================================================\n"); - //Set up the charging voltage, AXP2101/AXP192 4.2V gear is the same - // XPOWERS_AXP192_CHG_VOL_4V2 = XPOWERS_AXP2101_CHG_VOL_4V2 - PMU->setChargeTargetVoltage(XPOWERS_AXP192_CHG_VOL_4V2); // Set PMU shutdown voltage at 2.6V to maximize battery utilization PMU->setSysPowerDownVoltage(2600); diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 567215600..022576659 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -386,6 +386,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) int res = iface->startTransmit(radiobuf, numbytes); if (res != RADIOLIB_ERR_NONE) { + DEBUG_MSG("startTransmit failed, error=%d\n", res); RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG); // This send failed, but make sure to 'complete' it properly diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 05ed44cd7..aaaf3b144 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -214,7 +214,6 @@ int32_t SerialModule::runOnce() MeshPacket *SerialModuleRadio::allocReply() { - auto reply = allocDataPacket(); // Allocate a packet for sending return reply; @@ -266,7 +265,12 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_DEFAULT || moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_SIMPLE) { Serial2.printf("%s", p.payload.bytes); - + } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG) { + NodeInfo *node = nodeDB.getNode(getFrom(&mp)); + String sender = (node && node->has_user) ? node->user.short_name : "???"; + Serial2.println(); + Serial2.printf("%s: %s", sender, p.payload.bytes); + Serial2.println(); } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { // TODO this needs to be implemented } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index e51296824..9d1c44c18 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -16,52 +16,50 @@ StoreForwardModule *storeForwardModule; int32_t StoreForwardModule::runOnce() { - #ifdef ARCH_ESP32 + if (moduleConfig.store_forward.enabled && is_server) { + // Send out the message queue. + if (this->busy) { + // Only send packets if the channel is less than 25% utilized. + if (airTime->channelUtilizationPercent() < polite_channel_util_percent) { - if (moduleConfig.store_forward.enabled) { + // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); + storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); - if (config.device.role == Config_DeviceConfig_Role_ROUTER) { - - // Send out the message queue. - if (this->busy) { - - // Only send packets if the channel is less than 25% utilized. - if (airTime->channelUtilizationPercent() < polite_channel_util_percent) { - - // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); - storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); - - if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { - strcpy(this->routerMessage, "** S&F - Done"); - storeForwardModule->sendMessage(this->busyTo, this->routerMessage); - - // DEBUG_MSG("--- --- --- In busy loop - Done \n"); - this->packetHistoryTXQueue_index = 0; - this->busy = false; - } else { - this->packetHistoryTXQueue_index++; - } + if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { + strcpy(this->routerMessage, "** S&F - Done"); + storeForwardModule->sendMessage(this->busyTo, this->routerMessage); + // DEBUG_MSG("--- --- --- In busy loop - Done \n"); + this->packetHistoryTXQueue_index = 0; + this->busy = false; } else { - DEBUG_MSG("Channel utilization is too high. Skipping this opportunity to send and will retry later.\n"); + this->packetHistoryTXQueue_index++; } + + } else { + DEBUG_MSG("Channel utilization is too high. Retrying later.\n"); } - DEBUG_MSG("SF myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); + DEBUG_MSG("SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); - return (this->packetTimeMax); - } else { - DEBUG_MSG("Store & Forward Module - Disabled (is_router = false)\n"); + } else if (millis() - lastHeartbeat > 300000) { + lastHeartbeat = millis(); + DEBUG_MSG("Sending heartbeat\n"); + + StoreAndForward sf; + sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; + sf.has_heartbeat = true; + sf.heartbeat.period = 300; + sf.heartbeat.secondary = 0; // TODO we always have one primary router for now - return (INT32_MAX); + MeshPacket *p = allocDataProtobuf(sf); + p->to = NODENUM_BROADCAST; + p->decoded.want_response = false; + p->priority = MeshPacket_Priority_MIN; + service.sendToMesh(p); } - - } else { - DEBUG_MSG("Store & Forward Module - Disabled\n"); - - return (INT32_MAX); + return (this->packetTimeMax); } - #endif return (INT32_MAX); } @@ -76,12 +74,7 @@ void StoreForwardModule::populatePSRAM() https://learn.upesy.com/en/programmation/psram.html#psram-tab */ - DEBUG_MSG("Before PSRAM initilization:\n"); - - DEBUG_MSG(" Total heap: %d\n", ESP.getHeapSize()); - DEBUG_MSG(" Free heap: %d\n", ESP.getFreeHeap()); - DEBUG_MSG(" Total PSRAM: %d\n", ESP.getPsramSize()); - DEBUG_MSG(" Free PSRAM: %d\n", ESP.getFreePsram()); + DEBUG_MSG("Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); this->packetHistoryTXQueue = static_cast(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct))); @@ -93,19 +86,12 @@ void StoreForwardModule::populatePSRAM() this->packetHistory = static_cast(ps_calloc(numberOfPackets, sizeof(PacketHistoryStruct))); - DEBUG_MSG("After PSRAM initilization:\n"); - - DEBUG_MSG(" Total heap: %d\n", ESP.getHeapSize()); - DEBUG_MSG(" Free heap: %d\n", ESP.getFreeHeap()); - DEBUG_MSG(" Total PSRAM: %d\n", ESP.getPsramSize()); - DEBUG_MSG(" Free PSRAM: %d\n", ESP.getFreePsram()); - DEBUG_MSG("Store and Forward Stats:\n"); - DEBUG_MSG(" numberOfPackets for packetHistory - %u\n", numberOfPackets); + DEBUG_MSG("After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + DEBUG_MSG("numberOfPackets for packetHistory - %u\n", numberOfPackets); } void StoreForwardModule::historyReport() { - DEBUG_MSG("Iterating through the message history...\n"); DEBUG_MSG("Message history contains %u records\n", this->packetHistoryCurrent); } @@ -246,8 +232,8 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) DEBUG_MSG("--- S&F Received something\n"); - // The router node should not be sending messages as a client. - if (getFrom(&mp) != nodeDB.getNodeNum()) { + // The router node should not be sending messages as a client. Unless he is a ROUTER_CLIENT + if ((getFrom(&mp) != nodeDB.getNodeNum()) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { DEBUG_MSG("Packet came from - PortNum_TEXT_MESSAGE_APP\n"); @@ -264,6 +250,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) } else { storeForwardModule->historySend(1000 * 60, getFrom(&mp)); } + } else if ((p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 'm') && (p.payload.bytes[3] == 0x00)) { strlcpy(this->routerMessage, @@ -278,14 +265,12 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) } } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { + DEBUG_MSG("Packet came from an PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); } else { DEBUG_MSG("Packet came from an unknown port %u\n", mp.decoded.portnum); } } - - } else { - DEBUG_MSG("Store & Forward Module - Disabled\n"); } #endif @@ -293,92 +278,107 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) return ProcessMessage::CONTINUE; // Let others look at this message also if they want } -ProcessMessage StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p) +bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p) { if (!moduleConfig.store_forward.enabled) { // If this module is not enabled in any capacity, don't handle the packet, and allow other modules to consume - return ProcessMessage::CONTINUE; + return false; } - if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { - DEBUG_MSG("Packet came from an PortNum_TEXT_MESSAGE_APP port %u\n", mp.decoded.portnum); - return ProcessMessage::CONTINUE; - } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { - DEBUG_MSG("Packet came from an PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); - + if (mp.decoded.portnum != PortNum_STORE_FORWARD_APP) { + DEBUG_MSG("Packet came from port %u\n", mp.decoded.portnum); + return false; } else { - DEBUG_MSG("Packet came from an UNKNOWN port %u\n", mp.decoded.portnum); - return ProcessMessage::CONTINUE; - } + DEBUG_MSG("Packet came from PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); + switch (p->rr) { - case StoreAndForward_RequestResponse_CLIENT_ERROR: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_ERROR\n"); - break; + case StoreAndForward_RequestResponse_CLIENT_ERROR: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_ERROR\n"); + } + break; - case StoreAndForward_RequestResponse_CLIENT_HISTORY: - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_HISTORY\n"); + case StoreAndForward_RequestResponse_CLIENT_HISTORY: + if(is_server) { + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_HISTORY\n"); + // Send the last 60 minutes of messages. + if (this->busy) { + strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); + storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); + } else { + storeForwardModule->historySend(1000 * 60, getFrom(&mp)); + } + } + break; - // Send the last 60 minutes of messages. - if (this->busy) { - strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); - storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); - } else { - storeForwardModule->historySend(1000 * 60, getFrom(&mp)); + case StoreAndForward_RequestResponse_CLIENT_PING: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PING\n"); + } + break; + + case StoreAndForward_RequestResponse_CLIENT_PONG: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PONG\n"); + } + break; + + case StoreAndForward_RequestResponse_CLIENT_STATS: + if(is_server) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_STATS\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_BUSY: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_ERROR: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_ERROR\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_HEARTBEAT\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_PING: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PING\n"); + } + break; + + case StoreAndForward_RequestResponse_ROUTER_PONG: + if(is_client) { + // Do nothing + DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PONG\n"); + } + break; + + default: + assert(0); // unexpected state - FIXME, make an error code and reboot } - - break; - - case StoreAndForward_RequestResponse_CLIENT_PING: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PING\n"); - break; - - case StoreAndForward_RequestResponse_CLIENT_PONG: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PONG\n"); - break; - - case StoreAndForward_RequestResponse_CLIENT_STATS: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_STATS\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_BUSY: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_ERROR: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_ERROR\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_HEARTBEAT\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_PING: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PING\n"); - break; - - case StoreAndForward_RequestResponse_ROUTER_PONG: - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PONG\n"); - break; - - default: - assert(0); // unexpected state - FIXME, make an error code and reboot } - return ProcessMessage::STOP; // There's no need for others to look at this message. + return true; // There's no need for others to look at this message. } StoreForwardModule::StoreForwardModule() - : SinglePortModule("StoreForwardModule", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("StoreForwardModule") + : concurrency::OSThread("StoreForwardModule"), ProtobufModule("StoreForward", PortNum_STORE_FORWARD_APP, &StoreAndForward_msg) { #ifdef ARCH_ESP32 @@ -397,9 +397,9 @@ StoreForwardModule::StoreForwardModule() if (moduleConfig.store_forward.enabled) { // Router - if (config.device.role == Config_DeviceConfig_Role_ROUTER) { - DEBUG_MSG("Initializing Store & Forward Module - Enabled as Router\n"); - if (ESP.getPsramSize()) { + if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + DEBUG_MSG("Initializing Store & Forward Module in Router mode\n"); + if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { // Do the startup here @@ -416,26 +416,27 @@ StoreForwardModule::StoreForwardModule() if (moduleConfig.store_forward.records) this->records = moduleConfig.store_forward.records; - // Maximum number of records to store in memory + // send heartbeat advertising? if (moduleConfig.store_forward.heartbeat) this->heartbeat = moduleConfig.store_forward.heartbeat; // Popupate PSRAM with our data structures. this->populatePSRAM(); - + is_server = true; } else { - DEBUG_MSG("Device has less than 1M of PSRAM free. Aborting startup.\n"); - DEBUG_MSG("Store & Forward Module - Aborting Startup.\n"); + DEBUG_MSG("Device has less than 1M of PSRAM free.\n"); + DEBUG_MSG("Store & Forward Module - disabling server.\n"); } - } else { DEBUG_MSG("Device doesn't have PSRAM.\n"); - DEBUG_MSG("Store & Forward Module - Aborting Startup.\n"); + DEBUG_MSG("Store & Forward Module - disabling server.\n"); } // Client - } else { - DEBUG_MSG("Initializing Store & Forward Module - Enabled as Client\n"); + } + if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + is_client = true; + DEBUG_MSG("Initializing Store & Forward Module in Client mode\n"); } } #endif diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index 2c6d6ec6e..32d3cddc9 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -1,6 +1,6 @@ #pragma once -#include "SinglePortModule.h" +#include "ProtobufModule.h" #include "concurrency/OSThread.h" #include "mesh/generated/storeforward.pb.h" @@ -18,9 +18,8 @@ struct PacketHistoryStruct { pb_size_t payload_size; }; -class StoreForwardModule : public SinglePortModule, private concurrency::OSThread +class StoreForwardModule : private concurrency::OSThread, public ProtobufModule { - // bool firstTime = 1; bool busy = 0; uint32_t busyTo = 0; char routerMessage[Constants_DATA_PAYLOAD_LEN] = {0}; @@ -34,7 +33,12 @@ class StoreForwardModule : public SinglePortModule, private concurrency::OSThrea uint32_t packetHistoryTXQueue_size = 0; uint32_t packetHistoryTXQueue_index = 0; - uint32_t packetTimeMax = 2000; + uint32_t packetTimeMax = 5000; + + unsigned long lastHeartbeat = 0; + + bool is_client = false; + bool is_server = false; public: StoreForwardModule(); @@ -78,7 +82,7 @@ class StoreForwardModule : public SinglePortModule, private concurrency::OSThrea it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; - virtual ProcessMessage handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p); + virtual bool handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p); }; diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 8af009bad..96135bc34 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -61,7 +61,27 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) } else { DEBUG_MSG("JSON Ignoring downlink message we originally sent.\n"); } - } else { + } else if ((json.find("sender") != json.end()) && (json.find("payload") != json.end()) && (json.find("type") != json.end()) && json["type"]->IsString() && (json["type"]->AsString().compare("sendposition") == 0)) { + //invent the "sendposition" type for a valid envelope + if (json["payload"]->IsObject() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) { + JSONObject posit; + posit=json["payload"]->AsObject(); //get nested JSON Position + Position pos =Position_init_default; + pos.latitude_i=posit["latitude_i"]->AsNumber(); + pos.longitude_i=posit["longitude_i"]->AsNumber(); + pos.altitude=posit["altitude"]->AsNumber(); + pos.time=posit["time"]->AsNumber(); + + // construct protobuf data packet using POSITION, send it to the mesh + MeshPacket *p = router->allocForSending(); + p->decoded.portnum = PortNum_POSITION_APP; + p->decoded.payload.size=pb_encode_to_bytes(p->decoded.payload.bytes,sizeof(p->decoded.payload.bytes),Position_fields, &pos); //make the Data protobuf from position + service.sendToMesh(p, RX_SRC_LOCAL); + + } else { + DEBUG_MSG("JSON Ignoring downlink message we originally sent.\n"); + } + } else{ DEBUG_MSG("JSON Received payload on MQTT but not a valid envelope\n"); } } else { From 60e6dc113483d1c1d839d4e6ae57328e67003117 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 8 Dec 2022 10:43:18 +0100 Subject: [PATCH 024/119] update protobufs manually --- protobufs | 2 +- src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/module_config.pb.h | 26 ++++++++++++++++++++++---- src/mesh/generated/telemetry.pb.h | 8 ++++---- 4 files changed, 28 insertions(+), 10 deletions(-) diff --git a/protobufs b/protobufs index 0dbf6e9e2..c85791a85 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 0dbf6e9e24bfcaf5a2323f1480ae57304969989b +Subproject commit c85791a8543a5210786dc3579e099cb5ffbf72b9 diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 596bb7b9a..6f0635bdc 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -151,7 +151,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; /* Maximum encoded size of messages (where known) */ #define LocalConfig_size 387 -#define LocalModuleConfig_size 358 +#define LocalModuleConfig_size 378 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 4b2e29f17..9e77dd54c 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -93,6 +93,12 @@ typedef struct _ModuleConfig_ExternalNotificationConfig { bool alert_message; bool alert_bell; bool use_pwm; + uint32_t output_vibra; + uint32_t output_buzzer; + bool alert_message_vibra; + bool alert_message_buzzer; + bool alert_bell_vibra; + bool alert_bell_buzzer; } ModuleConfig_ExternalNotificationConfig; typedef struct _ModuleConfig_MQTTConfig { @@ -187,7 +193,7 @@ extern "C" { #define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} #define ModuleConfig_AudioConfig_init_default {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0} +#define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} #define ModuleConfig_RangeTestConfig_init_default {0, 0, 0} #define ModuleConfig_TelemetryConfig_init_default {0, 0, 0, 0, 0} @@ -196,7 +202,7 @@ extern "C" { #define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} #define ModuleConfig_AudioConfig_init_zero {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0} +#define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} #define ModuleConfig_RangeTestConfig_init_zero {0, 0, 0} #define ModuleConfig_TelemetryConfig_init_zero {0, 0, 0, 0, 0} @@ -228,6 +234,12 @@ extern "C" { #define ModuleConfig_ExternalNotificationConfig_alert_message_tag 5 #define ModuleConfig_ExternalNotificationConfig_alert_bell_tag 6 #define ModuleConfig_ExternalNotificationConfig_use_pwm_tag 7 +#define ModuleConfig_ExternalNotificationConfig_output_vibra_tag 8 +#define ModuleConfig_ExternalNotificationConfig_output_buzzer_tag 9 +#define ModuleConfig_ExternalNotificationConfig_alert_message_vibra_tag 10 +#define ModuleConfig_ExternalNotificationConfig_alert_message_buzzer_tag 11 +#define ModuleConfig_ExternalNotificationConfig_alert_bell_vibra_tag 12 +#define ModuleConfig_ExternalNotificationConfig_alert_bell_buzzer_tag 13 #define ModuleConfig_MQTTConfig_enabled_tag 1 #define ModuleConfig_MQTTConfig_address_tag 2 #define ModuleConfig_MQTTConfig_username_tag 3 @@ -323,7 +335,13 @@ X(a, STATIC, SINGULAR, UINT32, output, 3) \ X(a, STATIC, SINGULAR, BOOL, active, 4) \ X(a, STATIC, SINGULAR, BOOL, alert_message, 5) \ X(a, STATIC, SINGULAR, BOOL, alert_bell, 6) \ -X(a, STATIC, SINGULAR, BOOL, use_pwm, 7) +X(a, STATIC, SINGULAR, BOOL, use_pwm, 7) \ +X(a, STATIC, SINGULAR, UINT32, output_vibra, 8) \ +X(a, STATIC, SINGULAR, UINT32, output_buzzer, 9) \ +X(a, STATIC, SINGULAR, BOOL, alert_message_vibra, 10) \ +X(a, STATIC, SINGULAR, BOOL, alert_message_buzzer, 11) \ +X(a, STATIC, SINGULAR, BOOL, alert_bell_vibra, 12) \ +X(a, STATIC, SINGULAR, BOOL, alert_bell_buzzer, 13) #define ModuleConfig_ExternalNotificationConfig_CALLBACK NULL #define ModuleConfig_ExternalNotificationConfig_DEFAULT NULL @@ -391,7 +409,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; /* Maximum encoded size of messages (where known) */ #define ModuleConfig_AudioConfig_size 19 #define ModuleConfig_CannedMessageConfig_size 49 -#define ModuleConfig_ExternalNotificationConfig_size 22 +#define ModuleConfig_ExternalNotificationConfig_size 42 #define ModuleConfig_MQTTConfig_size 169 #define ModuleConfig_RangeTestConfig_size 10 #define ModuleConfig_SerialConfig_size 26 diff --git a/src/mesh/generated/telemetry.pb.h b/src/mesh/generated/telemetry.pb.h index 8c5c68bfa..16e69f442 100644 --- a/src/mesh/generated/telemetry.pb.h +++ b/src/mesh/generated/telemetry.pb.h @@ -69,10 +69,10 @@ typedef struct _EnvironmentMetrics { /* Types of Measurements the telemetry module is equipped to handle */ typedef struct _Telemetry { - /* This is usually not sent over the mesh (to save space), but it is sent - from the phone so that the local device can set its RTC If it is sent over - the mesh (because there are devices on the mesh without GPS), it will only - be sent by devices which has a hardware GPS clock (IE Mobile Phone). + /* This is usually not sent over the mesh (to save space), but it is sent + from the phone so that the local device can set its RTC If it is sent over + the mesh (because there are devices on the mesh without GPS), it will only + be sent by devices which has a hardware GPS clock (IE Mobile Phone). seconds since 1970 */ uint32_t time; pb_size_t which_variant; From 32d9a397aa5ef0515fd6344bcd17cb2b4f7015bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 8 Dec 2022 16:27:56 +0100 Subject: [PATCH 025/119] Toggle up to 3 pins after output_ms till nag_timeout or user button press happens --- protobufs | 2 +- src/ButtonThread.h | 5 + src/mesh/generated/localonly.pb.h | 2 +- src/mesh/generated/module_config.pb.h | 15 +- src/modules/ExternalNotificationModule.cpp | 230 +++++++++++++++------ src/modules/ExternalNotificationModule.h | 13 +- src/modules/Modules.cpp | 2 +- 7 files changed, 188 insertions(+), 81 deletions(-) diff --git a/protobufs b/protobufs index c85791a85..737d1fc01 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit c85791a8543a5210786dc3579e099cb5ffbf72b9 +Subproject commit 737d1fc01bd7f57e48e9b8cd53b780b314b09c5b diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 088642099..dff871f1f 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -4,6 +4,7 @@ #include "concurrency/OSThread.h" #include "configuration.h" #include "graphics/Screen.h" +#include "modules/ExternalNotificationModule.h" #include "power.h" #include @@ -114,6 +115,10 @@ class ButtonThread : public concurrency::OSThread { // DEBUG_MSG("press!\n"); #ifdef BUTTON_PIN + // If a nag notification is running, stop it + if (externalNotificationModule->nagCycleCutoff != UINT32_MAX) { + externalNotificationModule->nagCycleCutoff = 0; + } if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || !moduleConfig.canned_message.enabled) { powerFSM.trigger(EVENT_PRESS); diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 6f0635bdc..c154a98db 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -151,7 +151,7 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; /* Maximum encoded size of messages (where known) */ #define LocalConfig_size 387 -#define LocalModuleConfig_size 378 +#define LocalModuleConfig_size 376 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 9e77dd54c..47f410a5c 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -93,12 +93,13 @@ typedef struct _ModuleConfig_ExternalNotificationConfig { bool alert_message; bool alert_bell; bool use_pwm; - uint32_t output_vibra; - uint32_t output_buzzer; + uint8_t output_vibra; + uint8_t output_buzzer; bool alert_message_vibra; bool alert_message_buzzer; bool alert_bell_vibra; bool alert_bell_buzzer; + uint16_t nag_timeout; } ModuleConfig_ExternalNotificationConfig; typedef struct _ModuleConfig_MQTTConfig { @@ -193,7 +194,7 @@ extern "C" { #define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} #define ModuleConfig_AudioConfig_init_default {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} #define ModuleConfig_RangeTestConfig_init_default {0, 0, 0} #define ModuleConfig_TelemetryConfig_init_default {0, 0, 0, 0, 0} @@ -202,7 +203,7 @@ extern "C" { #define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} #define ModuleConfig_AudioConfig_init_zero {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} #define ModuleConfig_RangeTestConfig_init_zero {0, 0, 0} #define ModuleConfig_TelemetryConfig_init_zero {0, 0, 0, 0, 0} @@ -240,6 +241,7 @@ extern "C" { #define ModuleConfig_ExternalNotificationConfig_alert_message_buzzer_tag 11 #define ModuleConfig_ExternalNotificationConfig_alert_bell_vibra_tag 12 #define ModuleConfig_ExternalNotificationConfig_alert_bell_buzzer_tag 13 +#define ModuleConfig_ExternalNotificationConfig_nag_timeout_tag 14 #define ModuleConfig_MQTTConfig_enabled_tag 1 #define ModuleConfig_MQTTConfig_address_tag 2 #define ModuleConfig_MQTTConfig_username_tag 3 @@ -341,7 +343,8 @@ X(a, STATIC, SINGULAR, UINT32, output_buzzer, 9) \ X(a, STATIC, SINGULAR, BOOL, alert_message_vibra, 10) \ X(a, STATIC, SINGULAR, BOOL, alert_message_buzzer, 11) \ X(a, STATIC, SINGULAR, BOOL, alert_bell_vibra, 12) \ -X(a, STATIC, SINGULAR, BOOL, alert_bell_buzzer, 13) +X(a, STATIC, SINGULAR, BOOL, alert_bell_buzzer, 13) \ +X(a, STATIC, SINGULAR, UINT32, nag_timeout, 14) #define ModuleConfig_ExternalNotificationConfig_CALLBACK NULL #define ModuleConfig_ExternalNotificationConfig_DEFAULT NULL @@ -409,7 +412,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; /* Maximum encoded size of messages (where known) */ #define ModuleConfig_AudioConfig_size 19 #define ModuleConfig_CannedMessageConfig_size 49 -#define ModuleConfig_ExternalNotificationConfig_size 42 +#define ModuleConfig_ExternalNotificationConfig_size 40 #define ModuleConfig_MQTTConfig_size 169 #define ModuleConfig_RangeTestConfig_size 10 #define ModuleConfig_SerialConfig_size 26 diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index 5a95ceec1..e496e1699 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -11,41 +11,9 @@ #define PIN_BUZZER false #endif -//#include - /* - Documentation: - https://github.com/meshtastic/firmware/blob/master/docs/software/modules/ExternalNotificationModule.md - - This module supports: - https://github.com/meshtastic/firmware/issues/654 - - - Quick reference: - - moduleConfig.external_notification.enabled - 0 = Disabled (Default) - 1 = Enabled - - moduleConfig.external_notification.active - 0 = Active Low (Default) - 1 = Active High - - moduleConfig.external_notification.alert_message - 0 = Disabled (Default) - 1 = Alert when a text message comes - - moduleConfig.external_notification.alert_bell - 0 = Disabled (Default) - 1 = Alert when the bell character is received - - moduleConfig.external_notification.output - GPIO of the output. (Default = 13) - - moduleConfig.external_notification.output_ms - Amount of time in ms for the alert. Default is 1000. - + https://meshtastic.org/docs/settings/moduleconfig/external-notification */ // Default configurations @@ -58,8 +26,11 @@ #define ASCII_BELL 0x07 -bool externalCurrentState = 0; -uint32_t externalTurnedOn = 0; +ExternalNotificationModule *externalNotificationModule; + +bool externalCurrentState[3] = {}; + +uint32_t externalTurnedOn[3] = {}; int32_t ExternalNotificationModule::runOnce() { @@ -76,38 +47,89 @@ int32_t ExternalNotificationModule::runOnce() // moduleConfig.external_notification.output_ms = 1000; // moduleConfig.external_notification.output = 13; - if (externalCurrentState && !moduleConfig.external_notification.use_pwm) { + if (moduleConfig.external_notification.use_pwm || !moduleConfig.external_notification.enabled) { + return INT32_MAX; // we don't need this thread here... + } else { // If the output is turned on, turn it back off after the given period of time. - if (externalTurnedOn + (moduleConfig.external_notification.output_ms + if (nagCycleCutoff != UINT32_MAX) { + if (externalTurnedOn[0] + (moduleConfig.external_notification.output_ms ? moduleConfig.external_notification.output_ms - : EXT_NOTIFICATION_MODULE_OUTPUT_MS) < - millis()) { - DEBUG_MSG("Turning off external notification\n"); - setExternalOff(); + : EXT_NOTIFICATION_MODULE_OUTPUT_MS) < millis()) { + getExternal(0) ? setExternalOff(0) : setExternalOn(0); + } + if (externalTurnedOn[1] + (moduleConfig.external_notification.output_ms + ? moduleConfig.external_notification.output_ms + : EXT_NOTIFICATION_MODULE_OUTPUT_MS) < millis()) { + getExternal(1) ? setExternalOff(1) : setExternalOn(1); + } + if (externalTurnedOn[2] + (moduleConfig.external_notification.output_ms + ? moduleConfig.external_notification.output_ms + : EXT_NOTIFICATION_MODULE_OUTPUT_MS) < millis()) { + getExternal(2) ? setExternalOff(2) : setExternalOn(2); + } + } + + if (nagCycleCutoff < millis()) { + nagCycleCutoff = UINT32_MAX; + DEBUG_MSG("Turning off external notification: "); + for (int i = 0; i < 2; i++) { + if (getExternal(i)) { + setExternalOff(i); + externalTurnedOn[i] = 0; + DEBUG_MSG("%d ", i); + } + } + DEBUG_MSG("\n"); + return INT32_MAX; // save cycles till we're needed again } - } - if (moduleConfig.external_notification.use_pwm) - return INT32_MAX; // we don't need this thread here... - else return 25; + } } -void ExternalNotificationModule::setExternalOn() +void ExternalNotificationModule::setExternalOn(uint8_t index) { - externalCurrentState = 1; - externalTurnedOn = millis(); + externalCurrentState[index] = 1; + externalTurnedOn[index] = millis(); - digitalWrite(output, - (moduleConfig.external_notification.active ? true : false)); + switch(index) { + case 1: + if(moduleConfig.external_notification.output_vibra) + digitalWrite(moduleConfig.external_notification.output_vibra, true); + break; + case 2: + if(moduleConfig.external_notification.output_buzzer) + digitalWrite(moduleConfig.external_notification.output_buzzer, true); + break; + default: + digitalWrite(output, (moduleConfig.external_notification.active ? true : false)); + break; + } } -void ExternalNotificationModule::setExternalOff() +void ExternalNotificationModule::setExternalOff(uint8_t index) { - externalCurrentState = 0; + externalCurrentState[index] = 0; + externalTurnedOn[index] = millis(); - digitalWrite(output, - (moduleConfig.external_notification.active ? false : true)); + switch(index) { + case 1: + if(moduleConfig.external_notification.output_vibra) + digitalWrite(moduleConfig.external_notification.output_vibra, false); + break; + case 2: + if(moduleConfig.external_notification.output_buzzer) + digitalWrite(moduleConfig.external_notification.output_buzzer, false); + break; + default: + digitalWrite(output, (moduleConfig.external_notification.active ? false : true)); + break; + } +} + +bool ExternalNotificationModule::getExternal(uint8_t index) +{ + return externalCurrentState[index]; } // -------- @@ -141,8 +163,20 @@ ExternalNotificationModule::ExternalNotificationModule() // Set the direction of a pin DEBUG_MSG("Using Pin %i in digital mode\n", output); pinMode(output, OUTPUT); - // Turn off the pin - setExternalOff(); + setExternalOff(0); + externalTurnedOn[0] = 0; + if(moduleConfig.external_notification.output_vibra) { + DEBUG_MSG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); + pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); + setExternalOff(1); + externalTurnedOn[1] = 0; + } + if(moduleConfig.external_notification.output_buzzer) { + DEBUG_MSG("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); + pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT); + setExternalOff(2); + externalTurnedOn[2] = 0; + } } else { config.device.buzzer_gpio = config.device.buzzer_gpio ? config.device.buzzer_gpio @@ -163,17 +197,53 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (getFrom(&mp) != nodeDB.getNodeNum()) { - // TODO: This may be a problem if messages are sent in unicide, but I'm not sure if it will. - // Need to know if and how this could be a problem. + // Check if the message contains a bell character. Don't do this loop for every pin, just once. + auto &p = mp.decoded; + bool containsBell = false; + for (int i = 0; i < p.payload.size; i++) { + if (p.payload.bytes[i] == ASCII_BELL) { + containsBell = true; + } + } + if (moduleConfig.external_notification.alert_bell) { - auto &p = mp.decoded; - DEBUG_MSG("externalNotificationModule - Notification Bell\n"); - for (int i = 0; i < p.payload.size; i++) { - if (p.payload.bytes[i] == ASCII_BELL) { - if (!moduleConfig.external_notification.use_pwm) { - setExternalOn(); + if (containsBell) { + DEBUG_MSG("externalNotificationModule - Notification Bell\n"); + if (!moduleConfig.external_notification.use_pwm) { + setExternalOn(0); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; } else { - playBeep(); + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + // run_once now + } else { + playBeep(); + } + } + } + + if (!moduleConfig.external_notification.use_pwm) { + if (moduleConfig.external_notification.alert_bell_vibra) { + if (containsBell) { + DEBUG_MSG("externalNotificationModule - Notification Bell (Vibra)\n"); + setExternalOn(1); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + } + } + + if (moduleConfig.external_notification.alert_bell_buzzer) { + if (containsBell) { + DEBUG_MSG("externalNotificationModule - Notification Bell (Buzzer)\n"); + setExternalOn(2); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; } } } @@ -182,11 +252,39 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_message) { DEBUG_MSG("externalNotificationModule - Notification Module\n"); if (!moduleConfig.external_notification.use_pwm) { - setExternalOn(); + setExternalOn(0); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } } else { playBeep(); } } + + if (!moduleConfig.external_notification.use_pwm) { + if (moduleConfig.external_notification.alert_message_vibra) { + DEBUG_MSG("externalNotificationModule - Notification Module (Vibra)\n"); + setExternalOn(1); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + } + + if (moduleConfig.external_notification.alert_message_buzzer) { + DEBUG_MSG("externalNotificationModule - Notification Module (Buzzer)\n"); + setExternalOn(2); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + } + } + setIntervalFromNow(0); // run once so we know if we should do something } } else { diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index b5ab64b3c..1b1aeff21 100644 --- a/src/modules/ExternalNotificationModule.h +++ b/src/modules/ExternalNotificationModule.h @@ -17,18 +17,19 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: public: ExternalNotificationModule(); - void setExternalOn(); - void setExternalOff(); - void getExternal(); + uint32_t nagCycleCutoff = UINT32_MAX; + + void setExternalOn(uint8_t index = 0); + void setExternalOff(uint8_t index = 0); + bool getExternal(uint8_t index = 0); protected: - // virtual MeshPacket *allocReply(); - /** Called to handle a particular incoming message - @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; virtual int32_t runOnce() override; }; + +extern ExternalNotificationModule *externalNotificationModule; diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index ece160ced..9978f2487 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -69,7 +69,7 @@ void setupModules() #ifdef ARCH_ESP32 // Only run on an esp32 based device. audioModule = new AudioModule(); - new ExternalNotificationModule(); + externalNotificationModule = new ExternalNotificationModule(); storeForwardModule = new StoreForwardModule(); From 1a0d51495dda8d54b237501c1a7cc2ce8a86c3a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 8 Dec 2022 17:17:48 +0100 Subject: [PATCH 026/119] show appropriate message when going into OTA mode --- src/graphics/Screen.cpp | 6 +----- src/modules/AdminModule.cpp | 3 +++ 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index eac78dd64..b5a3ac4d5 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -329,11 +329,7 @@ static void drawFrameFirmware(OLEDDisplay *display, OLEDDisplayUiState *state, i display->drawString(64 + x, y, "Updating"); display->setFont(FONT_SMALL); - if ((millis() / 1000) % 2) { - display->drawString(64 + x, FONT_HEIGHT_SMALL + y + 2, "Please wait . . ."); - } else { - display->drawString(64 + x, FONT_HEIGHT_SMALL + y + 2, "Please wait . . "); - } + display->drawStringMaxWidth(0 + x, 2 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), "Please be patient and do not power off."); } /// Draw the last text message we received diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 434a42972..0b617adea 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -112,12 +112,15 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) #ifdef ARCH_ESP32 if (BleOta::getOtaAppVersion().isEmpty()) { DEBUG_MSG("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); + screen->startRebootScreen(); }else{ + screen->startFirmwareUpdateScreen(); BleOta::switchToOtaApp(); DEBUG_MSG("Rebooting to OTA in %d seconds\n", s); } #else DEBUG_MSG("Not on ESP32, scheduling regular reboot in %d seconds\n", s); + screen->startRebootScreen(); #endif rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; From f3d6f26a28c78eccac3038ab10be144a80fa9ce4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 8 Dec 2022 17:34:14 +0100 Subject: [PATCH 027/119] Format received message screen like sender in canned messages. --- src/graphics/Screen.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index b5a3ac4d5..7919e9891 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -360,6 +360,9 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state { displayedNodeNum = 0; // Not currently showing a node pane + // the max length of this buffer is much longer than we can possibly print + static char tempBuf[237]; + MeshPacket &mp = devicestate.rx_text_message; NodeInfo *node = nodeDB.getNode(getFrom(&mp)); // DEBUG_MSG("drawing text message from 0x%x: %s\n", mp.from, @@ -369,16 +372,13 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state // with the third parameter you can define the width after which words will // be wrapped. Currently only spaces and "-" are allowed for wrapping display->setTextAlignment(TEXT_ALIGN_LEFT); - display->setFont(FONT_MEDIUM); - String sender = (node && node->has_user) ? node->user.short_name : "???"; - display->drawString(0 + x, 0 + y, sender); display->setFont(FONT_SMALL); - - // the max length of this buffer is much longer than we can possibly print - static char tempBuf[96]; - snprintf(tempBuf, sizeof(tempBuf), " %s", mp.decoded.payload.bytes); - - display->drawStringMaxWidth(4 + x, 10 + y, SCREEN_WIDTH - (6 + x), tempBuf); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + display->drawStringf(0 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + display->setColor(WHITE); + snprintf(tempBuf, sizeof(tempBuf), "%s", mp.decoded.payload.bytes); + display->drawStringMaxWidth(0 + x, 0 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), tempBuf); } /// Draw a series of fields in a column, wrapping to multiple colums if needed From e3d8c5c7a6ceaf5ebf3444906d75a8aae2022f6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 8 Dec 2022 21:48:01 +0100 Subject: [PATCH 028/119] Change Boot Message format --- src/graphics/Screen.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 7919e9891..abd18d442 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -329,7 +329,8 @@ static void drawFrameFirmware(OLEDDisplay *display, OLEDDisplayUiState *state, i display->drawString(64 + x, y, "Updating"); display->setFont(FONT_SMALL); - display->drawStringMaxWidth(0 + x, 2 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), "Please be patient and do not power off."); + display->setTextAlignment(TEXT_ALIGN_LEFT); + display->drawStringMaxWidth(0 + x, 2 + y + FONT_HEIGHT_SMALL *2, x + display->getWidth(), "Please be patient and do not power off."); } /// Draw the last text message we received From edb674759f09798ff6ed61c472c831c9cd08157f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 9 Dec 2022 11:15:49 +0100 Subject: [PATCH 029/119] fixes critical error 8 does not reboot on nrf52 --- src/mesh/RadioLibInterface.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 022576659..18f2ef2f1 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -3,6 +3,7 @@ #include "NodeDB.h" #include "SPILock.h" #include "configuration.h" +#include "main.h" #include "error.h" #include "mesh-pb-constants.h" #include @@ -87,10 +88,8 @@ bool RadioLibInterface::canSendImmediately() if (busyTx && (millis() - lastTxStart > 60000)) { DEBUG_MSG("Hardware Failure! busyTx for more than 60s\n"); RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED); -#ifdef ARCH_ESP32 - if (busyTx && (millis() - lastTxStart > 65000)) // After 5s more, reboot - ESP.restart(); -#endif + // reboot in 5 seconds when this condition occurs. + rebootAtMsec = lastTxStart + 65000; } if (busyRx) DEBUG_MSG("Can not send yet, busyRx\n"); From 95eca75336709566513913722a3c151989922194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 9 Dec 2022 11:27:12 +0100 Subject: [PATCH 030/119] fix building for screenless devices --- src/graphics/Screen.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/graphics/Screen.h b/src/graphics/Screen.h index 23828b3ee..3988fa1a8 100644 --- a/src/graphics/Screen.h +++ b/src/graphics/Screen.h @@ -21,6 +21,7 @@ class Screen void startBluetoothPinScreen(uint32_t pin) {} void stopBluetoothPinScreen() {} void startRebootScreen() {} + void startFirmwareUpdateScreen() {} }; } From 5fbc63006140b1fa8a2be5a57da3f6bb789ee124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 11 Dec 2022 21:17:46 +0100 Subject: [PATCH 031/119] add IO7 to RAK pinouts - only comments changed --- variants/rak4631/variant.h | 1 + variants/rak4631_epaper/variant.h | 1 + 2 files changed, 2 insertions(+) diff --git a/variants/rak4631/variant.h b/variants/rak4631/variant.h index 51da8590f..d811bad20 100644 --- a/variants/rak4631/variant.h +++ b/variants/rak4631/variant.h @@ -169,6 +169,7 @@ static const uint8_t SCK = PIN_SPI_SCK; IO4 <-> P0.04 (Arduino GPIO number 4) IO5 <-> P0.09 (Arduino GPIO number 9) IO6 <-> P0.10 (Arduino GPIO number 10) + IO7 <-> P0.28 (Arduino GPIO number 28) SW1 <-> P0.01 (Arduino GPIO number 1) A0 <-> P0.04/AIN2 (Arduino Analog A2 A1 <-> P0.31/AIN7 (Arduino Analog A7 diff --git a/variants/rak4631_epaper/variant.h b/variants/rak4631_epaper/variant.h index cf1b8b07d..71ce58714 100644 --- a/variants/rak4631_epaper/variant.h +++ b/variants/rak4631_epaper/variant.h @@ -169,6 +169,7 @@ static const uint8_t SCK = PIN_SPI_SCK; IO4 <-> P0.04 (Arduino GPIO number 4) IO5 <-> P0.09 (Arduino GPIO number 9) IO6 <-> P0.10 (Arduino GPIO number 10) + IO7 <-> P0.28 (Arduino GPIO number 28) SW1 <-> P0.01 (Arduino GPIO number 1) A0 <-> P0.04/AIN2 (Arduino Analog A2 A1 <-> P0.31/AIN7 (Arduino Analog A7 From 24cc479f95c983a6d03f0dd00f1a9c4261b1cc29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 11 Dec 2022 23:12:00 +0100 Subject: [PATCH 032/119] if we get different frames than our own transmission setup, decode and play them anyway --- src/modules/esp32/AudioModule.cpp | 32 +++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 4e784e1a9..f29c11056 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -47,7 +47,7 @@ int Sine1KHz_index = 0; void run_codec2(void* parameter) { - // 4 bytes of header in each frame Kennung hex c0 de c2 plus the bitrate + // 4 bytes of header in each frame hex c0 de c2 plus the bitrate memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); while (true) { @@ -76,13 +76,29 @@ void run_codec2(void* parameter) } } if (audioModule->radio_state == RadioState::rx) { - //Make a cycle to get each codec2 frame from the received frame - for (int i = 0; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) - { - //Decode the codec2 frame - codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); - size_t bytesOut = 0; - i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); + size_t bytesOut = 0; + if (memcmp(audioModule->rx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header)) == 0) { + // Make a cycle to get each codec2 frame from the received frame + for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) + { + //Decode the codec2 frame + codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); + i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); + } + } else { + // if the buffer header does not match our own codec, make a temp decoding setup. + CODEC2* tmp_codec2 = codec2_create(audioModule->rx_encode_frame[3]); + codec2_set_lpc_post_filter(tmp_codec2, 1, 0, 0.8, 0.2); + int tmp_encode_codec_size = (codec2_bits_per_frame(tmp_codec2) + 7) / 8; + int tmp_adc_buffer_size = codec2_samples_per_frame(tmp_codec2); + // Make a cycle to get each codec2 frame from the received frame + for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size) + { + //Decode the codec2 frame + codec2_decode(tmp_codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); + i2s_write(I2S_PORT, &audioModule->output_buffer, tmp_adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); + } + codec2_destroy(tmp_codec2); } } } From 64cc6e0b918f78f5b8ec1b0f0da7d6087ffc2103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 13 Dec 2022 12:33:51 +0100 Subject: [PATCH 033/119] change on screen graphics to support bicolor screens --- src/graphics/Screen.cpp | 46 +++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index abd18d442..6f4c1fb58 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -377,6 +377,7 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); display->drawStringf(0 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + display->drawStringf(1 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); display->setColor(WHITE); snprintf(tempBuf, sizeof(tempBuf), "%s", mp.decoded.payload.bytes); display->drawStringMaxWidth(0 + x, 0 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), tempBuf); @@ -392,6 +393,10 @@ static void drawColumns(OLEDDisplay *display, int16_t x, int16_t y, const char * int xo = x, yo = y; while (*f) { display->drawString(xo, yo, *f); + if (display->getColor() == BLACK) + display->drawString(xo + 1, yo, *f); + + display->setColor(WHITE); yo += FONT_HEIGHT_SMALL; if (yo > SCREEN_HEIGHT - FONT_HEIGHT_SMALL) { xo += SCREEN_WIDTH / 2; @@ -462,6 +467,7 @@ static void drawNodes(OLEDDisplay *display, int16_t x, int16_t y, NodeStatus *no sprintf(usersString, "%d/%d", nodeStatus->getNumOnline(), nodeStatus->getNumTotal()); display->drawFastImage(x, y, 8, 8, imgUser); display->drawString(x + 10, y - 2, usersString); + display->drawString(x + 11, y - 2, usersString); } // Draw GPS status summary @@ -470,15 +476,18 @@ static void drawGPS(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus if (config.position.fixed_position) { // GPS coordinates are currently fixed display->drawString(x - 1, y - 2, "Fixed GPS"); + display->drawString(x, y - 2, "Fixed GPS"); return; } if (!gps->getIsConnected()) { display->drawString(x, y - 2, "No GPS"); + display->drawString(x + 1, y - 2, "No GPS"); return; } display->drawFastImage(x, y, 6, 8, gps->getHasLock() ? imgPositionSolid : imgPositionEmpty); if (!gps->getHasLock()) { display->drawString(x + 8, y - 2, "No sats"); + display->drawString(x + 9, y - 2, "No sats"); return; } else { char satsString[3]; @@ -666,16 +675,16 @@ static uint16_t getCompassDiam(OLEDDisplay *display) { uint16_t diam = 0; // get the smaller of the 2 dimensions and subtract 20 - if(display->getWidth() > display->getHeight()) { - diam = display->getHeight(); + if(display->getWidth() > (display->getHeight() - FONT_HEIGHT_SMALL)) { + diam = display->getHeight() - FONT_HEIGHT_SMALL; // if 2/3 of the other size would be smaller, use that if (diam > (display->getWidth() * 2 / 3)) { diam = display->getWidth() * 2 / 3; } } else { diam = display->getWidth(); - if (diam > (display->getHeight() * 2 / 3)) { - diam = display->getHeight() * 2 / 3; + if (diam > ((display->getHeight() - FONT_HEIGHT_SMALL) * 2 / 3)) { + diam = (display->getHeight() - FONT_HEIGHT_SMALL) * 2 / 3; } } @@ -755,6 +764,8 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + const char *username = node->has_user ? node->user.long_name : "Unknown Name"; static char signalStr[20]; @@ -785,7 +796,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ const char *fields[] = {username, distStr, signalStr, lastStr, NULL}; // coordinates for the center of the compass/circle - int16_t compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5, compassY = y + SCREEN_HEIGHT / 2; + int16_t compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5, compassY = y + FONT_HEIGHT_SMALL + (SCREEN_HEIGHT - FONT_HEIGHT_SMALL) / 2; bool hasNodeHeading = false; if (ourNode && hasPosition(ourNode)) { @@ -828,6 +839,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ display->drawString(compassX - FONT_HEIGHT_SMALL / 4, compassY - FONT_HEIGHT_SMALL / 2, "?"); display->drawCircle(compassX, compassY, getCompassDiam(display) / 2); + display->setColor(BLACK); // Must be after distStr is populated drawColumns(display, x, y, fields); } @@ -1354,6 +1366,9 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + char channelStr[20]; { concurrency::LockGuard guard(&lock); @@ -1363,14 +1378,15 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // Display power status if (powerStatus->getHasBattery()) - drawBattery(display, x, y + 2, imgBattery, powerStatus); + drawBattery(display, x + 1, y + 3, imgBattery, powerStatus); else if (powerStatus->knowsUSB()) - display->drawFastImage(x, y + 2, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); + display->drawFastImage(x + 1, y + 3, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); // Display nodes status - drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 2, nodeStatus); + drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 3, nodeStatus); // Display GPS status - drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 2, gpsStatus); + drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 3, gpsStatus); + display->setColor(WHITE); // Draw the channel name display->drawString(x, y + FONT_HEIGHT_SMALL, channelStr); // Draw our hardware ID to assist with bluetooth pairing @@ -1401,6 +1417,10 @@ void DebugInfo::drawFrameWiFi(OLEDDisplay *display, OLEDDisplayUiState *state, i // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + display->setColor(WHITE); + if (WiFi.status() != WL_CONNECTED) { display->drawString(x, y, String("WiFi: Not Connected")); } else { @@ -1518,6 +1538,9 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + char batStr[20]; if (powerStatus->getHasBattery()) { int batV = powerStatus->getBatteryVoltageMv() / 1000; @@ -1528,9 +1551,11 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // Line 1 display->drawString(x, y, batStr); + display->drawString(x + 1, y, batStr); } else { // Line 1 display->drawString(x, y, String("USB")); + display->drawString(x + 1, y, String("USB")); } auto mode = ""; @@ -1563,6 +1588,7 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat } display->drawString(x + SCREEN_WIDTH - display->getStringWidth(mode), y, mode); + display->drawString(x + SCREEN_WIDTH - display->getStringWidth(mode) - 1, y, mode); // Line 2 uint32_t currentMillis = millis(); @@ -1575,6 +1601,8 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // minutes %= 60; // hours %= 24; + display->setColor(WHITE); + // Show uptime as days, hours, minutes OR seconds String uptime; if (days >= 2) From 627b21f3f2089926b3e416886b75499c6f10dc58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 13 Dec 2022 17:31:01 +0100 Subject: [PATCH 034/119] made a nice PTT/RECV screen for audio module. And cleaned up screen graphics a bit. --- src/graphics/Screen.cpp | 7 +++- src/graphics/images.h | 30 --------------- src/graphics/img/compass.xbm | 28 -------------- src/graphics/img/pin.xbm | 6 --- src/modules/esp32/AudioModule.cpp | 62 +++++++++++++++++++++++++++++-- src/modules/esp32/AudioModule.h | 15 +++++++- 6 files changed, 78 insertions(+), 70 deletions(-) delete mode 100644 src/graphics/img/compass.xbm delete mode 100644 src/graphics/img/pin.xbm diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 6f4c1fb58..f1c3fdccc 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -1419,17 +1419,22 @@ void DebugInfo::drawFrameWiFi(OLEDDisplay *display, OLEDDisplayUiState *state, i display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); - display->setColor(WHITE); if (WiFi.status() != WL_CONNECTED) { display->drawString(x, y, String("WiFi: Not Connected")); + display->drawString(x + 1, y, String("WiFi: Not Connected")); } else { display->drawString(x, y, String("WiFi: Connected")); + display->drawString(x + 1, y, String("WiFi: Connected")); display->drawString(x + SCREEN_WIDTH - display->getStringWidth("RSSI " + String(WiFi.RSSI())), y, "RSSI " + String(WiFi.RSSI())); + display->drawString(x + SCREEN_WIDTH - display->getStringWidth("RSSI " + String(WiFi.RSSI())) - 1, y, + "RSSI " + String(WiFi.RSSI())); } + display->setColor(WHITE); + /* - WL_CONNECTED: assigned when connected to a WiFi network; - WL_NO_SSID_AVAIL: assigned when no SSID are available; diff --git a/src/graphics/images.h b/src/graphics/images.h index 41b390eaf..4680b9475 100644 --- a/src/graphics/images.h +++ b/src/graphics/images.h @@ -15,33 +15,3 @@ const uint8_t imgPositionSolid[] PROGMEM = { 0x20, 0x30, 0x38, 0x3C, 0x7E, 0xFF const uint8_t imgInfo[] PROGMEM = { 0xFF, 0x81, 0x81, 0xB5, 0xB5, 0x81, 0x81, 0xFF }; #include "img/icon.xbm" - -// We now programmatically draw our compass -#if 0 -const -#include "img/compass.xbm" -#endif - -#if 0 -const uint8_t activeSymbol[] PROGMEM = { - B00000000, - B00000000, - B00011000, - B00100100, - B01000010, - B01000010, - B00100100, - B00011000 -}; - -const uint8_t inactiveSymbol[] PROGMEM = { - B00000000, - B00000000, - B00000000, - B00000000, - B00011000, - B00011000, - B00000000, - B00000000 -}; -#endif \ No newline at end of file diff --git a/src/graphics/img/compass.xbm b/src/graphics/img/compass.xbm deleted file mode 100644 index 115a7a1d4..000000000 --- a/src/graphics/img/compass.xbm +++ /dev/null @@ -1,28 +0,0 @@ -#define compass_width 48 -#define compass_height 48 -static char compass_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, - 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, - 0x00, 0x00, 0xFC, 0x3F, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0x01, 0x00, - 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0xFC, 0x07, 0xE0, 0x3F, 0x00, - 0x00, 0xFE, 0x01, 0x80, 0x7F, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, - 0x00, 0x7F, 0x00, 0x00, 0xFE, 0x00, 0x80, 0x3F, 0x00, 0x00, 0xFC, 0x01, - 0x80, 0x1F, 0x00, 0x00, 0xF8, 0x01, 0x80, 0x0F, 0x00, 0x00, 0xF0, 0x01, - 0xC0, 0x0F, 0x00, 0x00, 0xF0, 0x03, 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, - 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, - 0xFC, 0x07, 0x00, 0x00, 0xE0, 0x3F, 0xFC, 0x07, 0x00, 0x00, 0xE0, 0x3F, - 0xFC, 0x07, 0x00, 0x00, 0xE0, 0x3F, 0xFC, 0x07, 0x00, 0x00, 0xE0, 0x3F, - 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, - 0xC0, 0x07, 0x00, 0x00, 0xE0, 0x03, 0xC0, 0x0F, 0x00, 0x00, 0xF0, 0x03, - 0x80, 0x0F, 0x00, 0x00, 0xF0, 0x01, 0x80, 0x1F, 0x00, 0x00, 0xF8, 0x01, - 0x80, 0x3F, 0x00, 0x00, 0xFC, 0x01, 0x00, 0x7F, 0x00, 0x00, 0xFE, 0x00, - 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x00, 0xFE, 0x01, 0x80, 0x7F, 0x00, - 0x00, 0xFC, 0x07, 0xE0, 0x3F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, - 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, - 0x00, 0x80, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0xFC, 0x3F, 0x00, 0x00, - 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, - 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }; diff --git a/src/graphics/img/pin.xbm b/src/graphics/img/pin.xbm deleted file mode 100644 index e8c8f8930..000000000 --- a/src/graphics/img/pin.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define pin_width 13 -#define pin_height 13 -static char pin_bits[] = { - 0x00, 0x00, 0xF0, 0x01, 0xF8, 0x03, 0xFC, 0x07, 0xBC, 0x07, 0xBC, 0x07, - 0xFC, 0x07, 0xF8, 0x03, 0xF8, 0x03, 0xF0, 0x01, 0xE0, 0x00, 0xE0, 0x00, - 0x00, 0x00, }; diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index f29c11056..75e329ce5 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -41,9 +41,26 @@ AudioModule *audioModule; #define YIELD_FROM_ISR(x) portYIELD_FROM_ISR(x) #endif -//int16_t 1KHz sine test tone -int16_t Sine1KHz[8] = { -21210 , -30000, -21210, 0 , 21210 , 30000 , 21210, 0 }; -int Sine1KHz_index = 0; +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) +// The screen is bigger so use bigger fonts +#define FONT_SMALL ArialMT_Plain_16 +#define FONT_MEDIUM ArialMT_Plain_24 +#define FONT_LARGE ArialMT_Plain_24 +#else +#ifdef OLED_RU +#define FONT_SMALL ArialMT_Plain_10_RU +#else +#define FONT_SMALL ArialMT_Plain_10 +#endif +#define FONT_MEDIUM ArialMT_Plain_16 +#define FONT_LARGE ArialMT_Plain_24 +#endif + +#define fontHeight(font) ((font)[1] + 1) // height is position 1 + +#define FONT_HEIGHT_SMALL fontHeight(FONT_SMALL) +#define FONT_HEIGHT_MEDIUM fontHeight(FONT_MEDIUM) +#define FONT_HEIGHT_LARGE fontHeight(FONT_LARGE) void run_codec2(void* parameter) { @@ -124,6 +141,30 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), } } +void AudioModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) +{ + displayedNodeNum = 0; // Not currently showing a node pane + + char buffer[50]; + + display->setTextAlignment(TEXT_ALIGN_LEFT); + display->setFont(FONT_SMALL); + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + display->drawStringf(0 + x, 0 + y, buffer, "Codec2 Mode %d Audio", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + display->setColor(WHITE); + display->setFont(FONT_LARGE); + display->setTextAlignment(TEXT_ALIGN_CENTER); + switch (radio_state) { + case RadioState::tx: + display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "PTT"); + break; + default: + display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "Receive"); + break; + } +} + int32_t AudioModule::runOnce() { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { @@ -170,11 +211,14 @@ int32_t AudioModule::runOnce() firstTime = false; } else { + UIFrameEvent e = {false, true}; // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { DEBUG_MSG("♪♫♪ PTT pressed, switching to TX\n"); radio_state = RadioState::tx; + e.frameChanged = true; + this->notifyObservers(&e); } } else { if (radio_state == RadioState::tx) { @@ -183,9 +227,11 @@ int32_t AudioModule::runOnce() DEBUG_MSG("♪♫♪ Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } - DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); + DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); tx_encode_frame_index = sizeof(tx_header); radio_state = RadioState::rx; + e.frameChanged = true; + this->notifyObservers(&e); } } if (radio_state == RadioState::tx) { @@ -222,6 +268,14 @@ MeshPacket *AudioModule::allocReply() return reply; } +bool AudioModule::shouldDraw() +{ + if (!moduleConfig.audio.codec2_enabled) { + return false; + } + return (radio_state == RadioState::tx); +} + void AudioModule::sendPayload(NodeNum dest, bool wantReplies) { MeshPacket *p = allocReply(); diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index 8e813ad1e..1a41ab6c4 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -10,6 +10,8 @@ #include #include #include +#include +#include enum RadioState { standby, rx, tx }; @@ -28,7 +30,7 @@ struct c2_header { #define AUDIO_MODULE_RX_BUFFER 128 #define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 -class AudioModule : public SinglePortModule, private concurrency::OSThread +class AudioModule : public SinglePortModule, public Observable, private concurrency::OSThread { public: unsigned char rx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; @@ -50,6 +52,8 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread AudioModule(); + bool shouldDraw(); + /** * Send our payload into the mesh */ @@ -63,6 +67,15 @@ class AudioModule : public SinglePortModule, private concurrency::OSThread virtual MeshPacket *allocReply() override; + virtual bool wantUIFrame() override { return this->shouldDraw(); } + virtual Observable* getUIFrameObservable() override { return this; } +#if !HAS_SCREEN + void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y); +#else + virtual void drawFrame( + OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override; +#endif + /** Called to handle a particular incoming message * @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it */ From 8507125e986f595f12e4ab8840fe31b30533bf23 Mon Sep 17 00:00:00 2001 From: code8buster Date: Tue, 13 Dec 2022 17:23:58 -0500 Subject: [PATCH 035/119] Remove extraneous flag, use gps_enabled. Ensure factory reset is not triggered while chip is off and gps_enabled=0 --- src/ButtonThread.h | 7 +++---- src/GPSStatus.h | 9 +++++++-- src/gps/GPS.cpp | 23 ++++++++++++++++++++--- src/gps/GPS.h | 3 ++- src/sleep.cpp | 6 +++++- src/sleep.h | 2 ++ 6 files changed, 39 insertions(+), 11 deletions(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 23859b8ad..985f0352b 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -5,7 +5,6 @@ #include "configuration.h" #include "graphics/Screen.h" #include "power.h" -#include "GPS.h" #include namespace concurrency @@ -164,7 +163,7 @@ class ButtonThread : public concurrency::OSThread digitalWrite(PIN_EINK_EN, digitalRead(PIN_EINK_EN) == LOW); #endif #if defined(GPS_POWER_TOGGLE) - if(gps->gpsPowerflag) + if(config.position.gps_enabled) { DEBUG_MSG("Flag set to false for gps power\n"); } @@ -172,8 +171,8 @@ class ButtonThread : public concurrency::OSThread { DEBUG_MSG("Flag set to true to restore power\n"); } - gps->gpsPowerflag = !(gps->gpsPowerflag); - doGPSpowersave(gps->gpsPowerflag); + config.position.gps_enabled = !(config.position.gps_enabled); + doGPSpowersave(config.position.gps_enabled); #endif } diff --git a/src/GPSStatus.h b/src/GPSStatus.h index 35a0b11f2..ef97c59b7 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -20,16 +20,19 @@ class GPSStatus : public Status bool hasLock = false; // default to false, until we complete our first read bool isConnected = false; // Do we have a GPS we are talking to + bool isPowerSaving = false; //Are we in power saving state + Position p = Position_init_default; public: GPSStatus() { statusType = STATUS_TYPE_GPS; } // preferred method - GPSStatus(bool hasLock, bool isConnected, const Position &pos) : Status() + GPSStatus(bool hasLock, bool isConnected, bool isPowerSaving, const Position &pos) : Status() { this->hasLock = hasLock; this->isConnected = isConnected; + this->isPowerSaving = isPowerSaving; // all-in-one struct copy this->p = pos; @@ -44,6 +47,8 @@ class GPSStatus : public Status bool getIsConnected() const { return isConnected; } + bool getIsPowerSaving() const { return isPowerSaving;} + int32_t getLatitude() const { if (config.position.fixed_position) { @@ -94,7 +99,7 @@ class GPSStatus : public Status #ifdef GPS_EXTRAVERBOSE DEBUG_MSG("GPSStatus.match() new pos@%x to old pos@%x\n", newStatus->p.pos_timestamp, p.pos_timestamp); #endif - return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || + return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || newStatus->isPowerSaving !=isPowerSaving || newStatus->p.latitude_i != p.latitude_i || newStatus->p.longitude_i != p.longitude_i || newStatus->p.altitude != p.altitude || newStatus->p.altitude_hae != p.altitude_hae || newStatus->p.PDOP != p.PDOP || newStatus->p.ground_track != p.ground_track || diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 2a00af475..7e860cdd0 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -270,6 +270,12 @@ bool GPS::setup() pinMode(PIN_GPS_EN, OUTPUT); #endif +#ifdef HAS_PMU +if(config.position.gps_enabled){ + setGPSPower(true); +} +#endif + #ifdef PIN_GPS_RESET digitalWrite(PIN_GPS_RESET, 1); // assert for 10ms pinMode(PIN_GPS_RESET, OUTPUT); @@ -282,8 +288,12 @@ bool GPS::setup() if (ok) { notifySleepObserver.observe(¬ifySleep); notifyDeepSleepObserver.observe(¬ifyDeepSleep); + notifyGPSSleepObserver.observe(¬ifyGPSSleep); + } + if (config.position.gps_enabled==false) { + setAwake(false); + doGPSpowersave(false); } - return ok; } @@ -292,6 +302,7 @@ GPS::~GPS() // we really should unregister our sleep observer notifySleepObserver.unobserve(¬ifySleep); notifyDeepSleepObserver.unobserve(¬ifyDeepSleep); + notifyGPSSleepObserver.observe(¬ifyGPSSleep); } bool GPS::hasLock() @@ -404,7 +415,7 @@ void GPS::publishUpdate() DEBUG_MSG("publishing pos@%x:2, hasVal=%d, GPSlock=%d\n", p.timestamp, hasValidLocation, hasLock()); // Notify any status instances that are observing us - const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasValidLocation, isConnected(), p); + const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasValidLocation, isConnected(), isPowerSaving(), p); newStatus.notifyObservers(&status); } } @@ -415,7 +426,7 @@ int32_t GPS::runOnce() // if we have received valid NMEA claim we are connected setConnected(); } else { - if(gnssModel == GNSS_MODEL_UBLOX){ + if((config.position.gps_enabled == 1) && (gnssModel == GNSS_MODEL_UBLOX)){ // reset the GPS on next bootup if(devicestate.did_gps_reset && (millis() > 60000) && !hasFlow()) { DEBUG_MSG("GPS is not communicating, trying factory reset on next bootup.\n"); @@ -517,6 +528,7 @@ int GPS::prepareDeepSleep(void *unused) DEBUG_MSG("GPS deep sleep!\n"); // For deep sleep we also want abandon any lock attempts (because we want minimum power) + getSleepTime(); setAwake(false); return 0; @@ -652,6 +664,11 @@ GPS *createGps() return new_gps; } } + else{ + GPS *new_gps = new NMEAGPS(); + new_gps->setup(); + return new_gps; + } return nullptr; #endif } diff --git a/src/gps/GPS.h b/src/gps/GPS.h index f77d13a80..a8a82a033 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -49,6 +49,7 @@ class GPS : private concurrency::OSThread CallbackObserver notifySleepObserver = CallbackObserver(this, &GPS::prepareSleep); CallbackObserver notifyDeepSleepObserver = CallbackObserver(this, &GPS::prepareDeepSleep); + CallbackObserver notifyGPSSleepObserver = CallbackObserver(this, &GPS::prepareDeepSleep); public: /** If !NULL we will use this serial port to construct our GPS */ @@ -77,7 +78,7 @@ class GPS : private concurrency::OSThread /// Return true if we are connected to a GPS bool isConnected() const { return hasGPS; } - bool gpsPowerflag = 1; + bool isPowerSaving() const { return !config.position.gps_enabled;} /** * Restart our lock attempt - try to get and broadcast a GPS reading ASAP diff --git a/src/sleep.cpp b/src/sleep.cpp index 7f6735939..46d14d623 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -29,7 +29,9 @@ Observable preflightSleep; /// Called to tell observers we are now entering sleep and you should prepare. Must return 0 /// notifySleep will be called for light or deep sleep, notifyDeepSleep is only called for deep sleep +/// notifyGPSSleep will be called when config.position.gps_enabled is set to 0 or from buttonthread when GPS_POWER_TOGGLE is enabled. Observable notifySleep, notifyDeepSleep; +Observable notifyGPSSleep; // deep sleep support RTC_DATA_ATTR int bootCount = 0; @@ -169,6 +171,7 @@ static void waitEnterSleep() void doGPSpowersave(bool on) { + #ifdef HAS_PMU if (on) { DEBUG_MSG("Turning GPS back on\n"); @@ -178,9 +181,10 @@ void doGPSpowersave(bool on) else { DEBUG_MSG("Turning off GPS chip\n"); - notifySleep.notifyObservers(NULL); + notifyGPSSleep.notifyObservers(NULL); setGPSPower(0); } + #endif } void doDeepSleep(uint64_t msecToWake) diff --git a/src/sleep.h b/src/sleep.h index f911a7cc8..af59a8dad 100644 --- a/src/sleep.h +++ b/src/sleep.h @@ -37,4 +37,6 @@ extern Observable notifySleep; /// Called to tell observers we are now entering (deep) sleep and you should prepare. Must return 0 extern Observable notifyDeepSleep; +/// Called to tell GPS thread to enter deep sleep independently of LoRa/MCU sleep, prior to full poweroff. Must return 0 +extern Observable notifyGPSSleep; void enableModemSleep(); \ No newline at end of file From bb24b86018c543b74a44bf2b579575aa6c25de85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 14 Dec 2022 13:32:26 +0100 Subject: [PATCH 036/119] support ESP32-S2 CPUs Note: these don't have Bluetooth and only a single physical core. --- arch/esp32/esp32s2.ini | 47 +++++++++++++++++++++++++++++++ src/modules/SerialModule.cpp | 4 +-- src/platform/esp32/main-esp32.cpp | 17 +++++++---- src/sleep.cpp | 2 ++ 4 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 arch/esp32/esp32s2.ini diff --git a/arch/esp32/esp32s2.ini b/arch/esp32/esp32s2.ini new file mode 100644 index 000000000..ca4f576d6 --- /dev/null +++ b/arch/esp32/esp32s2.ini @@ -0,0 +1,47 @@ +[esp32s2_base] +extends = arduino_base +platform = platformio/espressif32@^5.2.0 +build_src_filter = + ${arduino_base.build_src_filter} - - - - - +upload_speed = 961200 +monitor_speed = 115200 +debug_init_break = tbreak setup +monitor_filters = esp32_exception_decoder +board_build.filesystem = littlefs + +# Remove -DMYNEWT_VAL_BLE_HS_LOG_LVL=LOG_LEVEL_CRITICAL for low level BLE logging. +# See library directory for BLE logging possible values: .pio/libdeps/tbeam/NimBLE-Arduino/src/log_common/log_common.h +# This overrides the BLE logging default of LOG_LEVEL_INFO (1) from: .pio/libdeps/tbeam/NimBLE-Arduino/src/esp_nimble_cfg.h +build_flags = + ${arduino_base.build_flags} + -Wall + -Wextra + -Isrc/platform/esp32 + -std=c++11 + -DLOG_LOCAL_LEVEL=ESP_LOG_DEBUG + -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG + -DMYNEWT_VAL_BLE_HS_LOG_LVL=LOG_LEVEL_CRITICAL + -DAXP_DEBUG_PORT=Serial + -DCONFIG_BT_NIMBLE_ENABLED + -DCONFIG_NIMBLE_CPP_LOG_LEVEL=2 + -DCONFIG_BT_NIMBLE_MAX_CCCDS=20 + -DESP_OPENSSL_SUPPRESS_LEGACY_WARNING + -DHAS_BLUETOOTH=0 + -DDEBUG_HEAP + +lib_deps = + ${arduino_base.lib_deps} + ${networking_base.lib_deps} + ${environmental_base.lib_deps} + https://github.com/meshtastic/esp32_https_server.git#23665b3adc080a311dcbb586ed5941b5f94d6ea2 + https://github.com/lewisxhe/XPowersLib.git#84b7373faea3118b6c37954d52f98b8a337148d6 + caveman99/ESP32 Codec2@^1.0.1 + +lib_ignore = + segger_rtt + ESP32 BLE Arduino + +; customize the partition table +; http://docs.platformio.org/en/latest/platforms/espressif32.html#partition-tables +board_build.partitions = partition-table.csv + diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index aaaf3b144..d25e196a1 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -82,7 +82,7 @@ SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio") int32_t SerialModule::runOnce() { -#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) /* Uncomment the preferences below if you want to use the module without having to configure it from the PythonAPI or WebUI. @@ -235,7 +235,7 @@ void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) { -#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) if (moduleConfig.serial.enabled) { auto &p = mp.decoded; diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index 21df018d8..e36a8cfd8 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -3,7 +3,9 @@ #include "esp_task_wdt.h" #include "main.h" +#if !defined(CONFIG_IDF_TARGET_ESP32S2) #include "nimble/NimbleBluetooth.h" +#endif #include "BleOta.h" #include "mesh/http/WiFiAPClient.h" @@ -16,13 +18,9 @@ #include #include "soc/rtc.h" +#if !defined(CONFIG_IDF_TARGET_ESP32S2) NimbleBluetooth *nimbleBluetooth; -void getMacAddr(uint8_t *dmac) -{ - assert(esp_efuse_mac_get_default(dmac) == ESP_OK); -} - void setBluetoothEnable(bool on) { if (!isWifiAvailable() && config.bluetooth.enabled == true) { @@ -36,6 +34,15 @@ void setBluetoothEnable(bool on) { } } } +#else +void setBluetoothEnable(bool on) { } +void updateBatteryLevel(uint8_t level) { } +#endif + +void getMacAddr(uint8_t *dmac) +{ + assert(esp_efuse_mac_get_default(dmac) == ESP_OK); +} #ifdef HAS_32768HZ #define CALIBRATE_ONE(cali_clk) calibrate_one(cali_clk, #cali_clk) diff --git a/src/sleep.cpp b/src/sleep.cpp index 39ee43ebc..6625da2a3 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -300,6 +300,8 @@ void enableModemSleep() #if CONFIG_IDF_TARGET_ESP32S3 esp32_config.max_freq_mhz = CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ; +#elif CONFIG_IDF_TARGET_ESP32S2 + esp32_config.max_freq_mhz = CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ; #else esp32_config.max_freq_mhz = CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ; #endif From eae7f8a78694cac2af13a84e51b8868b2e6c6229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 14 Dec 2022 14:33:59 +0100 Subject: [PATCH 037/119] fix building DIY-1 target --- src/modules/esp32/AudioModule.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 75e329ce5..17e5cf4fa 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -10,6 +10,10 @@ #include +#ifdef OLED_RU +#include "graphics/fonts/OLEDDisplayFontsRU.h" +#endif + /* AudioModule A interface to send raw codec2 audio data over the mesh network. Based on the example code from the ESP32_codec2 project. From 06be74ae7c99c1ec33a2da61ade737b0632e64e5 Mon Sep 17 00:00:00 2001 From: code8buster Date: Wed, 14 Dec 2022 19:58:15 -0500 Subject: [PATCH 038/119] Added indicative text to screen for disabled GPS, made sleep methods private again --- src/gps/GPS.h | 2 +- src/graphics/Screen.cpp | 30 ++++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/gps/GPS.h b/src/gps/GPS.h index a8a82a033..5d24268d7 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -131,6 +131,7 @@ class GPS : private concurrency::OSThread void setNumSatellites(uint8_t n); + private: /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs /// always returns 0 to indicate okay to sleep int prepareSleep(void *unused); @@ -138,7 +139,6 @@ class GPS : private concurrency::OSThread /// Prepare the GPS for the cpu entering deep sleep, expect to be gone for at least 100s of msecs /// always returns 0 to indicate okay to sleep int prepareDeepSleep(void *unused); - private: /** * Switch the GPS into a mode where we are actively looking for a lock, or alternatively switch GPS into a low power mode diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index eac78dd64..81ed10444 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -506,6 +506,22 @@ static void drawGPS(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus } } +//Draw status when gps is disabled by PMU +static void drawGPSpowerstat(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps){ +String displayLine = ""; +displayLine = "GPS disabled"; +int16_t xPos = display->getStringWidth(displayLine); + #ifdef HAS_PMU + if (!config.position.gps_enabled){ + display->drawString(x + xPos, y, displayLine); + #ifdef GPS_POWER_TOGGLE + display->drawString(x + xPos, y - 2 + FONT_HEIGHT_SMALL, " by button"); + #endif + //display->drawString(x + xPos, y + 2, displayLine); + } + #endif +} + static void drawGPSAltitude(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps) { String displayLine = ""; @@ -1372,7 +1388,15 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // Display nodes status drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 2, nodeStatus); // Display GPS status + if (!config.position.gps_enabled){ + int16_t yPos = y + 2; + #ifdef GPS_POWER_TOGGLE + yPos = (y + 10 + FONT_HEIGHT_SMALL); + #endif + drawGPSpowerstat(display, x, yPos, gpsStatus); + } else { drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 2, gpsStatus); + } // Draw the channel name display->drawString(x, y + FONT_HEIGHT_SMALL, channelStr); @@ -1613,7 +1637,7 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat char chUtil[13]; sprintf(chUtil, "ChUtil %2.0f%%", airTime->channelUtilizationPercent()); display->drawString(x + SCREEN_WIDTH - display->getStringWidth(chUtil), y + FONT_HEIGHT_SMALL * 1, chUtil); - +if (config.position.gps_enabled) { // Line 3 if (config.display.gps_format != Config_DisplayConfig_GpsCoordinateFormat_DMS) // if DMS then don't draw altitude @@ -1621,7 +1645,9 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // Line 4 drawGPScoordinates(display, x, y + FONT_HEIGHT_SMALL * 3, gpsStatus); - +} else { + drawGPSpowerstat(display, x - (SCREEN_WIDTH / 4), y + FONT_HEIGHT_SMALL * 2, gpsStatus); +} /* Display a heartbeat pixel that blinks every time the frame is redrawn */ #ifdef SHOW_REDRAWS if (heartbeat) From f2229e6977315f01fc98c09febd30e9c54aa8706 Mon Sep 17 00:00:00 2001 From: code8buster Date: Thu, 15 Dec 2022 11:08:37 -0500 Subject: [PATCH 039/119] Decrease click time window to avoid spurious double press detections while cycling windows quickly, build power toggle by default --- src/ButtonThread.h | 1 + variants/tbeam/platformio.ini | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 985f0352b..0e9830f3f 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -51,6 +51,7 @@ class ButtonThread : public concurrency::OSThread pinMode(BUTTON_PIN, INPUT_PULLUP_SENSE); #endif userButton.attachClick(userButtonPressed); + userButton.setClickTicks(300); userButton.attachDuringLongPress(userButtonPressedLong); userButton.attachDoubleClick(userButtonDoublePressed); userButton.attachMultiClick(userButtonMultiPressed); diff --git a/variants/tbeam/platformio.ini b/variants/tbeam/platformio.ini index df526ae5b..76a03d126 100644 --- a/variants/tbeam/platformio.ini +++ b/variants/tbeam/platformio.ini @@ -6,5 +6,5 @@ lib_deps = ${esp32_base.lib_deps} build_flags = ${esp32_base.build_flags} -D TBEAM_V10 -I variants/tbeam - ;-DGPS_POWER_TOGGLE ;uncomment this line to allow a double press on the user button to turn off gps entirely. + -DGPS_POWER_TOGGLE ; comment this line to disable double press function on the user button to turn off gps entirely. upload_speed = 921600 From a788f16e91da9281ff8b3705fd3947babcdcd4ff Mon Sep 17 00:00:00 2001 From: code8buster Date: Thu, 15 Dec 2022 12:02:04 -0500 Subject: [PATCH 040/119] Potentially stop bad things happening on devices without a PMU --- src/sleep.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/sleep.cpp b/src/sleep.cpp index 46d14d623..72b7f7527 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -185,6 +185,18 @@ void doGPSpowersave(bool on) setGPSPower(0); } #endif + #ifdef PIN_GPS_WAKE + if (on) + { + DEBUG_MSG("Waking GPS"); + gps->forceWake(1); + } + else + { + DEBUG_MSG("GPS entering sleep"); + notifyGPSSleep.notifyObservers(NULL); + } + #endif } void doDeepSleep(uint64_t msecToWake) From 270746e30327269569c84d4287059b68d11dd60f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:25:51 +0100 Subject: [PATCH 041/119] Heap Debug: only show if delta occurs --- src/Power.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Power.cpp b/src/Power.cpp index 5a493c4fd..0d95a6ec4 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -284,7 +284,10 @@ void Power::readPowerStatus() powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP - DEBUG_MSG("Heap status: %d/%d bytes free, running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), concurrency::mainController.size(false)); + if (lastheap != ESP.getFreeHeap()){ + DEBUG_MSG("Heap status: %d/%d bytes free (%d), running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap , concurrency::mainController.size(false)); + lastheap = ESP.getFreeHeap(); + } #endif // If we have a battery at all and it is less than 10% full, force deep sleep if we have more than 3 low readings in a row From 1c8181dc7590acacb581046ceded845a7e975cc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:26:22 +0100 Subject: [PATCH 042/119] fix compiler warnings --- src/mesh/NodeDB.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index c30542def..1e40b8d92 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -215,9 +215,9 @@ void NodeDB::installDefaultModuleConfig() moduleConfig.has_external_notification = true; moduleConfig.has_canned_message = true; - strncpy(moduleConfig.mqtt.address, default_mqtt_address, sizeof(default_mqtt_address)); - strncpy(moduleConfig.mqtt.username, default_mqtt_username, sizeof(default_mqtt_username)); - strncpy(moduleConfig.mqtt.password, default_mqtt_password, sizeof(default_mqtt_password)); + strncpy(moduleConfig.mqtt.address, default_mqtt_address, sizeof(moduleConfig.mqtt.address)); + strncpy(moduleConfig.mqtt.username, default_mqtt_username, sizeof(moduleConfig.mqtt.username)); + strncpy(moduleConfig.mqtt.password, default_mqtt_password, sizeof(moduleConfig.mqtt.password)); initModuleConfigIntervals(); } From 68f6cfde0c75ee35ba930d67a8369467f9cdcfcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:28:28 +0100 Subject: [PATCH 043/119] Improve Wifi Reconnect handling and add outgoing queue for MQTT packets to bridge short connection issues. --- src/mesh/http/WiFiAPClient.cpp | 134 +++++++++++++++++++++------------ src/mesh/http/WiFiAPClient.h | 4 + src/mqtt/MQTT.cpp | 104 +++++++++++++++++++------ src/mqtt/MQTT.h | 7 ++ 4 files changed, 175 insertions(+), 74 deletions(-) diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index bb4542468..731197e60 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -1,7 +1,7 @@ -#include "mesh/http/WiFiAPClient.h" #include "NodeDB.h" #include "RTC.h" #include "concurrency/Periodic.h" +#include "mesh/http/WiFiAPClient.h" #include "configuration.h" #include "main.h" #include "mesh/http/WebServer.h" @@ -37,9 +37,9 @@ bool APStartupComplete = 0; unsigned long lastrun_ntp = 0; -static bool needReconnect = true; // If we create our reconnector, run it once at the beginning +bool needReconnect = true; // If we create our reconnector, run it once at the beginning -static Periodic *wifiReconnect; +Periodic *wifiReconnect; static int32_t reconnectWiFi() { @@ -56,29 +56,15 @@ static int32_t reconnectWiFi() // Make sure we clear old connection credentials WiFi.disconnect(false, true); - DEBUG_MSG("... Reconnecting to WiFi access point %s\n",wifiName); - - int n = WiFi.scanNetworks(); - - if (n > 0) { - for (int i = 0; i < n; ++i) { - DEBUG_MSG("Found WiFi network %s, signal strength %d\n", WiFi.SSID(i).c_str(), WiFi.RSSI(i)); - yield(); - } - WiFi.mode(WIFI_MODE_STA); - WiFi.begin(wifiName, wifiPsw); - } else { - DEBUG_MSG("No networks found during site survey. Rebooting MCU...\n"); - screen->startRebootScreen(); - rebootAtMsec = millis() + 5000; - } - + DEBUG_MSG("Reconnecting to WiFi access point %s\n",wifiName); + WiFi.mode(WIFI_MODE_STA); + WiFi.begin(wifiName, wifiPsw); } #ifndef DISABLE_NTP if (WiFi.isConnected() && (((millis() - lastrun_ntp) > 43200000) || (lastrun_ntp == 0))) { // every 12 hours - DEBUG_MSG("Updating NTP time\n"); + DEBUG_MSG("Updating NTP time from %s\n",config.network.ntp_server); if (timeClient.update()) { DEBUG_MSG("NTP Request Success - Setting RTCQualityNTP if needed\n"); @@ -129,7 +115,7 @@ static void onNetworkConnected() { if (!APStartupComplete) { // Start web server - DEBUG_MSG("... Starting network services\n"); + DEBUG_MSG("Starting network services\n"); // start mdns if (!MDNS.begin("Meshtastic")) { @@ -168,6 +154,8 @@ bool initWifi() createSSLCert(); + esp_wifi_set_storage(WIFI_STORAGE_RAM); // Disable flash storage for WiFi credentials + if (!*wifiPsw) // Treat empty password as no password wifiPsw = NULL; @@ -194,7 +182,7 @@ bool initWifi() WiFi.onEvent( [](WiFiEvent_t event, WiFiEventInfo_t info) { - Serial.print("\nWiFi lost connection. Reason: "); + Serial.print("WiFi lost connection. Reason: "); Serial.println(info.wifi_sta_disconnected.reason); /* @@ -221,91 +209,137 @@ bool initWifi() // Called by the Espressif SDK to static void WiFiEvent(WiFiEvent_t event) { - DEBUG_MSG("************ [WiFi-event] event: %d ************\n", event); + DEBUG_MSG("WiFi-Event %d: ", event); switch (event) { - case SYSTEM_EVENT_WIFI_READY: + case ARDUINO_EVENT_WIFI_READY: DEBUG_MSG("WiFi interface ready\n"); break; - case SYSTEM_EVENT_SCAN_DONE: + case ARDUINO_EVENT_WIFI_SCAN_DONE: DEBUG_MSG("Completed scan for access points\n"); break; - case SYSTEM_EVENT_STA_START: + case ARDUINO_EVENT_WIFI_STA_START: DEBUG_MSG("WiFi station started\n"); break; - case SYSTEM_EVENT_STA_STOP: + case ARDUINO_EVENT_WIFI_STA_STOP: DEBUG_MSG("WiFi station stopped\n"); break; - case SYSTEM_EVENT_STA_CONNECTED: + case ARDUINO_EVENT_WIFI_STA_CONNECTED: DEBUG_MSG("Connected to access point\n"); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: DEBUG_MSG("Disconnected from WiFi access point\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; - case SYSTEM_EVENT_STA_AUTHMODE_CHANGE: + case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: DEBUG_MSG("Authentication mode of access point has changed\n"); break; - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: DEBUG_MSG("Obtained IP address: "); Serial.println(WiFi.localIP()); onNetworkConnected(); break; - case SYSTEM_EVENT_STA_LOST_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP6: + DEBUG_MSG("Obtained IP6 address: "); + Serial.println(WiFi.localIPv6()); + break; + case ARDUINO_EVENT_WIFI_STA_LOST_IP: DEBUG_MSG("Lost IP address and IP address is reset to 0\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; - case SYSTEM_EVENT_STA_WPS_ER_SUCCESS: + case ARDUINO_EVENT_WPS_ER_SUCCESS: DEBUG_MSG("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); break; - case SYSTEM_EVENT_STA_WPS_ER_FAILED: + case ARDUINO_EVENT_WPS_ER_FAILED: DEBUG_MSG("WiFi Protected Setup (WPS): failed in enrollee mode\n"); break; - case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT: + case ARDUINO_EVENT_WPS_ER_TIMEOUT: DEBUG_MSG("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); break; - case SYSTEM_EVENT_STA_WPS_ER_PIN: + case ARDUINO_EVENT_WPS_ER_PIN: DEBUG_MSG("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); break; - case SYSTEM_EVENT_AP_START: + case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP: + DEBUG_MSG("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); + break; + case ARDUINO_EVENT_WIFI_AP_START: DEBUG_MSG("WiFi access point started\n"); break; - case SYSTEM_EVENT_AP_STOP: + case ARDUINO_EVENT_WIFI_AP_STOP: DEBUG_MSG("WiFi access point stopped\n"); break; - case SYSTEM_EVENT_AP_STACONNECTED: + case ARDUINO_EVENT_WIFI_AP_STACONNECTED: DEBUG_MSG("Client connected\n"); break; - case SYSTEM_EVENT_AP_STADISCONNECTED: + case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: DEBUG_MSG("Client disconnected\n"); break; - case SYSTEM_EVENT_AP_STAIPASSIGNED: + case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: DEBUG_MSG("Assigned IP address to client\n"); break; - case SYSTEM_EVENT_AP_PROBEREQRECVED: + case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: DEBUG_MSG("Received probe request\n"); break; - case SYSTEM_EVENT_GOT_IP6: + case ARDUINO_EVENT_WIFI_AP_GOT_IP6: DEBUG_MSG("IPv6 is preferred\n"); break; - case SYSTEM_EVENT_ETH_START: + case ARDUINO_EVENT_WIFI_FTM_REPORT: + DEBUG_MSG("Fast Transition Management report\n"); + break; + case ARDUINO_EVENT_ETH_START: DEBUG_MSG("Ethernet started\n"); break; - case SYSTEM_EVENT_ETH_STOP: + case ARDUINO_EVENT_ETH_STOP: DEBUG_MSG("Ethernet stopped\n"); break; - case SYSTEM_EVENT_ETH_CONNECTED: + case ARDUINO_EVENT_ETH_CONNECTED: DEBUG_MSG("Ethernet connected\n"); break; - case SYSTEM_EVENT_ETH_DISCONNECTED: + case ARDUINO_EVENT_ETH_DISCONNECTED: DEBUG_MSG("Ethernet disconnected\n"); break; - case SYSTEM_EVENT_ETH_GOT_IP: - DEBUG_MSG("Obtained IP address (SYSTEM_EVENT_ETH_GOT_IP)\n"); + case ARDUINO_EVENT_ETH_GOT_IP: + DEBUG_MSG("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); + break; + case ARDUINO_EVENT_ETH_GOT_IP6: + DEBUG_MSG("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); + break; + case ARDUINO_EVENT_SC_SCAN_DONE: + DEBUG_MSG("SmartConfig: Scan done\n"); + break; + case ARDUINO_EVENT_SC_FOUND_CHANNEL: + DEBUG_MSG("SmartConfig: Found channel\n"); + break; + case ARDUINO_EVENT_SC_GOT_SSID_PSWD: + DEBUG_MSG("SmartConfig: Got SSID and password\n"); + break; + case ARDUINO_EVENT_SC_SEND_ACK_DONE: + DEBUG_MSG("SmartConfig: Send ACK done\n"); + break; + case ARDUINO_EVENT_PROV_INIT: + DEBUG_MSG("Provisioning: Init\n"); + break; + case ARDUINO_EVENT_PROV_DEINIT: + DEBUG_MSG("Provisioning: Stopped\n"); + break; + case ARDUINO_EVENT_PROV_START: + DEBUG_MSG("Provisioning: Started\n"); + break; + case ARDUINO_EVENT_PROV_END: + DEBUG_MSG("Provisioning: End\n"); + break; + case ARDUINO_EVENT_PROV_CRED_RECV: + DEBUG_MSG("Provisioning: Credentials received\n"); + break; + case ARDUINO_EVENT_PROV_CRED_FAIL: + DEBUG_MSG("Provisioning: Credentials failed\n"); + break; + case ARDUINO_EVENT_PROV_CRED_SUCCESS: + DEBUG_MSG("Provisioning: Credentials success\n"); break; default: break; diff --git a/src/mesh/http/WiFiAPClient.h b/src/mesh/http/WiFiAPClient.h index 9729c24b5..a11330ad0 100644 --- a/src/mesh/http/WiFiAPClient.h +++ b/src/mesh/http/WiFiAPClient.h @@ -1,6 +1,7 @@ #pragma once #include "configuration.h" +#include "concurrency/Periodic.h" #include #include @@ -8,6 +9,9 @@ #include #endif +extern bool needReconnect; +extern concurrency::Periodic *wifiReconnect; + /// @return true if wifi is now in use bool initWifi(); diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 96135bc34..428f8ed86 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -7,6 +7,7 @@ #include "mesh/Router.h" #include "mesh/generated/mqtt.pb.h" #include "mesh/generated/telemetry.pb.h" +#include "mesh/http/WiFiAPClient.h" #include "sleep.h" #if HAS_WIFI #include @@ -20,6 +21,10 @@ String statusTopic = "msh/2/stat/"; String cryptTopic = "msh/2/c/"; // msh/2/c/CHANNELID/NODEID String jsonTopic = "msh/2/json/"; // msh/2/json/CHANNELID/NODEID +static MemoryDynamic staticMqttPool; + +Allocator &mqttPool = staticMqttPool; + void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length) { mqtt->onPublish(topic, payload, length); @@ -121,7 +126,7 @@ void mqttInit() new MQTT(); } -MQTT::MQTT() : concurrency::OSThread("mqtt"), pubSub(mqttClient) +MQTT::MQTT() : concurrency::OSThread("mqtt"), pubSub(mqttClient), mqttQueue(MAX_MQTT_QUEUE) { assert(!mqtt); mqtt = this; @@ -168,14 +173,23 @@ void MQTT::reconnect() DEBUG_MSG("MQTT connected\n"); enabled = true; // Start running background process again runASAP = true; + reconnectCount = 0; /// FIXME, include more information in the status text bool ok = pubSub.publish(myStatus.c_str(), "online", true); DEBUG_MSG("published %d\n", ok); sendSubscriptions(); - } else - DEBUG_MSG("Failed to contact MQTT server...\n"); + } else { + DEBUG_MSG("Failed to contact MQTT server (%d/10)...\n",reconnectCount); +#if HAS_WIFI + if (reconnectCount > 9) { + needReconnect = true; + wifiReconnect->setIntervalFromNow(1000); + } +#endif + reconnectCount++; + } } } @@ -231,8 +245,35 @@ int32_t MQTT::runOnce() if (wantConnection) { reconnect(); - // If we succeeded, start reading rapidly, else try again in 30 seconds (TCP connections are EXPENSIVE so try rarely) - return pubSub.connected() ? 20 : 30000; + // If we succeeded, empty the queue one by one and start reading rapidly, else try again in 30 seconds (TCP connections are EXPENSIVE so try rarely) + if (pubSub.connected()) { + if (!mqttQueue.isEmpty()) { + // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets + ServiceEnvelope *env = mqttQueue.dequeuePtr(0); + static uint8_t bytes[MeshPacket_size + 64]; + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), ServiceEnvelope_fields, env); + + String topic = cryptTopic + env->channel_id + "/" + owner.id; + DEBUG_MSG("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); + + + pubSub.publish(topic.c_str(), bytes, numBytes, false); + + if (moduleConfig.mqtt.json_enabled) { + // handle json topic + auto jsonString = this->downstreamPacketToJson(env->packet); + if (jsonString.length() != 0) { + String topicJson = jsonTopic + env->channel_id + "/" + owner.id; + DEBUG_MSG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); + } + } + mqttPool.release(env); + } + return 20; + } else { + return 30000; + } } else return 5000; // If we don't want connection now, check again in 5 secs } else { @@ -251,33 +292,48 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) { auto &ch = channels.getByIndex(chIndex); - // don't bother sending if not connected... - if (pubSub.connected() && ch.settings.uplink_enabled) { + if (ch.settings.uplink_enabled) { const char *channelId = channels.getGlobalId(chIndex); // FIXME, for now we just use the human name for the channel - ServiceEnvelope env = ServiceEnvelope_init_default; - env.channel_id = (char *)channelId; - env.gateway_id = owner.id; - env.packet = (MeshPacket *)∓ + ServiceEnvelope *env = mqttPool.allocZeroed(); + env->channel_id = (char *)channelId; + env->gateway_id = owner.id; + env->packet = (MeshPacket *)∓ - // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets - static uint8_t bytes[MeshPacket_size + 64]; - size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), ServiceEnvelope_fields, &env); + // don't bother sending if not connected... + if (pubSub.connected()) { - String topic = cryptTopic + channelId + "/" + owner.id; - DEBUG_MSG("publish %s, %u bytes\n", topic.c_str(), numBytes); + // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets + static uint8_t bytes[MeshPacket_size + 64]; + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), ServiceEnvelope_fields, env); - pubSub.publish(topic.c_str(), bytes, numBytes, false); + String topic = cryptTopic + channelId + "/" + owner.id; + DEBUG_MSG("publish %s, %u bytes\n", topic.c_str(), numBytes); - if (moduleConfig.mqtt.json_enabled) { - // handle json topic - auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp); - if (jsonString.length() != 0) { - String topicJson = jsonTopic + channelId + "/" + owner.id; - DEBUG_MSG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); - pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); + pubSub.publish(topic.c_str(), bytes, numBytes, false); + + if (moduleConfig.mqtt.json_enabled) { + // handle json topic + auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp); + if (jsonString.length() != 0) { + String topicJson = jsonTopic + channelId + "/" + owner.id; + DEBUG_MSG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); + } } + } else { + DEBUG_MSG("MQTT not connected, queueing packet\n"); + if (mqttQueue.numFree() == 0) { + DEBUG_MSG("NOTE: MQTT queue is full, discarding oldest\n"); + ServiceEnvelope *d = mqttQueue.dequeuePtr(0); + if (d) + mqttPool.release(d); + } + // make a copy of serviceEnvelope and queue it + ServiceEnvelope *copied = mqttPool.allocCopy(*env); + assert(mqttQueue.enqueue(copied, 0)); } + mqttPool.release(env); } } diff --git a/src/mqtt/MQTT.h b/src/mqtt/MQTT.h index c8381574c..ddbacbcc4 100644 --- a/src/mqtt/MQTT.h +++ b/src/mqtt/MQTT.h @@ -4,6 +4,7 @@ #include "concurrency/OSThread.h" #include "mesh/Channels.h" +#include "mesh/generated/mqtt.pb.h" #include #if HAS_WIFI #include @@ -12,6 +13,8 @@ #include #endif +#define MAX_MQTT_QUEUE 32 + /** * Our wrapper/singleton for sending/receiving MQTT "udp" packets. This object isolates the MQTT protocol implementation from * the two components that use it: MQTTPlugin and MQTTSimInterface. @@ -52,6 +55,10 @@ class MQTT : private concurrency::OSThread bool connected(); protected: + PointerQueue mqttQueue; + + int reconnectCount = 0; + virtual int32_t runOnce() override; private: From 6c84b3f01cb3a5c54a798e4ea6a7fc28c1a171c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:28:50 +0100 Subject: [PATCH 044/119] forgot variable define for heap debug --- src/power.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/power.h b/src/power.h index 64043eb86..b7f90ed6d 100644 --- a/src/power.h +++ b/src/power.h @@ -40,6 +40,7 @@ class Power : private concurrency::OSThread private: uint8_t low_voltage_counter; + uint32_t lastheap; }; extern Power *power; From 3cde75f97b04f43134a8f33958bf7730b53593d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:30:54 +0100 Subject: [PATCH 045/119] Audio Module: format messages better --- src/modules/esp32/AudioModule.cpp | 48 +++++++++++++++---------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 17e5cf4fa..e7132fcc4 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -71,27 +71,22 @@ void run_codec2(void* parameter) // 4 bytes of header in each frame hex c0 de c2 plus the bitrate memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); + DEBUG_MSG("Starting codec2 task\n"); + while (true) { uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); if (tcount != 0) { if (audioModule->radio_state == RadioState::tx) { - - // Apply the TX filter for (int i = 0; i < audioModule->adc_buffer_size; i++) audioModule->speech[i] = (int16_t)hp_filter.Update((float)audioModule->speech[i]); - // Encode the audio codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, audioModule->speech); - - //increment the pointer where the encoded frame must be saved audioModule->tx_encode_frame_index += audioModule->encode_codec_size; - //If it this is reached we have a ready trasnmission frame if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) { - //Transmit it - DEBUG_MSG("♪♫♪ Sending %d codec2 bytes\n", audioModule->encode_frame_size); + DEBUG_MSG("Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); } @@ -99,10 +94,8 @@ void run_codec2(void* parameter) if (audioModule->radio_state == RadioState::rx) { size_t bytesOut = 0; if (memcmp(audioModule->rx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header)) == 0) { - // Make a cycle to get each codec2 frame from the received frame for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) { - //Decode the codec2 frame codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); } @@ -112,10 +105,8 @@ void run_codec2(void* parameter) codec2_set_lpc_post_filter(tmp_codec2, 1, 0, 0.8, 0.2); int tmp_encode_codec_size = (codec2_bits_per_frame(tmp_codec2) + 7) / 8; int tmp_adc_buffer_size = codec2_samples_per_frame(tmp_codec2); - // Make a cycle to get each codec2 frame from the received frame for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size) { - //Decode the codec2 frame codec2_decode(tmp_codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); i2s_write(I2S_PORT, &audioModule->output_buffer, tmp_adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); } @@ -128,8 +119,15 @@ void run_codec2(void* parameter) AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { + // moduleConfig.audio.codec2_enabled = true; + // moduleConfig.audio.i2s_ws = 13; + // moduleConfig.audio.i2s_sd = 15; + // moduleConfig.audio.i2s_din = 22; + // moduleConfig.audio.i2s_sck = 14; + // moduleConfig.audio.ptt_pin = 39; + if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - DEBUG_MSG("♪♫♪ Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + DEBUG_MSG("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; @@ -141,7 +139,7 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { - DEBUG_MSG("♪♫♪ Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); + DEBUG_MSG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -175,7 +173,7 @@ int32_t AudioModule::runOnce() esp_err_t res; if (firstTime) { // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC - DEBUG_MSG("♪♫♪ Initializing I2S SD: %d DIN: %d WS: %d SCK:%d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); + DEBUG_MSG("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), .sample_rate = 8000, @@ -191,7 +189,7 @@ int32_t AudioModule::runOnce() }; res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to install I2S driver: %d\n", res); + DEBUG_MSG("Failed to install I2S driver: %d\n", res); const i2s_pin_config_t pin_config = { .bck_io_num = moduleConfig.audio.i2s_sck, @@ -201,16 +199,16 @@ int32_t AudioModule::runOnce() }; res = i2s_set_pin(I2S_PORT, &pin_config); if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to set I2S pin config: %d\n", res); + DEBUG_MSG("Failed to set I2S pin config: %d\n", res); res = i2s_start(I2S_PORT); if(res != ESP_OK) - DEBUG_MSG("♪♫♪ Failed to start I2S: %d\n", res); + DEBUG_MSG("Failed to start I2S: %d\n", res); radio_state = RadioState::rx; // Configure PTT input - DEBUG_MSG("♪♫♪ Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + DEBUG_MSG("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; @@ -219,19 +217,19 @@ int32_t AudioModule::runOnce() // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { - DEBUG_MSG("♪♫♪ PTT pressed, switching to TX\n"); + DEBUG_MSG("PTT pressed, switching to TX\n"); radio_state = RadioState::tx; e.frameChanged = true; this->notifyObservers(&e); } } else { if (radio_state == RadioState::tx) { + DEBUG_MSG("PTT released, switching to RX\n"); if (tx_encode_frame_index > sizeof(tx_header)) { // Send the incomplete frame - DEBUG_MSG("♪♫♪ Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); + DEBUG_MSG("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } - DEBUG_MSG("♪♫♪ PTT released, switching to RX\n"); tx_encode_frame_index = sizeof(tx_header); radio_state = RadioState::rx; e.frameChanged = true; @@ -260,7 +258,7 @@ int32_t AudioModule::runOnce() } return 100; } else { - DEBUG_MSG("♪♫♪ Audio Module Disabled\n"); + DEBUG_MSG("Audio Module Disabled\n"); return INT32_MAX; } @@ -268,7 +266,7 @@ int32_t AudioModule::runOnce() MeshPacket *AudioModule::allocReply() { - auto reply = allocDataPacket(); // Allocate a packet for sending + auto reply = allocDataPacket(); return reply; } @@ -286,7 +284,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) p->to = dest; p->decoded.want_response = wantReplies; - p->want_ack = false; // Audio is shoot&forget. TODO: Is this really suppressing retransmissions? + p->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs. p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime p->decoded.payload.size = tx_encode_frame_index; From 54686905dc41f66f42e3dcb86be3d7b50b8a0a1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:33:09 +0100 Subject: [PATCH 046/119] remove duplicate block of predefined messages --- src/modules/ExternalNotificationModule.cpp | 26 ++++++++-------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index e496e1699..b77f3a887 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -34,19 +34,6 @@ uint32_t externalTurnedOn[3] = {}; int32_t ExternalNotificationModule::runOnce() { - /* - Uncomment the preferences below if you want to use the module - without having to configure it from the PythonAPI or WebUI. - */ - - // moduleConfig.external_notification.enabled = 1; - // moduleConfig.external_notification.alert_message = 1; - - // moduleConfig.external_notification.active = 1; - // moduleConfig.external_notification.alert_bell = 1; - // moduleConfig.external_notification.output_ms = 1000; - // moduleConfig.external_notification.output = 13; - if (moduleConfig.external_notification.use_pwm || !moduleConfig.external_notification.enabled) { return INT32_MAX; // we don't need this thread here... } else { @@ -143,13 +130,18 @@ ExternalNotificationModule::ExternalNotificationModule() without having to configure it from the PythonAPI or WebUI. */ - // moduleConfig.external_notification.enabled = 1; - // moduleConfig.external_notification.alert_message = 1; + // moduleConfig.external_notification.enabled = true; + // moduleConfig.external_notification.alert_message = true; + // moduleConfig.external_notification.alert_message_buzzer = true; + // moduleConfig.external_notification.alert_message_vibra = true; - // moduleConfig.external_notification.active = 1; + // moduleConfig.external_notification.active = true; // moduleConfig.external_notification.alert_bell = 1; // moduleConfig.external_notification.output_ms = 1000; - // moduleConfig.external_notification.output = 13; + // moduleConfig.external_notification.output = 4; // RAK4631 IO4 + // moduleConfig.external_notification.output_buzzer = 10; // RAK4631 IO6 + // moduleConfig.external_notification.output_vibra = 28; // RAK4631 IO7 + // moduleConfig.external_notification.nag_timeout = 300; if (moduleConfig.external_notification.enabled) { From bbaeeb7ce9c074142e5b6dac0167a4bf862eefc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 16 Dec 2022 20:46:43 +0100 Subject: [PATCH 047/119] fixing portduino is getting old ... --- src/Power.cpp | 3 +++ src/mqtt/MQTT.cpp | 2 +- src/power.h | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Power.cpp b/src/Power.cpp index 0d95a6ec4..5b379f3c6 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -182,6 +182,9 @@ Power::Power() : OSThread("Power") { statusHandler = {}; low_voltage_counter = 0; +#ifdef DEBUG_HEAP + lastheap = ESP.getFreeHeap(); +#endif } bool Power::analogInit() diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 428f8ed86..03549f911 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -182,7 +182,7 @@ void MQTT::reconnect() sendSubscriptions(); } else { DEBUG_MSG("Failed to contact MQTT server (%d/10)...\n",reconnectCount); -#if HAS_WIFI +#if HAS_WIFI && !defined(ARCH_PORTDUINO) if (reconnectCount > 9) { needReconnect = true; wifiReconnect->setIntervalFromNow(1000); diff --git a/src/power.h b/src/power.h index b7f90ed6d..b370e0248 100644 --- a/src/power.h +++ b/src/power.h @@ -40,7 +40,9 @@ class Power : private concurrency::OSThread private: uint8_t low_voltage_counter; +#ifdef DEBUG_HEAP uint32_t lastheap; +#endif }; extern Power *power; From d9eb9758e2400c31862b16afe710afb882c56210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 18 Dec 2022 14:47:28 +0100 Subject: [PATCH 048/119] add bold print to canned messages freetext --- src/modules/CannedMessageModule.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index e7b34b9a7..d148768ad 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -451,11 +451,15 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st if (this->destSelect) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); + display->drawStringf(1 + x, 0 + y, buffer, "To: %s", cannedMessageModule->getNodeName(this->dest)); } display->drawStringf(0 + x, 0 + y, buffer, "To: %s", cannedMessageModule->getNodeName(this->dest)); // used chars right aligned sprintf(buffer, "%d left", Constants_DATA_PAYLOAD_LEN - this->freetext.length()); display->drawString(x + display->getWidth() - display->getStringWidth(buffer), y + 0, buffer); + if (this->destSelect) { + display->drawString(x + display->getWidth() - display->getStringWidth(buffer) - 1, y + 0, buffer); + } display->setColor(WHITE); display->drawStringMaxWidth(0 + x, 0 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), cannedMessageModule->drawWithCursor(cannedMessageModule->freetext, cannedMessageModule->cursor)); } else { From 34c73da886b0f4cbc70f73650464c01a8575dab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 12:55:12 +0100 Subject: [PATCH 049/119] update to nanopb 0.4.7 --- .github/workflows/update_protobufs.yml | 6 +++--- bin/regen-protos.bat | 2 +- bin/regen-protos.sh | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/update_protobufs.yml b/.github/workflows/update_protobufs.yml index 3b32c578c..6944d827e 100644 --- a/.github/workflows/update_protobufs.yml +++ b/.github/workflows/update_protobufs.yml @@ -17,9 +17,9 @@ jobs: - name: Download nanopb run: | - wget https://jpa.kapsi.fi/nanopb/download/nanopb-0.4.6-linux-x86.tar.gz - tar xvzf nanopb-0.4.6-linux-x86.tar.gz - mv nanopb-0.4.6-linux-x86 nanopb-0.4.6 + wget https://jpa.kapsi.fi/nanopb/download/nanopb-0.4.7-linux-x86.tar.gz + tar xvzf nanopb-0.4.7-linux-x86.tar.gz + mv nanopb-0.4.7-linux-x86 nanopb-0.4.7 - name: Re-generate protocol buffers run: | diff --git a/bin/regen-protos.bat b/bin/regen-protos.bat index 12ee7d7ab..5c576c5b2 100644 --- a/bin/regen-protos.bat +++ b/bin/regen-protos.bat @@ -1 +1 @@ -cd protobufs && ..\nanopb-0.4.6\generator-bin\protoc.exe --nanopb_out=-v:..\src\mesh\generated -I=..\protobufs *.proto +cd protobufs && ..\nanopb-0.4.7\generator-bin\protoc.exe --nanopb_out=-v:..\src\mesh\generated -I=..\protobufs *.proto diff --git a/bin/regen-protos.sh b/bin/regen-protos.sh index 2734c213b..133d587a3 100755 --- a/bin/regen-protos.sh +++ b/bin/regen-protos.sh @@ -2,13 +2,13 @@ set -e -echo "This script requires https://jpa.kapsi.fi/nanopb/download/ version 0.4.6 to be located in the" +echo "This script requires https://jpa.kapsi.fi/nanopb/download/ version 0.4.7 to be located in the" echo "firmware root directory if the following step fails, you should download the correct" -echo "prebuilt binaries for your computer into nanopb-0.4.6" +echo "prebuilt binaries for your computer into nanopb-0.4.7" # the nanopb tool seems to require that the .options file be in the current directory! cd protobufs -../nanopb-0.4.6/generator-bin/protoc --nanopb_out=-v:../src/mesh/generated -I=../protobufs *.proto +../nanopb-0.4.7/generator-bin/protoc --nanopb_out=-v:../src/mesh/generated -I=../protobufs *.proto #echo "Regenerating protobuf documentation - if you see an error message" #echo "you can ignore it unless doing a new protobuf release to github." From ae2ca1d89c0e94b0823da98005113d686ca6ce6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 12:57:42 +0100 Subject: [PATCH 050/119] WIP: S&F Progress --- protobufs | 2 +- src/mesh/generated/storeforward.pb.c | 2 +- src/mesh/generated/storeforward.pb.h | 157 +++++++++----- src/modules/esp32/StoreForwardModule.cpp | 259 +++++++++++------------ src/modules/esp32/StoreForwardModule.h | 33 ++- 5 files changed, 255 insertions(+), 198 deletions(-) diff --git a/protobufs b/protobufs index 737d1fc01..c70bbf033 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 737d1fc01bd7f57e48e9b8cd53b780b314b09c5b +Subproject commit c70bbf033aee8e0ae0c2cf5c4e1b60ad5782f56f diff --git a/src/mesh/generated/storeforward.pb.c b/src/mesh/generated/storeforward.pb.c index 034137116..69db0e3bf 100644 --- a/src/mesh/generated/storeforward.pb.c +++ b/src/mesh/generated/storeforward.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "storeforward.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/storeforward.pb.h b/src/mesh/generated/storeforward.pb.h index edc965cbd..3f21114ff 100644 --- a/src/mesh/generated/storeforward.pb.h +++ b/src/mesh/generated/storeforward.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_STOREFORWARD_PB_H_INCLUDED #define PB_STOREFORWARD_PB_H_INCLUDED @@ -10,88 +10,124 @@ #endif /* Enum definitions */ -typedef enum _StoreAndForward_RequestResponse { - StoreAndForward_RequestResponse_UNSET = 0, - StoreAndForward_RequestResponse_ROUTER_ERROR = 1, - StoreAndForward_RequestResponse_ROUTER_HEARTBEAT = 2, - StoreAndForward_RequestResponse_ROUTER_PING = 3, - StoreAndForward_RequestResponse_ROUTER_PONG = 4, - StoreAndForward_RequestResponse_ROUTER_BUSY = 5, - StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, - StoreAndForward_RequestResponse_CLIENT_ERROR = 101, - StoreAndForward_RequestResponse_CLIENT_HISTORY = 102, - StoreAndForward_RequestResponse_CLIENT_STATS = 103, - StoreAndForward_RequestResponse_CLIENT_PING = 104, - StoreAndForward_RequestResponse_CLIENT_PONG = 105, - StoreAndForward_RequestResponse_CLIENT_ABORT = 106 +/* 001 - 063 = From Router + 064 - 127 = From Client */ +typedef enum _StoreAndForward_RequestResponse { + /* Unset/unused */ + StoreAndForward_RequestResponse_UNSET = 0, + /* Router is an in error state. */ + StoreAndForward_RequestResponse_ROUTER_ERROR = 1, + /* Router heartbeat */ + StoreAndForward_RequestResponse_ROUTER_HEARTBEAT = 2, + /* Router has requested the client respond. This can work as a + "are you there" message. */ + StoreAndForward_RequestResponse_ROUTER_PING = 3, + /* The response to a "Ping" */ + StoreAndForward_RequestResponse_ROUTER_PONG = 4, + /* Router is currently busy. Please try again later. */ + StoreAndForward_RequestResponse_ROUTER_BUSY = 5, + /* Router is responding to a request for history. */ + StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, + /* Client is an in error state. */ + StoreAndForward_RequestResponse_CLIENT_ERROR = 64, + /* Client has requested a replay from the router. */ + StoreAndForward_RequestResponse_CLIENT_HISTORY = 65, + /* Client has requested stats from the router. */ + StoreAndForward_RequestResponse_CLIENT_STATS = 66, + /* Client has requested the router respond. This can work as a + "are you there" message. */ + StoreAndForward_RequestResponse_CLIENT_PING = 67, + /* The response to a "Ping" */ + StoreAndForward_RequestResponse_CLIENT_PONG = 68, + /* Client has requested that the router abort processing the client's request */ + StoreAndForward_RequestResponse_CLIENT_ABORT = 106 } StoreAndForward_RequestResponse; /* Struct definitions */ -typedef struct _StoreAndForward_Heartbeat { - uint32_t period; - uint32_t secondary; -} StoreAndForward_Heartbeat; - -typedef struct _StoreAndForward_History { - uint32_t history_messages; - uint32_t window; - uint32_t last_request; -} StoreAndForward_History; - -typedef struct _StoreAndForward_Statistics { +/* TODO: REPLACE */ +typedef struct _StoreAndForward_Statistics { + /* Number of messages we have ever seen */ uint32_t messages_total; + /* Number of messages we have currently saved our history. */ uint32_t messages_saved; + /* Maximum number of messages we will save */ uint32_t messages_max; + /* Router uptime in seconds */ uint32_t up_time; + /* Number of times any client sent a request to the S&F. */ uint32_t requests; + /* Number of times the history was requested. */ uint32_t requests_history; + /* Is the heartbeat enabled on the server? */ bool heartbeat; + /* Is the heartbeat enabled on the server? */ uint32_t return_max; + /* Is the heartbeat enabled on the server? */ uint32_t return_window; } StoreAndForward_Statistics; /* TODO: REPLACE */ -typedef struct _StoreAndForward { +typedef struct _StoreAndForward_History { + /* Number of that will be sent to the client */ + uint32_t history_messages; + /* The window of messages that was used to filter the history client requested */ + uint32_t window; + /* The window of messages that was used to filter the history client requested */ + uint32_t last_request; +} StoreAndForward_History; + +/* TODO: REPLACE */ +typedef struct _StoreAndForward_Heartbeat { + /* Number of that will be sent to the client */ + uint32_t period; + /* If set, this is not the primary Store & Forward router on the mesh */ + uint32_t secondary; +} StoreAndForward_Heartbeat; + +/* TODO: REPLACE */ +typedef struct _StoreAndForward { /* TODO: REPLACE */ StoreAndForward_RequestResponse rr; - /* TODO: REPLACE */ - bool has_stats; - StoreAndForward_Statistics stats; - /* TODO: REPLACE */ - bool has_history; - StoreAndForward_History history; - /* TODO: REPLACE */ - bool has_heartbeat; - StoreAndForward_Heartbeat heartbeat; + pb_size_t which_variant; + union { + /* TODO: REPLACE */ + StoreAndForward_Statistics stats; + /* TODO: REPLACE */ + StoreAndForward_History history; + /* TODO: REPLACE */ + StoreAndForward_Heartbeat heartbeat; + /* Empty Payload */ + bool empty; + } variant; } StoreAndForward; -/* Helper constants for enums */ -#define _StoreAndForward_RequestResponse_MIN StoreAndForward_RequestResponse_UNSET -#define _StoreAndForward_RequestResponse_MAX StoreAndForward_RequestResponse_CLIENT_ABORT -#define _StoreAndForward_RequestResponse_ARRAYSIZE ((StoreAndForward_RequestResponse)(StoreAndForward_RequestResponse_CLIENT_ABORT+1)) - - #ifdef __cplusplus extern "C" { #endif +/* Helper constants for enums */ +#define _StoreAndForward_RequestResponse_MIN StoreAndForward_RequestResponse_UNSET +#define _StoreAndForward_RequestResponse_MAX StoreAndForward_RequestResponse_CLIENT_ABORT +#define _StoreAndForward_RequestResponse_ARRAYSIZE ((StoreAndForward_RequestResponse)(StoreAndForward_RequestResponse_CLIENT_ABORT+1)) + +#define StoreAndForward_rr_ENUMTYPE StoreAndForward_RequestResponse + + + + + /* Initializer values for message structs */ -#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_default, false, StoreAndForward_History_init_default, false, StoreAndForward_Heartbeat_init_default} +#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_default}} #define StoreAndForward_Statistics_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_default {0, 0, 0} #define StoreAndForward_Heartbeat_init_default {0, 0} -#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_zero, false, StoreAndForward_History_init_zero, false, StoreAndForward_Heartbeat_init_zero} +#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_zero}} #define StoreAndForward_Statistics_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_zero {0, 0, 0} #define StoreAndForward_Heartbeat_init_zero {0, 0} /* Field tags (for use in manual encoding/decoding) */ -#define StoreAndForward_Heartbeat_period_tag 1 -#define StoreAndForward_Heartbeat_secondary_tag 2 -#define StoreAndForward_History_history_messages_tag 1 -#define StoreAndForward_History_window_tag 2 -#define StoreAndForward_History_last_request_tag 3 #define StoreAndForward_Statistics_messages_total_tag 1 #define StoreAndForward_Statistics_messages_saved_tag 2 #define StoreAndForward_Statistics_messages_max_tag 3 @@ -101,22 +137,29 @@ extern "C" { #define StoreAndForward_Statistics_heartbeat_tag 7 #define StoreAndForward_Statistics_return_max_tag 8 #define StoreAndForward_Statistics_return_window_tag 9 +#define StoreAndForward_History_history_messages_tag 1 +#define StoreAndForward_History_window_tag 2 +#define StoreAndForward_History_last_request_tag 3 +#define StoreAndForward_Heartbeat_period_tag 1 +#define StoreAndForward_Heartbeat_secondary_tag 2 #define StoreAndForward_rr_tag 1 #define StoreAndForward_stats_tag 2 #define StoreAndForward_history_tag 3 #define StoreAndForward_heartbeat_tag 4 +#define StoreAndForward_empty_tag 5 /* Struct field encoding specification for nanopb */ #define StoreAndForward_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, rr, 1) \ -X(a, STATIC, OPTIONAL, MESSAGE, stats, 2) \ -X(a, STATIC, OPTIONAL, MESSAGE, history, 3) \ -X(a, STATIC, OPTIONAL, MESSAGE, heartbeat, 4) +X(a, STATIC, ONEOF, MESSAGE, (variant,stats,variant.stats), 2) \ +X(a, STATIC, ONEOF, MESSAGE, (variant,history,variant.history), 3) \ +X(a, STATIC, ONEOF, MESSAGE, (variant,heartbeat,variant.heartbeat), 4) \ +X(a, STATIC, ONEOF, BOOL, (variant,empty,variant.empty), 5) #define StoreAndForward_CALLBACK NULL #define StoreAndForward_DEFAULT NULL -#define StoreAndForward_stats_MSGTYPE StoreAndForward_Statistics -#define StoreAndForward_history_MSGTYPE StoreAndForward_History -#define StoreAndForward_heartbeat_MSGTYPE StoreAndForward_Heartbeat +#define StoreAndForward_variant_stats_MSGTYPE StoreAndForward_Statistics +#define StoreAndForward_variant_history_MSGTYPE StoreAndForward_History +#define StoreAndForward_variant_heartbeat_MSGTYPE StoreAndForward_Heartbeat #define StoreAndForward_Statistics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, messages_total, 1) \ @@ -159,7 +202,7 @@ extern const pb_msgdesc_t StoreAndForward_Heartbeat_msg; #define StoreAndForward_Heartbeat_size 12 #define StoreAndForward_History_size 18 #define StoreAndForward_Statistics_size 50 -#define StoreAndForward_size 88 +#define StoreAndForward_size 54 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 9d1c44c18..54f124301 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -22,41 +22,31 @@ int32_t StoreForwardModule::runOnce() if (this->busy) { // Only send packets if the channel is less than 25% utilized. if (airTime->channelUtilizationPercent() < polite_channel_util_percent) { - - // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); - if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { - strcpy(this->routerMessage, "** S&F - Done"); - storeForwardModule->sendMessage(this->busyTo, this->routerMessage); - - // DEBUG_MSG("--- --- --- In busy loop - Done \n"); + // Tell the client we're done sending + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_PING; + storeForwardModule->sendMessage(this->busyTo, sf); + DEBUG_MSG("*** S&F - Done. (ROUTER_PING)\n"); this->packetHistoryTXQueue_index = 0; this->busy = false; } else { this->packetHistoryTXQueue_index++; } - } else { - DEBUG_MSG("Channel utilization is too high. Retrying later.\n"); + DEBUG_MSG("*** Channel utilization is too high. Retrying later.\n"); } - DEBUG_MSG("SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); + DEBUG_MSG("*** SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); - } else if (millis() - lastHeartbeat > 300000) { + } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && (airTime->channelUtilizationPercent() < polite_channel_util_percent)) { lastHeartbeat = millis(); - DEBUG_MSG("Sending heartbeat\n"); - + DEBUG_MSG("*** Sending heartbeat\n"); StoreAndForward sf; sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; - sf.has_heartbeat = true; - sf.heartbeat.period = 300; - sf.heartbeat.secondary = 0; // TODO we always have one primary router for now - - MeshPacket *p = allocDataProtobuf(sf); - p->to = NODENUM_BROADCAST; - p->decoded.want_response = false; - p->priority = MeshPacket_Priority_MIN; - service.sendToMesh(p); + sf.variant.heartbeat.period = 300; + sf.variant.heartbeat.secondary = 0; // TODO we always have one primary router for now + storeForwardModule->sendMessage(NODENUM_BROADCAST, sf); } return (this->packetTimeMax); } @@ -74,7 +64,7 @@ void StoreForwardModule::populatePSRAM() https://learn.upesy.com/en/programmation/psram.html#psram-tab */ - DEBUG_MSG("Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + DEBUG_MSG("*** Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); this->packetHistoryTXQueue = static_cast(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct))); @@ -83,46 +73,35 @@ void StoreForwardModule::populatePSRAM() Note: This needs to be done after every thing that would use PSRAM */ uint32_t numberOfPackets = (this->records ? this->records : (((ESP.getFreePsram() / 3) * 2) / sizeof(PacketHistoryStruct))); + this->records = numberOfPackets; this->packetHistory = static_cast(ps_calloc(numberOfPackets, sizeof(PacketHistoryStruct))); - DEBUG_MSG("After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); - DEBUG_MSG("numberOfPackets for packetHistory - %u\n", numberOfPackets); + DEBUG_MSG("*** After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + DEBUG_MSG("*** numberOfPackets for packetHistory - %u\n", numberOfPackets); } -void StoreForwardModule::historyReport() -{ - DEBUG_MSG("Message history contains %u records\n", this->packetHistoryCurrent); -} - -/* - * - */ void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) { - - // uint32_t packetsSent = 0; - uint32_t queueSize = storeForwardModule->historyQueueCreate(msAgo, to); if (queueSize) { - snprintf(this->routerMessage, 80, "** S&F - Sending %u message(s)", queueSize); - storeForwardModule->sendMessage(to, this->routerMessage); - + DEBUG_MSG ("*** S&F - Sending %u message(s)\n", queueSize); this->busy = true; // runOnce() will pickup the next steps once busy = true. this->busyTo = to; - } else { - strcpy(this->routerMessage, "** S&F - No history to send"); - storeForwardModule->sendMessage(to, this->routerMessage); + DEBUG_MSG ("*** S&F - No history to send\n"); } + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; + sf.which_variant = StoreAndForward_history_tag; + sf.variant.history.history_messages = queueSize; + storeForwardModule->sendMessage(to, sf); } uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) { - // uint32_t packetHistoryTXQueueIndex = 0; - this->packetHistoryTXQueue_size = 0; for (int i = 0; i < this->packetHistoryCurrent; i++) { @@ -133,7 +112,7 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) DEBUG_MSG("SF historyQueueCreate - math %d\n", (millis() - msAgo)); */ if (this->packetHistory[i].time && (this->packetHistory[i].time < (millis() - msAgo))) { - DEBUG_MSG("SF historyQueueCreate - Time matches - ok\n"); + DEBUG_MSG("*** SF historyQueueCreate - Time matches - ok\n"); /* Copy the messages that were received by the router in the last msAgo to the packetHistoryTXQueue structure. @@ -144,7 +123,6 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) if ((this->packetHistory[i].to & NODENUM_BROADCAST) == NODENUM_BROADCAST || ((this->packetHistory[i].to & NODENUM_BROADCAST) == to)) { this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].time = this->packetHistory[i].time; - this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].time = this->packetHistory[i].time; this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].to = this->packetHistory[i].to; this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].from = this->packetHistory[i].from; this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].channel = this->packetHistory[i].channel; @@ -153,9 +131,8 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) Constants_DATA_PAYLOAD_LEN); this->packetHistoryTXQueue_size++; - DEBUG_MSG("PacketHistoryStruct time=%d\n", this->packetHistory[i].time); - DEBUG_MSG("PacketHistoryStruct msg=%.*s\n", this->packetHistory[i].payload); - // DEBUG_MSG("PacketHistoryStruct msg=%.*s\n", this->packetHistoryTXQueue[packetHistoryTXQueueIndex].payload); + DEBUG_MSG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time); + DEBUG_MSG("*** PacketHistoryStruct msg=%s\n", this->packetHistory[i].payload); } } } @@ -174,6 +151,7 @@ void StoreForwardModule::historyAdd(const MeshPacket &mp) memcpy(this->packetHistory[this->packetHistoryCurrent].payload, p.payload.bytes, Constants_DATA_PAYLOAD_LEN); this->packetHistoryCurrent++; + this->packetHistoryMax++; } MeshPacket *StoreForwardModule::allocReply() @@ -184,7 +162,7 @@ MeshPacket *StoreForwardModule::allocReply() void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) { - DEBUG_MSG("Sending S&F Payload\n"); + DEBUG_MSG("*** Sending S&F Payload\n"); MeshPacket *p = allocReply(); p->to = dest; @@ -203,12 +181,14 @@ void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) service.sendToMesh(p); } -void StoreForwardModule::sendMessage(NodeNum dest, char *str) +void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward payload) { - MeshPacket *p = allocReply(); + MeshPacket *p = allocDataProtobuf(payload); p->to = dest; + p->priority = MeshPacket_Priority_MIN; + // FIXME - Determine if the delayed packet is broadcast or delayed. For now, assume // everything is broadcast. p->delayed = MeshPacket_Delayed_DELAYED_BROADCAST; @@ -216,60 +196,59 @@ void StoreForwardModule::sendMessage(NodeNum dest, char *str) // Let's assume that if the router received the S&F request that the client is in range. // TODO: Make this configurable. p->want_ack = false; - - p->decoded.payload.size = strlen(str); // You must specify how many bytes are in the reply - memcpy(p->decoded.payload.bytes, str, strlen(str)); + p->decoded.want_response = false; service.sendToMesh(p); // HardwareMessage_init_default } +void StoreForwardModule::statsSend(uint32_t to) +{ + StoreAndForward sf; + + sf.which_variant = StoreAndForward_stats_tag; + sf.variant.stats.messages_total = this->packetHistoryMax; + sf.variant.stats.messages_saved = this->packetHistoryCurrent; + sf.variant.stats.messages_max = this->records; + sf.variant.stats.up_time = millis() / 1000; + sf.variant.stats.requests = this->requests; + sf.variant.stats.requests_history = this->requests_history; + sf.variant.stats.heartbeat = this->heartbeat; + sf.variant.stats.return_max = this->historyReturnMax; + sf.variant.stats.return_window = this->historyReturnWindow; + + DEBUG_MSG("*** Sending S&F Stats\n"); + storeForwardModule->sendMessage(to, sf); +} + ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) { #ifdef ARCH_ESP32 if (moduleConfig.store_forward.enabled) { - DEBUG_MSG("--- S&F Received something\n"); - // The router node should not be sending messages as a client. Unless he is a ROUTER_CLIENT if ((getFrom(&mp) != nodeDB.getNodeNum()) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { - DEBUG_MSG("Packet came from - PortNum_TEXT_MESSAGE_APP\n"); - - auto &p = mp.decoded; - - if ((p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 0x00)) { - DEBUG_MSG("--- --- --- Request to send\n"); - - // Send the last 60 minutes of messages. - if (this->busy) { - strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); - storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); - } else { - storeForwardModule->historySend(1000 * 60, getFrom(&mp)); - } - - } else if ((p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 'm') && - (p.payload.bytes[3] == 0x00)) { - strlcpy(this->routerMessage, - "01234567890123456789012345678901234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789012345678901234567890123456", - sizeof(this->routerMessage)); - storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); - - } else { - storeForwardModule->historyAdd(mp); - } + storeForwardModule->historyAdd(mp); + DEBUG_MSG("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { - DEBUG_MSG("Packet came from an PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); - - } else { - DEBUG_MSG("Packet came from an unknown port %u\n", mp.decoded.portnum); - } + auto &p = mp.decoded; + StoreAndForward scratch; + StoreAndForward *decoded = NULL; + if (mp.which_payload_variant == MeshPacket_decoded_tag) { + if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &StoreAndForward_msg, &scratch)) { + decoded = &scratch; + } else { + DEBUG_MSG("Error decoding protobuf module!\n"); + // if we can't decode it, nobody can process it! + return ProcessMessage::STOP; + } + return handleReceivedProtobuf(mp, decoded) ? ProcessMessage::STOP : ProcessMessage::CONTINUE; + } + } // all others are irrelevant } } @@ -285,95 +264,115 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo return false; } - if (mp.decoded.portnum != PortNum_STORE_FORWARD_APP) { - DEBUG_MSG("Packet came from port %u\n", mp.decoded.portnum); - return false; - } else { - DEBUG_MSG("Packet came from PortNum_STORE_FORWARD_APP port %u\n", mp.decoded.portnum); - + requests++; switch (p->rr) { case StoreAndForward_RequestResponse_CLIENT_ERROR: + case StoreAndForward_RequestResponse_CLIENT_ABORT: if(is_server) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_ERROR\n"); + // stop sending stuff, the client wants to abort or has another error + if ((this->busy) && (this->busyTo == getFrom(&mp))) { + DEBUG_MSG("*** Client in ERROR or ABORT requested\n"); + this->packetHistoryTXQueue_index = 0; + this->busy = false; + } } break; case StoreAndForward_RequestResponse_CLIENT_HISTORY: if(is_server) { - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_HISTORY\n"); + requests_history++; + DEBUG_MSG("*** Client Request to send HISTORY\n"); // Send the last 60 minutes of messages. if (this->busy) { - strcpy(this->routerMessage, "** S&F - Busy. Try again shortly."); - storeForwardModule->sendMessage(getFrom(&mp), this->routerMessage); + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_BUSY; + storeForwardModule->sendMessage(getFrom(&mp), sf); + DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); } else { - storeForwardModule->historySend(1000 * 60, getFrom(&mp)); + if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)){ + storeForwardModule->historySend(p->variant.history.window * 1000 * 60, getFrom(&mp)); // window is in minutes + } else { + storeForwardModule->historySend(60 * 1000 * 60, getFrom(&mp)); // defaults to 60 minutes + } } } break; case StoreAndForward_RequestResponse_CLIENT_PING: if(is_server) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PING\n"); + DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); + // respond with a ROUTER PONG + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_PONG; + storeForwardModule->sendMessage(getFrom(&mp), sf); } break; case StoreAndForward_RequestResponse_CLIENT_PONG: if(is_server) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_PONG\n"); + DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); + // The Client is alive, update NodeDB + nodeDB.updateFrom(mp); } break; case StoreAndForward_RequestResponse_CLIENT_STATS: if(is_server) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_CLIENT_STATS\n"); + DEBUG_MSG("*** Client Request to send STATS\n"); + if (this->busy) { + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_BUSY; + storeForwardModule->sendMessage(getFrom(&mp), sf); + DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); + } else { + storeForwardModule->statsSend(getFrom(&mp)); + } } break; case StoreAndForward_RequestResponse_ROUTER_BUSY: if(is_client) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + // retry in messages_saved * packetTimeMax ms + retry_delay = millis() + packetHistoryCurrent * packetTimeMax; } break; case StoreAndForward_RequestResponse_ROUTER_ERROR: if(is_client) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_ERROR\n"); + DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_ERROR\n"); + // retry in messages_saved * packetTimeMax * 2 ms + retry_delay = millis() + packetHistoryCurrent * packetTimeMax * 2; } break; + case StoreAndForward_RequestResponse_ROUTER_PONG: + // A router responded, this is equal to receiving a heartbeat case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: if(is_client) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_HEARTBEAT\n"); + // register heartbeat and interval + if (p->which_variant == StoreAndForward_heartbeat_tag) { + heartbeatInterval = p->variant.heartbeat.period; + } + lastHeartbeat = millis(); + DEBUG_MSG("*** StoreAndForward Heartbeat received\n"); } break; case StoreAndForward_RequestResponse_ROUTER_PING: if(is_client) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PING\n"); - } - break; - - case StoreAndForward_RequestResponse_ROUTER_PONG: - if(is_client) { - // Do nothing - DEBUG_MSG("StoreAndForward_RequestResponse_ROUTER_PONG\n"); + DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); + // respond with a CLIENT PONG + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_CLIENT_PONG; + storeForwardModule->sendMessage(getFrom(&mp), sf); } break; default: assert(0); // unexpected state - FIXME, make an error code and reboot - } } - return true; // There's no need for others to look at this message. } @@ -398,7 +397,7 @@ StoreForwardModule::StoreForwardModule() // Router if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { - DEBUG_MSG("Initializing Store & Forward Module in Router mode\n"); + DEBUG_MSG("*** Initializing Store & Forward Module in Router mode\n"); if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { @@ -424,19 +423,19 @@ StoreForwardModule::StoreForwardModule() this->populatePSRAM(); is_server = true; } else { - DEBUG_MSG("Device has less than 1M of PSRAM free.\n"); - DEBUG_MSG("Store & Forward Module - disabling server.\n"); + DEBUG_MSG("*** Device has less than 1M of PSRAM free.\n"); + DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); } } else { - DEBUG_MSG("Device doesn't have PSRAM.\n"); - DEBUG_MSG("Store & Forward Module - disabling server.\n"); + DEBUG_MSG("*** Device doesn't have PSRAM.\n"); + DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); } // Client } if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { is_client = true; - DEBUG_MSG("Initializing Store & Forward Module in Client mode\n"); + DEBUG_MSG("*** Initializing Store & Forward Module in Client mode\n"); } } #endif diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index 32d3cddc9..84b3747b6 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -24,10 +24,9 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< uint32_t busyTo = 0; char routerMessage[Constants_DATA_PAYLOAD_LEN] = {0}; - uint32_t receivedRecord[50][2] = {{0}}; - PacketHistoryStruct *packetHistory = 0; uint32_t packetHistoryCurrent = 0; + uint32_t packetHistoryMax = 0; PacketHistoryStruct *packetHistoryTXQueue = 0; uint32_t packetHistoryTXQueue_size = 0; @@ -35,20 +34,21 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< uint32_t packetTimeMax = 5000; - unsigned long lastHeartbeat = 0; - bool is_client = false; bool is_server = false; public: StoreForwardModule(); + unsigned long lastHeartbeat = 0; + uint32_t heartbeatInterval = 300; + /** Update our local reference of when we last saw that node. @return 0 if we have never seen that node before otherwise return the last time we saw the node. */ void historyAdd(const MeshPacket &mp); - void historyReport(); + void statsSend(uint32_t to); void historySend(uint32_t msAgo, uint32_t to); uint32_t historyQueueCreate(uint32_t msAgo, uint32_t to); @@ -57,12 +57,21 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< * Send our payload into the mesh */ void sendPayload(NodeNum dest = NODENUM_BROADCAST, uint32_t packetHistory_index = 0); - void sendMessage(NodeNum dest, char *str); + void sendMessage(NodeNum dest, StoreAndForward payload); virtual MeshPacket *allocReply() override; /* - Override the wantPortnum method. - */ - virtual bool wantPortnum(PortNum p) { return true; }; + -Override the wantPacket method. + */ + virtual bool wantPacket(const MeshPacket *p) override + { + switch(p->decoded.portnum) { + case PortNum_TEXT_MESSAGE_APP: + case PortNum_STORE_FORWARD_APP: + return true; + default: + return false; + } + } private: void populatePSRAM(); @@ -73,6 +82,12 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< uint32_t records = 0; // Calculated bool heartbeat = false; // No heartbeat. + // stats + uint32_t requests = 0; + uint32_t requests_history = 0; + + uint32_t retry_delay = 0; + protected: virtual int32_t runOnce() override; From eae347ddac0e1796627e4dce6c5a97c20840bf10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 13:00:15 +0100 Subject: [PATCH 051/119] visual indicator for S&F Plugin 'Router on Network'. --- src/graphics/Screen.cpp | 89 ++++++++++++++++++++++------------------- src/graphics/images.h | 14 ++++++- 2 files changed, 61 insertions(+), 42 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 3ea4463ea..30fc396a9 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -35,6 +35,7 @@ along with this program. If not, see . #include "mesh/Channels.h" #include "mesh/generated/deviceonly.pb.h" #include "modules/TextMessageModule.h" +#include "modules/esp32/StoreForwardModule.h" #include "sleep.h" #include "target_specific.h" #include "utils.h" @@ -95,17 +96,17 @@ static uint16_t displayWidth, displayHeight; #if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) // The screen is bigger so use bigger fonts -#define FONT_SMALL ArialMT_Plain_16 -#define FONT_MEDIUM ArialMT_Plain_24 -#define FONT_LARGE ArialMT_Plain_24 +#define FONT_SMALL ArialMT_Plain_16 // Height: 19 +#define FONT_MEDIUM ArialMT_Plain_24 // Height: 28 +#define FONT_LARGE ArialMT_Plain_24 // Height: 28 #else #ifdef OLED_RU #define FONT_SMALL ArialMT_Plain_10_RU #else -#define FONT_SMALL ArialMT_Plain_10 +#define FONT_SMALL ArialMT_Plain_10 // Height: 13 #endif -#define FONT_MEDIUM ArialMT_Plain_16 -#define FONT_LARGE ArialMT_Plain_24 +#define FONT_MEDIUM ArialMT_Plain_16 // Height: 19 +#define FONT_LARGE ArialMT_Plain_24 // Height: 28 #endif #define fontHeight(font) ((font)[1] + 1) // height is position 1 @@ -465,7 +466,11 @@ static void drawNodes(OLEDDisplay *display, int16_t x, int16_t y, NodeStatus *no { char usersString[20]; sprintf(usersString, "%d/%d", nodeStatus->getNumOnline(), nodeStatus->getNumTotal()); +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) + display->drawFastImage(x, y + 3, 8, 8, imgUser); +#else display->drawFastImage(x, y, 8, 8, imgUser); +#endif display->drawString(x + 10, y - 2, usersString); display->drawString(x + 11, y - 2, usersString); } @@ -513,19 +518,20 @@ static void drawGPS(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus } //Draw status when gps is disabled by PMU -static void drawGPSpowerstat(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps){ -String displayLine = ""; -displayLine = "GPS disabled"; -int16_t xPos = display->getStringWidth(displayLine); - #ifdef HAS_PMU +static void drawGPSpowerstat(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps) +{ +#ifdef HAS_PMU + String displayLine = "GPS disabled"; + int16_t xPos = display->getStringWidth(displayLine); + if (!config.position.gps_enabled){ - display->drawString(x + xPos, y, displayLine); - #ifdef GPS_POWER_TOGGLE - display->drawString(x + xPos, y - 2 + FONT_HEIGHT_SMALL, " by button"); - #endif + display->drawString(x + xPos, y, displayLine); +#ifdef GPS_POWER_TOGGLE + display->drawString(x + xPos, y - 2 + FONT_HEIGHT_SMALL, " by button"); +#endif //display->drawString(x + xPos, y + 2, displayLine); } - #endif +#endif } static void drawGPSAltitude(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps) @@ -860,29 +866,6 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ drawColumns(display, x, y, fields); } -#if 0 -void _screen_header() -{ - if (!disp) - return; - - // Message count - //snprintf(buffer, sizeof(buffer), "#%03d", ttn_get_count() % 1000); - //display->setTextAlignment(TEXT_ALIGN_LEFT); - //display->drawString(0, 2, buffer); - - // Datetime - display->setTextAlignment(TEXT_ALIGN_CENTER); - display->drawString(display->getWidth()/2, 2, gps.getTimeStr()); - - // Satellite count - display->setTextAlignment(TEXT_ALIGN_RIGHT); - char buffer[10]; - display->drawString(display->getWidth() - SATELLITE_IMAGE_WIDTH - 4, 2, itoa(gps.satellites.value(), buffer, 10)); - display->drawXbm(display->getWidth() - SATELLITE_IMAGE_WIDTH, 0, SATELLITE_IMAGE_WIDTH, SATELLITE_IMAGE_HEIGHT, SATELLITE_IMAGE); -} -#endif - // #ifdef RAK4630 // Screen::Screen(uint8_t address, int sda, int scl) : OSThread("Screen"), cmdQueue(32), dispdev(address, sda, scl), // dispdev_oled(address, sda, scl), ui(&dispdev) @@ -1414,8 +1397,32 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 display->setColor(WHITE); // Draw the channel name display->drawString(x, y + FONT_HEIGHT_SMALL, channelStr); - // Draw our hardware ID to assist with bluetooth pairing - display->drawFastImage(x + SCREEN_WIDTH - (10) - display->getStringWidth(ourId), y + 2 + FONT_HEIGHT_SMALL, 8, 8, imgInfo); + // Draw our hardware ID to assist with bluetooth pairing. Either prefix with Info or S&F Logo + if (moduleConfig.store_forward.enabled) { + if (millis() - storeForwardModule->lastHeartbeat > (storeForwardModule->heartbeatInterval * 1200)) { //no heartbeat, overlap a bit +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) + display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 3 + FONT_HEIGHT_SMALL, 12, 8, imgQuestionL1); + display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 11 + FONT_HEIGHT_SMALL, 12, 8, imgQuestionL2); +#else + display->drawFastImage(x + SCREEN_WIDTH - 10 - display->getStringWidth(ourId), y + 2 + FONT_HEIGHT_SMALL, 8, 8, imgQuestion); +#endif + } else { +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) + display->drawFastImage(x + SCREEN_WIDTH - 18 - display->getStringWidth(ourId), y + 3 + FONT_HEIGHT_SMALL, 16, 8, imgSFL1); + display->drawFastImage(x + SCREEN_WIDTH - 18 - display->getStringWidth(ourId), y + 11 + FONT_HEIGHT_SMALL, 16, 8, imgSFL2); +#else + display->drawFastImage(x + SCREEN_WIDTH - 13 - display->getStringWidth(ourId), y + 2 + FONT_HEIGHT_SMALL, 11, 8, imgSF); +#endif + } + } else { +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) + display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 3 + FONT_HEIGHT_SMALL, 12, 8, imgInfoL1); + display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 11 + FONT_HEIGHT_SMALL, 12, 8, imgInfoL2); +#else + display->drawFastImage(x + SCREEN_WIDTH - 10 - display->getStringWidth(ourId), y + 2 + FONT_HEIGHT_SMALL, 8, 8, imgInfo); +#endif + } + display->drawString(x + SCREEN_WIDTH - display->getStringWidth(ourId), y + FONT_HEIGHT_SMALL, ourId); // Draw any log messages diff --git a/src/graphics/images.h b/src/graphics/images.h index 4680b9475..9bf66a3a3 100644 --- a/src/graphics/images.h +++ b/src/graphics/images.h @@ -12,6 +12,18 @@ const uint8_t imgPower[] PROGMEM = { 0x40, 0x40, 0x40, 0x58, 0x48, 0x08, const uint8_t imgUser[] PROGMEM = { 0x3C, 0x42, 0x99, 0xA5, 0xA5, 0x99, 0x42, 0x3C }; const uint8_t imgPositionEmpty[] PROGMEM = { 0x20, 0x30, 0x28, 0x24, 0x42, 0xFF }; const uint8_t imgPositionSolid[] PROGMEM = { 0x20, 0x30, 0x38, 0x3C, 0x7E, 0xFF }; -const uint8_t imgInfo[] PROGMEM = { 0xFF, 0x81, 0x81, 0xB5, 0xB5, 0x81, 0x81, 0xFF }; + +#if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) +const uint8_t imgQuestionL1[] PROGMEM = { 0xff, 0x01, 0x01, 0x32, 0x7b, 0x49, 0x49, 0x6f, 0x26, 0x01, 0x01, 0xff }; +const uint8_t imgQuestionL2[] PROGMEM = { 0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f }; +const uint8_t imgInfoL1[] PROGMEM = { 0xff, 0x01, 0x01, 0x01, 0x1e, 0x7f, 0x1e, 0x01, 0x01, 0x01, 0x01, 0xff }; +const uint8_t imgInfoL2[] PROGMEM = { 0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f }; +const uint8_t imgSFL1[] PROGMEM = { 0xb6, 0x8f, 0x19, 0x11, 0x31, 0xe3, 0xc2, 0x01, 0x01, 0xf9, 0xf9, 0x89, 0x89, 0x89, 0x09, 0xeb}; +const uint8_t imgSFL2[] PROGMEM = { 0x0e, 0x09, 0x09, 0x09, 0x09, 0x09, 0x08, 0x08, 0x00, 0x0f, 0x0f, 0x00, 0x08, 0x08, 0x08, 0x0f}; +#else +const uint8_t imgInfo[] PROGMEM = { 0xff, 0x81, 0x00, 0xfb, 0xfb, 0x00, 0x81, 0xff }; +const uint8_t imgQuestion[] PROGMEM = { 0xbf, 0x41, 0xc0, 0x8b, 0xdb, 0x70, 0xa1, 0xdf }; +const uint8_t imgSF[] PROGMEM = { 0xd2, 0xb7, 0xad, 0xbb, 0x92, 0x01, 0xfd, 0xfd, 0x15, 0x85, 0xf5}; +#endif #include "img/icon.xbm" From e40625d2ad1b6f40866a11777f56077ef901aed6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 13:10:45 +0100 Subject: [PATCH 052/119] fix protobufs --- protobufs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protobufs b/protobufs index c70bbf033..8f3972e57 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit c70bbf033aee8e0ae0c2cf5c4e1b60ad5782f56f +Subproject commit 8f3972e579b09c7f4682f49c609a88e9d0ee2097 From 6978e5799154ee4f1d4f518c7aa237a92b4947e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 13:49:26 +0100 Subject: [PATCH 053/119] fix nrf52 build --- src/PowerFSM.cpp | 7 +------ src/graphics/Screen.cpp | 4 +++- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/PowerFSM.cpp b/src/PowerFSM.cpp index 647167242..5bea8d796 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -326,10 +326,8 @@ void PowerFSM_setup() powerFSM.add_timed_transition(&stateON, &stateDARK, getConfiguredOrDefaultMs(config.display.screen_on_secs, default_screen_on_secs), NULL, "Screen-on timeout"); - // On most boards we use light-sleep to be our main state, but on NRF52 we just stay in DARK - State *lowPowerState = &stateLS; - #ifdef ARCH_ESP32 + State *lowPowerState = &stateLS; // We never enter light-sleep or NB states on NRF52 (because the CPU uses so little power normally) // See: https://github.com/meshtastic/firmware/issues/1071 @@ -340,9 +338,6 @@ void PowerFSM_setup() if (config.power.sds_secs != UINT32_MAX) powerFSM.add_timed_transition(lowPowerState, &stateSDS, getConfiguredOrDefaultMs(config.power.sds_secs), NULL, "mesh timeout"); - -#elif defined (ARCH_NRF52) - lowPowerState = &stateDARK; #endif diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 30fc396a9..394006622 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -35,7 +35,6 @@ along with this program. If not, see . #include "mesh/Channels.h" #include "mesh/generated/deviceonly.pb.h" #include "modules/TextMessageModule.h" -#include "modules/esp32/StoreForwardModule.h" #include "sleep.h" #include "target_specific.h" #include "utils.h" @@ -43,6 +42,7 @@ along with this program. If not, see . #ifdef ARCH_ESP32 #include "esp_task_wdt.h" #include "mesh/http/WiFiAPClient.h" +#include "modules/esp32/StoreForwardModule.h" #endif #ifdef OLED_RU @@ -1399,6 +1399,7 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 display->drawString(x, y + FONT_HEIGHT_SMALL, channelStr); // Draw our hardware ID to assist with bluetooth pairing. Either prefix with Info or S&F Logo if (moduleConfig.store_forward.enabled) { +#ifdef ARCH_ESP32 if (millis() - storeForwardModule->lastHeartbeat > (storeForwardModule->heartbeatInterval * 1200)) { //no heartbeat, overlap a bit #if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 3 + FONT_HEIGHT_SMALL, 12, 8, imgQuestionL1); @@ -1414,6 +1415,7 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 display->drawFastImage(x + SCREEN_WIDTH - 13 - display->getStringWidth(ourId), y + 2 + FONT_HEIGHT_SMALL, 11, 8, imgSF); #endif } +#endif } else { #if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) display->drawFastImage(x + SCREEN_WIDTH - 14 - display->getStringWidth(ourId), y + 3 + FONT_HEIGHT_SMALL, 12, 8, imgInfoL1); From 0992093f4d68656d27db654ca7952f1d5d96492d Mon Sep 17 00:00:00 2001 From: caveman99 Date: Wed, 21 Dec 2022 12:55:50 +0000 Subject: [PATCH 054/119] [create-pull-request] automated change --- protobufs | 2 +- src/mesh/generated/admin.pb.c | 2 +- src/mesh/generated/admin.pb.h | 64 ++- src/mesh/generated/apponly.pb.c | 2 +- src/mesh/generated/apponly.pb.h | 4 +- src/mesh/generated/cannedmessages.pb.c | 2 +- src/mesh/generated/cannedmessages.pb.h | 4 +- src/mesh/generated/channel.pb.c | 2 +- src/mesh/generated/channel.pb.h | 36 +- src/mesh/generated/config.pb.c | 2 +- src/mesh/generated/config.pb.h | 501 +++++++++++++----- src/mesh/generated/device_metadata.pb.c | 2 +- src/mesh/generated/device_metadata.pb.h | 4 +- src/mesh/generated/deviceonly.pb.c | 2 +- src/mesh/generated/deviceonly.pb.h | 50 +- src/mesh/generated/localonly.pb.c | 2 +- src/mesh/generated/localonly.pb.h | 6 +- src/mesh/generated/mesh.pb.c | 2 +- src/mesh/generated/mesh.pb.h | 675 ++++++++++++------------ src/mesh/generated/module_config.pb.c | 2 +- src/mesh/generated/module_config.pb.h | 366 ++++++++----- src/mesh/generated/mqtt.pb.c | 2 +- src/mesh/generated/mqtt.pb.h | 4 +- src/mesh/generated/portnums.pb.c | 2 +- src/mesh/generated/portnums.pb.h | 56 +- src/mesh/generated/remote_hardware.pb.c | 2 +- src/mesh/generated/remote_hardware.pb.h | 35 +- src/mesh/generated/storeforward.pb.h | 54 +- src/mesh/generated/telemetry.pb.c | 2 +- src/mesh/generated/telemetry.pb.h | 51 +- 30 files changed, 1178 insertions(+), 762 deletions(-) diff --git a/protobufs b/protobufs index 8f3972e57..0f2a3304e 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 8f3972e579b09c7f4682f49c609a88e9d0ee2097 +Subproject commit 0f2a3304eebd89b5950ccfab98082778de3353a0 diff --git a/src/mesh/generated/admin.pb.c b/src/mesh/generated/admin.pb.c index 43c32055f..3fdd0cb3d 100644 --- a/src/mesh/generated/admin.pb.c +++ b/src/mesh/generated/admin.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "admin.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/admin.pb.h b/src/mesh/generated/admin.pb.h index 4257405fa..cdc62c795 100644 --- a/src/mesh/generated/admin.pb.h +++ b/src/mesh/generated/admin.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_ADMIN_PB_H_INCLUDED #define PB_ADMIN_PB_H_INCLUDED @@ -15,32 +15,49 @@ #endif /* Enum definitions */ -typedef enum _AdminMessage_ConfigType { - AdminMessage_ConfigType_DEVICE_CONFIG = 0, - AdminMessage_ConfigType_POSITION_CONFIG = 1, - AdminMessage_ConfigType_POWER_CONFIG = 2, - AdminMessage_ConfigType_NETWORK_CONFIG = 3, - AdminMessage_ConfigType_DISPLAY_CONFIG = 4, - AdminMessage_ConfigType_LORA_CONFIG = 5, - AdminMessage_ConfigType_BLUETOOTH_CONFIG = 6 +/* TODO: REPLACE */ +typedef enum _AdminMessage_ConfigType { + /* TODO: REPLACE */ + AdminMessage_ConfigType_DEVICE_CONFIG = 0, + /* TODO: REPLACE */ + AdminMessage_ConfigType_POSITION_CONFIG = 1, + /* TODO: REPLACE */ + AdminMessage_ConfigType_POWER_CONFIG = 2, + /* TODO: REPLACE */ + AdminMessage_ConfigType_NETWORK_CONFIG = 3, + /* TODO: REPLACE */ + AdminMessage_ConfigType_DISPLAY_CONFIG = 4, + /* TODO: REPLACE */ + AdminMessage_ConfigType_LORA_CONFIG = 5, + /* TODO: REPLACE */ + AdminMessage_ConfigType_BLUETOOTH_CONFIG = 6 } AdminMessage_ConfigType; -typedef enum _AdminMessage_ModuleConfigType { - AdminMessage_ModuleConfigType_MQTT_CONFIG = 0, - AdminMessage_ModuleConfigType_SERIAL_CONFIG = 1, - AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG = 2, - AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG = 3, - AdminMessage_ModuleConfigType_RANGETEST_CONFIG = 4, - AdminMessage_ModuleConfigType_TELEMETRY_CONFIG = 5, - AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG = 6, - AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7 +/* TODO: REPLACE */ +typedef enum _AdminMessage_ModuleConfigType { + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_MQTT_CONFIG = 0, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_SERIAL_CONFIG = 1, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG = 2, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG = 3, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_RANGETEST_CONFIG = 4, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_TELEMETRY_CONFIG = 5, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG = 6, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7 } AdminMessage_ModuleConfigType; /* Struct definitions */ /* This message is handled by the Admin module and is responsible for all settings/channel read/write operations. This message is used to do settings operations to both remote AND local nodes. (Prior to 1.2 these operations were done via special ToRadio operations) */ -typedef struct _AdminMessage { +typedef struct _AdminMessage { pb_size_t which_payload_variant; union { /* Send the specified channel in the response to this message @@ -112,6 +129,10 @@ typedef struct _AdminMessage { } AdminMessage; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _AdminMessage_ConfigType_MIN AdminMessage_ConfigType_DEVICE_CONFIG #define _AdminMessage_ConfigType_MAX AdminMessage_ConfigType_BLUETOOTH_CONFIG @@ -121,10 +142,9 @@ typedef struct _AdminMessage { #define _AdminMessage_ModuleConfigType_MAX AdminMessage_ModuleConfigType_AUDIO_CONFIG #define _AdminMessage_ModuleConfigType_ARRAYSIZE ((AdminMessage_ModuleConfigType)(AdminMessage_ModuleConfigType_AUDIO_CONFIG+1)) +#define AdminMessage_payload_variant_get_config_request_ENUMTYPE AdminMessage_ConfigType +#define AdminMessage_payload_variant_get_module_config_request_ENUMTYPE AdminMessage_ModuleConfigType -#ifdef __cplusplus -extern "C" { -#endif /* Initializer values for message structs */ #define AdminMessage_init_default {0, {0}} diff --git a/src/mesh/generated/apponly.pb.c b/src/mesh/generated/apponly.pb.c index 092c8e0b3..ce68d47c6 100644 --- a/src/mesh/generated/apponly.pb.c +++ b/src/mesh/generated/apponly.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "apponly.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/apponly.pb.h b/src/mesh/generated/apponly.pb.h index e5e933873..e0a6d7cd5 100644 --- a/src/mesh/generated/apponly.pb.h +++ b/src/mesh/generated/apponly.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_APPONLY_PB_H_INCLUDED #define PB_APPONLY_PB_H_INCLUDED @@ -17,7 +17,7 @@ any SECONDARY channels. No DISABLED channels are included. This abstraction is used only on the the 'app side' of the world (ie python, javascript and android etc) to show a group of Channels as a (long) URL */ -typedef struct _ChannelSet { +typedef struct _ChannelSet { /* Channel list with settings */ pb_size_t settings_count; ChannelSettings settings[8]; diff --git a/src/mesh/generated/cannedmessages.pb.c b/src/mesh/generated/cannedmessages.pb.c index faea133e6..448517f13 100644 --- a/src/mesh/generated/cannedmessages.pb.c +++ b/src/mesh/generated/cannedmessages.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "cannedmessages.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/cannedmessages.pb.h b/src/mesh/generated/cannedmessages.pb.h index 274601e4c..4981fef18 100644 --- a/src/mesh/generated/cannedmessages.pb.h +++ b/src/mesh/generated/cannedmessages.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_CANNEDMESSAGES_PB_H_INCLUDED #define PB_CANNEDMESSAGES_PB_H_INCLUDED @@ -11,7 +11,7 @@ /* Struct definitions */ /* Canned message module configuration. */ -typedef struct _CannedMessageModuleConfig { +typedef struct _CannedMessageModuleConfig { /* Predefined messages for canned message module separated by '|' characters. */ char messages[201]; } CannedMessageModuleConfig; diff --git a/src/mesh/generated/channel.pb.c b/src/mesh/generated/channel.pb.c index 2df73d5b3..d8e4d8332 100644 --- a/src/mesh/generated/channel.pb.c +++ b/src/mesh/generated/channel.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "channel.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/channel.pb.h b/src/mesh/generated/channel.pb.h index cdb29c553..2dc16bce5 100644 --- a/src/mesh/generated/channel.pb.h +++ b/src/mesh/generated/channel.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_CHANNEL_PB_H_INCLUDED #define PB_CHANNEL_PB_H_INCLUDED @@ -10,10 +10,23 @@ #endif /* Enum definitions */ -typedef enum _Channel_Role { - Channel_Role_DISABLED = 0, - Channel_Role_PRIMARY = 1, - Channel_Role_SECONDARY = 2 +/* How this channel is being used (or not). + Note: this field is an enum to give us options for the future. + In particular, someday we might make a 'SCANNING' option. + SCANNING channels could have different frequencies and the radio would + occasionally check that freq to see if anything is being transmitted. + For devices that have multiple physical radios attached, we could keep multiple PRIMARY/SCANNING channels active at once to allow + cross band routing as needed. + If a device has only a single radio (the common case) only one channel can be PRIMARY at a time + (but any number of SECONDARY channels can't be sent received on that common frequency) */ +typedef enum _Channel_Role { + /* This channel is not in use right now */ + Channel_Role_DISABLED = 0, + /* This channel is used to set the frequency for the radio - all other enabled channels must be SECONDARY */ + Channel_Role_PRIMARY = 1, + /* Secondary channels are only used for encryption/decryption/authentication purposes. + Their radio settings (freq etc) are ignored, only psk is used. */ + Channel_Role_SECONDARY = 2 } Channel_Role; /* Struct definitions */ @@ -37,7 +50,7 @@ typedef PB_BYTES_ARRAY_T(32) ChannelSettings_psk_t; FIXME: Add description of multi-channel support and how primary vs secondary channels are used. FIXME: explain how apps use channels for security. explain how remote settings and remote gpio are managed as an example */ -typedef struct _ChannelSettings { +typedef struct _ChannelSettings { /* Deprecated in favor of LoraConfig.channel_num */ uint32_t channel_num; /* A simple pre-shared key for now for crypto. @@ -79,7 +92,7 @@ typedef struct _ChannelSettings { } ChannelSettings; /* A pair of a channel number, mode and the (sharable) settings for that channel */ -typedef struct _Channel { +typedef struct _Channel { /* The index of this channel in the channel table (from 0 to MAX_NUM_CHANNELS-1) (Someday - not currently implemented) An index of -1 could be used to mean "set by name", in which case the target node will find and set the channel by settings.name. */ @@ -92,15 +105,18 @@ typedef struct _Channel { } Channel; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _Channel_Role_MIN Channel_Role_DISABLED #define _Channel_Role_MAX Channel_Role_SECONDARY #define _Channel_Role_ARRAYSIZE ((Channel_Role)(Channel_Role_SECONDARY+1)) -#ifdef __cplusplus -extern "C" { -#endif +#define Channel_role_ENUMTYPE Channel_Role + /* Initializer values for message structs */ #define ChannelSettings_init_default {0, {0, {0}}, "", 0, 0, 0} diff --git a/src/mesh/generated/config.pb.c b/src/mesh/generated/config.pb.c index c5bc69552..8d1c55934 100644 --- a/src/mesh/generated/config.pb.c +++ b/src/mesh/generated/config.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/config.pb.h b/src/mesh/generated/config.pb.h index cdc89664c..95252bb4e 100644 --- a/src/mesh/generated/config.pb.h +++ b/src/mesh/generated/config.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_CONFIG_PB_H_INCLUDED #define PB_CONFIG_PB_H_INCLUDED @@ -10,169 +10,371 @@ #endif /* Enum definitions */ -typedef enum _Config_DeviceConfig_Role { - Config_DeviceConfig_Role_CLIENT = 0, - Config_DeviceConfig_Role_CLIENT_MUTE = 1, - Config_DeviceConfig_Role_ROUTER = 2, - Config_DeviceConfig_Role_ROUTER_CLIENT = 3 +/* Defines the device's role on the Mesh network */ +typedef enum _Config_DeviceConfig_Role { + /* Client device role */ + Config_DeviceConfig_Role_CLIENT = 0, + /* Client Mute device role + Same as a client except packets will not hop over this node, does not contribute to routing packets for mesh. */ + Config_DeviceConfig_Role_CLIENT_MUTE = 1, + /* Router device role. + Mesh packets will prefer to be routed over this node. This node will not be used by client apps. + The wifi/ble radios and the oled screen will be put to sleep. */ + Config_DeviceConfig_Role_ROUTER = 2, + /* Router Client device role + Mesh packets will prefer to be routed over this node. The Router Client can be used as both a Router and an app connected Client. */ + Config_DeviceConfig_Role_ROUTER_CLIENT = 3 } Config_DeviceConfig_Role; -typedef enum _Config_PositionConfig_PositionFlags { - Config_PositionConfig_PositionFlags_UNSET = 0, - Config_PositionConfig_PositionFlags_ALTITUDE = 1, - Config_PositionConfig_PositionFlags_ALTITUDE_MSL = 2, - Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION = 4, - Config_PositionConfig_PositionFlags_DOP = 8, - Config_PositionConfig_PositionFlags_HVDOP = 16, - Config_PositionConfig_PositionFlags_SATINVIEW = 32, - Config_PositionConfig_PositionFlags_SEQ_NO = 64, - Config_PositionConfig_PositionFlags_TIMESTAMP = 128, - Config_PositionConfig_PositionFlags_HEADING = 256, - Config_PositionConfig_PositionFlags_SPEED = 512 +/* Bit field of boolean configuration options, indicating which optional + fields to include when assembling POSITION messages + Longitude and latitude are always included (also time if GPS-synced) + NOTE: the more fields are included, the larger the message will be - + leading to longer airtime and a higher risk of packet loss */ +typedef enum _Config_PositionConfig_PositionFlags { + /* Required for compilation */ + Config_PositionConfig_PositionFlags_UNSET = 0, + /* Include an altitude value (if available) */ + Config_PositionConfig_PositionFlags_ALTITUDE = 1, + /* Altitude value is MSL */ + Config_PositionConfig_PositionFlags_ALTITUDE_MSL = 2, + /* Include geoidal separation */ + Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION = 4, + /* Include the DOP value ; PDOP used by default, see below */ + Config_PositionConfig_PositionFlags_DOP = 8, + /* If POS_DOP set, send separate HDOP / VDOP values instead of PDOP */ + Config_PositionConfig_PositionFlags_HVDOP = 16, + /* Include number of "satellites in view" */ + Config_PositionConfig_PositionFlags_SATINVIEW = 32, + /* Include a sequence number incremented per packet */ + Config_PositionConfig_PositionFlags_SEQ_NO = 64, + /* Include positional timestamp (from GPS solution) */ + Config_PositionConfig_PositionFlags_TIMESTAMP = 128, + /* Include positional heading + Intended for use with vehicle not walking speeds + walking speeds are likely to be error prone like the compass */ + Config_PositionConfig_PositionFlags_HEADING = 256, + /* Include positional speed + Intended for use with vehicle not walking speeds + walking speeds are likely to be error prone like the compass */ + Config_PositionConfig_PositionFlags_SPEED = 512 } Config_PositionConfig_PositionFlags; -typedef enum _Config_NetworkConfig_EthMode { - Config_NetworkConfig_EthMode_DHCP = 0, - Config_NetworkConfig_EthMode_STATIC = 1 +typedef enum _Config_NetworkConfig_EthMode { + /* obtain ip address via DHCP */ + Config_NetworkConfig_EthMode_DHCP = 0, + /* use static ip address */ + Config_NetworkConfig_EthMode_STATIC = 1 } Config_NetworkConfig_EthMode; -typedef enum _Config_DisplayConfig_GpsCoordinateFormat { - Config_DisplayConfig_GpsCoordinateFormat_DEC = 0, - Config_DisplayConfig_GpsCoordinateFormat_DMS = 1, - Config_DisplayConfig_GpsCoordinateFormat_UTM = 2, - Config_DisplayConfig_GpsCoordinateFormat_MGRS = 3, - Config_DisplayConfig_GpsCoordinateFormat_OLC = 4, - Config_DisplayConfig_GpsCoordinateFormat_OSGR = 5 +/* How the GPS coordinates are displayed on the OLED screen. */ +typedef enum _Config_DisplayConfig_GpsCoordinateFormat { + /* GPS coordinates are displayed in the normal decimal degrees format: + DD.DDDDDD DDD.DDDDDD */ + Config_DisplayConfig_GpsCoordinateFormat_DEC = 0, + /* GPS coordinates are displayed in the degrees minutes seconds format: + DD°MM'SS"C DDD°MM'SS"C, where C is the compass point representing the locations quadrant */ + Config_DisplayConfig_GpsCoordinateFormat_DMS = 1, + /* Universal Transverse Mercator format: + ZZB EEEEEE NNNNNNN, where Z is zone, B is band, E is easting, N is northing */ + Config_DisplayConfig_GpsCoordinateFormat_UTM = 2, + /* Military Grid Reference System format: + ZZB CD EEEEE NNNNN, where Z is zone, B is band, C is the east 100k square, D is the north 100k square, + E is easting, N is northing */ + Config_DisplayConfig_GpsCoordinateFormat_MGRS = 3, + /* Open Location Code (aka Plus Codes). */ + Config_DisplayConfig_GpsCoordinateFormat_OLC = 4, + /* Ordnance Survey Grid Reference (the National Grid System of the UK). + Format: AB EEEEE NNNNN, where A is the east 100k square, B is the north 100k square, + E is the easting, N is the northing */ + Config_DisplayConfig_GpsCoordinateFormat_OSGR = 5 } Config_DisplayConfig_GpsCoordinateFormat; -typedef enum _Config_DisplayConfig_DisplayUnits { - Config_DisplayConfig_DisplayUnits_METRIC = 0, - Config_DisplayConfig_DisplayUnits_IMPERIAL = 1 +/* Unit display preference */ +typedef enum _Config_DisplayConfig_DisplayUnits { + /* Metric (Default) */ + Config_DisplayConfig_DisplayUnits_METRIC = 0, + /* Imperial */ + Config_DisplayConfig_DisplayUnits_IMPERIAL = 1 } Config_DisplayConfig_DisplayUnits; -typedef enum _Config_DisplayConfig_OledType { - Config_DisplayConfig_OledType_OLED_AUTO = 0, - Config_DisplayConfig_OledType_OLED_SSD1306 = 1, - Config_DisplayConfig_OledType_OLED_SH1106 = 2 +/* Override OLED outo detect with this if it fails. */ +typedef enum _Config_DisplayConfig_OledType { + /* Default / Auto */ + Config_DisplayConfig_OledType_OLED_AUTO = 0, + /* Default / Auto */ + Config_DisplayConfig_OledType_OLED_SSD1306 = 1, + /* Default / Auto */ + Config_DisplayConfig_OledType_OLED_SH1106 = 2 } Config_DisplayConfig_OledType; -typedef enum _Config_LoRaConfig_RegionCode { - Config_LoRaConfig_RegionCode_UNSET = 0, - Config_LoRaConfig_RegionCode_US = 1, - Config_LoRaConfig_RegionCode_EU_433 = 2, - Config_LoRaConfig_RegionCode_EU_868 = 3, - Config_LoRaConfig_RegionCode_CN = 4, - Config_LoRaConfig_RegionCode_JP = 5, - Config_LoRaConfig_RegionCode_ANZ = 6, - Config_LoRaConfig_RegionCode_KR = 7, - Config_LoRaConfig_RegionCode_TW = 8, - Config_LoRaConfig_RegionCode_RU = 9, - Config_LoRaConfig_RegionCode_IN = 10, - Config_LoRaConfig_RegionCode_NZ_865 = 11, - Config_LoRaConfig_RegionCode_TH = 12, - Config_LoRaConfig_RegionCode_LORA_24 = 13 +typedef enum _Config_LoRaConfig_RegionCode { + /* Region is not set */ + Config_LoRaConfig_RegionCode_UNSET = 0, + /* United States */ + Config_LoRaConfig_RegionCode_US = 1, + /* European Union 433mhz */ + Config_LoRaConfig_RegionCode_EU_433 = 2, + /* European Union 433mhz */ + Config_LoRaConfig_RegionCode_EU_868 = 3, + /* China */ + Config_LoRaConfig_RegionCode_CN = 4, + /* Japan */ + Config_LoRaConfig_RegionCode_JP = 5, + /* Australia / New Zealand */ + Config_LoRaConfig_RegionCode_ANZ = 6, + /* Korea */ + Config_LoRaConfig_RegionCode_KR = 7, + /* Taiwan */ + Config_LoRaConfig_RegionCode_TW = 8, + /* Russia */ + Config_LoRaConfig_RegionCode_RU = 9, + /* India */ + Config_LoRaConfig_RegionCode_IN = 10, + /* New Zealand 865mhz */ + Config_LoRaConfig_RegionCode_NZ_865 = 11, + /* Thailand */ + Config_LoRaConfig_RegionCode_TH = 12, + /* WLAN Band */ + Config_LoRaConfig_RegionCode_LORA_24 = 13 } Config_LoRaConfig_RegionCode; -typedef enum _Config_LoRaConfig_ModemPreset { - Config_LoRaConfig_ModemPreset_LONG_FAST = 0, - Config_LoRaConfig_ModemPreset_LONG_SLOW = 1, - Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW = 2, - Config_LoRaConfig_ModemPreset_MEDIUM_SLOW = 3, - Config_LoRaConfig_ModemPreset_MEDIUM_FAST = 4, - Config_LoRaConfig_ModemPreset_SHORT_SLOW = 5, - Config_LoRaConfig_ModemPreset_SHORT_FAST = 6 +/* Standard predefined channel settings + Note: these mappings must match ModemPreset Choice in the device code. */ +typedef enum _Config_LoRaConfig_ModemPreset { + /* Long Range - Fast */ + Config_LoRaConfig_ModemPreset_LONG_FAST = 0, + /* Long Range - Slow */ + Config_LoRaConfig_ModemPreset_LONG_SLOW = 1, + /* Very Long Range - Slow */ + Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW = 2, + /* Medium Range - Slow */ + Config_LoRaConfig_ModemPreset_MEDIUM_SLOW = 3, + /* Medium Range - Fast */ + Config_LoRaConfig_ModemPreset_MEDIUM_FAST = 4, + /* Short Range - Slow */ + Config_LoRaConfig_ModemPreset_SHORT_SLOW = 5, + /* Short Range - Fast */ + Config_LoRaConfig_ModemPreset_SHORT_FAST = 6 } Config_LoRaConfig_ModemPreset; -typedef enum _Config_BluetoothConfig_PairingMode { - Config_BluetoothConfig_PairingMode_RANDOM_PIN = 0, - Config_BluetoothConfig_PairingMode_FIXED_PIN = 1, - Config_BluetoothConfig_PairingMode_NO_PIN = 2 +typedef enum _Config_BluetoothConfig_PairingMode { + /* Device generates a random pin that will be shown on the screen of the device for pairing */ + Config_BluetoothConfig_PairingMode_RANDOM_PIN = 0, + /* Device requires a specified fixed pin for pairing */ + Config_BluetoothConfig_PairingMode_FIXED_PIN = 1, + /* Device requires no pin for pairing */ + Config_BluetoothConfig_PairingMode_NO_PIN = 2 } Config_BluetoothConfig_PairingMode; /* Struct definitions */ -typedef struct _Config_BluetoothConfig { - bool enabled; - Config_BluetoothConfig_PairingMode mode; - uint32_t fixed_pin; -} Config_BluetoothConfig; - -typedef struct _Config_DeviceConfig { +/* Configuration */ +typedef struct _Config_DeviceConfig { + /* Sets the role of node */ Config_DeviceConfig_Role role; + /* Disabling this will disable the SerialConsole by not initilizing the StreamAPI */ bool serial_enabled; + /* By default we turn off logging as soon as an API client connects (to keep shared serial link quiet). + Set this to true to leave the debug log outputting even when API is active. */ bool debug_log_enabled; + /* For boards without a hard wired button, this is the pin number that will be used + Boards that have more than one button can swap the function with this one. defaults to BUTTON_PIN if defined. */ uint32_t button_gpio; + /* For boards without a PWM buzzer, this is the pin number that will be used + Defaults to PIN_BUZZER if defined. */ uint32_t buzzer_gpio; } Config_DeviceConfig; -typedef struct _Config_DisplayConfig { - uint32_t screen_on_secs; - Config_DisplayConfig_GpsCoordinateFormat gps_format; - uint32_t auto_screen_carousel_secs; - bool compass_north_top; - bool flip_screen; - Config_DisplayConfig_DisplayUnits units; - Config_DisplayConfig_OledType oled; -} Config_DisplayConfig; - -typedef struct _Config_LoRaConfig { - bool use_preset; - Config_LoRaConfig_ModemPreset modem_preset; - uint16_t bandwidth; - uint32_t spread_factor; - uint8_t coding_rate; - float frequency_offset; - Config_LoRaConfig_RegionCode region; - uint32_t hop_limit; - bool tx_enabled; - int8_t tx_power; - uint16_t channel_num; - bool override_duty_cycle; - pb_size_t ignore_incoming_count; - uint32_t ignore_incoming[3]; -} Config_LoRaConfig; - -typedef struct _Config_NetworkConfig_IpV4Config { - uint32_t ip; - uint32_t gateway; - uint32_t subnet; - uint32_t dns; -} Config_NetworkConfig_IpV4Config; - -typedef struct _Config_PositionConfig { +/* Position Config */ +typedef struct _Config_PositionConfig { + /* We should send our position this often (but only if it has changed significantly) + Defaults to 15 minutes */ uint32_t position_broadcast_secs; + /* Adaptive position braoadcast, which is now the default. */ bool position_broadcast_smart_enabled; + /* If set, this node is at a fixed position. + We will generate GPS position updates at the regular interval, but use whatever the last lat/lon/alt we have for the node. + The lat/lon/alt can be set by an internal GPS or with the help of the app. */ bool fixed_position; + /* Is GPS enabled for this node? */ bool gps_enabled; + /* How often should we try to get GPS position (in seconds) + or zero for the default of once every 30 seconds + or a very large value (maxint) to update only once at boot. */ uint32_t gps_update_interval; + /* How long should we try to get our position during each gps_update_interval attempt? (in seconds) + Or if zero, use the default of 30 seconds. + If we don't get a new gps fix in that time, the gps will be put into sleep until the next gps_update_rate + window. */ uint32_t gps_attempt_time; + /* Bit field of boolean configuration options for POSITION messages + (bitwise OR of PositionFlags) */ uint32_t position_flags; + /* (Re)define GPS_RX_PIN for your board. */ uint32_t rx_gpio; + /* (Re)define GPS_TX_PIN for your board. */ uint32_t tx_gpio; } Config_PositionConfig; -typedef struct _Config_PowerConfig { +/* Power Config\ + See [Power Config](/docs/settings/config/power) for additional power config details. */ +typedef struct _Config_PowerConfig { + /* If set, we are powered from a low-current source (i.e. solar), so even if it looks like we have power flowing in + we should try to minimize power consumption as much as possible. + YOU DO NOT NEED TO SET THIS IF YOU'VE set is_router (it is implied in that case). + Advanced Option */ bool is_power_saving; + /* If non-zero, the device will fully power off this many seconds after external power is removed. */ uint32_t on_battery_shutdown_after_secs; + /* Ratio of voltage divider for battery pin eg. 3.20 (R1=100k, R2=220k) + Overrides the ADC_MULTIPLIER defined in variant for battery voltage calculation. + Should be set to floating point value between 2 and 4 + Fixes issues on Heltec v2 */ float adc_multiplier_override; + /* Wait Bluetooth Seconds + The number of seconds for to wait before turning off BLE in No Bluetooth states + 0 for default of 1 minute */ uint32_t wait_bluetooth_secs; + /* Mesh Super Deep Sleep Timeout Seconds + While in Light Sleep if this value is exceeded we will lower into super deep sleep + for sds_secs (default 1 year) or a button press + 0 for default of two hours, MAXUINT for disabled */ uint32_t mesh_sds_timeout_secs; + /* Super Deep Sleep Seconds + While in Light Sleep if mesh_sds_timeout_secs is exceeded we will lower into super deep sleep + for this value (default 1 year) or a button press + 0 for default of one year */ uint32_t sds_secs; + /* Light Sleep Seconds + In light sleep the CPU is suspended, LoRa radio is on, BLE is off an GPS is on + ESP32 Only + 0 for default of 300 */ uint32_t ls_secs; + /* Minimum Wake Seconds + While in light sleep when we receive packets on the LoRa radio we will wake and handle them and stay awake in no BLE mode for this value + 0 for default of 10 seconds */ uint32_t min_wake_secs; } Config_PowerConfig; -typedef struct _Config_NetworkConfig { +typedef struct _Config_NetworkConfig_IpV4Config { + /* Static IP address */ + uint32_t ip; + /* Static gateway address */ + uint32_t gateway; + /* Static subnet mask */ + uint32_t subnet; + /* Static DNS server address */ + uint32_t dns; +} Config_NetworkConfig_IpV4Config; + +/* Network Config */ +typedef struct _Config_NetworkConfig { + /* Enable WiFi (disables Bluetooth) */ bool wifi_enabled; + /* If set, this node will try to join the specified wifi network and + acquire an address via DHCP */ char wifi_ssid[33]; + /* If set, will be use to authenticate to the named wifi */ char wifi_psk[64]; + /* NTP server to use if WiFi is conneced, defaults to `0.pool.ntp.org` */ char ntp_server[33]; + /* Enable Ethernet */ bool eth_enabled; + /* acquire an address via DHCP or assign static */ Config_NetworkConfig_EthMode eth_mode; + /* struct to keep static address */ bool has_ipv4_config; Config_NetworkConfig_IpV4Config ipv4_config; } Config_NetworkConfig; -typedef struct _Config { +/* Display Config */ +typedef struct _Config_DisplayConfig { + /* Number of seconds the screen stays on after pressing the user button or receiving a message + 0 for default of one minute MAXUINT for always on */ + uint32_t screen_on_secs; + /* How the GPS coordinates are formatted on the OLED screen. */ + Config_DisplayConfig_GpsCoordinateFormat gps_format; + /* Automatically toggles to the next page on the screen like a carousel, based the specified interval in seconds. + Potentially useful for devices without user buttons. */ + uint32_t auto_screen_carousel_secs; + /* If this is set, the displayed compass will always point north. if unset, the old behaviour + (top of display is heading direction) is used. */ + bool compass_north_top; + /* Flip screen vertically, for cases that mount the screen upside down */ + bool flip_screen; + /* Perferred display units */ + Config_DisplayConfig_DisplayUnits units; + /* Override auto-detect in screen */ + Config_DisplayConfig_OledType oled; +} Config_DisplayConfig; + +/* Lora Config */ +typedef struct _Config_LoRaConfig { + /* When enabled, the `modem_preset` fields will be adheared to, else the `bandwidth`/`spread_factor`/`coding_rate` + will be taked from their respective manually defined fields */ + bool use_preset; + /* Either modem_config or bandwidth/spreading/coding will be specified - NOT BOTH. + As a heuristic: If bandwidth is specified, do not use modem_config. + Because protobufs take ZERO space when the value is zero this works out nicely. + This value is replaced by bandwidth/spread_factor/coding_rate. + If you'd like to experiment with other options add them to MeshRadio.cpp in the device code. */ + Config_LoRaConfig_ModemPreset modem_preset; + /* Bandwidth in MHz + Certain bandwidth numbers are 'special' and will be converted to the + appropriate floating point value: 31 -> 31.25MHz */ + uint16_t bandwidth; + /* A number from 7 to 12. + Indicates number of chirps per symbol as 1<. Note: app developers are encouraged to also use the following standard @@ -481,8 +369,62 @@ typedef struct _User { bool is_licensed; } User; +/* A message used in our Dynamic Source Routing protocol (RFC 4728 based) */ +typedef struct _RouteDiscovery { + /* The list of nodenums this packet has visited so far */ + pb_size_t route_count; + uint32_t route[8]; +} RouteDiscovery; + +/* A Routing control Data packet handled by the routing module */ +typedef struct _Routing { + pb_size_t which_variant; + union { + /* A route request going from the requester */ + RouteDiscovery route_request; + /* A route reply */ + RouteDiscovery route_reply; + /* A failure in delivering a message (usually used for routing control messages, but might be provided + in addition to ack.fail_id to provide details on the type of failure). */ + Routing_Error error_reason; + }; +} Routing; + +typedef PB_BYTES_ARRAY_T(237) Data_payload_t; +/* (Formerly called SubPacket) + The payload portion fo a packet, this is the actual bytes that are sent + inside a radio packet (because from/to are broken out by the comms library) */ +typedef struct _Data { + /* Formerly named typ and of type Type */ + PortNum portnum; + /* TODO: REPLACE */ + Data_payload_t payload; + /* Not normally used, but for testing a sender can request that recipient + responds in kind (i.e. if it received a position, it should unicast back it's position). + Note: that if you set this on a broadcast you will receive many replies. */ + bool want_response; + /* The address of the destination node. + This field is is filled in by the mesh radio device software, application + layer software should never need it. + RouteDiscovery messages _must_ populate this. + Other message types might need to if they are doing multihop routing. */ + uint32_t dest; + /* The address of the original sender for this message. + This field should _only_ be populated for reliable multihop packets (to keep + packets small). */ + uint32_t source; + /* Only used in routing or response messages. + Indicates the original message ID that this message is reporting failure on. (formerly called original_id) */ + uint32_t request_id; + /* If set, this message is intened to be a reply to a previously sent message with the defined id. */ + uint32_t reply_id; + /* Defaults to false. If true, then what is in the payload should be treated as an emoji like giving + a message a heart or poop emoji. */ + uint32_t emoji; +} Data; + /* Waypoint message, used to share arbitrary locations across the mesh */ -typedef struct _Waypoint { +typedef struct _Waypoint { /* Id of the waypoint */ uint32_t id; /* latitude_i */ @@ -504,7 +446,7 @@ typedef PB_BYTES_ARRAY_T(256) MeshPacket_encrypted_t; /* A packet envelope sent/received over the mesh only payload_variant is sent in the payload portion of the LORA packet. The other fields are either not sent at all, or sent in the special 16 byte LORA header. */ -typedef struct _MeshPacket { +typedef struct _MeshPacket { /* The sending node number. Note: Our crypto implementation uses this field as well. See [crypto](/docs/overview/encryption) for details. @@ -588,7 +530,7 @@ typedef struct _MeshPacket { level etc) SET_CONFIG (switches device to a new set of radio params and preshared key, drops all existing nodes, force our node to rejoin this new group) Full information about a node on the mesh */ -typedef struct _NodeInfo { +typedef struct _NodeInfo { /* The node number */ uint32_t num; /* The user info for this node */ @@ -608,25 +550,80 @@ typedef struct _NodeInfo { DeviceMetrics device_metrics; } NodeInfo; -/* A Routing control Data packet handled by the routing module */ -typedef struct _Routing { - pb_size_t which_variant; - union { - /* A route request going from the requester */ - RouteDiscovery route_request; - /* A route reply */ - RouteDiscovery route_reply; - /* A failure in delivering a message (usually used for routing control messages, but might be provided - in addition to ack.fail_id to provide details on the type of failure). */ - Routing_Error error_reason; - }; -} Routing; +/* Unique local debugging info for this node + Note: we don't include position or the user info, because that will come in the + Sent to the phone in response to WantNodes. */ +typedef struct _MyNodeInfo { + /* Tells the phone what our node number is, default starting value is + lowbyte of macaddr, but it will be fixed if that is already in use */ + uint32_t my_node_num; + /* Note: This flag merely means we detected a hardware GPS in our node. + Not the same as UserPreferences.location_sharing */ + bool has_gps; + /* The maximum number of 'software' channels that can be set on this node. */ + uint32_t max_channels; + /* 0.0.5 etc... */ + char firmware_version[18]; + /* An error message we'd like to report back to the mothership through analytics. + It indicates a serious bug occurred on the device, the device coped with it, + but we still want to tell the devs about the bug. + This field will be cleared after the phone reads MyNodeInfo + (i.e. it will only be reported once) + a numeric error code to go with error message, zero means no error */ + CriticalErrorCode error_code; + /* A numeric error address (nonzero if available) */ + uint32_t error_address; + /* The total number of errors this node has ever encountered + (well - since the last time we discarded preferences) */ + uint32_t error_count; + /* The total number of reboots this node has ever encountered + (well - since the last time we discarded preferences) */ + uint32_t reboot_count; + /* Calculated bitrate of the current channel (in Bytes Per Second) */ + float bitrate; + /* How long before we consider a message abandoned and we can clear our + caches of any messages in flight Normally quite large to handle the worst case + message delivery time, 5 minutes. + Formerly called FLOOD_EXPIRE_TIME in the device code */ + uint32_t message_timeout_msec; + /* The minimum app version that can talk to this device. + Phone/PC apps should compare this to their build number and if too low tell the user they must update their app */ + uint32_t min_app_version; + /* 24 time windows of 1hr each with the airtime transmitted out of the device per hour. */ + pb_size_t air_period_tx_count; + uint32_t air_period_tx[8]; + /* 24 time windows of 1hr each with the airtime of valid packets for your mesh. */ + pb_size_t air_period_rx_count; + uint32_t air_period_rx[8]; + /* Is the device wifi capable? */ + bool has_wifi; + /* Utilization for the current channel, including well formed TX, RX and malformed RX (aka noise). */ + float channel_utilization; + /* Percent of airtime for transmission used within the last hour. */ + float air_util_tx; +} MyNodeInfo; + +/* Debug output from the device. + To minimize the size of records inside the device code, if a time/source/level is not set + on the message it is assumed to be a continuation of the previously sent message. + This allows the device code to use fixed maxlen 64 byte strings for messages, + and then extend as needed by emitting multiple records. */ +typedef struct _LogRecord { + /* Log levels, chosen to match python logging conventions. */ + char message[64]; + /* Seconds since 1970 - or 0 for unknown/unset */ + uint32_t time; + /* Usually based on thread name - if known */ + char source[8]; + /* Not yet set */ + LogRecord_Level level; +} LogRecord; /* Packets from the radio to the phone will appear on the fromRadio characteristic. It will support READ and NOTIFY. When a new packet arrives the device will BLE notify? It will sit in that descriptor until consumed by the phone, at which point the next item in the FIFO will be populated. */ -typedef struct _FromRadio { +typedef struct _FromRadio { /* The packet id, used to allow the phone to request missing read packets from the FIFO, see our bluetooth docs */ uint32_t id; @@ -663,7 +660,7 @@ typedef struct _FromRadio { /* Packets/commands to the radio will be written (reliably) to the toRadio characteristic. Once the write completes the phone can assume it is handled. */ -typedef struct _ToRadio { +typedef struct _ToRadio { pb_size_t which_payload_variant; union { /* Send this packet on the mesh */ @@ -684,6 +681,19 @@ typedef struct _ToRadio { }; } ToRadio; +typedef PB_BYTES_ARRAY_T(237) Compressed_data_t; +/* Compressed message payload */ +typedef struct _Compressed { + /* PortNum to determine the how to handle the compressed payload. */ + PortNum portnum; + /* Compressed data. */ + Compressed_data_t data; +} Compressed; + + +#ifdef __cplusplus +extern "C" { +#endif /* Helper constants for enums */ #define _HardwareModel_MIN HardwareModel_UNSET @@ -722,10 +732,29 @@ typedef struct _ToRadio { #define _LogRecord_Level_MAX LogRecord_Level_CRITICAL #define _LogRecord_Level_ARRAYSIZE ((LogRecord_Level)(LogRecord_Level_CRITICAL+1)) +#define Position_location_source_ENUMTYPE Position_LocSource +#define Position_altitude_source_ENUMTYPE Position_AltSource + +#define User_hw_model_ENUMTYPE HardwareModel + + +#define Routing_variant_error_reason_ENUMTYPE Routing_Error + +#define Data_portnum_ENUMTYPE PortNum + + +#define MeshPacket_priority_ENUMTYPE MeshPacket_Priority +#define MeshPacket_delayed_ENUMTYPE MeshPacket_Delayed + + +#define MyNodeInfo_error_code_ENUMTYPE CriticalErrorCode + +#define LogRecord_level_ENUMTYPE LogRecord_Level + + + +#define Compressed_portnum_ENUMTYPE PortNum -#ifdef __cplusplus -extern "C" { -#endif /* Initializer values for message structs */ #define Position_init_default {0, 0, 0, 0, _Position_LocSource_MIN, _Position_AltSource_MIN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} @@ -756,36 +785,6 @@ extern "C" { #define Compressed_init_zero {_PortNum_MIN, {0, {0}}} /* Field tags (for use in manual encoding/decoding) */ -#define Compressed_portnum_tag 1 -#define Compressed_data_tag 2 -#define Data_portnum_tag 1 -#define Data_payload_tag 2 -#define Data_want_response_tag 3 -#define Data_dest_tag 4 -#define Data_source_tag 5 -#define Data_request_id_tag 6 -#define Data_reply_id_tag 7 -#define Data_emoji_tag 8 -#define LogRecord_message_tag 1 -#define LogRecord_time_tag 2 -#define LogRecord_source_tag 3 -#define LogRecord_level_tag 4 -#define MyNodeInfo_my_node_num_tag 1 -#define MyNodeInfo_has_gps_tag 2 -#define MyNodeInfo_max_channels_tag 3 -#define MyNodeInfo_firmware_version_tag 4 -#define MyNodeInfo_error_code_tag 5 -#define MyNodeInfo_error_address_tag 6 -#define MyNodeInfo_error_count_tag 7 -#define MyNodeInfo_reboot_count_tag 8 -#define MyNodeInfo_bitrate_tag 9 -#define MyNodeInfo_message_timeout_msec_tag 10 -#define MyNodeInfo_min_app_version_tag 11 -#define MyNodeInfo_air_period_tx_tag 12 -#define MyNodeInfo_air_period_rx_tag 13 -#define MyNodeInfo_has_wifi_tag 14 -#define MyNodeInfo_channel_utilization_tag 15 -#define MyNodeInfo_air_util_tx_tag 16 #define Position_latitude_i_tag 1 #define Position_longitude_i_tag 2 #define Position_altitude_tag 3 @@ -808,13 +807,24 @@ extern "C" { #define Position_sensor_id_tag 20 #define Position_next_update_tag 21 #define Position_seq_number_tag 22 -#define RouteDiscovery_route_tag 1 #define User_id_tag 1 #define User_long_name_tag 2 #define User_short_name_tag 3 #define User_macaddr_tag 4 #define User_hw_model_tag 5 #define User_is_licensed_tag 6 +#define RouteDiscovery_route_tag 1 +#define Routing_route_request_tag 1 +#define Routing_route_reply_tag 2 +#define Routing_error_reason_tag 3 +#define Data_portnum_tag 1 +#define Data_payload_tag 2 +#define Data_want_response_tag 3 +#define Data_dest_tag 4 +#define Data_source_tag 5 +#define Data_request_id_tag 6 +#define Data_reply_id_tag 7 +#define Data_emoji_tag 8 #define Waypoint_id_tag 1 #define Waypoint_latitude_i_tag 2 #define Waypoint_longitude_i_tag 3 @@ -841,9 +851,26 @@ extern "C" { #define NodeInfo_snr_tag 4 #define NodeInfo_last_heard_tag 5 #define NodeInfo_device_metrics_tag 6 -#define Routing_route_request_tag 1 -#define Routing_route_reply_tag 2 -#define Routing_error_reason_tag 3 +#define MyNodeInfo_my_node_num_tag 1 +#define MyNodeInfo_has_gps_tag 2 +#define MyNodeInfo_max_channels_tag 3 +#define MyNodeInfo_firmware_version_tag 4 +#define MyNodeInfo_error_code_tag 5 +#define MyNodeInfo_error_address_tag 6 +#define MyNodeInfo_error_count_tag 7 +#define MyNodeInfo_reboot_count_tag 8 +#define MyNodeInfo_bitrate_tag 9 +#define MyNodeInfo_message_timeout_msec_tag 10 +#define MyNodeInfo_min_app_version_tag 11 +#define MyNodeInfo_air_period_tx_tag 12 +#define MyNodeInfo_air_period_rx_tag 13 +#define MyNodeInfo_has_wifi_tag 14 +#define MyNodeInfo_channel_utilization_tag 15 +#define MyNodeInfo_air_util_tx_tag 16 +#define LogRecord_message_tag 1 +#define LogRecord_time_tag 2 +#define LogRecord_source_tag 3 +#define LogRecord_level_tag 4 #define FromRadio_id_tag 1 #define FromRadio_packet_tag 2 #define FromRadio_my_info_tag 3 @@ -857,6 +884,8 @@ extern "C" { #define ToRadio_packet_tag 1 #define ToRadio_want_config_id_tag 3 #define ToRadio_disconnect_tag 4 +#define Compressed_portnum_tag 1 +#define Compressed_data_tag 2 /* Struct field encoding specification for nanopb */ #define Position_FIELDLIST(X, a) \ diff --git a/src/mesh/generated/module_config.pb.c b/src/mesh/generated/module_config.pb.c index 381ce6351..7d7de956e 100644 --- a/src/mesh/generated/module_config.pb.c +++ b/src/mesh/generated/module_config.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "module_config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 47f410a5c..6d677fd41 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_MODULE_CONFIG_PB_H_INCLUDED #define PB_MODULE_CONFIG_PB_H_INCLUDED @@ -10,141 +10,244 @@ #endif /* Enum definitions */ -typedef enum _ModuleConfig_AudioConfig_Audio_Baud { - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT = 0, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_3200 = 1, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_2400 = 2, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1600 = 3, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1400 = 4, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1300 = 5, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1200 = 6, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 = 7, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B = 8 +/* Baudrate for codec2 voice */ +typedef enum _ModuleConfig_AudioConfig_Audio_Baud { + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT = 0, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_3200 = 1, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_2400 = 2, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1600 = 3, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1400 = 4, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1300 = 5, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1200 = 6, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 = 7, + ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B = 8 } ModuleConfig_AudioConfig_Audio_Baud; -typedef enum _ModuleConfig_SerialConfig_Serial_Baud { - ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT = 0, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_110 = 1, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_300 = 2, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_600 = 3, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200 = 4, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400 = 5, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800 = 6, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600 = 7, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200 = 8, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400 = 9, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600 = 10, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200 = 11, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400 = 12, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800 = 13, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000 = 14, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 = 15 +/* TODO: REPLACE */ +typedef enum _ModuleConfig_SerialConfig_Serial_Baud { + ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT = 0, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_110 = 1, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_300 = 2, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_600 = 3, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200 = 4, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400 = 5, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800 = 6, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600 = 7, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200 = 8, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400 = 9, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600 = 10, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200 = 11, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400 = 12, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800 = 13, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000 = 14, + ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 = 15 } ModuleConfig_SerialConfig_Serial_Baud; -typedef enum _ModuleConfig_SerialConfig_Serial_Mode { - ModuleConfig_SerialConfig_Serial_Mode_DEFAULT = 0, - ModuleConfig_SerialConfig_Serial_Mode_SIMPLE = 1, - ModuleConfig_SerialConfig_Serial_Mode_PROTO = 2, - ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG = 3, - ModuleConfig_SerialConfig_Serial_Mode_NMEA = 4 +/* TODO: REPLACE */ +typedef enum _ModuleConfig_SerialConfig_Serial_Mode { + ModuleConfig_SerialConfig_Serial_Mode_DEFAULT = 0, + ModuleConfig_SerialConfig_Serial_Mode_SIMPLE = 1, + ModuleConfig_SerialConfig_Serial_Mode_PROTO = 2, + ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG = 3, + ModuleConfig_SerialConfig_Serial_Mode_NMEA = 4 } ModuleConfig_SerialConfig_Serial_Mode; -typedef enum _ModuleConfig_CannedMessageConfig_InputEventChar { - ModuleConfig_CannedMessageConfig_InputEventChar_NONE = 0, - ModuleConfig_CannedMessageConfig_InputEventChar_UP = 17, - ModuleConfig_CannedMessageConfig_InputEventChar_DOWN = 18, - ModuleConfig_CannedMessageConfig_InputEventChar_LEFT = 19, - ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT = 20, - ModuleConfig_CannedMessageConfig_InputEventChar_SELECT = 10, - ModuleConfig_CannedMessageConfig_InputEventChar_BACK = 27, - ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL = 24 +/* TODO: REPLACE */ +typedef enum _ModuleConfig_CannedMessageConfig_InputEventChar { + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_NONE = 0, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_UP = 17, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_DOWN = 18, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_LEFT = 19, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT = 20, + /* '\n' */ + ModuleConfig_CannedMessageConfig_InputEventChar_SELECT = 10, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_BACK = 27, + /* TODO: REPLACE */ + ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL = 24 } ModuleConfig_CannedMessageConfig_InputEventChar; /* Struct definitions */ -typedef struct _ModuleConfig_AudioConfig { - bool codec2_enabled; - uint8_t ptt_pin; - ModuleConfig_AudioConfig_Audio_Baud bitrate; - uint8_t i2s_ws; - uint8_t i2s_sd; - uint8_t i2s_din; - uint8_t i2s_sck; -} ModuleConfig_AudioConfig; - -typedef struct _ModuleConfig_CannedMessageConfig { - bool rotary1_enabled; - uint32_t inputbroker_pin_a; - uint32_t inputbroker_pin_b; - uint32_t inputbroker_pin_press; - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_cw; - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_ccw; - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_press; - bool updown1_enabled; - bool enabled; - char allow_input_source[16]; - bool send_bell; -} ModuleConfig_CannedMessageConfig; - -typedef struct _ModuleConfig_ExternalNotificationConfig { - bool enabled; - uint32_t output_ms; - uint32_t output; - bool active; - bool alert_message; - bool alert_bell; - bool use_pwm; - uint8_t output_vibra; - uint8_t output_buzzer; - bool alert_message_vibra; - bool alert_message_buzzer; - bool alert_bell_vibra; - bool alert_bell_buzzer; - uint16_t nag_timeout; -} ModuleConfig_ExternalNotificationConfig; - -typedef struct _ModuleConfig_MQTTConfig { +/* MQTT Client Config */ +typedef struct _ModuleConfig_MQTTConfig { + /* If a meshtastic node is able to reach the internet it will normally attempt to gateway any channels that are marked as + is_uplink_enabled or is_downlink_enabled. */ bool enabled; + /* The server to use for our MQTT global message gateway feature. + If not set, the default server will be used */ char address[32]; + /* MQTT username to use (most useful for a custom MQTT server). + If using a custom server, this will be honoured even if empty. + If using the default server, this will only be honoured if set, otherwise the device will use the default username */ char username[64]; + /* MQTT password to use (most useful for a custom MQTT server). + If using a custom server, this will be honoured even if empty. + If using the default server, this will only be honoured if set, otherwise the device will use the default password */ char password[64]; + /* Whether to send encrypted or decrypted packets to MQTT. + This parameter is only honoured if you also set server + (the default official mqtt.meshtastic.org server can handle encrypted packets) + Decrypted packets may be useful for external systems that want to consume meshtastic packets */ bool encryption_enabled; + /* Whether to send / consume json packets on MQTT */ bool json_enabled; } ModuleConfig_MQTTConfig; -typedef struct _ModuleConfig_RangeTestConfig { - bool enabled; - uint32_t sender; - bool save; -} ModuleConfig_RangeTestConfig; +/* Audio Config for codec2 voice */ +typedef struct _ModuleConfig_AudioConfig { + /* Whether Audio is enabled */ + bool codec2_enabled; + /* PTT Pin */ + uint8_t ptt_pin; + /* The audio sample rate to use for codec2 */ + ModuleConfig_AudioConfig_Audio_Baud bitrate; + /* I2S Word Select */ + uint8_t i2s_ws; + /* I2S Data IN */ + uint8_t i2s_sd; + /* I2S Data OUT */ + uint8_t i2s_din; + /* I2S Clock */ + uint8_t i2s_sck; +} ModuleConfig_AudioConfig; -typedef struct _ModuleConfig_SerialConfig { +/* Serial Config */ +typedef struct _ModuleConfig_SerialConfig { + /* Preferences for the SerialModule + FIXME - Move this out of UserPreferences and into a section for module configuration. */ bool enabled; + /* TODO: REPLACE */ bool echo; + /* TODO: REPLACE */ uint32_t rxd; + /* TODO: REPLACE */ uint32_t txd; + /* TODO: REPLACE */ ModuleConfig_SerialConfig_Serial_Baud baud; + /* TODO: REPLACE */ uint32_t timeout; + /* TODO: REPLACE */ ModuleConfig_SerialConfig_Serial_Mode mode; } ModuleConfig_SerialConfig; -typedef struct _ModuleConfig_StoreForwardConfig { +/* External Notifications Config */ +typedef struct _ModuleConfig_ExternalNotificationConfig { + /* Enable the ExternalNotificationModule */ bool enabled; + /* When using in On/Off mode, keep the output on for this many + milliseconds. Default 1000ms (1 second). */ + uint32_t output_ms; + /* Define the output pin GPIO setting Defaults to + EXT_NOTIFY_OUT if set for the board. + In standalone devices this pin should drive the LED to match the UI. */ + uint32_t output; + /* IF this is true, the 'output' Pin will be pulled active high, false + means active low. */ + bool active; + /* True: Alert when a text message arrives (output) */ + bool alert_message; + /* True: Alert when the bell character is received (output) */ + bool alert_bell; + /* use a PWM output instead of a simple on/off output. This will ignore + the 'output', 'output_ms' and 'active' settings and use the + device.buzzer_gpio instead. */ + bool use_pwm; + /* Optional: Define a secondary output pin for a vibra motor + This is used in standalone devices to match the UI. */ + uint8_t output_vibra; + /* Optional: Define a tertiary output pin for an active buzzer + This is used in standalone devices to to match the UI. */ + uint8_t output_buzzer; + /* True: Alert when a text message arrives (output_vibra) */ + bool alert_message_vibra; + /* True: Alert when a text message arrives (output_buzzer) */ + bool alert_message_buzzer; + /* True: Alert when the bell character is received (output_vibra) */ + bool alert_bell_vibra; + /* True: Alert when the bell character is received (output_buzzer) */ + bool alert_bell_buzzer; + /* The notification will toggle with 'output_ms' for this time of seconds. + Default is 0 which means don't repeat at all. 60 would mean blink + and/or beep for 60 seconds */ + uint16_t nag_timeout; +} ModuleConfig_ExternalNotificationConfig; + +/* Store and Forward Module Config */ +typedef struct _ModuleConfig_StoreForwardConfig { + /* Enable the Store and Forward Module */ + bool enabled; + /* TODO: REPLACE */ bool heartbeat; + /* TODO: REPLACE */ uint32_t records; + /* TODO: REPLACE */ uint32_t history_return_max; + /* TODO: REPLACE */ uint32_t history_return_window; } ModuleConfig_StoreForwardConfig; -typedef struct _ModuleConfig_TelemetryConfig { +/* Preferences for the RangeTestModule */ +typedef struct _ModuleConfig_RangeTestConfig { + /* Enable the Range Test Module */ + bool enabled; + /* Send out range test messages from this node */ + uint32_t sender; + /* Bool value indicating that this node should save a RangeTest.csv file. + ESP32 Only */ + bool save; +} ModuleConfig_RangeTestConfig; + +/* Configuration for both device and environment metrics */ +typedef struct _ModuleConfig_TelemetryConfig { + /* Interval in seconds of how often we should try to send our + device metrics to the mesh */ uint32_t device_update_interval; uint32_t environment_update_interval; + /* Preferences for the Telemetry Module (Environment) + Enable/Disable the telemetry measurement module measurement collection */ bool environment_measurement_enabled; + /* Enable/Disable the telemetry measurement module on-device display */ bool environment_screen_enabled; + /* We'll always read the sensor in Celsius, but sometimes we might want to + display the results in Fahrenheit as a "user preference". */ bool environment_display_fahrenheit; } ModuleConfig_TelemetryConfig; +/* TODO: REPLACE */ +typedef struct _ModuleConfig_CannedMessageConfig { + /* Enable the rotary encoder #1. This is a 'dumb' encoder sending pulses on both A and B pins while rotating. */ + bool rotary1_enabled; + /* GPIO pin for rotary encoder A port. */ + uint32_t inputbroker_pin_a; + /* GPIO pin for rotary encoder B port. */ + uint32_t inputbroker_pin_b; + /* GPIO pin for rotary encoder Press port. */ + uint32_t inputbroker_pin_press; + /* Generate input event on CW of this kind. */ + ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_cw; + /* Generate input event on CCW of this kind. */ + ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_ccw; + /* Generate input event on Press of this kind. */ + ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_press; + /* Enable the Up/Down/Select input device. Can be RAK rotary encoder or 3 buttons. Uses the a/b/press definitions from inputbroker. */ + bool updown1_enabled; + /* Enable/disable CannedMessageModule. */ + bool enabled; + /* Input event origin accepted by the canned message module. + Can be e.g. "rotEnc1", "upDownEnc1" or keyword "_any" */ + char allow_input_source[16]; + /* CannedMessageModule also sends a bell character with the messages. + ExternalNotificationModule can benefit from this feature. */ + bool send_bell; +} ModuleConfig_CannedMessageConfig; + /* Module Config */ -typedef struct _ModuleConfig { +typedef struct _ModuleConfig { pb_size_t which_payload_variant; union { /* TODO: REPLACE */ @@ -167,6 +270,10 @@ typedef struct _ModuleConfig { } ModuleConfig; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _ModuleConfig_AudioConfig_Audio_Baud_MIN ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT #define _ModuleConfig_AudioConfig_Audio_Baud_MAX ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B @@ -185,9 +292,20 @@ typedef struct _ModuleConfig { #define _ModuleConfig_CannedMessageConfig_InputEventChar_ARRAYSIZE ((ModuleConfig_CannedMessageConfig_InputEventChar)(ModuleConfig_CannedMessageConfig_InputEventChar_BACK+1)) -#ifdef __cplusplus -extern "C" { -#endif + +#define ModuleConfig_AudioConfig_bitrate_ENUMTYPE ModuleConfig_AudioConfig_Audio_Baud + +#define ModuleConfig_SerialConfig_baud_ENUMTYPE ModuleConfig_SerialConfig_Serial_Baud +#define ModuleConfig_SerialConfig_mode_ENUMTYPE ModuleConfig_SerialConfig_Serial_Mode + + + + + +#define ModuleConfig_CannedMessageConfig_inputbroker_event_cw_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar +#define ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar +#define ModuleConfig_CannedMessageConfig_inputbroker_event_press_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar + /* Initializer values for message structs */ #define ModuleConfig_init_default {0, {ModuleConfig_MQTTConfig_init_default}} @@ -210,6 +328,12 @@ extern "C" { #define ModuleConfig_CannedMessageConfig_init_zero {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} /* Field tags (for use in manual encoding/decoding) */ +#define ModuleConfig_MQTTConfig_enabled_tag 1 +#define ModuleConfig_MQTTConfig_address_tag 2 +#define ModuleConfig_MQTTConfig_username_tag 3 +#define ModuleConfig_MQTTConfig_password_tag 4 +#define ModuleConfig_MQTTConfig_encryption_enabled_tag 5 +#define ModuleConfig_MQTTConfig_json_enabled_tag 6 #define ModuleConfig_AudioConfig_codec2_enabled_tag 1 #define ModuleConfig_AudioConfig_ptt_pin_tag 2 #define ModuleConfig_AudioConfig_bitrate_tag 3 @@ -217,17 +341,13 @@ extern "C" { #define ModuleConfig_AudioConfig_i2s_sd_tag 5 #define ModuleConfig_AudioConfig_i2s_din_tag 6 #define ModuleConfig_AudioConfig_i2s_sck_tag 7 -#define ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_press_tag 4 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_cw_tag 5 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_tag 6 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_press_tag 7 -#define ModuleConfig_CannedMessageConfig_updown1_enabled_tag 8 -#define ModuleConfig_CannedMessageConfig_enabled_tag 9 -#define ModuleConfig_CannedMessageConfig_allow_input_source_tag 10 -#define ModuleConfig_CannedMessageConfig_send_bell_tag 11 +#define ModuleConfig_SerialConfig_enabled_tag 1 +#define ModuleConfig_SerialConfig_echo_tag 2 +#define ModuleConfig_SerialConfig_rxd_tag 3 +#define ModuleConfig_SerialConfig_txd_tag 4 +#define ModuleConfig_SerialConfig_baud_tag 5 +#define ModuleConfig_SerialConfig_timeout_tag 6 +#define ModuleConfig_SerialConfig_mode_tag 7 #define ModuleConfig_ExternalNotificationConfig_enabled_tag 1 #define ModuleConfig_ExternalNotificationConfig_output_ms_tag 2 #define ModuleConfig_ExternalNotificationConfig_output_tag 3 @@ -242,32 +362,30 @@ extern "C" { #define ModuleConfig_ExternalNotificationConfig_alert_bell_vibra_tag 12 #define ModuleConfig_ExternalNotificationConfig_alert_bell_buzzer_tag 13 #define ModuleConfig_ExternalNotificationConfig_nag_timeout_tag 14 -#define ModuleConfig_MQTTConfig_enabled_tag 1 -#define ModuleConfig_MQTTConfig_address_tag 2 -#define ModuleConfig_MQTTConfig_username_tag 3 -#define ModuleConfig_MQTTConfig_password_tag 4 -#define ModuleConfig_MQTTConfig_encryption_enabled_tag 5 -#define ModuleConfig_MQTTConfig_json_enabled_tag 6 -#define ModuleConfig_RangeTestConfig_enabled_tag 1 -#define ModuleConfig_RangeTestConfig_sender_tag 2 -#define ModuleConfig_RangeTestConfig_save_tag 3 -#define ModuleConfig_SerialConfig_enabled_tag 1 -#define ModuleConfig_SerialConfig_echo_tag 2 -#define ModuleConfig_SerialConfig_rxd_tag 3 -#define ModuleConfig_SerialConfig_txd_tag 4 -#define ModuleConfig_SerialConfig_baud_tag 5 -#define ModuleConfig_SerialConfig_timeout_tag 6 -#define ModuleConfig_SerialConfig_mode_tag 7 #define ModuleConfig_StoreForwardConfig_enabled_tag 1 #define ModuleConfig_StoreForwardConfig_heartbeat_tag 2 #define ModuleConfig_StoreForwardConfig_records_tag 3 #define ModuleConfig_StoreForwardConfig_history_return_max_tag 4 #define ModuleConfig_StoreForwardConfig_history_return_window_tag 5 +#define ModuleConfig_RangeTestConfig_enabled_tag 1 +#define ModuleConfig_RangeTestConfig_sender_tag 2 +#define ModuleConfig_RangeTestConfig_save_tag 3 #define ModuleConfig_TelemetryConfig_device_update_interval_tag 1 #define ModuleConfig_TelemetryConfig_environment_update_interval_tag 2 #define ModuleConfig_TelemetryConfig_environment_measurement_enabled_tag 3 #define ModuleConfig_TelemetryConfig_environment_screen_enabled_tag 4 #define ModuleConfig_TelemetryConfig_environment_display_fahrenheit_tag 5 +#define ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 +#define ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 +#define ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 +#define ModuleConfig_CannedMessageConfig_inputbroker_pin_press_tag 4 +#define ModuleConfig_CannedMessageConfig_inputbroker_event_cw_tag 5 +#define ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_tag 6 +#define ModuleConfig_CannedMessageConfig_inputbroker_event_press_tag 7 +#define ModuleConfig_CannedMessageConfig_updown1_enabled_tag 8 +#define ModuleConfig_CannedMessageConfig_enabled_tag 9 +#define ModuleConfig_CannedMessageConfig_allow_input_source_tag 10 +#define ModuleConfig_CannedMessageConfig_send_bell_tag 11 #define ModuleConfig_mqtt_tag 1 #define ModuleConfig_serial_tag 2 #define ModuleConfig_external_notification_tag 3 diff --git a/src/mesh/generated/mqtt.pb.c b/src/mesh/generated/mqtt.pb.c index 4fd6c6812..9c2a7eb63 100644 --- a/src/mesh/generated/mqtt.pb.c +++ b/src/mesh/generated/mqtt.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "mqtt.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/mqtt.pb.h b/src/mesh/generated/mqtt.pb.h index 789d38865..36de161cc 100644 --- a/src/mesh/generated/mqtt.pb.h +++ b/src/mesh/generated/mqtt.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_MQTT_PB_H_INCLUDED #define PB_MQTT_PB_H_INCLUDED @@ -12,7 +12,7 @@ /* Struct definitions */ /* This message wraps a MeshPacket with extra metadata about the sender and how it arrived. */ -typedef struct _ServiceEnvelope { +typedef struct _ServiceEnvelope { /* The (probably encrypted) packet */ struct _MeshPacket *packet; /* The global channel ID it was sent on */ diff --git a/src/mesh/generated/portnums.pb.c b/src/mesh/generated/portnums.pb.c index c8ef38c58..4e674aac5 100644 --- a/src/mesh/generated/portnums.pb.c +++ b/src/mesh/generated/portnums.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "portnums.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/portnums.pb.h b/src/mesh/generated/portnums.pb.h index 74805ed10..9e6a0b5b4 100644 --- a/src/mesh/generated/portnums.pb.h +++ b/src/mesh/generated/portnums.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_PORTNUMS_PB_H_INCLUDED #define PB_PORTNUMS_PB_H_INCLUDED @@ -22,89 +22,89 @@ Note: This was formerly a Type enum named 'typ' with the same id # We have change to this 'portnum' based scheme for specifying app handlers for particular payloads. This change is backwards compatible by treating the legacy OPAQUE/CLEAR_TEXT values identically. */ -typedef enum _PortNum { +typedef enum _PortNum { /* Deprecated: do not use in new code (formerly called OPAQUE) A message sent from a device outside of the mesh, in a form the mesh does not understand NOTE: This must be 0, because it is documented in IMeshService.aidl to be so */ - PortNum_UNKNOWN_APP = 0, + PortNum_UNKNOWN_APP = 0, /* A simple UTF-8 text message, which even the little micros in the mesh can understand and show on their screen eventually in some circumstances even signal might send messages in this form (see below) */ - PortNum_TEXT_MESSAGE_APP = 1, + PortNum_TEXT_MESSAGE_APP = 1, /* Reserved for built-in GPIO/example app. See remote_hardware.proto/HardwareMessage for details on the message sent/received to this port number */ - PortNum_REMOTE_HARDWARE_APP = 2, + PortNum_REMOTE_HARDWARE_APP = 2, /* The built-in position messaging app. Payload is a [Position](/docs/developers/protobufs/api#position) message */ - PortNum_POSITION_APP = 3, + PortNum_POSITION_APP = 3, /* The built-in user info app. Payload is a [User](/docs/developers/protobufs/api#user) message */ - PortNum_NODEINFO_APP = 4, + PortNum_NODEINFO_APP = 4, /* Protocol control packets for mesh protocol use. Payload is a [Routing](/docs/developers/protobufs/api#routing) message */ - PortNum_ROUTING_APP = 5, + PortNum_ROUTING_APP = 5, /* Admin control packets. Payload is a [AdminMessage](/docs/developers/protobufs/api#adminmessage) message */ - PortNum_ADMIN_APP = 6, + PortNum_ADMIN_APP = 6, /* Compressed TEXT_MESSAGE payloads. */ - PortNum_TEXT_MESSAGE_COMPRESSED_APP = 7, + PortNum_TEXT_MESSAGE_COMPRESSED_APP = 7, /* Waypoint payloads. Payload is a [Waypoint](/docs/developers/protobufs/api#waypoint) message */ - PortNum_WAYPOINT_APP = 8, + PortNum_WAYPOINT_APP = 8, /* Audio Payloads. Encapsulated codec2 packets. On 2.4 GHZ Bandwidths only for now */ - PortNum_AUDIO_APP = 9, + PortNum_AUDIO_APP = 9, /* Provides a 'ping' service that replies to any packet it receives. Also serves as a small example module. */ - PortNum_REPLY_APP = 32, + PortNum_REPLY_APP = 32, /* Used for the python IP tunnel feature */ - PortNum_IP_TUNNEL_APP = 33, + PortNum_IP_TUNNEL_APP = 33, /* Provides a hardware serial interface to send and receive from the Meshtastic network. Connect to the RX/TX pins of a device with 38400 8N1. Packets received from the Meshtastic network is forwarded to the RX pin while sending a packet to TX will go out to the Mesh network. Maximum packet size of 240 bytes. Module is disabled by default can be turned on by setting SERIAL_MODULE_ENABLED = 1 in SerialPlugh.cpp. */ - PortNum_SERIAL_APP = 64, + PortNum_SERIAL_APP = 64, /* STORE_FORWARD_APP (Work in Progress) Maintained by Jm Casler (MC Hamster) : jm@casler.org */ - PortNum_STORE_FORWARD_APP = 65, + PortNum_STORE_FORWARD_APP = 65, /* Optional port for messages for the range test module. */ - PortNum_RANGE_TEST_APP = 66, + PortNum_RANGE_TEST_APP = 66, /* Provides a format to send and receive telemetry data from the Meshtastic network. Maintained by Charles Crossan (crossan007) : crossan007@gmail.com */ - PortNum_TELEMETRY_APP = 67, + PortNum_TELEMETRY_APP = 67, /* Experimental tools for estimating node position without a GPS Maintained by Github user a-f-G-U-C (a Meshtastic contributor) Project files at https://github.com/a-f-G-U-C/Meshtastic-ZPS */ - PortNum_ZPS_APP = 68, + PortNum_ZPS_APP = 68, /* Used to let multiple instances of Linux native applications communicate as if they did using their LoRa chip. Maintained by GitHub user GUVWAF. Project files at https://github.com/GUVWAF/Meshtasticator */ - PortNum_SIMULATOR_APP = 69, + PortNum_SIMULATOR_APP = 69, /* Provides a traceroute functionality to show the route a packet towards a certain destination would take on the mesh. */ - PortNum_TRACEROUTE_APP = 70, + PortNum_TRACEROUTE_APP = 70, /* Private applications should use portnums >= 256. To simplify initial development and testing you can use "PRIVATE_APP" in your code without needing to rebuild protobuf files (via [regen-protos.sh](https://github.com/meshtastic/firmware/blob/master/bin/regen-protos.sh)) */ - PortNum_PRIVATE_APP = 256, + PortNum_PRIVATE_APP = 256, /* ATAK Forwarder Module https://github.com/paulmandal/atak-forwarder */ - PortNum_ATAK_FORWARDER = 257, + PortNum_ATAK_FORWARDER = 257, /* Currently we limit port nums to no higher than this value */ - PortNum_MAX = 511 + PortNum_MAX = 511 } PortNum; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _PortNum_MIN PortNum_UNKNOWN_APP #define _PortNum_MAX PortNum_MAX #define _PortNum_ARRAYSIZE ((PortNum)(PortNum_MAX+1)) -#ifdef __cplusplus -extern "C" { -#endif - #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/mesh/generated/remote_hardware.pb.c b/src/mesh/generated/remote_hardware.pb.c index 9168bd71f..de6c4dc4b 100644 --- a/src/mesh/generated/remote_hardware.pb.c +++ b/src/mesh/generated/remote_hardware.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "remote_hardware.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/remote_hardware.pb.h b/src/mesh/generated/remote_hardware.pb.h index d923c1189..6c09809c5 100644 --- a/src/mesh/generated/remote_hardware.pb.h +++ b/src/mesh/generated/remote_hardware.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_REMOTE_HARDWARE_PB_H_INCLUDED #define PB_REMOTE_HARDWARE_PB_H_INCLUDED @@ -10,13 +10,22 @@ #endif /* Enum definitions */ -typedef enum _HardwareMessage_Type { - HardwareMessage_Type_UNSET = 0, - HardwareMessage_Type_WRITE_GPIOS = 1, - HardwareMessage_Type_WATCH_GPIOS = 2, - HardwareMessage_Type_GPIOS_CHANGED = 3, - HardwareMessage_Type_READ_GPIOS = 4, - HardwareMessage_Type_READ_GPIOS_REPLY = 5 +/* TODO: REPLACE */ +typedef enum _HardwareMessage_Type { + /* Unset/unused */ + HardwareMessage_Type_UNSET = 0, + /* Set gpio gpios based on gpio_mask/gpio_value */ + HardwareMessage_Type_WRITE_GPIOS = 1, + /* We are now interested in watching the gpio_mask gpios. + If the selected gpios change, please broadcast GPIOS_CHANGED. + Will implicitly change the gpios requested to be INPUT gpios. */ + HardwareMessage_Type_WATCH_GPIOS = 2, + /* The gpios listed in gpio_mask have changed, the new values are listed in gpio_value */ + HardwareMessage_Type_GPIOS_CHANGED = 3, + /* Read the gpios specified in gpio_mask, send back a READ_GPIOS_REPLY reply with gpio_value populated */ + HardwareMessage_Type_READ_GPIOS = 4, + /* A reply to READ_GPIOS. gpio_mask and gpio_value will be populated */ + HardwareMessage_Type_READ_GPIOS_REPLY = 5 } HardwareMessage_Type; /* Struct definitions */ @@ -29,7 +38,7 @@ typedef enum _HardwareMessage_Type { because no security yet (beyond the channel mechanism). It should be off by default and then protected based on some TBD mechanism (a special channel once multichannel support is included?) */ -typedef struct _HardwareMessage { +typedef struct _HardwareMessage { /* What type of HardwareMessage is this? */ HardwareMessage_Type type; /* What gpios are we changing. Not used for all MessageTypes, see MessageType for details */ @@ -40,15 +49,17 @@ typedef struct _HardwareMessage { } HardwareMessage; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _HardwareMessage_Type_MIN HardwareMessage_Type_UNSET #define _HardwareMessage_Type_MAX HardwareMessage_Type_READ_GPIOS_REPLY #define _HardwareMessage_Type_ARRAYSIZE ((HardwareMessage_Type)(HardwareMessage_Type_READ_GPIOS_REPLY+1)) +#define HardwareMessage_type_ENUMTYPE HardwareMessage_Type -#ifdef __cplusplus -extern "C" { -#endif /* Initializer values for message structs */ #define HardwareMessage_init_default {_HardwareMessage_Type_MIN, 0, 0} diff --git a/src/mesh/generated/storeforward.pb.h b/src/mesh/generated/storeforward.pb.h index 3f21114ff..625fb273c 100644 --- a/src/mesh/generated/storeforward.pb.h +++ b/src/mesh/generated/storeforward.pb.h @@ -10,8 +10,8 @@ #endif /* Enum definitions */ -/* 001 - 063 = From Router - 064 - 127 = From Client */ +/* 1 - 99 = From Router + 101 - 199 = From Client */ typedef enum _StoreAndForward_RequestResponse { /* Unset/unused */ StoreAndForward_RequestResponse_UNSET = 0, @@ -29,16 +29,16 @@ typedef enum _StoreAndForward_RequestResponse { /* Router is responding to a request for history. */ StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, /* Client is an in error state. */ - StoreAndForward_RequestResponse_CLIENT_ERROR = 64, + StoreAndForward_RequestResponse_CLIENT_ERROR = 101, /* Client has requested a replay from the router. */ - StoreAndForward_RequestResponse_CLIENT_HISTORY = 65, + StoreAndForward_RequestResponse_CLIENT_HISTORY = 102, /* Client has requested stats from the router. */ - StoreAndForward_RequestResponse_CLIENT_STATS = 66, + StoreAndForward_RequestResponse_CLIENT_STATS = 103, /* Client has requested the router respond. This can work as a "are you there" message. */ - StoreAndForward_RequestResponse_CLIENT_PING = 67, + StoreAndForward_RequestResponse_CLIENT_PING = 104, /* The response to a "Ping" */ - StoreAndForward_RequestResponse_CLIENT_PONG = 68, + StoreAndForward_RequestResponse_CLIENT_PONG = 105, /* Client has requested that the router abort processing the client's request */ StoreAndForward_RequestResponse_CLIENT_ABORT = 106 } StoreAndForward_RequestResponse; @@ -88,17 +88,15 @@ typedef struct _StoreAndForward_Heartbeat { typedef struct _StoreAndForward { /* TODO: REPLACE */ StoreAndForward_RequestResponse rr; - pb_size_t which_variant; - union { - /* TODO: REPLACE */ - StoreAndForward_Statistics stats; - /* TODO: REPLACE */ - StoreAndForward_History history; - /* TODO: REPLACE */ - StoreAndForward_Heartbeat heartbeat; - /* Empty Payload */ - bool empty; - } variant; + /* TODO: REPLACE */ + bool has_stats; + StoreAndForward_Statistics stats; + /* TODO: REPLACE */ + bool has_history; + StoreAndForward_History history; + /* TODO: REPLACE */ + bool has_heartbeat; + StoreAndForward_Heartbeat heartbeat; } StoreAndForward; @@ -118,11 +116,11 @@ extern "C" { /* Initializer values for message structs */ -#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_default}} +#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_default, false, StoreAndForward_History_init_default, false, StoreAndForward_Heartbeat_init_default} #define StoreAndForward_Statistics_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_default {0, 0, 0} #define StoreAndForward_Heartbeat_init_default {0, 0} -#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_zero}} +#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_zero, false, StoreAndForward_History_init_zero, false, StoreAndForward_Heartbeat_init_zero} #define StoreAndForward_Statistics_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_zero {0, 0, 0} #define StoreAndForward_Heartbeat_init_zero {0, 0} @@ -146,20 +144,18 @@ extern "C" { #define StoreAndForward_stats_tag 2 #define StoreAndForward_history_tag 3 #define StoreAndForward_heartbeat_tag 4 -#define StoreAndForward_empty_tag 5 /* Struct field encoding specification for nanopb */ #define StoreAndForward_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, rr, 1) \ -X(a, STATIC, ONEOF, MESSAGE, (variant,stats,variant.stats), 2) \ -X(a, STATIC, ONEOF, MESSAGE, (variant,history,variant.history), 3) \ -X(a, STATIC, ONEOF, MESSAGE, (variant,heartbeat,variant.heartbeat), 4) \ -X(a, STATIC, ONEOF, BOOL, (variant,empty,variant.empty), 5) +X(a, STATIC, OPTIONAL, MESSAGE, stats, 2) \ +X(a, STATIC, OPTIONAL, MESSAGE, history, 3) \ +X(a, STATIC, OPTIONAL, MESSAGE, heartbeat, 4) #define StoreAndForward_CALLBACK NULL #define StoreAndForward_DEFAULT NULL -#define StoreAndForward_variant_stats_MSGTYPE StoreAndForward_Statistics -#define StoreAndForward_variant_history_MSGTYPE StoreAndForward_History -#define StoreAndForward_variant_heartbeat_MSGTYPE StoreAndForward_Heartbeat +#define StoreAndForward_stats_MSGTYPE StoreAndForward_Statistics +#define StoreAndForward_history_MSGTYPE StoreAndForward_History +#define StoreAndForward_heartbeat_MSGTYPE StoreAndForward_Heartbeat #define StoreAndForward_Statistics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, messages_total, 1) \ @@ -202,7 +198,7 @@ extern const pb_msgdesc_t StoreAndForward_Heartbeat_msg; #define StoreAndForward_Heartbeat_size 12 #define StoreAndForward_History_size 18 #define StoreAndForward_Statistics_size 50 -#define StoreAndForward_size 54 +#define StoreAndForward_size 88 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/telemetry.pb.c b/src/mesh/generated/telemetry.pb.c index a68af6e14..50202f4d6 100644 --- a/src/mesh/generated/telemetry.pb.c +++ b/src/mesh/generated/telemetry.pb.c @@ -1,5 +1,5 @@ /* Automatically generated nanopb constant definitions */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #include "telemetry.pb.h" #if PB_PROTO_HEADER_VERSION != 40 diff --git a/src/mesh/generated/telemetry.pb.h b/src/mesh/generated/telemetry.pb.h index 16e69f442..df5458a1c 100644 --- a/src/mesh/generated/telemetry.pb.h +++ b/src/mesh/generated/telemetry.pb.h @@ -1,5 +1,5 @@ /* Automatically generated nanopb header */ -/* Generated by nanopb-0.4.6 */ +/* Generated by nanopb-0.4.7 */ #ifndef PB_TELEMETRY_PB_H_INCLUDED #define PB_TELEMETRY_PB_H_INCLUDED @@ -11,36 +11,36 @@ /* Enum definitions */ /* TODO: REPLACE */ -typedef enum _TelemetrySensorType { +typedef enum _TelemetrySensorType { /* No external telemetry sensor explicitly set */ - TelemetrySensorType_SENSOR_UNSET = 0, + TelemetrySensorType_SENSOR_UNSET = 0, /* High accuracy temperature, pressure, humidity */ - TelemetrySensorType_BME280 = 1, + TelemetrySensorType_BME280 = 1, /* High accuracy temperature, pressure, humidity, and air resistance */ - TelemetrySensorType_BME680 = 2, + TelemetrySensorType_BME680 = 2, /* Very high accuracy temperature */ - TelemetrySensorType_MCP9808 = 3, + TelemetrySensorType_MCP9808 = 3, /* Moderate accuracy current and voltage */ - TelemetrySensorType_INA260 = 4, + TelemetrySensorType_INA260 = 4, /* Moderate accuracy current and voltage */ - TelemetrySensorType_INA219 = 5, + TelemetrySensorType_INA219 = 5, /* High accuracy temperature and pressure */ - TelemetrySensorType_BMP280 = 6, + TelemetrySensorType_BMP280 = 6, /* High accuracy temperature and humidity */ - TelemetrySensorType_SHTC3 = 7, + TelemetrySensorType_SHTC3 = 7, /* High accuracy pressure */ - TelemetrySensorType_LPS22 = 8, + TelemetrySensorType_LPS22 = 8, /* 3-Axis magnetic sensor */ - TelemetrySensorType_QMC6310 = 9, + TelemetrySensorType_QMC6310 = 9, /* 6-Axis inertial measurement sensor */ - TelemetrySensorType_QMI8658 = 10, + TelemetrySensorType_QMI8658 = 10, /* 3-Axis magnetic sensor */ - TelemetrySensorType_QMC5883L = 11 + TelemetrySensorType_QMC5883L = 11 } TelemetrySensorType; /* Struct definitions */ /* Key native device metrics such as battery level */ -typedef struct _DeviceMetrics { +typedef struct _DeviceMetrics { /* 1-100 (0 means powered) */ uint32_t battery_level; /* Voltage measured */ @@ -52,7 +52,7 @@ typedef struct _DeviceMetrics { } DeviceMetrics; /* Weather station or other environmental metrics */ -typedef struct _EnvironmentMetrics { +typedef struct _EnvironmentMetrics { /* Temperature measured */ float temperature; /* Relative humidity percent measured */ @@ -68,11 +68,11 @@ typedef struct _EnvironmentMetrics { } EnvironmentMetrics; /* Types of Measurements the telemetry module is equipped to handle */ -typedef struct _Telemetry { - /* This is usually not sent over the mesh (to save space), but it is sent - from the phone so that the local device can set its RTC If it is sent over - the mesh (because there are devices on the mesh without GPS), it will only - be sent by devices which has a hardware GPS clock (IE Mobile Phone). +typedef struct _Telemetry { + /* This is usually not sent over the mesh (to save space), but it is sent + from the phone so that the local device can set its RTC If it is sent over + the mesh (because there are devices on the mesh without GPS), it will only + be sent by devices which has a hardware GPS clock (IE Mobile Phone). seconds since 1970 */ uint32_t time; pb_size_t which_variant; @@ -85,15 +85,18 @@ typedef struct _Telemetry { } Telemetry; +#ifdef __cplusplus +extern "C" { +#endif + /* Helper constants for enums */ #define _TelemetrySensorType_MIN TelemetrySensorType_SENSOR_UNSET #define _TelemetrySensorType_MAX TelemetrySensorType_QMC5883L #define _TelemetrySensorType_ARRAYSIZE ((TelemetrySensorType)(TelemetrySensorType_QMC5883L+1)) -#ifdef __cplusplus -extern "C" { -#endif + + /* Initializer values for message structs */ #define DeviceMetrics_init_default {0, 0, 0, 0} From 812b3211544a8f905f8872396d4066ce283e5799 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 14:44:13 +0100 Subject: [PATCH 055/119] update protobufs --- protobufs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protobufs b/protobufs index 0f2a3304e..8f3972e57 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 0f2a3304eebd89b5950ccfab98082778de3353a0 +Subproject commit 8f3972e579b09c7f4682f49c609a88e9d0ee2097 From fb41b0f5c8e5df0b86f0672de9e9481da47ff69c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 14:45:33 +0100 Subject: [PATCH 056/119] update generated protos --- src/mesh/generated/storeforward.pb.h | 54 +++++++++++++++------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/src/mesh/generated/storeforward.pb.h b/src/mesh/generated/storeforward.pb.h index 625fb273c..3f21114ff 100644 --- a/src/mesh/generated/storeforward.pb.h +++ b/src/mesh/generated/storeforward.pb.h @@ -10,8 +10,8 @@ #endif /* Enum definitions */ -/* 1 - 99 = From Router - 101 - 199 = From Client */ +/* 001 - 063 = From Router + 064 - 127 = From Client */ typedef enum _StoreAndForward_RequestResponse { /* Unset/unused */ StoreAndForward_RequestResponse_UNSET = 0, @@ -29,16 +29,16 @@ typedef enum _StoreAndForward_RequestResponse { /* Router is responding to a request for history. */ StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, /* Client is an in error state. */ - StoreAndForward_RequestResponse_CLIENT_ERROR = 101, + StoreAndForward_RequestResponse_CLIENT_ERROR = 64, /* Client has requested a replay from the router. */ - StoreAndForward_RequestResponse_CLIENT_HISTORY = 102, + StoreAndForward_RequestResponse_CLIENT_HISTORY = 65, /* Client has requested stats from the router. */ - StoreAndForward_RequestResponse_CLIENT_STATS = 103, + StoreAndForward_RequestResponse_CLIENT_STATS = 66, /* Client has requested the router respond. This can work as a "are you there" message. */ - StoreAndForward_RequestResponse_CLIENT_PING = 104, + StoreAndForward_RequestResponse_CLIENT_PING = 67, /* The response to a "Ping" */ - StoreAndForward_RequestResponse_CLIENT_PONG = 105, + StoreAndForward_RequestResponse_CLIENT_PONG = 68, /* Client has requested that the router abort processing the client's request */ StoreAndForward_RequestResponse_CLIENT_ABORT = 106 } StoreAndForward_RequestResponse; @@ -88,15 +88,17 @@ typedef struct _StoreAndForward_Heartbeat { typedef struct _StoreAndForward { /* TODO: REPLACE */ StoreAndForward_RequestResponse rr; - /* TODO: REPLACE */ - bool has_stats; - StoreAndForward_Statistics stats; - /* TODO: REPLACE */ - bool has_history; - StoreAndForward_History history; - /* TODO: REPLACE */ - bool has_heartbeat; - StoreAndForward_Heartbeat heartbeat; + pb_size_t which_variant; + union { + /* TODO: REPLACE */ + StoreAndForward_Statistics stats; + /* TODO: REPLACE */ + StoreAndForward_History history; + /* TODO: REPLACE */ + StoreAndForward_Heartbeat heartbeat; + /* Empty Payload */ + bool empty; + } variant; } StoreAndForward; @@ -116,11 +118,11 @@ extern "C" { /* Initializer values for message structs */ -#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_default, false, StoreAndForward_History_init_default, false, StoreAndForward_Heartbeat_init_default} +#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_default}} #define StoreAndForward_Statistics_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_default {0, 0, 0} #define StoreAndForward_Heartbeat_init_default {0, 0} -#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, false, StoreAndForward_Statistics_init_zero, false, StoreAndForward_History_init_zero, false, StoreAndForward_Heartbeat_init_zero} +#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_zero}} #define StoreAndForward_Statistics_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} #define StoreAndForward_History_init_zero {0, 0, 0} #define StoreAndForward_Heartbeat_init_zero {0, 0} @@ -144,18 +146,20 @@ extern "C" { #define StoreAndForward_stats_tag 2 #define StoreAndForward_history_tag 3 #define StoreAndForward_heartbeat_tag 4 +#define StoreAndForward_empty_tag 5 /* Struct field encoding specification for nanopb */ #define StoreAndForward_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, rr, 1) \ -X(a, STATIC, OPTIONAL, MESSAGE, stats, 2) \ -X(a, STATIC, OPTIONAL, MESSAGE, history, 3) \ -X(a, STATIC, OPTIONAL, MESSAGE, heartbeat, 4) +X(a, STATIC, ONEOF, MESSAGE, (variant,stats,variant.stats), 2) \ +X(a, STATIC, ONEOF, MESSAGE, (variant,history,variant.history), 3) \ +X(a, STATIC, ONEOF, MESSAGE, (variant,heartbeat,variant.heartbeat), 4) \ +X(a, STATIC, ONEOF, BOOL, (variant,empty,variant.empty), 5) #define StoreAndForward_CALLBACK NULL #define StoreAndForward_DEFAULT NULL -#define StoreAndForward_stats_MSGTYPE StoreAndForward_Statistics -#define StoreAndForward_history_MSGTYPE StoreAndForward_History -#define StoreAndForward_heartbeat_MSGTYPE StoreAndForward_Heartbeat +#define StoreAndForward_variant_stats_MSGTYPE StoreAndForward_Statistics +#define StoreAndForward_variant_history_MSGTYPE StoreAndForward_History +#define StoreAndForward_variant_heartbeat_MSGTYPE StoreAndForward_Heartbeat #define StoreAndForward_Statistics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, messages_total, 1) \ @@ -198,7 +202,7 @@ extern const pb_msgdesc_t StoreAndForward_Heartbeat_msg; #define StoreAndForward_Heartbeat_size 12 #define StoreAndForward_History_size 18 #define StoreAndForward_Statistics_size 50 -#define StoreAndForward_size 88 +#define StoreAndForward_size 54 #ifdef __cplusplus } /* extern "C" */ From 30240ac14bdeac22ede75f4810f38448cce1251c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 15:13:16 +0100 Subject: [PATCH 057/119] fix cppcheck complaints --- protobufs | 2 +- src/mesh/generated/storeforward.pb.h | 2 ++ src/modules/esp32/StoreForwardModule.cpp | 8 +++++--- src/modules/esp32/StoreForwardModule.h | 2 +- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/protobufs b/protobufs index 8f3972e57..0985b94c2 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 8f3972e579b09c7f4682f49c609a88e9d0ee2097 +Subproject commit 0985b94c20287552daf63831fd9eda4e0ed1bd0e diff --git a/src/mesh/generated/storeforward.pb.h b/src/mesh/generated/storeforward.pb.h index 3f21114ff..0f0761949 100644 --- a/src/mesh/generated/storeforward.pb.h +++ b/src/mesh/generated/storeforward.pb.h @@ -28,6 +28,8 @@ typedef enum _StoreAndForward_RequestResponse { StoreAndForward_RequestResponse_ROUTER_BUSY = 5, /* Router is responding to a request for history. */ StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, + /* Router is responding to a request for stats. */ + StoreAndForward_RequestResponse_ROUTER_STATS = 7, /* Client is an in error state. */ StoreAndForward_RequestResponse_CLIENT_ERROR = 64, /* Client has requested a replay from the router. */ diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 54f124301..a79c390f0 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -42,8 +42,9 @@ int32_t StoreForwardModule::runOnce() } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && (airTime->channelUtilizationPercent() < polite_channel_util_percent)) { lastHeartbeat = millis(); DEBUG_MSG("*** Sending heartbeat\n"); - StoreAndForward sf; + StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; + sf.which_variant = StoreAndForward_heartbeat_tag; sf.variant.heartbeat.period = 300; sf.variant.heartbeat.secondary = 0; // TODO we always have one primary router for now storeForwardModule->sendMessage(NODENUM_BROADCAST, sf); @@ -181,7 +182,7 @@ void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) service.sendToMesh(p); } -void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward payload) +void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward &payload) { MeshPacket *p = allocDataProtobuf(payload); @@ -205,8 +206,9 @@ void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward payload) void StoreForwardModule::statsSend(uint32_t to) { - StoreAndForward sf; + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = StoreAndForward_RequestResponse_ROUTER_STATS; sf.which_variant = StoreAndForward_stats_tag; sf.variant.stats.messages_total = this->packetHistoryMax; sf.variant.stats.messages_saved = this->packetHistoryCurrent; diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index 84b3747b6..011b7cf6d 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -57,7 +57,7 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< * Send our payload into the mesh */ void sendPayload(NodeNum dest = NODENUM_BROADCAST, uint32_t packetHistory_index = 0); - void sendMessage(NodeNum dest, StoreAndForward payload); + void sendMessage(NodeNum dest, StoreAndForward &payload); virtual MeshPacket *allocReply() override; /* -Override the wantPacket method. From e0194528ddfe5f39c310320e6dafbff8066cc2e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 15:22:38 +0100 Subject: [PATCH 058/119] S&F WIP --- src/modules/esp32/StoreForwardModule.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index a79c390f0..27934ac83 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -372,6 +372,23 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; + case StoreAndForward_RequestResponse_ROUTER_STATS: + if(is_client) { + DEBUG_MSG("*** Router Response STATS\n"); + // These fields only have informational purpose on a client. Fill them to consume later. + if (p->which_variant == StoreAndForward_stats_tag) { + this->packetHistoryMax = p->variant.stats.messages_total; + this->packetHistoryCurrent = p->variant.stats.messages_saved; + this->records = p->variant.stats.messages_max; + this->requests = p->variant.stats.requests; + this->requests_history = p->variant.stats.requests_history; + this->heartbeat = p->variant.stats.heartbeat; + this->historyReturnMax = p->variant.stats.return_max; + this->historyReturnWindow = p->variant.stats.return_window; + } + } + break; + default: assert(0); // unexpected state - FIXME, make an error code and reboot } From 6f5a6d5cb4b7557374c011b92e6f3411565d44c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 17:56:34 +0100 Subject: [PATCH 059/119] consolidate code and add missing message. --- src/modules/esp32/StoreForwardModule.cpp | 50 ++++++++++++------------ 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 27934ac83..b2191d0ce 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -97,6 +97,7 @@ void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; sf.which_variant = StoreAndForward_history_tag; sf.variant.history.history_messages = queueSize; + sf.variant.history.window = msAgo; storeForwardModule->sendMessage(to, sf); } @@ -200,8 +201,14 @@ void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward &payload) p->decoded.want_response = false; service.sendToMesh(p); +} - // HardwareMessage_init_default +void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward_RequestResponse rr) +{ + // Craft an empty response, save some bytes in flash + StoreAndForward sf = StoreAndForward_init_zero; + sf.rr = rr; + storeForwardModule->sendMessage(dest, sf); } void StoreForwardModule::statsSend(uint32_t to) @@ -287,15 +294,13 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo DEBUG_MSG("*** Client Request to send HISTORY\n"); // Send the last 60 minutes of messages. if (this->busy) { - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_BUSY; - storeForwardModule->sendMessage(getFrom(&mp), sf); + storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); } else { if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)){ - storeForwardModule->historySend(p->variant.history.window * 1000 * 60, getFrom(&mp)); // window is in minutes + storeForwardModule->historySend(p->variant.history.window * 60000, getFrom(&mp)); // window is in minutes } else { - storeForwardModule->historySend(60 * 1000 * 60, getFrom(&mp)); // defaults to 60 minutes + storeForwardModule->historySend(historyReturnWindow * 60000, getFrom(&mp)); // defaults to 4 hours } } } @@ -305,9 +310,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_server) { DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); // respond with a ROUTER PONG - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_PONG; - storeForwardModule->sendMessage(getFrom(&mp), sf); + storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_PONG); } break; @@ -323,9 +326,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_server) { DEBUG_MSG("*** Client Request to send STATS\n"); if (this->busy) { - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_BUSY; - storeForwardModule->sendMessage(getFrom(&mp), sf); + storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); } else { storeForwardModule->statsSend(getFrom(&mp)); @@ -333,19 +334,12 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; + case StoreAndForward_RequestResponse_ROUTER_ERROR: case StoreAndForward_RequestResponse_ROUTER_BUSY: if(is_client) { DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); // retry in messages_saved * packetTimeMax ms - retry_delay = millis() + packetHistoryCurrent * packetTimeMax; - } - break; - - case StoreAndForward_RequestResponse_ROUTER_ERROR: - if(is_client) { - DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_ERROR\n"); - // retry in messages_saved * packetTimeMax * 2 ms - retry_delay = millis() + packetHistoryCurrent * packetTimeMax * 2; + retry_delay = millis() + packetHistoryCurrent * packetTimeMax * StoreAndForward_RequestResponse_ROUTER_ERROR? 2 : 1; } break; @@ -366,9 +360,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_client) { DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); // respond with a CLIENT PONG - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_CLIENT_PONG; - storeForwardModule->sendMessage(getFrom(&mp), sf); + storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_CLIENT_PONG); } break; @@ -389,6 +381,16 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; + case StoreAndForward_RequestResponse_ROUTER_HISTORY: + if(is_client) { + // These fields only have informational purpose on a client. Fill them to consume later. + if (p->which_variant == StoreAndForward_history_tag) { + this->historyReturnWindow = p->variant.history.window / 60000; + DEBUG_MSG("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); + } + } + break; + default: assert(0); // unexpected state - FIXME, make an error code and reboot } From 0064d18e643bb5d812fe0b3ce4029ae979a009e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 21 Dec 2022 18:39:34 +0100 Subject: [PATCH 060/119] remember to save your work before committing next time --- src/modules/esp32/StoreForwardModule.cpp | 2 +- src/modules/esp32/StoreForwardModule.h | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index b2191d0ce..54a250d2a 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -339,7 +339,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_client) { DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); // retry in messages_saved * packetTimeMax ms - retry_delay = millis() + packetHistoryCurrent * packetTimeMax * StoreAndForward_RequestResponse_ROUTER_ERROR? 2 : 1; + retry_delay = millis() + packetHistoryCurrent * packetTimeMax * (StoreAndForward_RequestResponse_ROUTER_ERROR ? 2 : 1); } break; diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index 011b7cf6d..c9cb72a5b 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -58,6 +58,8 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< */ void sendPayload(NodeNum dest = NODENUM_BROADCAST, uint32_t packetHistory_index = 0); void sendMessage(NodeNum dest, StoreAndForward &payload); + void sendMessage(NodeNum dest, StoreAndForward_RequestResponse rr); + virtual MeshPacket *allocReply() override; /* -Override the wantPacket method. From 16d826d6c7ecf6b151c8303f28ad1e39e87650d8 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Wed, 21 Dec 2022 07:41:26 -0600 Subject: [PATCH 061/119] Move to upstream espressif arduino --- variants/heltec_v3/platformio.ini | 4 ++-- variants/heltec_wsl_v3/platformio.ini | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 372f42d64..d90eec63c 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -2,8 +2,8 @@ platform = https://github.com/Baptou88/platform-espressif32.git extends = esp32s3_base board = heltec_wifi_lora_32_V3 -# Temporary: https://community.platformio.org/t/heltec-esp32-lora-v3-board-support/30406/2 +# Temporary until espressif creates a release with this new target platform_packages = - framework-arduinoespressif32@https://github.com/Baptou88/arduino-esp32.git + framework-arduinoespressif32@https://github.com/espressif/arduino-esp32.git build_flags = ${esp32s3_base.build_flags} -D HELTEC_V3 -I variants/heltec_v3 diff --git a/variants/heltec_wsl_v3/platformio.ini b/variants/heltec_wsl_v3/platformio.ini index 336e44936..76ffe0a74 100644 --- a/variants/heltec_wsl_v3/platformio.ini +++ b/variants/heltec_wsl_v3/platformio.ini @@ -2,8 +2,8 @@ platform = https://github.com/Baptou88/platform-espressif32.git extends = esp32s3_base board = heltec_wifi_lora_32_V3 -# Temporary: https://community.platformio.org/t/heltec-esp32-lora-v3-board-support/30406/2 +# Temporary until espressif creates a release with this new target platform_packages = - framework-arduinoespressif32@https://github.com/Baptou88/arduino-esp32.git + framework-arduinoespressif32@tps://github.com/espressif/arduino-esp32.git build_flags = ${esp32s3_base.build_flags} -D HELTEC_WSL_V3 -I variants/heltec_wsl_v3 From 28b954017f0774346eb5fc173db4beb2c93ce10d Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Wed, 21 Dec 2022 07:46:57 -0600 Subject: [PATCH 062/119] Copy pasta --- variants/heltec_wsl_v3/platformio.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/heltec_wsl_v3/platformio.ini b/variants/heltec_wsl_v3/platformio.ini index 76ffe0a74..ea2874e0b 100644 --- a/variants/heltec_wsl_v3/platformio.ini +++ b/variants/heltec_wsl_v3/platformio.ini @@ -4,6 +4,6 @@ extends = esp32s3_base board = heltec_wifi_lora_32_V3 # Temporary until espressif creates a release with this new target platform_packages = - framework-arduinoespressif32@tps://github.com/espressif/arduino-esp32.git + framework-arduinoespressif32@https://github.com/espressif/arduino-esp32.git build_flags = ${esp32s3_base.build_flags} -D HELTEC_WSL_V3 -I variants/heltec_wsl_v3 From cb8247559dd6f751bbda000f3d9ec8c99318d426 Mon Sep 17 00:00:00 2001 From: thebentern Date: Wed, 21 Dec 2022 18:54:52 +0000 Subject: [PATCH 063/119] [create-pull-request] automated change --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index 9964c8bdb..6a242ed9b 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 0 -build = 8 +build = 9 From e1feb5eb30f67c06661f649a403d7d4ed6696c84 Mon Sep 17 00:00:00 2001 From: Mykhailo Lesyk Date: Wed, 21 Dec 2022 22:37:30 -0800 Subject: [PATCH 064/119] [modules][serial] switch simple mode from ascii to bytes --- src/modules/SerialModule.cpp | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index d25e196a1..33bae7746 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -49,7 +49,6 @@ #define RXD2 16 #define TXD2 17 #define RX_BUFFER 128 -#define STRING_MAX Constants_DATA_PAYLOAD_LEN #define TIMEOUT 250 #define BAUD 38400 #define ACK 1 @@ -59,7 +58,8 @@ SerialModuleRadio *serialModuleRadio; SerialModule::SerialModule() : concurrency::OSThread("SerialModule") {} -char serialStringChar[Constants_DATA_PAYLOAD_LEN]; +char serialBytes[Constants_DATA_PAYLOAD_LEN]; +size_t serialPayloadSize; SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio") { @@ -188,15 +188,9 @@ int32_t SerialModule::runOnce() Serial2.printf("%s", outbuf); } } else { - String serialString; - while (Serial2.available()) { - serialString = Serial2.readString(); - serialString.toCharArray(serialStringChar, Constants_DATA_PAYLOAD_LEN); - + serialPayloadSize = Serial2.readBytes(serialBytes, Constants_DATA_PAYLOAD_LEN); serialModuleRadio->sendPayload(); - - DEBUG_MSG("Received: %s\n", serialStringChar); } } } @@ -227,8 +221,8 @@ void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) p->want_ack = ACK; - p->decoded.payload.size = strlen(serialStringChar); // You must specify how many bytes are in the reply - memcpy(p->decoded.payload.bytes, serialStringChar, p->decoded.payload.size); + p->decoded.payload.size = serialPayloadSize; // You must specify how many bytes are in the reply + memcpy(p->decoded.payload.bytes, serialBytes, p->decoded.payload.size); service.sendToMesh(p); } @@ -264,7 +258,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_DEFAULT || moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_SIMPLE) { - Serial2.printf("%s", p.payload.bytes); + Serial2.write(p.payload.bytes, p.payload.size); } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG) { NodeInfo *node = nodeDB.getNode(getFrom(&mp)); String sender = (node && node->has_user) ? node->user.short_name : "???"; From 23d6b815f5d38fdc0f23666689b14e92b999a226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 22 Dec 2022 17:25:15 +0100 Subject: [PATCH 065/119] WIP: ProtobufAPI in SerialModule --- src/modules/SerialModule.cpp | 47 +++++++++++++++++++++++++++--------- src/modules/SerialModule.h | 5 +++- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 33bae7746..94f48aa9a 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -49,17 +49,20 @@ #define RXD2 16 #define TXD2 17 #define RX_BUFFER 128 +#define STRING_MAX Constants_DATA_PAYLOAD_LEN #define TIMEOUT 250 #define BAUD 38400 #define ACK 1 +// API: Defaulting to the formerly removed phone_timeout_secs value of 15 minutes +#define SERIAL_CONNECTION_TIMEOUT (15 * 60) * 1000UL + SerialModule *serialModule; SerialModuleRadio *serialModuleRadio; -SerialModule::SerialModule() : concurrency::OSThread("SerialModule") {} +SerialModule::SerialModule() : StreamAPI(&Serial2), concurrency::OSThread("SerialModule") {} -char serialBytes[Constants_DATA_PAYLOAD_LEN]; -size_t serialPayloadSize; +char serialStringChar[Constants_DATA_PAYLOAD_LEN]; SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio") { @@ -80,6 +83,13 @@ SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio") } } +// For the serial2 port we can't really detect if any client is on the other side, so instead just look for recent messages +bool SerialModule::checkIsConnected() +{ + uint32_t now = millis(); + return (now - lastContactMsec) < SERIAL_CONNECTION_TIMEOUT; +} + int32_t SerialModule::runOnce() { #if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) @@ -178,19 +188,32 @@ int32_t SerialModule::runOnce() firstTime = 0; + // in API mode send rebooted sequence + if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + emitRebooted(); + } + } else { - // in NMEA mode send out GGA every 2 seconds, Don't read from Port - if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { + if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + return StreamAPI::runOnce(); + } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { + // in NMEA mode send out GGA every 2 seconds, Don't read from Port if (millis() - lastNmeaTime > 2000) { lastNmeaTime = millis(); printGGA(outbuf, nodeDB.getNode(myNodeInfo.my_node_num)->position); Serial2.printf("%s", outbuf); } } else { + String serialString; + while (Serial2.available()) { - serialPayloadSize = Serial2.readBytes(serialBytes, Constants_DATA_PAYLOAD_LEN); + serialString = Serial2.readString(); + serialString.toCharArray(serialStringChar, Constants_DATA_PAYLOAD_LEN); + serialModuleRadio->sendPayload(); + + DEBUG_MSG("Received: %s\n", serialStringChar); } } } @@ -221,8 +244,8 @@ void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) p->want_ack = ACK; - p->decoded.payload.size = serialPayloadSize; // You must specify how many bytes are in the reply - memcpy(p->decoded.payload.bytes, serialBytes, p->decoded.payload.size); + p->decoded.payload.size = strlen(serialStringChar); // You must specify how many bytes are in the reply + memcpy(p->decoded.payload.bytes, serialStringChar, p->decoded.payload.size); service.sendToMesh(p); } @@ -231,6 +254,10 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) { #if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) if (moduleConfig.serial.enabled) { + if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + // in API mode we don't care about stuff from radio. + return ProcessMessage::CONTINUE; + } auto &p = mp.decoded; // DEBUG_MSG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", @@ -258,15 +285,13 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_DEFAULT || moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_SIMPLE) { - Serial2.write(p.payload.bytes, p.payload.size); + Serial2.printf("%s", p.payload.bytes); } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG) { NodeInfo *node = nodeDB.getNode(getFrom(&mp)); String sender = (node && node->has_user) ? node->user.short_name : "???"; Serial2.println(); Serial2.printf("%s: %s", sender, p.payload.bytes); Serial2.println(); - } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { - // TODO this needs to be implemented } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { // Decode the Payload some more Position scratch; diff --git a/src/modules/SerialModule.h b/src/modules/SerialModule.h index 0130bbe2d..b390d545e 100644 --- a/src/modules/SerialModule.h +++ b/src/modules/SerialModule.h @@ -8,7 +8,7 @@ #include "Router.h" #include -class SerialModule : private concurrency::OSThread +class SerialModule : public StreamAPI, private concurrency::OSThread { bool firstTime = 1; unsigned long lastNmeaTime = millis(); @@ -19,6 +19,9 @@ class SerialModule : private concurrency::OSThread protected: virtual int32_t runOnce() override; + + /// Check the current underlying physical link to see if the client is currently connected + virtual bool checkIsConnected() override; }; extern SerialModule *serialModule; From 1a3f2a8ab53869fac3e95a351cbccff08695d0f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 22 Dec 2022 17:43:55 +0100 Subject: [PATCH 066/119] don't touch that code if you don't even know about "Serial2" --- src/modules/Modules.cpp | 4 ++-- src/modules/SerialModule.cpp | 11 +++-------- src/modules/SerialModule.h | 4 ++++ 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index 9978f2487..96a6c0582 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -24,7 +24,7 @@ #endif #if defined(ARCH_ESP32) || defined(ARCH_NRF52) #include "modules/ExternalNotificationModule.h" -#if !defined(TTGO_T_ECHO) +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) #include "modules/SerialModule.h" #endif #endif @@ -63,7 +63,7 @@ void setupModules() new DeviceTelemetryModule(); new EnvironmentTelemetryModule(); #endif -#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) new SerialModule(); #endif #ifdef ARCH_ESP32 diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 94f48aa9a..958faeebe 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -46,6 +46,8 @@ */ +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) + #define RXD2 16 #define TXD2 17 #define RX_BUFFER 128 @@ -92,7 +94,6 @@ bool SerialModule::checkIsConnected() int32_t SerialModule::runOnce() { -#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) /* Uncomment the preferences below if you want to use the module without having to configure it from the PythonAPI or WebUI. @@ -224,9 +225,6 @@ int32_t SerialModule::runOnce() return INT32_MAX; } -#else - return INT32_MAX; -#endif } MeshPacket *SerialModuleRadio::allocReply() @@ -252,7 +250,6 @@ void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) { -#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) if (moduleConfig.serial.enabled) { if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { // in API mode we don't care about stuff from radio. @@ -311,8 +308,6 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } else { DEBUG_MSG("Serial Module Disabled\n"); } - -#endif - return ProcessMessage::CONTINUE; // Let others look at this message also if they want } +#endif diff --git a/src/modules/SerialModule.h b/src/modules/SerialModule.h index b390d545e..c853263b6 100644 --- a/src/modules/SerialModule.h +++ b/src/modules/SerialModule.h @@ -8,6 +8,8 @@ #include "Router.h" #include +#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) + class SerialModule : public StreamAPI, private concurrency::OSThread { bool firstTime = 1; @@ -68,3 +70,5 @@ class SerialModuleRadio : public MeshModule }; extern SerialModuleRadio *serialModuleRadio; + +#endif From a2894068632238572c9a6a4ed728f16bc3bc28bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 22 Dec 2022 18:24:42 +0100 Subject: [PATCH 067/119] refactor classes to accomodate SerialModule --- src/SerialConsole.cpp | 6 +++++- src/SerialConsole.h | 4 +++- src/mesh/StreamAPI.cpp | 2 +- src/mesh/StreamAPI.h | 6 +++--- src/mesh/eth/ethServerAPI.cpp | 4 ++-- src/mesh/eth/ethServerAPI.h | 2 +- src/mesh/wifi/WiFiServerAPI.cpp | 4 ++-- src/mesh/wifi/WiFiServerAPI.h | 2 +- src/modules/SerialModule.cpp | 2 +- 9 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/SerialConsole.cpp b/src/SerialConsole.cpp index b7854b2cf..e7355db29 100644 --- a/src/SerialConsole.cpp +++ b/src/SerialConsole.cpp @@ -25,7 +25,7 @@ void consolePrintf(const char *format, ...) #endif } -SerialConsole::SerialConsole() : StreamAPI(&Port), RedirectablePrint(&Port) +SerialConsole::SerialConsole() : StreamAPI(&Port), RedirectablePrint(&Port), concurrency::OSThread("SerialConsole") { assert(!console); console = this; @@ -46,6 +46,10 @@ SerialConsole::SerialConsole() : StreamAPI(&Port), RedirectablePrint(&Port) emitRebooted(); } +int32_t SerialConsole::runOnce() +{ + return runOncePart(); +} // For the serial port we can't really detect if any client is on the other side, so instead just look for recent messages bool SerialConsole::checkIsConnected() diff --git a/src/SerialConsole.h b/src/SerialConsole.h index e7b8af34f..d1f2abac8 100644 --- a/src/SerialConsole.h +++ b/src/SerialConsole.h @@ -6,7 +6,7 @@ * Provides both debug printing and, if the client starts sending protobufs to us, switches to send/receive protobufs * (and starts dropping debug printing - FIXME, eventually those prints should be encapsulated in protobufs). */ -class SerialConsole : public StreamAPI, public RedirectablePrint +class SerialConsole : public StreamAPI, public RedirectablePrint, private concurrency::OSThread { public: SerialConsole(); @@ -24,6 +24,8 @@ class SerialConsole : public StreamAPI, public RedirectablePrint return RedirectablePrint::write(c); } + virtual int32_t runOnce() override; + protected: /// Check the current underlying physical link to see if the client is currently connected diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index 0b959ddcb..d1213ac54 100644 --- a/src/mesh/StreamAPI.cpp +++ b/src/mesh/StreamAPI.cpp @@ -6,7 +6,7 @@ #define START2 0xc3 #define HEADER_LEN 4 -int32_t StreamAPI::runOnce() +int32_t StreamAPI::runOncePart() { auto result = readStream(); writeStream(); diff --git a/src/mesh/StreamAPI.h b/src/mesh/StreamAPI.h index 0f36ecb06..3196e96f8 100644 --- a/src/mesh/StreamAPI.h +++ b/src/mesh/StreamAPI.h @@ -28,7 +28,7 @@ valid utf8 encoding. This makes it a bit easier to start a device outputting reg after it has received a valid packet from the PC, turn off unencoded debug printing and switch to this packet encoding. */ -class StreamAPI : public PhoneAPI, protected concurrency::OSThread +class StreamAPI : public PhoneAPI { /** * The stream we read/write from @@ -42,13 +42,13 @@ class StreamAPI : public PhoneAPI, protected concurrency::OSThread uint32_t lastRxMsec = 0; public: - StreamAPI(Stream *_stream) : concurrency::OSThread("StreamAPI"), stream(_stream) {} + StreamAPI(Stream *_stream) : stream(_stream) {} /** * Currently we require frequent invocation from loop() to check for arrived serial packets and to send new packets to the * phone. */ - virtual int32_t runOnce() override; + virtual int32_t runOncePart(); private: /** diff --git a/src/mesh/eth/ethServerAPI.cpp b/src/mesh/eth/ethServerAPI.cpp index bb7dd927d..3b3b6bbc8 100644 --- a/src/mesh/eth/ethServerAPI.cpp +++ b/src/mesh/eth/ethServerAPI.cpp @@ -14,7 +14,7 @@ void initApiServer(int port) } } -ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), client(_client) +ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), concurrency::OSThread("ethServerAPI"), client(_client) { DEBUG_MSG("Incoming ethernet connection\n"); } @@ -42,7 +42,7 @@ bool ethServerAPI::checkIsConnected() int32_t ethServerAPI::runOnce() { if (client.connected()) { - return StreamAPI::runOnce(); + return StreamAPI::runOncePart(); } else { DEBUG_MSG("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run diff --git a/src/mesh/eth/ethServerAPI.h b/src/mesh/eth/ethServerAPI.h index c92ab2f17..962841c80 100644 --- a/src/mesh/eth/ethServerAPI.h +++ b/src/mesh/eth/ethServerAPI.h @@ -7,7 +7,7 @@ * Provides both debug printing and, if the client starts sending protobufs to us, switches to send/receive protobufs * (and starts dropping debug printing - FIXME, eventually those prints should be encapsulated in protobufs). */ -class ethServerAPI : public StreamAPI +class ethServerAPI : public StreamAPI, private concurrency::OSThread { private: EthernetClient client; diff --git a/src/mesh/wifi/WiFiServerAPI.cpp b/src/mesh/wifi/WiFiServerAPI.cpp index 34a15f71b..78936176b 100644 --- a/src/mesh/wifi/WiFiServerAPI.cpp +++ b/src/mesh/wifi/WiFiServerAPI.cpp @@ -14,7 +14,7 @@ void initApiServer(int port) } } -WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), client(_client) +WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), concurrency::OSThread("WiFiServerAPI"), client(_client) { DEBUG_MSG("Incoming wifi connection\n"); } @@ -42,7 +42,7 @@ bool WiFiServerAPI::checkIsConnected() int32_t WiFiServerAPI::runOnce() { if (client.connected()) { - return StreamAPI::runOnce(); + return StreamAPI::runOncePart(); } else { DEBUG_MSG("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run diff --git a/src/mesh/wifi/WiFiServerAPI.h b/src/mesh/wifi/WiFiServerAPI.h index 84a23be06..812408818 100644 --- a/src/mesh/wifi/WiFiServerAPI.h +++ b/src/mesh/wifi/WiFiServerAPI.h @@ -7,7 +7,7 @@ * Provides both debug printing and, if the client starts sending protobufs to us, switches to send/receive protobufs * (and starts dropping debug printing - FIXME, eventually those prints should be encapsulated in protobufs). */ -class WiFiServerAPI : public StreamAPI +class WiFiServerAPI : public StreamAPI, private concurrency::OSThread { private: WiFiClient client; diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 958faeebe..f0374bb41 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -197,7 +197,7 @@ int32_t SerialModule::runOnce() } else { if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { - return StreamAPI::runOnce(); + return runOncePart(); } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { // in NMEA mode send out GGA every 2 seconds, Don't read from Port if (millis() - lastNmeaTime > 2000) { From 70f5f8301b48e7a9846c35f97098493e485d359a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 23 Dec 2022 09:01:59 +0100 Subject: [PATCH 068/119] added this in back by mistake --- src/modules/SerialModule.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index f0374bb41..4acf18e65 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -51,7 +51,6 @@ #define RXD2 16 #define TXD2 17 #define RX_BUFFER 128 -#define STRING_MAX Constants_DATA_PAYLOAD_LEN #define TIMEOUT 250 #define BAUD 38400 #define ACK 1 From b8657158be08bdb5e9eeeb1df7f59f8a14689643 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 23 Dec 2022 09:45:56 +0100 Subject: [PATCH 069/119] Remove unused parameter on save --- src/mesh/NodeDB.cpp | 10 +++++----- src/modules/CannedMessageModule.cpp | 7 +++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 1e40b8d92..9615c1715 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -450,7 +450,7 @@ void NodeDB::loadFromDisk() } /** Save a protobuf from a file, return true for success */ -bool saveProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, const void *dest_struct) +bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct) { bool okay = false; #ifdef FSCom @@ -498,7 +498,7 @@ void NodeDB::saveChannelsToDisk() #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(channelFileName, ChannelFile_size, sizeof(channelFile), ChannelFile_fields, &channelFile); + saveProto(channelFileName, ChannelFile_size, ChannelFile_fields, &channelFile); } } @@ -508,7 +508,7 @@ void NodeDB::saveDeviceStateToDisk() #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(prefFileName, DeviceState_size, sizeof(devicestate), DeviceState_fields, &devicestate); + saveProto(prefFileName, DeviceState_size, DeviceState_fields, &devicestate); } } @@ -530,7 +530,7 @@ void NodeDB::saveToDisk(int saveWhat) config.has_power = true; config.has_network = true; config.has_bluetooth = true; - saveProto(configFileName, LocalConfig_size, sizeof(config), LocalConfig_fields, &config); + saveProto(configFileName, LocalConfig_size, LocalConfig_fields, &config); } if (saveWhat & SEGMENT_MODULECONFIG) { @@ -541,7 +541,7 @@ void NodeDB::saveToDisk(int saveWhat) moduleConfig.has_serial = true; moduleConfig.has_store_forward = true; moduleConfig.has_telemetry = true; - saveProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(moduleConfig), LocalModuleConfig_fields, &moduleConfig); + saveProto(moduleConfigFileName, LocalModuleConfig_size, LocalModuleConfig_fields, &moduleConfig); } if (saveWhat & SEGMENT_CHANNELS) { diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index d148768ad..d549b2120 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -45,8 +45,7 @@ CannedMessageModule *cannedMessageModule; // TODO: move it into NodeDB.h! extern bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct); -extern bool saveProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, - const void *dest_struct); +extern bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct); CannedMessageModule::CannedMessageModule() : SinglePortModule("canned", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("CannedMessageModule") @@ -499,8 +498,8 @@ bool CannedMessageModule::saveProtoForModule() FS.mkdir("/prefs"); #endif - okay &= saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, sizeof(cannedMessageModuleConfig), - CannedMessageModuleConfig_fields, &cannedMessageModuleConfig); + okay &= saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, + CannedMessageModuleConfig_fields, &cannedMessageModuleConfig); return okay; } From 2ac2b6d1b669b56f7e862422af96170c6ea7b70b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 23 Dec 2022 10:00:34 +0100 Subject: [PATCH 070/119] replace PB03 compat macros with the real deal. --- src/mesh/MeshModule.cpp | 2 +- src/mesh/NodeDB.cpp | 18 ++++++++--------- src/mesh/PhoneAPI.cpp | 4 ++-- src/mesh/RadioInterface.cpp | 2 +- src/mesh/Router.cpp | 4 ++-- src/mesh/StreamAPI.cpp | 2 +- src/modules/AdminModule.cpp | 2 +- src/modules/CannedMessageModule.cpp | 4 ++-- src/modules/NodeInfoModule.cpp | 2 +- src/modules/PositionModule.cpp | 2 +- src/modules/RemoteHardwareModule.cpp | 2 +- src/modules/RoutingModule.cpp | 2 +- src/modules/SerialModule.cpp | 2 +- .../Telemetry/EnvironmentTelemetry.cpp | 2 +- src/modules/TraceRouteModule.cpp | 8 ++++---- src/mqtt/MQTT.cpp | 20 +++++++++---------- src/platform/portduino/SimRadio.cpp | 2 +- 17 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index ca1fb5b50..923b4f471 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -44,7 +44,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr // auto p = allocDataProtobuf(c); MeshPacket *p = router->allocForSending(); p->decoded.portnum = PortNum_ROUTING_APP; - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), Routing_fields, &c); + p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Routing_msg, &c); p->priority = MeshPacket_Priority_ACK; diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 9615c1715..b9107515f 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -401,7 +401,7 @@ bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_ void NodeDB::loadFromDisk() { // static DeviceState scratch; We no longer read into a tempbuf because this structure is 15KB of valuable RAM - if (!loadProto(prefFileName, DeviceState_size, sizeof(devicestate), DeviceState_fields, &devicestate)) { + if (!loadProto(prefFileName, DeviceState_size, sizeof(DeviceState), &DeviceState_msg, &devicestate)) { installDefaultDeviceState(); // Our in RAM copy might now be corrupt } else { if (devicestate.version < DEVICESTATE_MIN_VER) { @@ -412,7 +412,7 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(configFileName, LocalConfig_size, sizeof(LocalConfig), LocalConfig_fields, &config)) { + if (!loadProto(configFileName, LocalConfig_size, sizeof(LocalConfig), &LocalConfig_msg, &config)) { installDefaultConfig(); // Our in RAM copy might now be corrupt } else { if (config.version < DEVICESTATE_MIN_VER) { @@ -423,7 +423,7 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(LocalModuleConfig), LocalModuleConfig_fields, &moduleConfig)) { + if (!loadProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(LocalModuleConfig), &LocalModuleConfig_msg, &moduleConfig)) { installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { @@ -434,7 +434,7 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(channelFileName, ChannelFile_size, sizeof(ChannelFile), ChannelFile_fields, &channelFile)) { + if (!loadProto(channelFileName, ChannelFile_size, sizeof(ChannelFile), &ChannelFile_msg, &channelFile)) { installDefaultChannels(); // Our in RAM copy might now be corrupt } else { if (channelFile.version < DEVICESTATE_MIN_VER) { @@ -445,7 +445,7 @@ void NodeDB::loadFromDisk() } } - if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), OEMStore_fields, &oemStore)) + if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), &OEMStore_msg, &oemStore)) DEBUG_MSG("Loaded OEMStore\n"); } @@ -498,7 +498,7 @@ void NodeDB::saveChannelsToDisk() #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(channelFileName, ChannelFile_size, ChannelFile_fields, &channelFile); + saveProto(channelFileName, ChannelFile_size, &ChannelFile_msg, &channelFile); } } @@ -508,7 +508,7 @@ void NodeDB::saveDeviceStateToDisk() #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(prefFileName, DeviceState_size, DeviceState_fields, &devicestate); + saveProto(prefFileName, DeviceState_size, &DeviceState_msg, &devicestate); } } @@ -530,7 +530,7 @@ void NodeDB::saveToDisk(int saveWhat) config.has_power = true; config.has_network = true; config.has_bluetooth = true; - saveProto(configFileName, LocalConfig_size, LocalConfig_fields, &config); + saveProto(configFileName, LocalConfig_size, &LocalConfig_msg, &config); } if (saveWhat & SEGMENT_MODULECONFIG) { @@ -541,7 +541,7 @@ void NodeDB::saveToDisk(int saveWhat) moduleConfig.has_serial = true; moduleConfig.has_store_forward = true; moduleConfig.has_telemetry = true; - saveProto(moduleConfigFileName, LocalModuleConfig_size, LocalModuleConfig_fields, &moduleConfig); + saveProto(moduleConfigFileName, LocalModuleConfig_size, &LocalModuleConfig_msg, &moduleConfig); } if (saveWhat & SEGMENT_CHANNELS) { diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index ea08bf769..b50f93bf0 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -77,7 +77,7 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) // return (lastContactMsec != 0) && memset(&toRadioScratch, 0, sizeof(toRadioScratch)); - if (pb_decode_from_bytes(buf, bufLength, ToRadio_fields, &toRadioScratch)) { + if (pb_decode_from_bytes(buf, bufLength, &ToRadio_msg, &toRadioScratch)) { switch (toRadioScratch.which_payload_variant) { case ToRadio_packet_tag: return handleToRadioPacket(toRadioScratch.packet); @@ -291,7 +291,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Do we have a message from the mesh? if (fromRadioScratch.which_payload_variant != 0) { // Encapsulate as a FromRadio packet - size_t numbytes = pb_encode_to_bytes(buf, FromRadio_size, FromRadio_fields, &fromRadioScratch); + size_t numbytes = pb_encode_to_bytes(buf, FromRadio_size, &FromRadio_msg, &fromRadioScratch); DEBUG_MSG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes); return numbytes; diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 4a40c6600..222e5d14b 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -175,7 +175,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) { assert(slotTimeMsec); // Better be non zero static uint8_t bytes[MAX_RHPACKETLEN]; - size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), Data_fields, &p->decoded); + size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); uint32_t packetAirtime = getPacketTime(numbytes + sizeof(PacketHeader)); // Make sure enough time has elapsed for this packet to be sent and an ACK is received. // DEBUG_MSG("Waiting for flooding message with airtime %d and slotTime is %d\n", packetAirtime, slotTimeMsec); diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 5ce26f49a..66e21d21d 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -306,7 +306,7 @@ bool perhapsDecode(MeshPacket *p) // Take those raw bytes and convert them back into a well structured protobuf we can understand memset(&p->decoded, 0, sizeof(p->decoded)); - if (!pb_decode_from_bytes(bytes, rawSize, Data_fields, &p->decoded)) { + if (!pb_decode_from_bytes(bytes, rawSize, &Data_msg, &p->decoded)) { DEBUG_MSG("Invalid protobufs in received mesh packet (bad psk?)!\n"); } else if (p->decoded.portnum == PortNum_UNKNOWN_APP) { DEBUG_MSG("Invalid portnum (bad psk?)!\n"); @@ -360,7 +360,7 @@ Routing_Error perhapsEncode(MeshPacket *p) if (p->which_payload_variant == MeshPacket_decoded_tag) { static uint8_t bytes[MAX_RHPACKETLEN]; // we have to use a scratch buffer because a union - size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), Data_fields, &p->decoded); + size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); // Only allow encryption on the text message app. // TODO: Allow modules to opt into compression. diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index d1213ac54..57911cf77 100644 --- a/src/mesh/StreamAPI.cpp +++ b/src/mesh/StreamAPI.cpp @@ -115,7 +115,7 @@ void StreamAPI::emitRebooted() fromRadioScratch.rebooted = true; // DEBUG_MSG("Emitting reboot packet for serial shell\n"); - emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, FromRadio_fields, &fromRadioScratch)); + emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, &FromRadio_msg, &fromRadioScratch)); } /// Hookable to find out when connection changes diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 0b617adea..2ed050f66 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -515,7 +515,7 @@ void AdminModule::saveChanges(int saveWhat, bool shouldReboot) } } -AdminModule::AdminModule() : ProtobufModule("Admin", PortNum_ADMIN_APP, AdminMessage_fields) +AdminModule::AdminModule() : ProtobufModule("Admin", PortNum_ADMIN_APP, &AdminMessage_msg) { // restrict to the admin channel for rx boundChannel = Channels::adminChannel; diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index d549b2120..4357ee2ca 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -479,7 +479,7 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st void CannedMessageModule::loadProtoForModule() { if (!loadProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, sizeof(cannedMessagesConfigFile), - CannedMessageModuleConfig_fields, &cannedMessageModuleConfig)) { + &CannedMessageModuleConfig_msg, &cannedMessageModuleConfig)) { installDefaultCannedMessageModuleConfig(); } } @@ -499,7 +499,7 @@ bool CannedMessageModule::saveProtoForModule() #endif okay &= saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, - CannedMessageModuleConfig_fields, &cannedMessageModuleConfig); + &CannedMessageModuleConfig_msg, &cannedMessageModuleConfig); return okay; } diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index c3d58fd51..1ce1acf33 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -51,7 +51,7 @@ MeshPacket *NodeInfoModule::allocReply() } NodeInfoModule::NodeInfoModule() - : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, User_fields), concurrency::OSThread("NodeInfoModule") + : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 5159de278..013f2ee44 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -10,7 +10,7 @@ PositionModule *positionModule; PositionModule::PositionModule() - : ProtobufModule("position", PortNum_POSITION_APP, Position_fields), concurrency::OSThread("PositionModule") + : ProtobufModule("position", PortNum_POSITION_APP, &Position_msg), concurrency::OSThread("PositionModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 7a859c87a..26f1c4dba 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -47,7 +47,7 @@ static uint64_t digitalReads(uint64_t mask) } RemoteHardwareModule::RemoteHardwareModule() - : ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, HardwareMessage_fields), concurrency::OSThread( + : ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, &HardwareMessage_msg), concurrency::OSThread( "remotehardware") { } diff --git a/src/modules/RoutingModule.cpp b/src/modules/RoutingModule.cpp index 40919eef9..8c4eeb4ff 100644 --- a/src/modules/RoutingModule.cpp +++ b/src/modules/RoutingModule.cpp @@ -41,7 +41,7 @@ void RoutingModule::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, C router->sendLocal(p); // we sometimes send directly to the local node } -RoutingModule::RoutingModule() : ProtobufModule("routing", PortNum_ROUTING_APP, Routing_fields) +RoutingModule::RoutingModule() : ProtobufModule("routing", PortNum_ROUTING_APP, &Routing_msg) { isPromiscuous = true; encryptedOk = true; diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 4acf18e65..eb8f0986b 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -294,7 +294,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) Position *decoded = NULL; if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.decoded.portnum == ourPortNum) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, Position_fields, &scratch)) { + if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Position_msg, &scratch)) { decoded = &scratch; } // send position packet as WPL to the serial port diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index cd5cd03bc..b676dfd42 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -155,7 +155,7 @@ void EnvironmentTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiSt const char *lastSender = getSenderShortName(*lastMeasurementPacket); auto &p = lastMeasurementPacket->decoded; - if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, Telemetry_fields, &lastMeasurement)) { + if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Telemetry_msg, &lastMeasurement)) { display->setFont(FONT_SMALL); display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error"); DEBUG_MSG("Unable to decode last packet"); diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index 1c5fd97d3..fcb234664 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -24,14 +24,14 @@ void TraceRouteModule::updateRoute(MeshPacket* p) RouteDiscovery scratch; RouteDiscovery *updated = NULL; memset(&scratch, 0, sizeof(scratch)); - pb_decode_from_bytes(incoming.payload.bytes, incoming.payload.size, RouteDiscovery_fields, &scratch); + pb_decode_from_bytes(incoming.payload.bytes, incoming.payload.size, &RouteDiscovery_msg, &scratch); updated = &scratch; appendMyID(updated); printRoute(updated, p->from, NODENUM_BROADCAST); // Set updated route to the payload of the to be flooded packet - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), RouteDiscovery_fields, updated); + p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &RouteDiscovery_msg, updated); } } @@ -69,7 +69,7 @@ MeshPacket* TraceRouteModule::allocReply() RouteDiscovery scratch; RouteDiscovery *updated = NULL; memset(&scratch, 0, sizeof(scratch)); - pb_decode_from_bytes(p.payload.bytes, p.payload.size, RouteDiscovery_fields, &scratch); + pb_decode_from_bytes(p.payload.bytes, p.payload.size, &RouteDiscovery_msg, &scratch); updated = &scratch; printRoute(updated, req.from, req.to); @@ -81,6 +81,6 @@ MeshPacket* TraceRouteModule::allocReply() } -TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, RouteDiscovery_fields) { +TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg) { ourPortNum = PortNum_TRACEROUTE_APP; } diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 03549f911..df2d9b093 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -70,17 +70,17 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) //invent the "sendposition" type for a valid envelope if (json["payload"]->IsObject() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) { JSONObject posit; - posit=json["payload"]->AsObject(); //get nested JSON Position - Position pos =Position_init_default; - pos.latitude_i=posit["latitude_i"]->AsNumber(); - pos.longitude_i=posit["longitude_i"]->AsNumber(); - pos.altitude=posit["altitude"]->AsNumber(); - pos.time=posit["time"]->AsNumber(); + posit = json["payload"]->AsObject(); //get nested JSON Position + Position pos = Position_init_default; + pos.latitude_i = posit["latitude_i"]->AsNumber(); + pos.longitude_i = posit["longitude_i"]->AsNumber(); + pos.altitude = posit["altitude"]->AsNumber(); + pos.time = posit["time"]->AsNumber(); // construct protobuf data packet using POSITION, send it to the mesh MeshPacket *p = router->allocForSending(); p->decoded.portnum = PortNum_POSITION_APP; - p->decoded.payload.size=pb_encode_to_bytes(p->decoded.payload.bytes,sizeof(p->decoded.payload.bytes),Position_fields, &pos); //make the Data protobuf from position + p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Position_msg, &pos); //make the Data protobuf from position service.sendToMesh(p, RX_SRC_LOCAL); } else { @@ -95,7 +95,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) } delete json_value; } else { - if (!pb_decode_from_bytes(payload, length, ServiceEnvelope_fields, &e)) { + if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) { DEBUG_MSG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); return; }else { @@ -251,7 +251,7 @@ int32_t MQTT::runOnce() // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets ServiceEnvelope *env = mqttQueue.dequeuePtr(0); static uint8_t bytes[MeshPacket_size + 64]; - size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), ServiceEnvelope_fields, env); + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); String topic = cryptTopic + env->channel_id + "/" + owner.id; DEBUG_MSG("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); @@ -305,7 +305,7 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets static uint8_t bytes[MeshPacket_size + 64]; - size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), ServiceEnvelope_fields, env); + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); String topic = cryptTopic + channelId + "/" + owner.id; DEBUG_MSG("publish %s, %u bytes\n", topic.c_str(), numBytes); diff --git a/src/platform/portduino/SimRadio.cpp b/src/platform/portduino/SimRadio.cpp index b3af114e5..06427a6d5 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -201,7 +201,7 @@ void SimRadio::startSend(MeshPacket * txp) } else { DEBUG_MSG("Payload size is larger than compressed message allows! Sending empty payload.\n"); } - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), Compressed_fields, &c); + p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Compressed_msg, &c); p->decoded.portnum = PortNum_SIMULATOR_APP; service.sendToPhone(p); // Sending back to simulator } From 3f988c8b69aa9ce5252939900ab313f2af5b6ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 23 Dec 2022 11:41:58 +0100 Subject: [PATCH 071/119] something broke pico toolchain. 'twasn'tme .. --- arch/rp2040/rp2040.ini | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/arch/rp2040/rp2040.ini b/arch/rp2040/rp2040.ini index 8b7bdbff9..cf898a60f 100644 --- a/arch/rp2040/rp2040.ini +++ b/arch/rp2040/rp2040.ini @@ -1,6 +1,8 @@ ; Common settings for rp2040 Processor based targets [rp2040_base] -platform = https://github.com/maxgerhardt/platform-raspberrypi.git#5ce1a228e7cae453f366deb8962252b9b7356bbc +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#20c7dbfcfe6677c5305fa28ecf5e3870321cb157 +platform_packages = + earlephilhower/toolchain-rp2040-earlephilhower@^5.100300.221223 extends = arduino_base board_build.core = earlephilhower board_build.filesystem_size = 0.5m From 6f6ca64cfd7acda9fd23bcdfcd6ba7073907ef19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 27 Dec 2022 21:51:35 +0100 Subject: [PATCH 072/119] potential bugfix for nag cutoff --- src/ButtonThread.h | 5 ---- src/graphics/Screen.cpp | 5 ++++ src/modules/ExternalNotificationModule.cpp | 28 +++++++++++----------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index f9131c84a..0e9830f3f 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -4,7 +4,6 @@ #include "concurrency/OSThread.h" #include "configuration.h" #include "graphics/Screen.h" -#include "modules/ExternalNotificationModule.h" #include "power.h" #include @@ -116,10 +115,6 @@ class ButtonThread : public concurrency::OSThread { // DEBUG_MSG("press!\n"); #ifdef BUTTON_PIN - // If a nag notification is running, stop it - if (externalNotificationModule->nagCycleCutoff != UINT32_MAX) { - externalNotificationModule->nagCycleCutoff = 0; - } if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || !moduleConfig.canned_message.enabled) { powerFSM.trigger(EVENT_PRESS); diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 394006622..4f1c9a5e3 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -35,6 +35,7 @@ along with this program. If not, see . #include "mesh/Channels.h" #include "mesh/generated/deviceonly.pb.h" #include "modules/TextMessageModule.h" +#include "modules/ExternalNotificationModule.h" #include "sleep.h" #include "target_specific.h" #include "utils.h" @@ -1070,6 +1071,10 @@ int32_t Screen::runOnce() handleSetOn(false); break; case Cmd::ON_PRESS: + // If a nag notification is running, stop it + if (externalNotificationModule->nagCycleCutoff != UINT32_MAX) { + externalNotificationModule->nagCycleCutoff = 0; + } handleOnPress(); break; case Cmd::START_BLUETOOTH_PIN_SCREEN: diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index b77f3a887..e0f4282ab 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -38,6 +38,20 @@ int32_t ExternalNotificationModule::runOnce() return INT32_MAX; // we don't need this thread here... } else { + if (nagCycleCutoff < millis()) { + nagCycleCutoff = UINT32_MAX; + DEBUG_MSG("Turning off external notification: "); + for (int i = 0; i < 2; i++) { + if (getExternal(i)) { + setExternalOff(i); + externalTurnedOn[i] = 0; + DEBUG_MSG("%d ", i); + } + } + DEBUG_MSG("\n"); + return INT32_MAX; // save cycles till we're needed again + } + // If the output is turned on, turn it back off after the given period of time. if (nagCycleCutoff != UINT32_MAX) { if (externalTurnedOn[0] + (moduleConfig.external_notification.output_ms @@ -56,20 +70,6 @@ int32_t ExternalNotificationModule::runOnce() getExternal(2) ? setExternalOff(2) : setExternalOn(2); } } - - if (nagCycleCutoff < millis()) { - nagCycleCutoff = UINT32_MAX; - DEBUG_MSG("Turning off external notification: "); - for (int i = 0; i < 2; i++) { - if (getExternal(i)) { - setExternalOff(i); - externalTurnedOn[i] = 0; - DEBUG_MSG("%d ", i); - } - } - DEBUG_MSG("\n"); - return INT32_MAX; // save cycles till we're needed again - } return 25; } } From 430908f5d697a0fb08a6e2d5481af847bf2884e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 13:56:56 +0100 Subject: [PATCH 073/119] TLORA_T3_S3 --- boards/tlora-t3s3-v1.json | 47 +++++++++++++++++++++++ protobufs | 2 +- src/main.cpp | 12 ------ src/mesh/SX128xInterface.cpp | 15 ++++++++ src/mesh/generated/mesh.pb.h | 2 + src/platform/esp32/architecture.h | 2 + variants/tlora_t3s3_v1/pins_arduino.h | 34 +++++++++++++++++ variants/tlora_t3s3_v1/platformio.ini | 9 +++++ variants/tlora_t3s3_v1/variant.h | 54 +++++++++++++++++++++++++++ 9 files changed, 164 insertions(+), 13 deletions(-) create mode 100644 boards/tlora-t3s3-v1.json create mode 100644 variants/tlora_t3s3_v1/pins_arduino.h create mode 100644 variants/tlora_t3s3_v1/platformio.ini create mode 100644 variants/tlora_t3s3_v1/variant.h diff --git a/boards/tlora-t3s3-v1.json b/boards/tlora-t3s3-v1.json new file mode 100644 index 000000000..36a54ad2b --- /dev/null +++ b/boards/tlora-t3s3-v1.json @@ -0,0 +1,47 @@ +{ + "build": { + "arduino": { + "ldscript": "esp32s3_out.ld" + }, + "core": "esp32", + "extra_flags": [ + "-DLILYGO_T3S3_V1", + "-DARDUINO_USB_CDC_ON_BOOT=1", + "-DARDUINO_USB_MODE=0", + "-DARDUINO_RUNNING_CORE=1", + "-DARDUINO_EVENT_RUNNING_CORE=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "dio", + "hwids": [ + [ + "0X303A", + "0x1001" + ] + ], + "mcu": "esp32s3", + "variant": "tlora-t3s3-v1" + }, + "connectivity": [ + "wifi" + ], + "debug": { + "openocd_target": "esp32s3.cfg" + }, + "frameworks": [ + "arduino", + "espidf" + ], + "name": "LilyGo TLora-T3S3-V1", + "upload": { + "flash_size": "4MB", + "maximum_ram_size": 327680, + "maximum_size": 4194304, + "wait_for_upload_port": true, + "require_upload_port": true, + "speed": 921600 + }, + "url": "http://www.lilygo.cn/", + "vendor": "LilyGo" +} \ No newline at end of file diff --git a/protobufs b/protobufs index 0985b94c2..05209dee1 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 0985b94c20287552daf63831fd9eda4e0ed1bd0e +Subproject commit 05209dee1b8fe4376c221eabd29fc165273edd43 diff --git a/src/main.cpp b/src/main.cpp index c0fcaf96e..f999ac708 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -242,7 +242,6 @@ void setup() digitalWrite(PIN_3V3_EN, 1); #endif - // Currently only the tbeam has a PMU // PMU initialization needs to be placed before scanI2Cdevice power = new Power(); @@ -462,17 +461,6 @@ if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLo } } -if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (rIf->wideLora())){ - DEBUG_MSG("Warning: Radio chip only supports 2.4GHz LoRa. Adjusting Region.\n"); - config.lora.region = Config_LoRaConfig_RegionCode_LORA_24; - nodeDB.saveToDisk(SEGMENT_CONFIG); - if(!rIf->reconfigure()) { - DEBUG_MSG("Reconfigure failed, rebooting\n"); - screen->startRebootScreen(); - rebootAtMsec = millis() + 5000; - } -} - #if HAS_WIFI || HAS_ETHERNET mqttInit(); #endif diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index 0a51d618a..fa85963b2 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -1,5 +1,6 @@ #include "configuration.h" #include "SX128xInterface.h" +#include "mesh/NodeDB.h" #include "error.h" // Particular boards might define a different max power based on what their hardware can do @@ -50,6 +51,20 @@ bool SX128xInterface::init() // \todo Display actual typename of the adapter, not just `SX128x` DEBUG_MSG("SX128x init result %d\n", res); + if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (res == RADIOLIB_ERR_INVALID_FREQUENCY)) { + DEBUG_MSG("Warning: Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting.\n"); + config.lora.region = Config_LoRaConfig_RegionCode_LORA_24; + nodeDB.saveToDisk(SEGMENT_CONFIG); + delay(2000); +#if defined(ARCH_ESP32) + ESP.restart(); +#elif defined(ARCH_NRF52) + NVIC_SystemReset(); +#else + DEBUG_MSG("FIXME implement reboot for this platform. Skipping for now.\n"); +#endif + } + DEBUG_MSG("Frequency set to %f\n", getFreq()); DEBUG_MSG("Bandwidth set to %f\n", bw); DEBUG_MSG("Power output set to %d\n", power); diff --git a/src/mesh/generated/mesh.pb.h b/src/mesh/generated/mesh.pb.h index 6fa6c8d33..31e7817a0 100644 --- a/src/mesh/generated/mesh.pb.h +++ b/src/mesh/generated/mesh.pb.h @@ -54,6 +54,8 @@ typedef enum _HardwareModel { HardwareModel_NANO_G1 = 14, /* TODO: REPLACE */ HardwareModel_TLORA_V2_1_1P8 = 15, + /* TODO: REPLACE */ + HardwareModel_TLORA_T3_S3 = 16, /* B&Q Consulting Station Edition G1: https://uniteng.com/wiki/doku.php?id=meshtastic:station */ HardwareModel_STATION_G1 = 25, /* Less common/prototype boards listed here (needs one more byte over the air) */ diff --git a/src/platform/esp32/architecture.h b/src/platform/esp32/architecture.h index f80008ca2..212df9f46 100644 --- a/src/platform/esp32/architecture.h +++ b/src/platform/esp32/architecture.h @@ -88,6 +88,8 @@ #define HW_VENDOR HardwareModel_HELTEC_V3 #elif defined(HELTEC_WSL_V3) #define HW_VENDOR HardwareModel_HELTEC_WSL_V3 +#elif defined(TLORA_T3S3_V1) + #define HW_VENDOR HardwareModel_TLORA_T3_S3 #endif // diff --git a/variants/tlora_t3s3_v1/pins_arduino.h b/variants/tlora_t3s3_v1/pins_arduino.h new file mode 100644 index 000000000..9b8eba7c1 --- /dev/null +++ b/variants/tlora_t3s3_v1/pins_arduino.h @@ -0,0 +1,34 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define USB_VID 0x303a +#define USB_PID 0x1001 + +#define EXTERNAL_NUM_INTERRUPTS 46 +#define NUM_DIGITAL_PINS 48 +#define NUM_ANALOG_INPUTS 20 + +#define analogInputToDigitalPin(p) (((p)<20)?(analogChannelToDigitalPin(p)):-1) +#define digitalPinToInterrupt(p) (((p)<48)?(p):-1) +#define digitalPinHasPWM(p) (p < 46) + +// The default Wire will be mapped to PMU and RTC +static const uint8_t SDA = 18; +static const uint8_t SCL = 17; + +// Default SPI will be mapped to Radio +static const uint8_t SS = 7; +static const uint8_t MOSI = 6; +static const uint8_t MISO = 3; +static const uint8_t SCK = 5; + +#define SPI_MOSI (11) +#define SPI_SCK (14) +#define SPI_MISO (2) +#define SPI_CS (13) + +#define SDCARD_CS SPI_CS + +#endif /* Pins_Arduino_h */ diff --git a/variants/tlora_t3s3_v1/platformio.ini b/variants/tlora_t3s3_v1/platformio.ini new file mode 100644 index 000000000..aa8189199 --- /dev/null +++ b/variants/tlora_t3s3_v1/platformio.ini @@ -0,0 +1,9 @@ +[env:tlora-t3s3-v1] +extends = esp32s3_base +board = tlora-t3s3-v1 +lib_deps = + ${esp32_base.lib_deps} + caveman99/ESP32 Codec2@^1.0.1 + +build_flags = + ${esp32_base.build_flags} -D TLORA_T3S3_V1 -I variants/tlora_t3s3_v1 \ No newline at end of file diff --git a/variants/tlora_t3s3_v1/variant.h b/variants/tlora_t3s3_v1/variant.h new file mode 100644 index 000000000..64874dac0 --- /dev/null +++ b/variants/tlora_t3s3_v1/variant.h @@ -0,0 +1,54 @@ +#undef GPS_RX_PIN +#undef GPS_TX_PIN + +#define HAS_SDCARD +#define SDCARD_USE_SPI1 + +#define USE_SSD1306 + +#define BATTERY_PIN 1 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +// ratio of voltage divider = 2.0 (R42=100k, R43=100k) +#define ADC_MULTIPLIER 2.11 // 2.0 + 10% for correction of display undervoltage. + +#define I2C_SDA 18 // I2C pins for this board +#define I2C_SCL 17 + +#define LED_PIN 37 // If defined we will blink this LED +#define BUTTON_PIN 0 // If defined, this will be used for user button presses, + +#define BUTTON_NEED_PULLUP + +// TTGO uses a common pinout for their SX1262 vs RF95 modules - both can be enabled and we will probe at runtime for RF95 and if +// not found then probe for SX1262 +#define USE_RF95 // RFM95/SX127x +#define USE_SX1262 +#define USE_SX1280 + +#define RF95_SCK 5 +#define RF95_MISO 3 +#define RF95_MOSI 6 +#define RF95_NSS 7 + +#define LORA_RESET 8 +#define LORA_DIO0 9 +#define LORA_DIO1 9 +#define LORA_DIO2 33 // SX1262 BUSY +#define LORA_DIO3 34 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled + +#ifdef USE_SX1262 +#define SX126X_CS RF95_NSS // FIXME - we really should define LORA_CS instead +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY 36 +#define SX126X_RESET LORA_RESET +#define SX126X_RXEN 21 +#define SX126X_TXEN 10 +#endif + +#ifdef USE_SX1280 +#define SX128X_CS RF95_NSS +#define SX128X_DIO1 LORA_DIO1 +#define SX128X_BUSY 36 +#define SX128X_RESET LORA_RESET +#define SX128X_RXEN 21 +#define SX128X_TXEN 10 +#endif \ No newline at end of file From 3b9b33a5ee10936d13302a260f169ad53f34c33b Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Fri, 16 Dec 2022 19:31:20 +0100 Subject: [PATCH 074/119] Use hopLimit setting for ACKs as well --- src/mesh/FloodingRouter.cpp | 3 ++- src/mesh/MeshModule.cpp | 2 +- src/mesh/PacketHistory.cpp | 10 ++++++++-- src/mesh/PacketHistory.h | 1 + src/mesh/RadioInterface.cpp | 2 +- src/mesh/ReliableRouter.cpp | 30 ++++++++++++++++-------------- src/modules/NodeInfoModule.cpp | 2 +- src/modules/PositionModule.cpp | 2 +- 8 files changed, 31 insertions(+), 21 deletions(-) diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 925735903..92df575b1 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -34,7 +34,8 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) // do not flood direct message that is ACKed DEBUG_MSG("Receiving an ACK not for me, but don't need to rebroadcast this direct message anymore.\n"); Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM - } else if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) { + } + if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) { if (p->id != 0) { if (config.device.role != Config_DeviceConfig_Role_CLIENT_MUTE) { MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index 923b4f471..02289f863 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -48,7 +48,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr p->priority = MeshPacket_Priority_ACK; - p->hop_limit = 0; // Assume just immediate neighbors for now + p->hop_limit = config.lora.hop_limit; // Assume just immediate neighbors for now p->to = to; p->decoded.request_id = idFrom; p->channel = chIndex; diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index c8008689d..9d2c7a8ed 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -11,7 +11,7 @@ PacketHistory::PacketHistory() /** * Update recentBroadcasts and return true if we have already seen this packet */ -bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) +bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) //, bool checkAck { if (p->id == 0) { DEBUG_MSG("Ignoring message with zero id\n"); @@ -24,6 +24,12 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) r.id = p->id; r.sender = getFrom(p); r.rxTimeMsec = now; + // if (checkAck) + // if (p->which_payload_variant == MeshPacket_decoded_tag && p->decoded.portnum == PortNum_ROUTING_APP) { + // perhapsDecode(p); + // bool seenAck = (p-> == ) + // } + // r.seenAck = p-> auto found = recentPackets.find(r); bool seenRecently = (found != recentPackets.end()); // found not equal to .end() means packet was seen recently @@ -52,7 +58,7 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) clearExpiredRecentPackets(); } - return seenRecently; + return seenRecently; //checkAck ? seenAck : } /** diff --git a/src/mesh/PacketHistory.h b/src/mesh/PacketHistory.h index d44a3d369..abdc78c4f 100644 --- a/src/mesh/PacketHistory.h +++ b/src/mesh/PacketHistory.h @@ -13,6 +13,7 @@ struct PacketRecord { NodeNum sender; PacketId id; uint32_t rxTimeMsec; // Unix time in msecs - the time we received it + //bool seenAck; bool operator==(const PacketRecord &p) const { return sender == p.sender && id == p.id; } }; diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 222e5d14b..9ee66da0d 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -182,7 +182,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); // Assuming we pick max. of CWsize and there will be a receiver with SNR at half the range - return 2*packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax+CWmin)/2))) * slotTimeMsec + PROCESSING_TIME_MSEC; + return 1000*packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax+CWmin)/2))) * slotTimeMsec + PROCESSING_TIME_MSEC; } /** The delay to use when we want to send something */ diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index 7933a7920..a60c37ebc 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -21,7 +21,7 @@ ErrorCode ReliableRouter::send(MeshPacket *p) } auto copy = packetPool.allocCopy(*p); - startRetransmission(copy); + startRetransmission(copy); // TODO: also on not want_ack? } return FloodingRouter::send(p); @@ -37,27 +37,29 @@ bool ReliableRouter::shouldFilterReceived(MeshPacket *p) // If this is the first time we saw this, cancel any retransmissions we have queued up and generate an internal ack for // the original sending process. - // FIXME - we might want to turn off this "optimization", it does save lots of airtime but it assumes that once we've - // heard one one adjacent node hear our packet that a) probably other adjacent nodes heard it and b) we can trust those - // nodes to reach our destination. Both of which might be incorrect. + // This "optimization", does save lots of airtime, but can be turned off for direct messages to get + // a confirmation from the specific node it was sent to. auto key = GlobalPacketId(getFrom(p), p->id); auto old = findPendingPacket(key); if (old) { - DEBUG_MSG("generating implicit ack\n"); - // NOTE: we do NOT check p->wantAck here because p is the INCOMING rebroadcast and that packet is not expected to be - // marked as wantAck - sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); - + // Only if want_ack was not set, we mark the packet as ACKed already on an implicit ACK + if (!p->want_ack) { + DEBUG_MSG("generating implicit ack\n"); + sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); + } + // At this point we assume it will arrive. + // We don't now how long we have to wait for the real ACK so stop retransmissions. + DEBUG_MSG("Stopping retransmissions\n"); stopRetransmission(key); - } else { - DEBUG_MSG("didn't find pending packet\n"); } } + + //bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK /* send acks for repeated packets that want acks and are destined for us - * this way if an ACK is dropped and a packet is resent we'll ACK the resent packet - * make sure wasSeenRecently _doesn't_ update - * finding the channel requires decoding the packet. */ + * this way if an ACK is dropped and a packet is resent we'll ACK the resent packet + * make sure wasSeenRecently _doesn't_ update + * finding the channel requires decoding the packet. */ if (p->want_ack && (p->to == getNodeNum()) && wasSeenRecently(p, false) && !MeshModule::currentReply) { if (perhapsDecode(p)) { sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index 1ce1acf33..b5d6c30da 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -54,7 +54,7 @@ NodeInfoModule::NodeInfoModule() : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others - setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) + //setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) } int32_t NodeInfoModule::runOnce() diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 013f2ee44..df9ee6816 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -13,7 +13,7 @@ PositionModule::PositionModule() : ProtobufModule("position", PortNum_POSITION_APP, &Position_msg), concurrency::OSThread("PositionModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others - setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) + //setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) } bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr) From b4735f4224d46b84ec9602703699499332006d35 Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Tue, 27 Dec 2022 14:32:07 +0100 Subject: [PATCH 075/119] Don't resend ACK every time you receive the packet --- src/mesh/FloodingRouter.cpp | 2 +- src/mesh/FloodingRouter.h | 2 +- src/mesh/MeshModule.cpp | 2 +- src/mesh/ReliableRouter.cpp | 18 +++++------------- src/mesh/ReliableRouter.h | 2 +- src/mesh/Router.h | 2 +- 6 files changed, 10 insertions(+), 18 deletions(-) diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 92df575b1..e21820305 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -17,7 +17,7 @@ ErrorCode FloodingRouter::send(MeshPacket *p) return Router::send(p); } -bool FloodingRouter::shouldFilterReceived(MeshPacket *p) +bool FloodingRouter::shouldFilterReceived(const MeshPacket *p) { if (wasSeenRecently(p)) { // Note: this will also add a recent packet record printPacket("Ignoring incoming msg, because we've already seen it", p); diff --git a/src/mesh/FloodingRouter.h b/src/mesh/FloodingRouter.h index 7e6271fc0..01b51c9a2 100644 --- a/src/mesh/FloodingRouter.h +++ b/src/mesh/FloodingRouter.h @@ -51,7 +51,7 @@ class FloodingRouter : public Router, protected PacketHistory * Called immedately on receiption, before any further processing. * @return true to abandon the packet */ - virtual bool shouldFilterReceived(MeshPacket *p) override; + virtual bool shouldFilterReceived(const MeshPacket *p) override; /** * Look for broadcasts we need to rebroadcast diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index 02289f863..8019cda1e 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -48,7 +48,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr p->priority = MeshPacket_Priority_ACK; - p->hop_limit = config.lora.hop_limit; // Assume just immediate neighbors for now + p->hop_limit = config.lora.hop_limit; // Flood ACK back to original sender p->to = to; p->decoded.request_id = idFrom; p->channel = chIndex; diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index a60c37ebc..ba886ed71 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -27,7 +27,7 @@ ErrorCode ReliableRouter::send(MeshPacket *p) return FloodingRouter::send(p); } -bool ReliableRouter::shouldFilterReceived(MeshPacket *p) +bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) { // Note: do not use getFrom() here, because we want to ignore messages sent from phone if (p->from == getNodeNum()) { @@ -54,18 +54,10 @@ bool ReliableRouter::shouldFilterReceived(MeshPacket *p) } } - - //bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK - /* send acks for repeated packets that want acks and are destined for us - * this way if an ACK is dropped and a packet is resent we'll ACK the resent packet - * make sure wasSeenRecently _doesn't_ update - * finding the channel requires decoding the packet. */ - if (p->want_ack && (p->to == getNodeNum()) && wasSeenRecently(p, false) && !MeshModule::currentReply) { - if (perhapsDecode(p)) { - sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); - DEBUG_MSG("acking a repeated want_ack packet\n"); - } - } else if (wasSeenRecently(p, false) && p->hop_limit == HOP_RELIABLE && !MeshModule::currentReply && p->to != nodeDB.getNodeNum()) { + /* Resend implicit ACKs for repeated packets (assuming original packet was sent with HOP_RELIABLE) + * this way if an implicit ACK is dropped and a packet is resent we'll rebroadcast again + * Not used for real ACKs, as you might receive a packet multiple times due to flooding. */ + if (wasSeenRecently(p, false) && p->hop_limit == HOP_RELIABLE && !MeshModule::currentReply && p->to != nodeDB.getNodeNum()) { // retransmission on broadcast has hop_limit still equal to HOP_RELIABLE DEBUG_MSG("Resending implicit ack for a repeated floodmsg\n"); MeshPacket *tosend = packetPool.allocCopy(*p); diff --git a/src/mesh/ReliableRouter.h b/src/mesh/ReliableRouter.h index ff304cdd7..65f486e5b 100644 --- a/src/mesh/ReliableRouter.h +++ b/src/mesh/ReliableRouter.h @@ -96,7 +96,7 @@ class ReliableRouter : public FloodingRouter /** * We hook this method so we can see packets before FloodingRouter says they should be discarded */ - virtual bool shouldFilterReceived(MeshPacket *p) override; + virtual bool shouldFilterReceived(const MeshPacket *p) override; /** * Add p to the list of packets to retransmit occasionally. We will free it once we stop retransmitting. diff --git a/src/mesh/Router.h b/src/mesh/Router.h index 3f079d92c..f7748bb2b 100644 --- a/src/mesh/Router.h +++ b/src/mesh/Router.h @@ -90,7 +90,7 @@ class Router : protected concurrency::OSThread * Called immedately on receiption, before any further processing. * @return true to abandon the packet */ - virtual bool shouldFilterReceived(MeshPacket *p) { return false; } + virtual bool shouldFilterReceived(const MeshPacket *p) { return false; } /** * Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to From 6c5602e88d8f5038c0e10c9dd11d62462f0aa9fa Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Wed, 28 Dec 2022 14:04:26 +0100 Subject: [PATCH 076/119] Cleanup --- src/mesh/PacketHistory.cpp | 12 +++--------- src/mesh/PacketHistory.h | 1 - src/mesh/RadioInterface.cpp | 2 +- src/mesh/ReliableRouter.cpp | 28 ++++++++++++++-------------- src/modules/NodeInfoModule.cpp | 4 ++-- src/modules/PositionModule.cpp | 2 +- 6 files changed, 21 insertions(+), 28 deletions(-) diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index 9d2c7a8ed..a1e0f6bd5 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -11,7 +11,7 @@ PacketHistory::PacketHistory() /** * Update recentBroadcasts and return true if we have already seen this packet */ -bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) //, bool checkAck +bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) { if (p->id == 0) { DEBUG_MSG("Ignoring message with zero id\n"); @@ -24,12 +24,6 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) //, b r.id = p->id; r.sender = getFrom(p); r.rxTimeMsec = now; - // if (checkAck) - // if (p->which_payload_variant == MeshPacket_decoded_tag && p->decoded.portnum == PortNum_ROUTING_APP) { - // perhapsDecode(p); - // bool seenAck = (p-> == ) - // } - // r.seenAck = p-> auto found = recentPackets.find(r); bool seenRecently = (found != recentPackets.end()); // found not equal to .end() means packet was seen recently @@ -58,7 +52,7 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) //, b clearExpiredRecentPackets(); } - return seenRecently; //checkAck ? seenAck : + return seenRecently; } /** @@ -78,4 +72,4 @@ void PacketHistory::clearExpiredRecentPackets() { } DEBUG_MSG("recentPackets size=%ld (after clearing expired packets)\n", recentPackets.size()); -} \ No newline at end of file +} diff --git a/src/mesh/PacketHistory.h b/src/mesh/PacketHistory.h index abdc78c4f..d44a3d369 100644 --- a/src/mesh/PacketHistory.h +++ b/src/mesh/PacketHistory.h @@ -13,7 +13,6 @@ struct PacketRecord { NodeNum sender; PacketId id; uint32_t rxTimeMsec; // Unix time in msecs - the time we received it - //bool seenAck; bool operator==(const PacketRecord &p) const { return sender == p.sender && id == p.id; } }; diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 9ee66da0d..222e5d14b 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -182,7 +182,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); // Assuming we pick max. of CWsize and there will be a receiver with SNR at half the range - return 1000*packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax+CWmin)/2))) * slotTimeMsec + PROCESSING_TIME_MSEC; + return 2*packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax+CWmin)/2))) * slotTimeMsec + PROCESSING_TIME_MSEC; } /** The delay to use when we want to send something */ diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index ba886ed71..22f3692b9 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -21,7 +21,7 @@ ErrorCode ReliableRouter::send(MeshPacket *p) } auto copy = packetPool.allocCopy(*p); - startRetransmission(copy); // TODO: also on not want_ack? + startRetransmission(copy); } return FloodingRouter::send(p); @@ -37,26 +37,26 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) // If this is the first time we saw this, cancel any retransmissions we have queued up and generate an internal ack for // the original sending process. - // This "optimization", does save lots of airtime, but can be turned off for direct messages to get - // a confirmation from the specific node it was sent to. + // This "optimization", does save lots of airtime. For DMs, you also get a real ACK back + // from the intended recipient. auto key = GlobalPacketId(getFrom(p), p->id); auto old = findPendingPacket(key); if (old) { - // Only if want_ack was not set, we mark the packet as ACKed already on an implicit ACK - if (!p->want_ack) { - DEBUG_MSG("generating implicit ack\n"); - sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); - } - // At this point we assume it will arrive. - // We don't now how long we have to wait for the real ACK so stop retransmissions. - DEBUG_MSG("Stopping retransmissions\n"); + DEBUG_MSG("generating implicit ack\n"); + // NOTE: we do NOT check p->wantAck here because p is the INCOMING rebroadcast and that packet is not expected to be + // marked as wantAck + sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); + stopRetransmission(key); + } else { + DEBUG_MSG("didn't find pending packet\n"); } } - /* Resend implicit ACKs for repeated packets (assuming original packet was sent with HOP_RELIABLE) - * this way if an implicit ACK is dropped and a packet is resent we'll rebroadcast again - * Not used for real ACKs, as you might receive a packet multiple times due to flooding. */ + /* Resend implicit ACKs for repeated packets (assuming the original packet was sent with HOP_RELIABLE) + * this way if an implicit ACK is dropped and a packet is resent we'll rebroadcast again. + * Resending real ACKs is omitted, as you might receive a packet multiple times due to flooding and + * flooding this ACK back to the original sender already adds redundancy. */ if (wasSeenRecently(p, false) && p->hop_limit == HOP_RELIABLE && !MeshModule::currentReply && p->to != nodeDB.getNodeNum()) { // retransmission on broadcast has hop_limit still equal to HOP_RELIABLE DEBUG_MSG("Resending implicit ack for a repeated floodmsg\n"); diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index b5d6c30da..fc1d143ee 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -54,7 +54,7 @@ NodeInfoModule::NodeInfoModule() : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others - //setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) + setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) } int32_t NodeInfoModule::runOnce() @@ -69,4 +69,4 @@ int32_t NodeInfoModule::runOnce() sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies) return default_broadcast_interval_secs * 1000; -} \ No newline at end of file +} diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index df9ee6816..013f2ee44 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -13,7 +13,7 @@ PositionModule::PositionModule() : ProtobufModule("position", PortNum_POSITION_APP, &Position_msg), concurrency::OSThread("PositionModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others - //setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) + setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) } bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr) From 5c859da4e40bc9cd5a2792f2ca737ad1a9d0b746 Mon Sep 17 00:00:00 2001 From: GUVWAF Date: Wed, 28 Dec 2022 14:40:10 +0100 Subject: [PATCH 077/119] Remove unnecessary changes --- src/mesh/PacketHistory.cpp | 2 +- src/modules/NodeInfoModule.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index a1e0f6bd5..c8008689d 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -72,4 +72,4 @@ void PacketHistory::clearExpiredRecentPackets() { } DEBUG_MSG("recentPackets size=%ld (after clearing expired packets)\n", recentPackets.size()); -} +} \ No newline at end of file diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index fc1d143ee..1ce1acf33 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -69,4 +69,4 @@ int32_t NodeInfoModule::runOnce() sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies) return default_broadcast_interval_secs * 1000; -} +} \ No newline at end of file From e25d05689b96a863dfaff66ca77c0a13cb6b7749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 14:57:40 +0100 Subject: [PATCH 078/119] Updates to external notification and radiolib for SX128x. Rip out Godmode again for these --- platformio.ini | 4 +- src/graphics/Screen.cpp | 6 +- src/mesh/RadioLibRF95.h | 5 - src/mesh/SX128xInterface.cpp | 4 - src/mesh/SX128xInterface.h | 2 - src/modules/ExternalNotificationModule.cpp | 147 +++++++++++---------- src/modules/ExternalNotificationModule.h | 5 + variants/tlora_v2_1_18/platformio.ini | 4 +- 8 files changed, 91 insertions(+), 86 deletions(-) diff --git a/platformio.ini b/platformio.ini index dbddf7535..fa483f8ef 100644 --- a/platformio.ini +++ b/platformio.ini @@ -66,7 +66,8 @@ lib_deps = https://github.com/meshtastic/ArduinoThread.git#72921ac222eed6f526ba1682023cee290d9aa1b3 nanopb/Nanopb@^0.4.6 erriez/ErriezCRC32@^1.0.1 - jgromes/RadioLib@^5.5.0 +; jgromes/RadioLib@^5.5.1 + https://github.com/jgromes/RadioLib.git#395844922c5d88d5db0481a9c91479931172428d ; Used for the code analysis in PIO Home / Inspect check_tool = cppcheck @@ -82,6 +83,7 @@ framework = arduino lib_deps = ${env.lib_deps} mprograms/QMC5883LCompass@^1.1.1 + end2endzone/NonBlockingRTTTL@^1.3.0 https://github.com/meshtastic/SparkFun_ATECCX08a_Arduino_Library.git#52b5282639d08a8cbd4b748363089eed6102dc76 build_flags = ${env.build_flags} -Os -DRADIOLIB_SPI_PARANOID=0 diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 4f1c9a5e3..7b34aee55 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -1073,9 +1073,11 @@ int32_t Screen::runOnce() case Cmd::ON_PRESS: // If a nag notification is running, stop it if (externalNotificationModule->nagCycleCutoff != UINT32_MAX) { - externalNotificationModule->nagCycleCutoff = 0; + externalNotificationModule->stopNow(); + } else { + // Don't advance the screen if we just wanted to switch off the nag notification + handleOnPress(); } - handleOnPress(); break; case Cmd::START_BLUETOOTH_PIN_SCREEN: handleStartBluetoothPinScreen(cmd.bluetooth_pin); diff --git a/src/mesh/RadioLibRF95.h b/src/mesh/RadioLibRF95.h index ff8164ef2..7fbaff780 100644 --- a/src/mesh/RadioLibRF95.h +++ b/src/mesh/RadioLibRF95.h @@ -66,10 +66,5 @@ class RadioLibRF95: public SX1278 { // since default current limit for SX126x/127x in updated RadioLib is 60mA // use the previous value float currentLimit = 100; - -#ifndef RADIOLIB_GODMODE - private: -#endif - }; diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index fa85963b2..d056ab8dd 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -238,13 +238,9 @@ bool SX128xInterface::isChannelActive() template bool SX128xInterface::isActivelyReceiving() { -#ifdef RADIOLIB_GODMODE uint16_t irq = lora.getIrqStatus(); bool hasPreamble = (irq & RADIOLIB_SX128X_IRQ_HEADER_VALID); return hasPreamble; -#else - return isChannelActive(); -#endif } template diff --git a/src/mesh/SX128xInterface.h b/src/mesh/SX128xInterface.h index 5a6ed95f9..2010a65c4 100644 --- a/src/mesh/SX128xInterface.h +++ b/src/mesh/SX128xInterface.h @@ -27,9 +27,7 @@ class SX128xInterface : public RadioLibInterface /// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep. virtual bool sleep() override; -#ifdef RADIOLIB_GODMODE bool isIRQPending() override { return lora.getIrqStatus() != 0; } -#endif protected: diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index e0f4282ab..6c31fdabc 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -34,11 +34,10 @@ uint32_t externalTurnedOn[3] = {}; int32_t ExternalNotificationModule::runOnce() { - if (moduleConfig.external_notification.use_pwm || !moduleConfig.external_notification.enabled) { + if (!moduleConfig.external_notification.enabled) { return INT32_MAX; // we don't need this thread here... } else { - - if (nagCycleCutoff < millis()) { + if ((nagCycleCutoff < millis()) && !rtttl::isPlaying()) { nagCycleCutoff = UINT32_MAX; DEBUG_MSG("Turning off external notification: "); for (int i = 0; i < 2; i++) { @@ -70,6 +69,16 @@ int32_t ExternalNotificationModule::runOnce() getExternal(2) ? setExternalOff(2) : setExternalOn(2); } } + + // now let the PWM buzzer play + if (moduleConfig.external_notification.use_pwm) { + if (rtttl::isPlaying()) { + rtttl::play(); + } else if (nagCycleCutoff >= millis()) { + // start the song again if we have time left + rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + } + } return 25; } } @@ -119,7 +128,11 @@ bool ExternalNotificationModule::getExternal(uint8_t index) return externalCurrentState[index]; } -// -------- +void ExternalNotificationModule::stopNow() { + rtttl::stop(); + nagCycleCutoff = 1; // small value + setIntervalFromNow(0); +} ExternalNotificationModule::ExternalNotificationModule() : SinglePortModule("ExternalNotificationModule", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread( @@ -151,31 +164,30 @@ ExternalNotificationModule::ExternalNotificationModule() ? moduleConfig.external_notification.output : EXT_NOTIFICATION_MODULE_OUTPUT; - if (!moduleConfig.external_notification.use_pwm) { - // Set the direction of a pin - DEBUG_MSG("Using Pin %i in digital mode\n", output); - pinMode(output, OUTPUT); - setExternalOff(0); - externalTurnedOn[0] = 0; - if(moduleConfig.external_notification.output_vibra) { - DEBUG_MSG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); - pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); - setExternalOff(1); - externalTurnedOn[1] = 0; - } - if(moduleConfig.external_notification.output_buzzer) { + // Set the direction of a pin + DEBUG_MSG("Using Pin %i in digital mode\n", output); + pinMode(output, OUTPUT); + setExternalOff(0); + externalTurnedOn[0] = 0; + if(moduleConfig.external_notification.output_vibra) { + DEBUG_MSG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); + pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); + setExternalOff(1); + externalTurnedOn[1] = 0; + } + if(moduleConfig.external_notification.output_buzzer) { + if (!moduleConfig.external_notification.use_pwm) { DEBUG_MSG("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT); setExternalOff(2); externalTurnedOn[2] = 0; + } else { + config.device.buzzer_gpio = config.device.buzzer_gpio + ? config.device.buzzer_gpio + : PIN_BUZZER; + // in PWM Mode we force the buzzer pin if it is set + DEBUG_MSG("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); } - } else { - config.device.buzzer_gpio = config.device.buzzer_gpio - ? config.device.buzzer_gpio - : PIN_BUZZER; - - // in PWM Mode we force the buzzer pin if it is set - DEBUG_MSG("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); } } else { DEBUG_MSG("External Notification Module Disabled\n"); @@ -201,57 +213,50 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell) { if (containsBell) { DEBUG_MSG("externalNotificationModule - Notification Bell\n"); - if (!moduleConfig.external_notification.use_pwm) { - setExternalOn(0); - if (moduleConfig.external_notification.nag_timeout) { - nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; - } else { - nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; - } - // run_once now - } else { - playBeep(); - } - } - } - - if (!moduleConfig.external_notification.use_pwm) { - if (moduleConfig.external_notification.alert_bell_vibra) { - if (containsBell) { - DEBUG_MSG("externalNotificationModule - Notification Bell (Vibra)\n"); - setExternalOn(1); - if (moduleConfig.external_notification.nag_timeout) { - nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; - } else { - nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; - } - } - } - - if (moduleConfig.external_notification.alert_bell_buzzer) { - if (containsBell) { - DEBUG_MSG("externalNotificationModule - Notification Bell (Buzzer)\n"); - setExternalOn(2); - if (moduleConfig.external_notification.nag_timeout) { - nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; - } else { - nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; - } - } - } - } - - if (moduleConfig.external_notification.alert_message) { - DEBUG_MSG("externalNotificationModule - Notification Module\n"); - if (!moduleConfig.external_notification.use_pwm) { setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; } else { nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; } + } + } + + if (moduleConfig.external_notification.alert_bell_vibra) { + if (containsBell) { + DEBUG_MSG("externalNotificationModule - Notification Bell (Vibra)\n"); + setExternalOn(1); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + } + } + + if (moduleConfig.external_notification.alert_bell_buzzer) { + if (containsBell) { + DEBUG_MSG("externalNotificationModule - Notification Bell (Buzzer)\n"); + if (!moduleConfig.external_notification.use_pwm) { + setExternalOn(2); + } else { + rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + } + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; + } else { + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; + } + } + } + + if (moduleConfig.external_notification.alert_message) { + DEBUG_MSG("externalNotificationModule - Notification Module\n"); + setExternalOn(0); + if (moduleConfig.external_notification.nag_timeout) { + nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; } else { - playBeep(); + nagCycleCutoff = millis() + moduleConfig.external_notification.output_ms; } } @@ -268,7 +273,11 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_message_buzzer) { DEBUG_MSG("externalNotificationModule - Notification Module (Buzzer)\n"); - setExternalOn(2); + if (!moduleConfig.external_notification.use_pwm) { + setExternalOn(2); + } else { + rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + } if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; } else { diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index 1b1aeff21..04de235cf 100644 --- a/src/modules/ExternalNotificationModule.h +++ b/src/modules/ExternalNotificationModule.h @@ -3,6 +3,7 @@ #include "SinglePortModule.h" #include "concurrency/OSThread.h" #include "configuration.h" +#include #include #include @@ -23,6 +24,10 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: void setExternalOff(uint8_t index = 0); bool getExternal(uint8_t index = 0); + void stopNow(); + + char pwmRingtone[Constants_DATA_PAYLOAD_LEN] = "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#"; + protected: /** Called to handle a particular incoming message @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it diff --git a/variants/tlora_v2_1_18/platformio.ini b/variants/tlora_v2_1_18/platformio.ini index 9c79fa259..c61b8a28c 100644 --- a/variants/tlora_v2_1_18/platformio.ini +++ b/variants/tlora_v2_1_18/platformio.ini @@ -5,7 +5,5 @@ lib_deps = ${esp32_base.lib_deps} caveman99/ESP32 Codec2@^1.0.1 -; the RADIOLIB_GODMODE flag can be removed once the next version of RadioLib is released. (>5.5.0) - build_flags = - ${esp32_base.build_flags} -D TLORA_V2_1_18 -I variants/tlora_v2_1_18 -D RADIOLIB_GODMODE \ No newline at end of file + ${esp32_base.build_flags} -D TLORA_V2_1_18 -I variants/tlora_v2_1_18 \ No newline at end of file From 94cb100e3f564f36cf6764ce3e7ed7810aa4403a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 15:30:23 +0100 Subject: [PATCH 079/119] Master to Develop --- platformio.ini | 3 +- src/configuration.h | 1 + src/detect/i2cScan.h | 4 +++ src/mesh/Channels.cpp | 11 +++++++ src/mesh/Channels.h | 3 ++ src/mesh/generated/telemetry.pb.h | 8 +++-- .../Telemetry/EnvironmentTelemetry.cpp | 6 ++++ src/modules/Telemetry/Sensor/SHT31Sensor.cpp | 31 +++++++++++++++++++ src/modules/Telemetry/Sensor/SHT31Sensor.h | 16 ++++++++++ variants/tbeam-s3-core/variant.h | 1 + 10 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 src/modules/Telemetry/Sensor/SHT31Sensor.cpp create mode 100644 src/modules/Telemetry/Sensor/SHT31Sensor.h diff --git a/platformio.ini b/platformio.ini index fa483f8ef..5f7f2dbac 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,6 @@ ;default_envs = heltec-v2.0 ;default_envs = heltec-v2.1 ;default_envs = tlora-v1 -;default_envs = tlora-v1 ;default_envs = tlora_v1_3 ;default_envs = tlora-v2 ;default_envs = tlora-v2-1-1.6 @@ -108,4 +107,4 @@ lib_deps = adafruit/Adafruit INA260 Library@^1.5.0 adafruit/Adafruit INA219@^1.2.0 adafruit/Adafruit SHTC3 Library@^1.0.0 - adafruit/Adafruit LPS2X@^2.0.4 \ No newline at end of file + adafruit/Adafruit LPS2X@^2.0.4 adafruit/Adafruit SHT31 Library@^2.2.0 diff --git a/src/configuration.h b/src/configuration.h index e68bd8d16..67862609a 100644 --- a/src/configuration.h +++ b/src/configuration.h @@ -114,6 +114,7 @@ along with this program. If not, see . #define SHTC3_ADDR 0x70 #define LPS22HB_ADDR 0x5C #define LPS22HB_ADDR_ALT 0x5D +#define SHT31_ADDR 0x44 // ----------------------------------------------------------------------------- // Security diff --git a/src/detect/i2cScan.h b/src/detect/i2cScan.h index 4eac50f03..940ebb100 100644 --- a/src/detect/i2cScan.h +++ b/src/detect/i2cScan.h @@ -191,6 +191,10 @@ void scanI2Cdevice() nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr; DEBUG_MSG("MCP9808 sensor found\n"); } + if (addr == SHT31_ADDR) { + DEBUG_MSG("SHT31 sensor found\n"); + nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; + } if (addr == SHTC3_ADDR) { DEBUG_MSG("SHTC3 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index 9ae211e6e..e7f1cb3ed 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -196,6 +196,17 @@ Channel &Channels::getByIndex(ChannelIndex chIndex) return *ch; } +Channel &Channels::getByName(const char* chName) +{ + for (ChannelIndex i = 0; i < getNumChannels(); i++) { + if (strcasecmp(channelFile.channels[i].settings.name, chName) == 0) { + return channelFile.channels[i]; + } + } + + return getByIndex(getPrimaryIndex()); +} + void Channels::setChannel(const Channel &c) { Channel &old = getByIndex(c.index); diff --git a/src/mesh/Channels.h b/src/mesh/Channels.h index ebf08d32c..79e96b7f6 100644 --- a/src/mesh/Channels.h +++ b/src/mesh/Channels.h @@ -40,6 +40,9 @@ class Channels /** Return the Channel for a specified index */ Channel &getByIndex(ChannelIndex chIndex); + /** Return the Channel for a specified name, return primary if not found. */ + Channel &getByName(const char* chName); + /** Using the index inside the channel, update the specified channel's settings and role. If this channel is being promoted * to be primary, force all other channels to be secondary. */ diff --git a/src/mesh/generated/telemetry.pb.h b/src/mesh/generated/telemetry.pb.h index df5458a1c..e5c71a2b7 100644 --- a/src/mesh/generated/telemetry.pb.h +++ b/src/mesh/generated/telemetry.pb.h @@ -35,7 +35,9 @@ typedef enum _TelemetrySensorType { /* 6-Axis inertial measurement sensor */ TelemetrySensorType_QMI8658 = 10, /* 3-Axis magnetic sensor */ - TelemetrySensorType_QMC5883L = 11 + TelemetrySensorType_QMC5883L = 11, + /* High accuracy temperature and humidity */ + TelemetrySensorType_SHT31 = 12 } TelemetrySensorType; /* Struct definitions */ @@ -91,8 +93,8 @@ extern "C" { /* Helper constants for enums */ #define _TelemetrySensorType_MIN TelemetrySensorType_SENSOR_UNSET -#define _TelemetrySensorType_MAX TelemetrySensorType_QMC5883L -#define _TelemetrySensorType_ARRAYSIZE ((TelemetrySensorType)(TelemetrySensorType_QMC5883L+1)) +#define _TelemetrySensorType_MAX TelemetrySensorType_SHT31 +#define _TelemetrySensorType_ARRAYSIZE ((TelemetrySensorType)(TelemetrySensorType_SHT31+1)) diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index b676dfd42..11955f3f6 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -20,6 +20,7 @@ #include "Sensor/INA219Sensor.h" #include "Sensor/SHTC3Sensor.h" #include "Sensor/LPS22HBSensor.h" +#include "Sensor/SHT31Sensor.h" BMP280Sensor bmp280Sensor; BME280Sensor bme280Sensor; @@ -29,6 +30,7 @@ INA260Sensor ina260Sensor; INA219Sensor ina219Sensor; SHTC3Sensor shtc3Sensor; LPS22HBSensor lps22hbSensor; +SHT31Sensor sht31Sensor; #define FAILED_STATE_SENSOR_READ_MULTIPLIER 10 #define DISPLAY_RECEIVEID_MEASUREMENTS_ON_SCREEN true @@ -93,6 +95,8 @@ int32_t EnvironmentTelemetryModule::runOnce() if (lps22hbSensor.hasSensor()) { result = lps22hbSensor.runOnce(); } + if (sht31Sensor.hasSensor()) + result = sht31Sensor.runOnce(); } return result; } else { @@ -211,6 +215,8 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) m.variant.environment_metrics.temperature = 0; m.variant.environment_metrics.voltage = 0; + if (sht31Sensor.hasSensor()) + sht31Sensor.getMetrics(&m); if (lps22hbSensor.hasSensor()) lps22hbSensor.getMetrics(&m); if (shtc3Sensor.hasSensor()) diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp new file mode 100644 index 000000000..94591e6cb --- /dev/null +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp @@ -0,0 +1,31 @@ +#include "../mesh/generated/telemetry.pb.h" +#include "configuration.h" +#include "TelemetrySensor.h" +#include "SHT31Sensor.h" +#include + +SHT31Sensor::SHT31Sensor() : + TelemetrySensor(TelemetrySensorType_SHT31, "SHT31") +{ +} + +int32_t SHT31Sensor::runOnce() { + DEBUG_MSG("Init sensor: %s\n", sensorName); + if (!hasSensor()) { + return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; + } + status = sht31.begin(); + return initI2CSensor(); +} + +void SHT31Sensor::setup() +{ + // Set up oversampling and filter initialization +} + +bool SHT31Sensor::getMetrics(Telemetry *measurement) { + measurement->variant.environment_metrics.temperature = sht31.readTemperature(); + measurement->variant.environment_metrics.relative_humidity = sht31.readHumidity(); + + return true; +} diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.h b/src/modules/Telemetry/Sensor/SHT31Sensor.h new file mode 100644 index 000000000..5f236e21e --- /dev/null +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.h @@ -0,0 +1,16 @@ +#include "../mesh/generated/telemetry.pb.h" +#include "TelemetrySensor.h" +#include + +class SHT31Sensor : virtual public TelemetrySensor { +private: + Adafruit_SHT31 sht31 = Adafruit_SHT31(); + +protected: + virtual void setup() override; + +public: + SHT31Sensor(); + virtual int32_t runOnce() override; + virtual bool getMetrics(Telemetry *measurement) override; +}; diff --git a/variants/tbeam-s3-core/variant.h b/variants/tbeam-s3-core/variant.h index 9aaba6010..001b50a30 100644 --- a/variants/tbeam-s3-core/variant.h +++ b/variants/tbeam-s3-core/variant.h @@ -66,3 +66,4 @@ //has 32768 Hz crystal #define HAS_32768HZ +#define USE_SH1106 \ No newline at end of file From 3b19040590a010fb7dc6febeb430ea419809c64b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 15:37:17 +0100 Subject: [PATCH 080/119] protobuf update --- protobufs | 2 +- src/mesh/generated/telemetry.pb.h | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/protobufs b/protobufs index 05209dee1..79e213fbc 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 05209dee1b8fe4376c221eabd29fc165273edd43 +Subproject commit 79e213fbcc6f432923ab131bfa7b8630eb93270e diff --git a/src/mesh/generated/telemetry.pb.h b/src/mesh/generated/telemetry.pb.h index e5c71a2b7..1b294dc1a 100644 --- a/src/mesh/generated/telemetry.pb.h +++ b/src/mesh/generated/telemetry.pb.h @@ -71,10 +71,10 @@ typedef struct _EnvironmentMetrics { /* Types of Measurements the telemetry module is equipped to handle */ typedef struct _Telemetry { - /* This is usually not sent over the mesh (to save space), but it is sent - from the phone so that the local device can set its RTC If it is sent over - the mesh (because there are devices on the mesh without GPS), it will only - be sent by devices which has a hardware GPS clock (IE Mobile Phone). + /* This is usually not sent over the mesh (to save space), but it is sent + from the phone so that the local device can set its RTC If it is sent over + the mesh (because there are devices on the mesh without GPS), it will only + be sent by devices which has a hardware GPS clock (IE Mobile Phone). seconds since 1970 */ uint32_t time; pb_size_t which_variant; From d9d8c7eb749dba968435690be9727d1b431bf14a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 15:41:58 +0100 Subject: [PATCH 081/119] I think this will fix portduino... --- src/modules/ExternalNotificationModule.cpp | 8 ++++++++ src/modules/ExternalNotificationModule.h | 2 ++ 2 files changed, 10 insertions(+) diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index 6c31fdabc..1235524a4 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -71,6 +71,7 @@ int32_t ExternalNotificationModule::runOnce() } // now let the PWM buzzer play +#ifndef ARCH_PORTDUINO if (moduleConfig.external_notification.use_pwm) { if (rtttl::isPlaying()) { rtttl::play(); @@ -79,6 +80,7 @@ int32_t ExternalNotificationModule::runOnce() rtttl::begin(config.device.buzzer_gpio, pwmRingtone); } } +#endif return 25; } } @@ -129,7 +131,9 @@ bool ExternalNotificationModule::getExternal(uint8_t index) } void ExternalNotificationModule::stopNow() { +#ifndef ARCH_PORTDUINO rtttl::stop(); +#endif nagCycleCutoff = 1; // small value setIntervalFromNow(0); } @@ -240,7 +244,9 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { +#ifndef ARCH_PORTDUINO rtttl::begin(config.device.buzzer_gpio, pwmRingtone); +#endif } if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -276,7 +282,9 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { +#ifndef ARCH_PORTDUINO rtttl::begin(config.device.buzzer_gpio, pwmRingtone); +#endif } if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index 04de235cf..258078357 100644 --- a/src/modules/ExternalNotificationModule.h +++ b/src/modules/ExternalNotificationModule.h @@ -3,7 +3,9 @@ #include "SinglePortModule.h" #include "concurrency/OSThread.h" #include "configuration.h" +#ifndef ARCH_PORTDUINO #include +#endif #include #include From b134f0bb46270f8a178d853602c3d122908a7838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 15:45:46 +0100 Subject: [PATCH 082/119] missed one --- src/modules/ExternalNotificationModule.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index 1235524a4..be3e6cd8b 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -37,7 +37,11 @@ int32_t ExternalNotificationModule::runOnce() if (!moduleConfig.external_notification.enabled) { return INT32_MAX; // we don't need this thread here... } else { +#ifndef ARCH_PORTDUINO if ((nagCycleCutoff < millis()) && !rtttl::isPlaying()) { +#else + if (nagCycleCutoff < millis()) { +#endif nagCycleCutoff = UINT32_MAX; DEBUG_MSG("Turning off external notification: "); for (int i = 0; i < 2; i++) { From 259d442d8f932ac369bbedb584a79b3d4f55ff11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 15:50:47 +0100 Subject: [PATCH 083/119] how did that happen? --- platformio.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platformio.ini b/platformio.ini index 5f7f2dbac..e58656dd2 100644 --- a/platformio.ini +++ b/platformio.ini @@ -107,4 +107,5 @@ lib_deps = adafruit/Adafruit INA260 Library@^1.5.0 adafruit/Adafruit INA219@^1.2.0 adafruit/Adafruit SHTC3 Library@^1.0.0 - adafruit/Adafruit LPS2X@^2.0.4 adafruit/Adafruit SHT31 Library@^2.2.0 + adafruit/Adafruit LPS2X@^2.0.4 + adafruit/Adafruit SHT31 Library@^2.2.0 From ab6c4e61a6b61226f7e7c5d0aa5f0cd1783ef9f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Wed, 28 Dec 2022 16:20:23 +0100 Subject: [PATCH 084/119] Build and Check the SX1280 Boards too --- .github/workflows/main_matrix.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main_matrix.yml b/.github/workflows/main_matrix.yml index e10369465..1953619c8 100644 --- a/.github/workflows/main_matrix.yml +++ b/.github/workflows/main_matrix.yml @@ -32,7 +32,8 @@ jobs: - board: station-g1 - board: m5stack-coreink - board: tbeam-s3-core - + - board: tlora-t3s3-v1 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 @@ -53,6 +54,7 @@ jobs: - board: tlora-v1 - board: tlora_v1_3 - board: tlora-v2-1-1.6 + - board: tlora-v2-1-1.8 - board: tbeam - board: heltec-v1 - board: heltec-v2.0 @@ -67,6 +69,7 @@ jobs: - board: m5stack-core - board: m5stack-coreink - board: tbeam-s3-core + - board: tlora-t3s3-v1 uses: ./.github/workflows/build_esp32.yml with: board: ${{ matrix.board }} From 1736dada7da30734489eea732e3fe1b725c7fd59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 11:56:47 +0100 Subject: [PATCH 085/119] hotfix for user button. Also update version number on develop --- src/graphics/Screen.cpp | 2 +- version.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 7b34aee55..6c09c89cc 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -1072,7 +1072,7 @@ int32_t Screen::runOnce() break; case Cmd::ON_PRESS: // If a nag notification is running, stop it - if (externalNotificationModule->nagCycleCutoff != UINT32_MAX) { + if (moduleConfig.external_notification.enabled && (externalNotificationModule->nagCycleCutoff != UINT32_MAX)) { externalNotificationModule->stopNow(); } else { // Don't advance the screen if we just wanted to switch off the nag notification diff --git a/version.properties b/version.properties index 6a242ed9b..4ba2878d1 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 0 -build = 9 +build = 10 From d633212f70f4b49679a8427a7d873ef9fa39d766 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 14:11:57 +0100 Subject: [PATCH 086/119] 2.0.11-dev --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index 4ba2878d1..5c253336e 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 0 -build = 10 +build = 11 From 887405cc08ba91984c1204183dae6dd44e13a861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 14:18:33 +0100 Subject: [PATCH 087/119] update protobufs on develop --- protobufs | 2 +- src/mesh/generated/admin.pb.h | 22 +++++++++--- src/mesh/generated/config.pb.c | 1 + src/mesh/generated/config.pb.h | 32 ++++++++++++++--- src/mesh/generated/localonly.pb.h | 16 ++++++--- src/mesh/generated/module_config.pb.c | 3 ++ src/mesh/generated/module_config.pb.h | 25 +++++++++++++- src/mesh/generated/rtttl.pb.c | 12 +++++++ src/mesh/generated/rtttl.pb.h | 49 +++++++++++++++++++++++++++ 9 files changed, 147 insertions(+), 15 deletions(-) create mode 100644 src/mesh/generated/rtttl.pb.c create mode 100644 src/mesh/generated/rtttl.pb.h diff --git a/protobufs b/protobufs index 79e213fbc..e406029f6 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 79e213fbcc6f432923ab131bfa7b8630eb93270e +Subproject commit e406029f68d8a554f43fd1f250baca6b3c1a9a33 diff --git a/src/mesh/generated/admin.pb.h b/src/mesh/generated/admin.pb.h index cdc62c795..a00376f21 100644 --- a/src/mesh/generated/admin.pb.h +++ b/src/mesh/generated/admin.pb.h @@ -50,7 +50,9 @@ typedef enum _AdminMessage_ModuleConfigType { /* TODO: REPLACE */ AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG = 6, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7 + AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7, + /* TODO: REPLACE */ + AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG = 8 } AdminMessage_ModuleConfigType; /* Struct definitions */ @@ -85,6 +87,10 @@ typedef struct _AdminMessage { bool get_device_metadata_request; /* Device metadata response */ DeviceMetadata get_device_metadata_response; + /* Get the Ringtone in the response to this message. */ + bool get_ringtone_request; + /* Get the Ringtone in the response to this message. */ + char get_ringtone_response[231]; /* Set the owner for this node */ User set_owner; /* Set channels (using the new API). @@ -99,6 +105,8 @@ typedef struct _AdminMessage { ModuleConfig set_module_config; /* Set the Canned Message Module messages text. */ char set_canned_message_module_messages[201]; + /* Set the ringtone for ExternalNotification. */ + char set_ringtone_message[231]; /* Begins an edit transaction for config, module config, owner, and channel settings changes This will delay the standard *implicit* save to the file system and subsequent reboot behavior until committed (commit_edit_settings) */ bool begin_edit_settings; @@ -139,8 +147,8 @@ extern "C" { #define _AdminMessage_ConfigType_ARRAYSIZE ((AdminMessage_ConfigType)(AdminMessage_ConfigType_BLUETOOTH_CONFIG+1)) #define _AdminMessage_ModuleConfigType_MIN AdminMessage_ModuleConfigType_MQTT_CONFIG -#define _AdminMessage_ModuleConfigType_MAX AdminMessage_ModuleConfigType_AUDIO_CONFIG -#define _AdminMessage_ModuleConfigType_ARRAYSIZE ((AdminMessage_ModuleConfigType)(AdminMessage_ModuleConfigType_AUDIO_CONFIG+1)) +#define _AdminMessage_ModuleConfigType_MAX AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG +#define _AdminMessage_ModuleConfigType_ARRAYSIZE ((AdminMessage_ModuleConfigType)(AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG+1)) #define AdminMessage_payload_variant_get_config_request_ENUMTYPE AdminMessage_ConfigType #define AdminMessage_payload_variant_get_module_config_request_ENUMTYPE AdminMessage_ModuleConfigType @@ -163,11 +171,14 @@ extern "C" { #define AdminMessage_get_canned_message_module_messages_response_tag 11 #define AdminMessage_get_device_metadata_request_tag 12 #define AdminMessage_get_device_metadata_response_tag 13 +#define AdminMessage_get_ringtone_request_tag 14 +#define AdminMessage_get_ringtone_response_tag 15 #define AdminMessage_set_owner_tag 32 #define AdminMessage_set_channel_tag 33 #define AdminMessage_set_config_tag 34 #define AdminMessage_set_module_config_tag 35 #define AdminMessage_set_canned_message_module_messages_tag 36 +#define AdminMessage_set_ringtone_message_tag 37 #define AdminMessage_begin_edit_settings_tag 64 #define AdminMessage_commit_edit_settings_tag 65 #define AdminMessage_confirm_set_channel_tag 66 @@ -193,11 +204,14 @@ X(a, STATIC, ONEOF, BOOL, (payload_variant,get_canned_message_module_me X(a, STATIC, ONEOF, STRING, (payload_variant,get_canned_message_module_messages_response,get_canned_message_module_messages_response), 11) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,get_device_metadata_request,get_device_metadata_request), 12) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,get_device_metadata_response,get_device_metadata_response), 13) \ +X(a, STATIC, ONEOF, BOOL, (payload_variant,get_ringtone_request,get_ringtone_request), 14) \ +X(a, STATIC, ONEOF, STRING, (payload_variant,get_ringtone_response,get_ringtone_response), 15) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,set_owner,set_owner), 32) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,set_channel,set_channel), 33) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,set_config,set_config), 34) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,set_module_config,set_module_config), 35) \ X(a, STATIC, ONEOF, STRING, (payload_variant,set_canned_message_module_messages,set_canned_message_module_messages), 36) \ +X(a, STATIC, ONEOF, STRING, (payload_variant,set_ringtone_message,set_ringtone_message), 37) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,begin_edit_settings,begin_edit_settings), 64) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,commit_edit_settings,commit_edit_settings), 65) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,confirm_set_channel,confirm_set_channel), 66) \ @@ -226,7 +240,7 @@ extern const pb_msgdesc_t AdminMessage_msg; #define AdminMessage_fields &AdminMessage_msg /* Maximum encoded size of messages (where known) */ -#define AdminMessage_size 204 +#define AdminMessage_size 234 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/config.pb.c b/src/mesh/generated/config.pb.c index 8d1c55934..d43f4beae 100644 --- a/src/mesh/generated/config.pb.c +++ b/src/mesh/generated/config.pb.c @@ -43,3 +43,4 @@ PB_BIND(Config_BluetoothConfig, Config_BluetoothConfig, AUTO) + diff --git a/src/mesh/generated/config.pb.h b/src/mesh/generated/config.pb.h index 95252bb4e..a5f7694cb 100644 --- a/src/mesh/generated/config.pb.h +++ b/src/mesh/generated/config.pb.h @@ -108,6 +108,17 @@ typedef enum _Config_DisplayConfig_OledType { Config_DisplayConfig_OledType_OLED_SH1106 = 2 } Config_DisplayConfig_OledType; +typedef enum _Config_DisplayConfig_DisplayMode { + /* Default. The old style for the 128x64 OLED screen */ + Config_DisplayConfig_DisplayMode_DEFAULT = 0, + /* Rearrange display elements to cater for bicolor OLED displays */ + Config_DisplayConfig_DisplayMode_TWOCOLOR = 1, + /* Same as TwoColor, but with inverted top bar. Not so good for Epaper displays */ + Config_DisplayConfig_DisplayMode_INVERTED = 2, + /* TFT Full Color Displays (not implemented yet) */ + Config_DisplayConfig_DisplayMode_COLOR = 3 +} Config_DisplayConfig_DisplayMode; + typedef enum _Config_LoRaConfig_RegionCode { /* Region is not set */ Config_LoRaConfig_RegionCode_UNSET = 0, @@ -306,6 +317,10 @@ typedef struct _Config_DisplayConfig { Config_DisplayConfig_DisplayUnits units; /* Override auto-detect in screen */ Config_DisplayConfig_OledType oled; + /* Display Mode */ + Config_DisplayConfig_DisplayMode displaymode; + /* Print first line in pseudo-bold? FALSE is original style, TRUE is bold */ + bool heading_bold; } Config_DisplayConfig; /* Lora Config */ @@ -417,6 +432,10 @@ extern "C" { #define _Config_DisplayConfig_OledType_MAX Config_DisplayConfig_OledType_OLED_SH1106 #define _Config_DisplayConfig_OledType_ARRAYSIZE ((Config_DisplayConfig_OledType)(Config_DisplayConfig_OledType_OLED_SH1106+1)) +#define _Config_DisplayConfig_DisplayMode_MIN Config_DisplayConfig_DisplayMode_DEFAULT +#define _Config_DisplayConfig_DisplayMode_MAX Config_DisplayConfig_DisplayMode_COLOR +#define _Config_DisplayConfig_DisplayMode_ARRAYSIZE ((Config_DisplayConfig_DisplayMode)(Config_DisplayConfig_DisplayMode_COLOR+1)) + #define _Config_LoRaConfig_RegionCode_MIN Config_LoRaConfig_RegionCode_UNSET #define _Config_LoRaConfig_RegionCode_MAX Config_LoRaConfig_RegionCode_LORA_24 #define _Config_LoRaConfig_RegionCode_ARRAYSIZE ((Config_LoRaConfig_RegionCode)(Config_LoRaConfig_RegionCode_LORA_24+1)) @@ -440,6 +459,7 @@ extern "C" { #define Config_DisplayConfig_gps_format_ENUMTYPE Config_DisplayConfig_GpsCoordinateFormat #define Config_DisplayConfig_units_ENUMTYPE Config_DisplayConfig_DisplayUnits #define Config_DisplayConfig_oled_ENUMTYPE Config_DisplayConfig_OledType +#define Config_DisplayConfig_displaymode_ENUMTYPE Config_DisplayConfig_DisplayMode #define Config_LoRaConfig_modem_preset_ENUMTYPE Config_LoRaConfig_ModemPreset #define Config_LoRaConfig_region_ENUMTYPE Config_LoRaConfig_RegionCode @@ -454,7 +474,7 @@ extern "C" { #define Config_PowerConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0} #define Config_NetworkConfig_init_default {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_default} #define Config_NetworkConfig_IpV4Config_init_default {0, 0, 0, 0} -#define Config_DisplayConfig_init_default {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN} +#define Config_DisplayConfig_init_default {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} #define Config_LoRaConfig_init_default {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} #define Config_BluetoothConfig_init_default {0, _Config_BluetoothConfig_PairingMode_MIN, 0} #define Config_init_zero {0, {Config_DeviceConfig_init_zero}} @@ -463,7 +483,7 @@ extern "C" { #define Config_PowerConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0} #define Config_NetworkConfig_init_zero {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_zero} #define Config_NetworkConfig_IpV4Config_init_zero {0, 0, 0, 0} -#define Config_DisplayConfig_init_zero {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN} +#define Config_DisplayConfig_init_zero {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} #define Config_LoRaConfig_init_zero {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} #define Config_BluetoothConfig_init_zero {0, _Config_BluetoothConfig_PairingMode_MIN, 0} @@ -508,6 +528,8 @@ extern "C" { #define Config_DisplayConfig_flip_screen_tag 5 #define Config_DisplayConfig_units_tag 6 #define Config_DisplayConfig_oled_tag 7 +#define Config_DisplayConfig_displaymode_tag 8 +#define Config_DisplayConfig_heading_bold_tag 9 #define Config_LoRaConfig_use_preset_tag 1 #define Config_LoRaConfig_modem_preset_tag 2 #define Config_LoRaConfig_bandwidth_tag 3 @@ -612,7 +634,9 @@ X(a, STATIC, SINGULAR, UINT32, auto_screen_carousel_secs, 3) \ X(a, STATIC, SINGULAR, BOOL, compass_north_top, 4) \ X(a, STATIC, SINGULAR, BOOL, flip_screen, 5) \ X(a, STATIC, SINGULAR, UENUM, units, 6) \ -X(a, STATIC, SINGULAR, UENUM, oled, 7) +X(a, STATIC, SINGULAR, UENUM, oled, 7) \ +X(a, STATIC, SINGULAR, UENUM, displaymode, 8) \ +X(a, STATIC, SINGULAR, BOOL, heading_bold, 9) #define Config_DisplayConfig_CALLBACK NULL #define Config_DisplayConfig_DEFAULT NULL @@ -664,7 +688,7 @@ extern const pb_msgdesc_t Config_BluetoothConfig_msg; /* Maximum encoded size of messages (where known) */ #define Config_BluetoothConfig_size 10 #define Config_DeviceConfig_size 18 -#define Config_DisplayConfig_size 22 +#define Config_DisplayConfig_size 26 #define Config_LoRaConfig_size 70 #define Config_NetworkConfig_IpV4Config_size 20 #define Config_NetworkConfig_size 161 diff --git a/src/mesh/generated/localonly.pb.h b/src/mesh/generated/localonly.pb.h index 3f024d013..d2b9dfcae 100644 --- a/src/mesh/generated/localonly.pb.h +++ b/src/mesh/generated/localonly.pb.h @@ -69,6 +69,9 @@ typedef struct _LocalModuleConfig { /* The part of the config that is specific to the Audio module */ bool has_audio; ModuleConfig_AudioConfig audio; + /* The part of the config that is specific to the Remote Hardware module */ + bool has_remote_hardware; + ModuleConfig_RemoteHardwareConfig remote_hardware; } LocalModuleConfig; @@ -78,9 +81,9 @@ extern "C" { /* Initializer values for message structs */ #define LocalConfig_init_default {false, Config_DeviceConfig_init_default, false, Config_PositionConfig_init_default, false, Config_PowerConfig_init_default, false, Config_NetworkConfig_init_default, false, Config_DisplayConfig_init_default, false, Config_LoRaConfig_init_default, false, Config_BluetoothConfig_init_default, 0} -#define LocalModuleConfig_init_default {false, ModuleConfig_MQTTConfig_init_default, false, ModuleConfig_SerialConfig_init_default, false, ModuleConfig_ExternalNotificationConfig_init_default, false, ModuleConfig_StoreForwardConfig_init_default, false, ModuleConfig_RangeTestConfig_init_default, false, ModuleConfig_TelemetryConfig_init_default, false, ModuleConfig_CannedMessageConfig_init_default, 0, false, ModuleConfig_AudioConfig_init_default} +#define LocalModuleConfig_init_default {false, ModuleConfig_MQTTConfig_init_default, false, ModuleConfig_SerialConfig_init_default, false, ModuleConfig_ExternalNotificationConfig_init_default, false, ModuleConfig_StoreForwardConfig_init_default, false, ModuleConfig_RangeTestConfig_init_default, false, ModuleConfig_TelemetryConfig_init_default, false, ModuleConfig_CannedMessageConfig_init_default, 0, false, ModuleConfig_AudioConfig_init_default, false, ModuleConfig_RemoteHardwareConfig_init_default} #define LocalConfig_init_zero {false, Config_DeviceConfig_init_zero, false, Config_PositionConfig_init_zero, false, Config_PowerConfig_init_zero, false, Config_NetworkConfig_init_zero, false, Config_DisplayConfig_init_zero, false, Config_LoRaConfig_init_zero, false, Config_BluetoothConfig_init_zero, 0} -#define LocalModuleConfig_init_zero {false, ModuleConfig_MQTTConfig_init_zero, false, ModuleConfig_SerialConfig_init_zero, false, ModuleConfig_ExternalNotificationConfig_init_zero, false, ModuleConfig_StoreForwardConfig_init_zero, false, ModuleConfig_RangeTestConfig_init_zero, false, ModuleConfig_TelemetryConfig_init_zero, false, ModuleConfig_CannedMessageConfig_init_zero, 0, false, ModuleConfig_AudioConfig_init_zero} +#define LocalModuleConfig_init_zero {false, ModuleConfig_MQTTConfig_init_zero, false, ModuleConfig_SerialConfig_init_zero, false, ModuleConfig_ExternalNotificationConfig_init_zero, false, ModuleConfig_StoreForwardConfig_init_zero, false, ModuleConfig_RangeTestConfig_init_zero, false, ModuleConfig_TelemetryConfig_init_zero, false, ModuleConfig_CannedMessageConfig_init_zero, 0, false, ModuleConfig_AudioConfig_init_zero, false, ModuleConfig_RemoteHardwareConfig_init_zero} /* Field tags (for use in manual encoding/decoding) */ #define LocalConfig_device_tag 1 @@ -100,6 +103,7 @@ extern "C" { #define LocalModuleConfig_canned_message_tag 7 #define LocalModuleConfig_version_tag 8 #define LocalModuleConfig_audio_tag 9 +#define LocalModuleConfig_remote_hardware_tag 10 /* Struct field encoding specification for nanopb */ #define LocalConfig_FIELDLIST(X, a) \ @@ -130,7 +134,8 @@ X(a, STATIC, OPTIONAL, MESSAGE, range_test, 5) \ X(a, STATIC, OPTIONAL, MESSAGE, telemetry, 6) \ X(a, STATIC, OPTIONAL, MESSAGE, canned_message, 7) \ X(a, STATIC, SINGULAR, UINT32, version, 8) \ -X(a, STATIC, OPTIONAL, MESSAGE, audio, 9) +X(a, STATIC, OPTIONAL, MESSAGE, audio, 9) \ +X(a, STATIC, OPTIONAL, MESSAGE, remote_hardware, 10) #define LocalModuleConfig_CALLBACK NULL #define LocalModuleConfig_DEFAULT NULL #define LocalModuleConfig_mqtt_MSGTYPE ModuleConfig_MQTTConfig @@ -141,6 +146,7 @@ X(a, STATIC, OPTIONAL, MESSAGE, audio, 9) #define LocalModuleConfig_telemetry_MSGTYPE ModuleConfig_TelemetryConfig #define LocalModuleConfig_canned_message_MSGTYPE ModuleConfig_CannedMessageConfig #define LocalModuleConfig_audio_MSGTYPE ModuleConfig_AudioConfig +#define LocalModuleConfig_remote_hardware_MSGTYPE ModuleConfig_RemoteHardwareConfig extern const pb_msgdesc_t LocalConfig_msg; extern const pb_msgdesc_t LocalModuleConfig_msg; @@ -150,8 +156,8 @@ extern const pb_msgdesc_t LocalModuleConfig_msg; #define LocalModuleConfig_fields &LocalModuleConfig_msg /* Maximum encoded size of messages (where known) */ -#define LocalConfig_size 387 -#define LocalModuleConfig_size 376 +#define LocalConfig_size 391 +#define LocalModuleConfig_size 380 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/module_config.pb.c b/src/mesh/generated/module_config.pb.c index 7d7de956e..eb22a5ec3 100644 --- a/src/mesh/generated/module_config.pb.c +++ b/src/mesh/generated/module_config.pb.c @@ -12,6 +12,9 @@ PB_BIND(ModuleConfig, ModuleConfig, AUTO) PB_BIND(ModuleConfig_MQTTConfig, ModuleConfig_MQTTConfig, AUTO) +PB_BIND(ModuleConfig_RemoteHardwareConfig, ModuleConfig_RemoteHardwareConfig, AUTO) + + PB_BIND(ModuleConfig_AudioConfig, ModuleConfig_AudioConfig, AUTO) diff --git a/src/mesh/generated/module_config.pb.h b/src/mesh/generated/module_config.pb.h index 6d677fd41..da13ac706 100644 --- a/src/mesh/generated/module_config.pb.h +++ b/src/mesh/generated/module_config.pb.h @@ -98,6 +98,12 @@ typedef struct _ModuleConfig_MQTTConfig { bool json_enabled; } ModuleConfig_MQTTConfig; +/* RemoteHardwareModule Config */ +typedef struct _ModuleConfig_RemoteHardwareConfig { + /* Whether the Module is enabled */ + bool enabled; +} ModuleConfig_RemoteHardwareConfig; + /* Audio Config for codec2 voice */ typedef struct _ModuleConfig_AudioConfig { /* Whether Audio is enabled */ @@ -266,6 +272,8 @@ typedef struct _ModuleConfig { ModuleConfig_CannedMessageConfig canned_message; /* TODO: REPLACE */ ModuleConfig_AudioConfig audio; + /* TODO: REPLACE */ + ModuleConfig_RemoteHardwareConfig remote_hardware; } payload_variant; } ModuleConfig; @@ -293,6 +301,7 @@ extern "C" { + #define ModuleConfig_AudioConfig_bitrate_ENUMTYPE ModuleConfig_AudioConfig_Audio_Baud #define ModuleConfig_SerialConfig_baud_ENUMTYPE ModuleConfig_SerialConfig_Serial_Baud @@ -310,6 +319,7 @@ extern "C" { /* Initializer values for message structs */ #define ModuleConfig_init_default {0, {ModuleConfig_MQTTConfig_init_default}} #define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} +#define ModuleConfig_RemoteHardwareConfig_init_default {0} #define ModuleConfig_AudioConfig_init_default {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} @@ -319,6 +329,7 @@ extern "C" { #define ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} #define ModuleConfig_init_zero {0, {ModuleConfig_MQTTConfig_init_zero}} #define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} +#define ModuleConfig_RemoteHardwareConfig_init_zero {0} #define ModuleConfig_AudioConfig_init_zero {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} #define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} #define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} @@ -334,6 +345,7 @@ extern "C" { #define ModuleConfig_MQTTConfig_password_tag 4 #define ModuleConfig_MQTTConfig_encryption_enabled_tag 5 #define ModuleConfig_MQTTConfig_json_enabled_tag 6 +#define ModuleConfig_RemoteHardwareConfig_enabled_tag 1 #define ModuleConfig_AudioConfig_codec2_enabled_tag 1 #define ModuleConfig_AudioConfig_ptt_pin_tag 2 #define ModuleConfig_AudioConfig_bitrate_tag 3 @@ -394,6 +406,7 @@ extern "C" { #define ModuleConfig_telemetry_tag 6 #define ModuleConfig_canned_message_tag 7 #define ModuleConfig_audio_tag 8 +#define ModuleConfig_remote_hardware_tag 9 /* Struct field encoding specification for nanopb */ #define ModuleConfig_FIELDLIST(X, a) \ @@ -404,7 +417,8 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,store_forward,payload_varian X(a, STATIC, ONEOF, MESSAGE, (payload_variant,range_test,payload_variant.range_test), 5) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,telemetry,payload_variant.telemetry), 6) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,canned_message,payload_variant.canned_message), 7) \ -X(a, STATIC, ONEOF, MESSAGE, (payload_variant,audio,payload_variant.audio), 8) +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,audio,payload_variant.audio), 8) \ +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,remote_hardware,payload_variant.remote_hardware), 9) #define ModuleConfig_CALLBACK NULL #define ModuleConfig_DEFAULT NULL #define ModuleConfig_payload_variant_mqtt_MSGTYPE ModuleConfig_MQTTConfig @@ -415,6 +429,7 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,audio,payload_variant.audio) #define ModuleConfig_payload_variant_telemetry_MSGTYPE ModuleConfig_TelemetryConfig #define ModuleConfig_payload_variant_canned_message_MSGTYPE ModuleConfig_CannedMessageConfig #define ModuleConfig_payload_variant_audio_MSGTYPE ModuleConfig_AudioConfig +#define ModuleConfig_payload_variant_remote_hardware_MSGTYPE ModuleConfig_RemoteHardwareConfig #define ModuleConfig_MQTTConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ @@ -426,6 +441,11 @@ X(a, STATIC, SINGULAR, BOOL, json_enabled, 6) #define ModuleConfig_MQTTConfig_CALLBACK NULL #define ModuleConfig_MQTTConfig_DEFAULT NULL +#define ModuleConfig_RemoteHardwareConfig_FIELDLIST(X, a) \ +X(a, STATIC, SINGULAR, BOOL, enabled, 1) +#define ModuleConfig_RemoteHardwareConfig_CALLBACK NULL +#define ModuleConfig_RemoteHardwareConfig_DEFAULT NULL + #define ModuleConfig_AudioConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, codec2_enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, ptt_pin, 2) \ @@ -508,6 +528,7 @@ X(a, STATIC, SINGULAR, BOOL, send_bell, 11) extern const pb_msgdesc_t ModuleConfig_msg; extern const pb_msgdesc_t ModuleConfig_MQTTConfig_msg; +extern const pb_msgdesc_t ModuleConfig_RemoteHardwareConfig_msg; extern const pb_msgdesc_t ModuleConfig_AudioConfig_msg; extern const pb_msgdesc_t ModuleConfig_SerialConfig_msg; extern const pb_msgdesc_t ModuleConfig_ExternalNotificationConfig_msg; @@ -519,6 +540,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ #define ModuleConfig_fields &ModuleConfig_msg #define ModuleConfig_MQTTConfig_fields &ModuleConfig_MQTTConfig_msg +#define ModuleConfig_RemoteHardwareConfig_fields &ModuleConfig_RemoteHardwareConfig_msg #define ModuleConfig_AudioConfig_fields &ModuleConfig_AudioConfig_msg #define ModuleConfig_SerialConfig_fields &ModuleConfig_SerialConfig_msg #define ModuleConfig_ExternalNotificationConfig_fields &ModuleConfig_ExternalNotificationConfig_msg @@ -533,6 +555,7 @@ extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; #define ModuleConfig_ExternalNotificationConfig_size 40 #define ModuleConfig_MQTTConfig_size 169 #define ModuleConfig_RangeTestConfig_size 10 +#define ModuleConfig_RemoteHardwareConfig_size 2 #define ModuleConfig_SerialConfig_size 26 #define ModuleConfig_StoreForwardConfig_size 22 #define ModuleConfig_TelemetryConfig_size 18 diff --git a/src/mesh/generated/rtttl.pb.c b/src/mesh/generated/rtttl.pb.c new file mode 100644 index 000000000..960d1ebcd --- /dev/null +++ b/src/mesh/generated/rtttl.pb.c @@ -0,0 +1,12 @@ +/* Automatically generated nanopb constant definitions */ +/* Generated by nanopb-0.4.7 */ + +#include "rtttl.pb.h" +#if PB_PROTO_HEADER_VERSION != 40 +#error Regenerate this file with the current version of nanopb generator. +#endif + +PB_BIND(RTTTLConfig, RTTTLConfig, AUTO) + + + diff --git a/src/mesh/generated/rtttl.pb.h b/src/mesh/generated/rtttl.pb.h new file mode 100644 index 000000000..7c4de8f73 --- /dev/null +++ b/src/mesh/generated/rtttl.pb.h @@ -0,0 +1,49 @@ +/* Automatically generated nanopb header */ +/* Generated by nanopb-0.4.7 */ + +#ifndef PB_RTTTL_PB_H_INCLUDED +#define PB_RTTTL_PB_H_INCLUDED +#include + +#if PB_PROTO_HEADER_VERSION != 40 +#error Regenerate this file with the current version of nanopb generator. +#endif + +/* Struct definitions */ +/* Canned message module configuration. */ +typedef struct _RTTTLConfig { + /* Ringtone for PWM Buzzer in RTTTL Format. */ + char ringtone[230]; +} RTTTLConfig; + + +#ifdef __cplusplus +extern "C" { +#endif + +/* Initializer values for message structs */ +#define RTTTLConfig_init_default {""} +#define RTTTLConfig_init_zero {""} + +/* Field tags (for use in manual encoding/decoding) */ +#define RTTTLConfig_ringtone_tag 1 + +/* Struct field encoding specification for nanopb */ +#define RTTTLConfig_FIELDLIST(X, a) \ +X(a, STATIC, SINGULAR, STRING, ringtone, 1) +#define RTTTLConfig_CALLBACK NULL +#define RTTTLConfig_DEFAULT NULL + +extern const pb_msgdesc_t RTTTLConfig_msg; + +/* Defines for backwards compatibility with code written before nanopb-0.4.0 */ +#define RTTTLConfig_fields &RTTTLConfig_msg + +/* Maximum encoded size of messages (where known) */ +#define RTTTLConfig_size 232 + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif From 1a949b7ca6f56fef237d7169703c814fe1f9730d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 15:44:22 +0100 Subject: [PATCH 088/119] Plumbing for new display layout protos --- src/graphics/Screen.cpp | 130 ++++++++++++++++++++++++++++------------ 1 file changed, 93 insertions(+), 37 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 6c09c89cc..02159940a 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -376,10 +376,14 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state // be wrapped. Currently only spaces and "-" are allowed for wrapping display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(FONT_SMALL); - display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); - display->setColor(BLACK); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + } display->drawStringf(0 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); - display->drawStringf(1 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + if(config.display.heading_bold) { + display->drawStringf(1 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + } display->setColor(WHITE); snprintf(tempBuf, sizeof(tempBuf), "%s", mp.decoded.payload.bytes); display->drawStringMaxWidth(0 + x, 0 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), tempBuf); @@ -395,7 +399,7 @@ static void drawColumns(OLEDDisplay *display, int16_t x, int16_t y, const char * int xo = x, yo = y; while (*f) { display->drawString(xo, yo, *f); - if (display->getColor() == BLACK) + if ((display->getColor() == BLACK) && config.display.heading_bold) display->drawString(xo + 1, yo, *f); display->setColor(WHITE); @@ -473,7 +477,8 @@ static void drawNodes(OLEDDisplay *display, int16_t x, int16_t y, NodeStatus *no display->drawFastImage(x, y, 8, 8, imgUser); #endif display->drawString(x + 10, y - 2, usersString); - display->drawString(x + 11, y - 2, usersString); + if(config.display.heading_bold) + display->drawString(x + 11, y - 2, usersString); } // Draw GPS status summary @@ -482,18 +487,21 @@ static void drawGPS(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus if (config.position.fixed_position) { // GPS coordinates are currently fixed display->drawString(x - 1, y - 2, "Fixed GPS"); - display->drawString(x, y - 2, "Fixed GPS"); + if(config.display.heading_bold) + display->drawString(x, y - 2, "Fixed GPS"); return; } if (!gps->getIsConnected()) { display->drawString(x, y - 2, "No GPS"); - display->drawString(x + 1, y - 2, "No GPS"); + if(config.display.heading_bold) + display->drawString(x + 1, y - 2, "No GPS"); return; } display->drawFastImage(x, y, 6, 8, gps->getHasLock() ? imgPositionSolid : imgPositionEmpty); if (!gps->getHasLock()) { display->drawString(x + 8, y - 2, "No sats"); - display->drawString(x + 9, y - 2, "No sats"); + if(config.display.heading_bold) + display->drawString(x + 9, y - 2, "No sats"); return; } else { char satsString[3]; @@ -515,6 +523,8 @@ static void drawGPS(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus // Draw the number of satellites sprintf(satsString, "%u", gps->getNumSatellites()); display->drawString(x + 34, y - 2, satsString); + if(config.display.heading_bold) + display->drawString(x + 35, y - 2, satsString); } } @@ -697,17 +707,22 @@ static bool hasPosition(NodeInfo *n) static uint16_t getCompassDiam(OLEDDisplay *display) { uint16_t diam = 0; + uint16_t offset = 0; + + if (config.display.displaymode != Config_DisplayConfig_DisplayMode_DEFAULT) + offset = FONT_HEIGHT_SMALL; + // get the smaller of the 2 dimensions and subtract 20 - if(display->getWidth() > (display->getHeight() - FONT_HEIGHT_SMALL)) { - diam = display->getHeight() - FONT_HEIGHT_SMALL; + if(display->getWidth() > (display->getHeight() - offset)) { + diam = display->getHeight() - offset; // if 2/3 of the other size would be smaller, use that if (diam > (display->getWidth() * 2 / 3)) { diam = display->getWidth() * 2 / 3; } } else { diam = display->getWidth(); - if (diam > ((display->getHeight() - FONT_HEIGHT_SMALL) * 2 / 3)) { - diam = (display->getHeight() - FONT_HEIGHT_SMALL) * 2 / 3; + if (diam > ((display->getHeight() - offset) * 2 / 3)) { + diam = (display->getHeight() - offset) * 2 / 3; } } @@ -787,7 +802,9 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + } const char *username = node->has_user ? node->user.long_name : "Unknown Name"; @@ -817,9 +834,16 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ strcpy(distStr, "? km"); // might not have location data NodeInfo *ourNode = nodeDB.getNode(nodeDB.getNodeNum()); const char *fields[] = {username, distStr, signalStr, lastStr, NULL}; + int16_t compassX = 0, compassY = 0; // coordinates for the center of the compass/circle - int16_t compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5, compassY = y + FONT_HEIGHT_SMALL + (SCREEN_HEIGHT - FONT_HEIGHT_SMALL) / 2; + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5; + compassY = y + SCREEN_HEIGHT / 2; + } else { + compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5; + compassY = y + FONT_HEIGHT_SMALL + (SCREEN_HEIGHT - FONT_HEIGHT_SMALL) / 2; + } bool hasNodeHeading = false; if (ourNode && hasPosition(ourNode)) { @@ -855,14 +879,17 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ drawNodeHeading(display, compassX, compassY, bearingToOther); } } - if (!hasNodeHeading) + if (!hasNodeHeading) { // direction to node is unknown so display question mark // Debug info for gps lock errors // DEBUG_MSG("ourNode %d, ourPos %d, theirPos %d\n", !!ourNode, ourNode && hasPosition(ourNode), hasPosition(node)); display->drawString(compassX - FONT_HEIGHT_SMALL / 4, compassY - FONT_HEIGHT_SMALL / 2, "?"); + } display->drawCircle(compassX, compassY, getCompassDiam(display) / 2); - display->setColor(BLACK); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->setColor(BLACK); + } // Must be after distStr is populated drawColumns(display, x, y, fields); } @@ -1372,8 +1399,10 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); - display->setColor(BLACK); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + } char channelStr[20]; { @@ -1383,12 +1412,25 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 } // Display power status - if (powerStatus->getHasBattery()) - drawBattery(display, x + 1, y + 3, imgBattery, powerStatus); - else if (powerStatus->knowsUSB()) - display->drawFastImage(x + 1, y + 3, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); + if (powerStatus->getHasBattery()) { + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + drawBattery(display, x , y + 2, imgBattery, powerStatus); + } else { + drawBattery(display, x + 1, y + 3, imgBattery, powerStatus); + } + } else if (powerStatus->knowsUSB()) { + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + display->drawFastImage(x, y + 2, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); + } else { + display->drawFastImage(x + 1, y + 3, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); + } + } // Display nodes status - drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 3, nodeStatus); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 2, nodeStatus); + } else { + drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 3, nodeStatus); + } // Display GPS status if (!config.position.gps_enabled){ int16_t yPos = y + 2; @@ -1397,8 +1439,11 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 #endif drawGPSpowerstat(display, x, yPos, gpsStatus); } else { - drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 2, gpsStatus); - drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 3, gpsStatus); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 2, gpsStatus); + } else { + drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 3, gpsStatus); + } } display->setColor(WHITE); @@ -1458,23 +1503,29 @@ void DebugInfo::drawFrameWiFi(OLEDDisplay *display, OLEDDisplayUiState *state, i // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); - display->setColor(BLACK); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + } if (WiFi.status() != WL_CONNECTED) { display->drawString(x, y, String("WiFi: Not Connected")); - display->drawString(x + 1, y, String("WiFi: Not Connected")); + if(config.display.heading_bold) + display->drawString(x + 1, y, String("WiFi: Not Connected")); } else { display->drawString(x, y, String("WiFi: Connected")); - display->drawString(x + 1, y, String("WiFi: Connected")); + if(config.display.heading_bold) + display->drawString(x + 1, y, String("WiFi: Connected")); display->drawString(x + SCREEN_WIDTH - display->getStringWidth("RSSI " + String(WiFi.RSSI())), y, "RSSI " + String(WiFi.RSSI())); - display->drawString(x + SCREEN_WIDTH - display->getStringWidth("RSSI " + String(WiFi.RSSI())) - 1, y, - "RSSI " + String(WiFi.RSSI())); + if(config.display.heading_bold) { + display->drawString(x + SCREEN_WIDTH - display->getStringWidth("RSSI " + String(WiFi.RSSI())) - 1, y, + "RSSI " + String(WiFi.RSSI())); + } } - display->setColor(WHITE); + display->setColor(WHITE); /* - WL_CONNECTED: assigned when connected to a WiFi network; @@ -1584,8 +1635,10 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); - display->setColor(BLACK); + if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); + display->setColor(BLACK); + } char batStr[20]; if (powerStatus->getHasBattery()) { @@ -1597,11 +1650,13 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // Line 1 display->drawString(x, y, batStr); - display->drawString(x + 1, y, batStr); + if(config.display.heading_bold) + display->drawString(x + 1, y, batStr); } else { // Line 1 display->drawString(x, y, String("USB")); - display->drawString(x + 1, y, String("USB")); + if(config.display.heading_bold) + display->drawString(x + 1, y, String("USB")); } auto mode = ""; @@ -1634,7 +1689,8 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat } display->drawString(x + SCREEN_WIDTH - display->getStringWidth(mode), y, mode); - display->drawString(x + SCREEN_WIDTH - display->getStringWidth(mode) - 1, y, mode); + if(config.display.heading_bold) + display->drawString(x + SCREEN_WIDTH - display->getStringWidth(mode) - 1, y, mode); // Line 2 uint32_t currentMillis = millis(); From 41a1dfec7942448f5275f45f3cfbd22aeef7a7c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 15:45:49 +0100 Subject: [PATCH 089/119] a lot of thread housekeeping. Switch them off when not needed / disabled. --- src/input/RotaryEncoderInterruptBase.cpp | 2 +- src/input/RotaryEncoderInterruptBase.h | 2 +- src/input/RotaryEncoderInterruptImpl1.cpp | 2 + src/input/cardKbI2cImpl.cpp | 2 + src/input/kbI2cBase.h | 2 +- src/mesh/http/WebServer.cpp | 13 ++- src/modules/CannedMessageModule.cpp | 8 ++ src/modules/ExternalNotificationModule.cpp | 1 + src/modules/RemoteHardwareModule.cpp | 97 ++++++++++--------- src/modules/SerialModule.cpp | 4 +- .../Telemetry/EnvironmentTelemetry.cpp | 1 + src/modules/esp32/AudioModule.cpp | 3 + src/modules/esp32/RangeTestModule.cpp | 2 + src/modules/esp32/StoreForwardModule.cpp | 4 + src/mqtt/MQTT.cpp | 18 +++- 15 files changed, 102 insertions(+), 59 deletions(-) diff --git a/src/input/RotaryEncoderInterruptBase.cpp b/src/input/RotaryEncoderInterruptBase.cpp index 6914824fd..f6df7fb2c 100644 --- a/src/input/RotaryEncoderInterruptBase.cpp +++ b/src/input/RotaryEncoderInterruptBase.cpp @@ -54,7 +54,7 @@ int32_t RotaryEncoderInterruptBase::runOnce() this->action = ROTARY_ACTION_NONE; - return 30000; // TODO: technically this can be MAX_INT + return INT32_MAX; } void RotaryEncoderInterruptBase::intPressHandler() diff --git a/src/input/RotaryEncoderInterruptBase.h b/src/input/RotaryEncoderInterruptBase.h index c468f4dc6..88d619178 100644 --- a/src/input/RotaryEncoderInterruptBase.h +++ b/src/input/RotaryEncoderInterruptBase.h @@ -7,7 +7,7 @@ enum RotaryEncoderInterruptBaseStateType { ROTARY_EVENT_OCCURRED, ROTARY_EVENT_C enum RotaryEncoderInterruptBaseActionType { ROTARY_ACTION_NONE, ROTARY_ACTION_PRESSED, ROTARY_ACTION_CW, ROTARY_ACTION_CCW }; -class RotaryEncoderInterruptBase : public Observable, private concurrency::OSThread +class RotaryEncoderInterruptBase : public Observable, public concurrency::OSThread { public: explicit RotaryEncoderInterruptBase(const char *name); diff --git a/src/input/RotaryEncoderInterruptImpl1.cpp b/src/input/RotaryEncoderInterruptImpl1.cpp index bc897deef..f5fd6855a 100644 --- a/src/input/RotaryEncoderInterruptImpl1.cpp +++ b/src/input/RotaryEncoderInterruptImpl1.cpp @@ -9,6 +9,8 @@ void RotaryEncoderInterruptImpl1::init() { if (!moduleConfig.canned_message.rotary1_enabled) { // Input device is disabled. + setInterval(INT32_MAX); + enabled = false; return; } diff --git a/src/input/cardKbI2cImpl.cpp b/src/input/cardKbI2cImpl.cpp index de0fbbd38..4b4fc764b 100644 --- a/src/input/cardKbI2cImpl.cpp +++ b/src/input/cardKbI2cImpl.cpp @@ -13,6 +13,8 @@ void CardKbI2cImpl::init() if (cardkb_found != CARDKB_ADDR) { // Input device is not detected. + setInterval(INT32_MAX); + enabled = false; return; } diff --git a/src/input/kbI2cBase.h b/src/input/kbI2cBase.h index 086078cea..2fdacbc28 100644 --- a/src/input/kbI2cBase.h +++ b/src/input/kbI2cBase.h @@ -5,7 +5,7 @@ class KbI2cBase : public Observable, - private concurrency::OSThread + public concurrency::OSThread { public: explicit KbI2cBase(const char *name); diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index c1844b0cb..95850f5d8 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -165,11 +165,20 @@ void createSSLCert() WebServerThread *webServerThread; -WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") {} +WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") { + if(!config.network.wifi_enabled) { + setInterval(INT32_MAX); + enabled = false; + } +} int32_t WebServerThread::runOnce() { - // DEBUG_MSG("WebServerThread::runOnce()\n"); + if(!config.network.wifi_enabled) { + setInterval(INT32_MAX); + enabled = false; + } + handleWebResponse(); if (requestRestart && (millis() / 1000) > requestRestart) { diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index 4357ee2ca..a36e95a05 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -55,10 +55,18 @@ CannedMessageModule::CannedMessageModule() if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) { DEBUG_MSG("CannedMessageModule: No messages are configured. Module is disabled\n"); this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; + setInterval(INT32_MAX); + enabled = false; } else { DEBUG_MSG("CannedMessageModule is enabled\n"); this->inputObserver.observe(inputBroker); } + setInterval(INT32_MAX); + enabled = false; + } else { + this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; + setInterval(INT32_MAX); + enabled = false; } } diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index be3e6cd8b..8746f8048 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -199,6 +199,7 @@ ExternalNotificationModule::ExternalNotificationModule() } } else { DEBUG_MSG("External Notification Module Disabled\n"); + setInterval(INT32_MAX); enabled = false; } } diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 26f1c4dba..419885822 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -48,64 +48,66 @@ static uint64_t digitalReads(uint64_t mask) RemoteHardwareModule::RemoteHardwareModule() : ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, &HardwareMessage_msg), concurrency::OSThread( - "remotehardware") + "RemoteHardwareModule") { } bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr) { - auto p = *pptr; - DEBUG_MSG("Received RemoteHardware typ=%d\n", p.type); + if (moduleConfig.remote_hardware.enabled) { + auto p = *pptr; + DEBUG_MSG("Received RemoteHardware typ=%d\n", p.type); - switch (p.type) { - case HardwareMessage_Type_WRITE_GPIOS: - // Print notification to LCD screen - screen->print("Write GPIOs\n"); + switch (p.type) { + case HardwareMessage_Type_WRITE_GPIOS: + // Print notification to LCD screen + screen->print("Write GPIOs\n"); - for (uint8_t i = 0; i < NUM_GPIOS; i++) { - uint64_t mask = 1 << i; - if (p.gpio_mask & mask) { - digitalWrite(i, (p.gpio_value & mask) ? 1 : 0); + for (uint8_t i = 0; i < NUM_GPIOS; i++) { + uint64_t mask = 1 << i; + if (p.gpio_mask & mask) { + digitalWrite(i, (p.gpio_value & mask) ? 1 : 0); + } } + pinModes(p.gpio_mask, OUTPUT); + + break; + + case HardwareMessage_Type_READ_GPIOS: { + // Print notification to LCD screen + if (screen) + screen->print("Read GPIOs\n"); + + uint64_t res = digitalReads(p.gpio_mask); + + // Send the reply + HardwareMessage r = HardwareMessage_init_default; + r.type = HardwareMessage_Type_READ_GPIOS_REPLY; + r.gpio_value = res; + r.gpio_mask = p.gpio_mask; + MeshPacket *p2 = allocDataProtobuf(r); + setReplyTo(p2, req); + myReply = p2; + break; } - pinModes(p.gpio_mask, OUTPUT); - break; + case HardwareMessage_Type_WATCH_GPIOS: { + watchGpios = p.gpio_mask; + lastWatchMsec = 0; // Force a new publish soon + previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) + enabled = true; // Let our thread run at least once + DEBUG_MSG("Now watching GPIOs 0x%llx\n", watchGpios); + break; + } - case HardwareMessage_Type_READ_GPIOS: { - // Print notification to LCD screen - if (screen) - screen->print("Read GPIOs\n"); + case HardwareMessage_Type_READ_GPIOS_REPLY: + case HardwareMessage_Type_GPIOS_CHANGED: + break; // Ignore - we might see our own replies - uint64_t res = digitalReads(p.gpio_mask); - - // Send the reply - HardwareMessage r = HardwareMessage_init_default; - r.type = HardwareMessage_Type_READ_GPIOS_REPLY; - r.gpio_value = res; - r.gpio_mask = p.gpio_mask; - MeshPacket *p2 = allocDataProtobuf(r); - setReplyTo(p2, req); - myReply = p2; - break; - } - - case HardwareMessage_Type_WATCH_GPIOS: { - watchGpios = p.gpio_mask; - lastWatchMsec = 0; // Force a new publish soon - previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) - enabled = true; // Let our thread run at least once - DEBUG_MSG("Now watching GPIOs 0x%llx\n", watchGpios); - break; - } - - case HardwareMessage_Type_READ_GPIOS_REPLY: - case HardwareMessage_Type_GPIOS_CHANGED: - break; // Ignore - we might see our own replies - - default: - DEBUG_MSG("Hardware operation %d not yet implemented! FIXME\n", p.type); - break; + default: + DEBUG_MSG("Hardware operation %d not yet implemented! FIXME\n", p.type); + break; + } } return false; @@ -113,7 +115,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar int32_t RemoteHardwareModule::runOnce() { - if (watchGpios) { + if (moduleConfig.remote_hardware.enabled && watchGpios) { uint32_t now = millis(); if (now - lastWatchMsec >= WATCH_INTERVAL_MSEC) { @@ -134,6 +136,7 @@ int32_t RemoteHardwareModule::runOnce() } else { // No longer watching anything - stop using CPU enabled = false; + return INT32_MAX; } return 200; // Poll our GPIOs every 200ms (FIXME, make adjustable via protobuf arg) diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index eb8f0986b..00d8df9d2 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -222,6 +222,7 @@ int32_t SerialModule::runOnce() } else { DEBUG_MSG("Serial Module Disabled\n"); + enabled = false; return INT32_MAX; } } @@ -303,9 +304,6 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } } } - - } else { - DEBUG_MSG("Serial Module Disabled\n"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want } diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index 11955f3f6..500acd7f7 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -67,6 +67,7 @@ int32_t EnvironmentTelemetryModule::runOnce() if (!(moduleConfig.telemetry.environment_measurement_enabled || moduleConfig.telemetry.environment_screen_enabled)) { // If this module is not enabled, and the user doesn't want the display screen don't waste any OSThread time on it + enabled = false; return result; } diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index e7132fcc4..bd79be7cb 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -139,6 +139,8 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { + setInterval(INT32_MAX); + enabled = false; DEBUG_MSG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -259,6 +261,7 @@ int32_t AudioModule::runOnce() return 100; } else { DEBUG_MSG("Audio Module Disabled\n"); + enabled = false; return INT32_MAX; } diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index d706f8ed3..5e52fea40 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -82,6 +82,7 @@ int32_t RangeTestModule::runOnce() return (senderHeartbeat); } else { + enabled = false; return (INT32_MAX); // This thread does not need to run as a receiver } @@ -94,6 +95,7 @@ int32_t RangeTestModule::runOnce() } #endif + enabled = false; return (INT32_MAX); } diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 54a250d2a..ec1e3d695 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -52,6 +52,7 @@ int32_t StoreForwardModule::runOnce() return (this->packetTimeMax); } #endif + enabled = false; // Client doesn't need periodical return (INT32_MAX); } @@ -458,6 +459,9 @@ StoreForwardModule::StoreForwardModule() is_client = true; DEBUG_MSG("*** Initializing Store & Forward Module in Client mode\n"); } + } else { + setInterval(INT32_MAX); + enabled = false; } #endif } diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index df2d9b093..8dcf7eb90 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -128,12 +128,18 @@ void mqttInit() MQTT::MQTT() : concurrency::OSThread("mqtt"), pubSub(mqttClient), mqttQueue(MAX_MQTT_QUEUE) { - assert(!mqtt); - mqtt = this; + if(moduleConfig.mqtt.enabled) { - pubSub.setCallback(mqttCallback); + assert(!mqtt); + mqtt = this; - // preflightSleepObserver.observe(&preflightSleep); + pubSub.setCallback(mqttCallback); + + // preflightSleepObserver.observe(&preflightSleep); + } else { + setInterval(INT32_MAX); + enabled = false; + } } bool MQTT::connected() @@ -238,6 +244,10 @@ bool MQTT::wantsLink() const int32_t MQTT::runOnce() { + if(!moduleConfig.mqtt.enabled) { + enabled = false; + return INT32_MAX; + } bool wantConnection = wantsLink(); // If connected poll rapidly, otherwise only occasionally check for a wifi connection change and ability to contact server From 4e4a74379e1d042656ec7b56f0799d8bbc6d47dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 15:48:02 +0100 Subject: [PATCH 090/119] fix copy/paste error --- src/modules/CannedMessageModule.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index a36e95a05..74a4aaeaf 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -61,8 +61,6 @@ CannedMessageModule::CannedMessageModule() DEBUG_MSG("CannedMessageModule is enabled\n"); this->inputObserver.observe(inputBroker); } - setInterval(INT32_MAX); - enabled = false; } else { this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; setInterval(INT32_MAX); From 3c5710e65b5c6e1a812b342346391573bc2b922f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 16:53:36 +0100 Subject: [PATCH 091/119] - add storage for ringtone - Refactor file load and save - fix a size error in Canned Messages --- src/mesh/NodeDB.cpp | 4 +- src/mesh/NodeDB.h | 3 + src/modules/CannedMessageModule.cpp | 8 +-- src/modules/ExternalNotificationModule.cpp | 73 +++++++++++++++++++++- src/modules/ExternalNotificationModule.h | 5 +- 5 files changed, 81 insertions(+), 12 deletions(-) diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index b9107515f..f2139b82b 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -367,7 +367,7 @@ static const char *oemConfigFile = "/oem/oem.proto"; /** Load a protobuf from a file, return true for success */ -bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct) +bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct) { bool okay = false; #ifdef FSCom @@ -450,7 +450,7 @@ void NodeDB::loadFromDisk() } /** Save a protobuf from a file, return true for success */ -bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct) +bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct) { bool okay = false; #ifdef FSCom diff --git a/src/mesh/NodeDB.h b/src/mesh/NodeDB.h index 1622a57ff..991e577c7 100644 --- a/src/mesh/NodeDB.h +++ b/src/mesh/NodeDB.h @@ -125,6 +125,9 @@ class NodeDB bool factoryReset(); + bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct); + bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct); + private: /// Find a node in our DB, create an empty NodeInfo if missing NodeInfo *getOrCreateNode(NodeNum n); diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index 4357ee2ca..c0563f666 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -43,10 +43,6 @@ CannedMessageModuleConfig cannedMessageModuleConfig; CannedMessageModule *cannedMessageModule; -// TODO: move it into NodeDB.h! -extern bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct); -extern bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct); - CannedMessageModule::CannedMessageModule() : SinglePortModule("canned", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("CannedMessageModule") { @@ -478,7 +474,7 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st void CannedMessageModule::loadProtoForModule() { - if (!loadProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, sizeof(cannedMessagesConfigFile), + if (!nodeDB.loadProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, sizeof(CannedMessageModuleConfig), &CannedMessageModuleConfig_msg, &cannedMessageModuleConfig)) { installDefaultCannedMessageModuleConfig(); } @@ -498,7 +494,7 @@ bool CannedMessageModule::saveProtoForModule() FS.mkdir("/prefs"); #endif - okay &= saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, + okay &= nodeDB.saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, &CannedMessageModuleConfig_msg, &cannedMessageModuleConfig); return okay; diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index be3e6cd8b..c042aa966 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -5,6 +5,7 @@ #include "Router.h" #include "buzz/buzz.h" #include "configuration.h" +#include "mesh/generated/rtttl.pb.h" #include #ifndef PIN_BUZZER @@ -26,12 +27,16 @@ #define ASCII_BELL 0x07 +RTTTLConfig rtttlConfig; + ExternalNotificationModule *externalNotificationModule; bool externalCurrentState[3] = {}; uint32_t externalTurnedOn[3] = {}; +static const char *rtttlConfigFile = "/prefs/ringtone.proto"; + int32_t ExternalNotificationModule::runOnce() { if (!moduleConfig.external_notification.enabled) { @@ -81,7 +86,7 @@ int32_t ExternalNotificationModule::runOnce() rtttl::play(); } else if (nagCycleCutoff >= millis()) { // start the song again if we have time left - rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + rtttl::begin(config.device.buzzer_gpio, rtttlConfig.ringtone); } } #endif @@ -165,6 +170,10 @@ ExternalNotificationModule::ExternalNotificationModule() // moduleConfig.external_notification.nag_timeout = 300; if (moduleConfig.external_notification.enabled) { + if (!nodeDB.loadProto(rtttlConfigFile, RTTTLConfig_size, sizeof(RTTTLConfig), &RTTTLConfig_msg, &rtttlConfig)) { + memset(rtttlConfig.ringtone, 0, sizeof(rtttlConfig.ringtone)); + strncpy(rtttlConfig.ringtone, "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#", sizeof(rtttlConfig.ringtone)); + } DEBUG_MSG("Initializing External Notification Module\n"); @@ -249,7 +258,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) setExternalOn(2); } else { #ifndef ARCH_PORTDUINO - rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + rtttl::begin(config.device.buzzer_gpio, rtttlConfig.ringtone); #endif } if (moduleConfig.external_notification.nag_timeout) { @@ -287,7 +296,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) setExternalOn(2); } else { #ifndef ARCH_PORTDUINO - rtttl::begin(config.device.buzzer_gpio, pwmRingtone); + rtttl::begin(config.device.buzzer_gpio, rtttlConfig.ringtone); #endif } if (moduleConfig.external_notification.nag_timeout) { @@ -306,3 +315,61 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) return ProcessMessage::CONTINUE; // Let others look at this message also if they want } + +/** + * @brief An admin message arrived to AdminModule. We are asked whether we want to handle that. + * + * @param mp The mesh packet arrived. + * @param request The AdminMessage request extracted from the packet. + * @param response The prepared response + * @return AdminMessageHandleResult HANDLED if message was handled + * HANDLED_WITH_RESULT if a result is also prepared. + */ +AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) +{ + AdminMessageHandleResult result; + + switch (request->which_payload_variant) { + case AdminMessage_get_ringtone_request_tag: + DEBUG_MSG("Client is getting ringtone\n"); + this->handleGetRingtone(mp, response); + result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; + break; + + case AdminMessage_set_ringtone_message_tag: + DEBUG_MSG("Client is setting ringtone\n"); + this->handleSetRingtone(request->set_canned_message_module_messages); + result = AdminMessageHandleResult::HANDLED; + break; + + default: + result = AdminMessageHandleResult::NOT_HANDLED; + } + + return result; +} + +void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response) +{ + DEBUG_MSG("*** handleGetRingtone\n"); + assert(req.decoded.want_response); + + response->which_payload_variant = AdminMessage_get_ringtone_response_tag; + strcpy(response->get_ringtone_response, rtttlConfig.ringtone); +} + + +void ExternalNotificationModule::handleSetRingtone(const char *from_msg) +{ + int changed = 0; + + if (*from_msg) { + changed |= strcmp(rtttlConfig.ringtone, from_msg); + strcpy(rtttlConfig.ringtone, from_msg); + DEBUG_MSG("*** from_msg.text:%s\n", from_msg); + } + + if (changed) { + nodeDB.saveProto(rtttlConfigFile, RTTTLConfig_size, &RTTTLConfig_msg, &rtttlConfig); + } +} \ No newline at end of file diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index 258078357..50af360c1 100644 --- a/src/modules/ExternalNotificationModule.h +++ b/src/modules/ExternalNotificationModule.h @@ -28,7 +28,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: void stopNow(); - char pwmRingtone[Constants_DATA_PAYLOAD_LEN] = "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#"; + void handleGetRingtone(const MeshPacket &req, AdminMessage *response); + void handleSetRingtone(const char *from_msg); protected: /** Called to handle a particular incoming message @@ -37,6 +38,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: virtual ProcessMessage handleReceived(const MeshPacket &mp) override; virtual int32_t runOnce() override; + + virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override; }; extern ExternalNotificationModule *externalNotificationModule; From f73b8661de5ee28718b64180a641be35ad5dbcb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 21:34:18 +0100 Subject: [PATCH 092/119] Wait for 5 seconds for serial port on ESP32-S2/3 too... --- src/SerialConsole.cpp | 2 +- src/platform/esp32/main-esp32.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SerialConsole.cpp b/src/SerialConsole.cpp index e7355db29..0b6b9ee24 100644 --- a/src/SerialConsole.cpp +++ b/src/SerialConsole.cpp @@ -33,7 +33,7 @@ SerialConsole::SerialConsole() : StreamAPI(&Port), RedirectablePrint(&Port), con // setDestination(&noopPrint); for testing, try turning off 'all' debug output and see what leaks Port.begin(SERIAL_BAUD); -#ifdef ARCH_NRF52 +#if defined(ARCH_NRF52) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) time_t timeout = millis(); while (!Port) { if ((millis() - timeout) < 5000) { diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index e36a8cfd8..2fcdf9318 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -114,7 +114,7 @@ void esp32Setup() if (BLEOTA.isEmpty()) { DEBUG_MSG("No OTA firmware available\n"); }else{ - DEBUG_MSG("OTA firmware version %s\n", BLEOTA); + DEBUG_MSG("OTA firmware version %s\n", BLEOTA.c_str()); } // enableModemSleep(); From 45e6e86ff9e23df0efcce09bebf3f68c34279be1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 21:35:32 +0100 Subject: [PATCH 093/119] - add RemoteHardware (and the missing S&F config) in - make the config boundaries automatic --- src/mesh/PhoneAPI.cpp | 16 ++++++++++++---- src/modules/AdminModule.cpp | 12 +++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index b50f93bf0..ac134f352 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -171,7 +171,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Advance when we have sent all of our Channels if (config_state >= MAX_NUM_CHANNELS) { state = STATE_SEND_CONFIG; - config_state = Config_device_tag; + config_state = _AdminMessage_ConfigType_MIN + 1; } break; @@ -215,9 +215,9 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) config_state++; // Advance when we have sent all of our config objects - if (config_state > Config_bluetooth_tag) { + if (config_state > (_AdminMessage_ConfigType_MAX + 1)) { state = STATE_SEND_MODULECONFIG; - config_state = ModuleConfig_mqtt_tag; + config_state = _AdminMessage_ModuleConfigType_MIN + 1; } break; @@ -237,6 +237,10 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_external_notification_tag; fromRadioScratch.moduleConfig.payload_variant.external_notification = moduleConfig.external_notification; break; + case ModuleConfig_store_forward_tag: + fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_store_forward_tag; + fromRadioScratch.moduleConfig.payload_variant.store_forward = moduleConfig.store_forward; + break; case ModuleConfig_range_test_tag: fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_range_test_tag; fromRadioScratch.moduleConfig.payload_variant.range_test = moduleConfig.range_test; @@ -253,11 +257,15 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_audio_tag; fromRadioScratch.moduleConfig.payload_variant.audio = moduleConfig.audio; break; + case ModuleConfig_remote_hardware_tag: + fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_remote_hardware_tag; + fromRadioScratch.moduleConfig.payload_variant.remote_hardware = moduleConfig.remote_hardware; + break; } config_state++; // Advance when we have sent all of our ModuleConfig objects - if (config_state > ModuleConfig_audio_tag) { + if (config_state > (_AdminMessage_ModuleConfigType_MAX + 1)) { state = STATE_SEND_COMPLETE_ID; config_state = 0; } diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 2ed050f66..023cf7396 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -323,8 +323,13 @@ void AdminModule::handleSetModuleConfig(const ModuleConfig &c) moduleConfig.has_audio = true; moduleConfig.audio = c.payload_variant.audio; break; + case ModuleConfig_remote_hardware_tag: + DEBUG_MSG("Setting module config: Remote Hardware\n"); + moduleConfig.has_remote_hardware = true; + moduleConfig.remote_hardware = c.payload_variant.remote_hardware; + break; } - + saveChanges(SEGMENT_MODULECONFIG); } @@ -453,6 +458,11 @@ void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t co res.get_module_config_response.which_payload_variant = ModuleConfig_audio_tag; res.get_module_config_response.payload_variant.audio = moduleConfig.audio; break; + case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: + DEBUG_MSG("Getting module config: Remote Hardware\n"); + res.get_module_config_response.which_payload_variant = ModuleConfig_remote_hardware_tag; + res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware; + break; } // NOTE: The phone app needs to know the ls_secsvalue so it can properly expect sleep behavior. From a8f93d5f47392aed69e6ddcfd331ecdf9af3896b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 29 Dec 2022 22:42:05 +0100 Subject: [PATCH 094/119] Heap Debugging and Thread Disable --- src/concurrency/OSThread.cpp | 14 ++++++++++++++ src/concurrency/OSThread.h | 2 ++ 2 files changed, 16 insertions(+) diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 88c21d1c5..c5adf297b 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -74,8 +74,16 @@ bool OSThread::shouldRun(unsigned long time) void OSThread::run() { +#ifdef DEBUG_HEAP + auto heap = ESP.getFreeHeap(); +#endif currentThread = this; auto newDelay = runOnce(); +#ifdef DEBUG_HEAP + auto newHeap = ESP.getFreeHeap(); + if (newHeap < heap) + DEBUG_MSG("Thread %s leaked heap %d -> %d (%d)\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); +#endif runned(); @@ -85,6 +93,12 @@ void OSThread::run() currentThread = NULL; } +void OSThread::disable() { + enabled = false; + setInterval(INT32_MAX); + +} + /** * This flag is set **only** when setup() starts, to provide a way for us to check for sloppy static constructor calls. * Call assertIsSetup() to force a crash if someone tries to create an instance too early. diff --git a/src/concurrency/OSThread.h b/src/concurrency/OSThread.h index 7a86498b9..f0071c516 100644 --- a/src/concurrency/OSThread.h +++ b/src/concurrency/OSThread.h @@ -53,6 +53,8 @@ class OSThread : public Thread static void setup(); + void disable(); + /** * Wait a specified number msecs starting from the current time (rather than the last time we were run) */ From 38a1315599bbfd2c79fdae2f5456520aedb20f82 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 16:26:25 -0600 Subject: [PATCH 095/119] Refactor OSThread consumers to use disable() --- src/concurrency/OSThread.cpp | 4 ++-- src/input/RotaryEncoderInterruptImpl1.cpp | 3 +-- src/input/cardKbI2cImpl.cpp | 4 +--- src/mesh/http/WebServer.cpp | 10 ++++------ src/modules/CannedMessageModule.cpp | 6 ++---- src/modules/ExternalNotificationModule.cpp | 3 +-- src/modules/esp32/AudioModule.cpp | 3 +-- src/modules/esp32/StoreForwardModule.cpp | 3 +-- src/mqtt/MQTT.cpp | 3 +-- 9 files changed, 14 insertions(+), 25 deletions(-) diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index c5adf297b..53058de6a 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -93,10 +93,10 @@ void OSThread::run() currentThread = NULL; } -void OSThread::disable() { +void OSThread::disable() +{ enabled = false; setInterval(INT32_MAX); - } /** diff --git a/src/input/RotaryEncoderInterruptImpl1.cpp b/src/input/RotaryEncoderInterruptImpl1.cpp index f5fd6855a..7bf66ac55 100644 --- a/src/input/RotaryEncoderInterruptImpl1.cpp +++ b/src/input/RotaryEncoderInterruptImpl1.cpp @@ -9,8 +9,7 @@ void RotaryEncoderInterruptImpl1::init() { if (!moduleConfig.canned_message.rotary1_enabled) { // Input device is disabled. - setInterval(INT32_MAX); - enabled = false; + disable(); return; } diff --git a/src/input/cardKbI2cImpl.cpp b/src/input/cardKbI2cImpl.cpp index 4b4fc764b..3d30fb867 100644 --- a/src/input/cardKbI2cImpl.cpp +++ b/src/input/cardKbI2cImpl.cpp @@ -12,9 +12,7 @@ void CardKbI2cImpl::init() { if (cardkb_found != CARDKB_ADDR) { - // Input device is not detected. - setInterval(INT32_MAX); - enabled = false; + disable(); return; } diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index 95850f5d8..860c10219 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -166,17 +166,15 @@ void createSSLCert() WebServerThread *webServerThread; WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") { - if(!config.network.wifi_enabled) { - setInterval(INT32_MAX); - enabled = false; + if (!config.network.wifi_enabled) { + disable(); } } int32_t WebServerThread::runOnce() { - if(!config.network.wifi_enabled) { - setInterval(INT32_MAX); - enabled = false; + if (!config.network.wifi_enabled) { + disable(); } handleWebResponse(); diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index 74a4aaeaf..682d0efdb 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -55,16 +55,14 @@ CannedMessageModule::CannedMessageModule() if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) { DEBUG_MSG("CannedMessageModule: No messages are configured. Module is disabled\n"); this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; - setInterval(INT32_MAX); - enabled = false; + disable(); } else { DEBUG_MSG("CannedMessageModule is enabled\n"); this->inputObserver.observe(inputBroker); } } else { this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; - setInterval(INT32_MAX); - enabled = false; + disable(); } } diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index 8746f8048..f22bdf8f1 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -199,8 +199,7 @@ ExternalNotificationModule::ExternalNotificationModule() } } else { DEBUG_MSG("External Notification Module Disabled\n"); - setInterval(INT32_MAX); - enabled = false; + disable(); } } diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index bd79be7cb..25762aa3f 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -139,8 +139,7 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { - setInterval(INT32_MAX); - enabled = false; + disable(); DEBUG_MSG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index ec1e3d695..af0e60ed7 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -460,8 +460,7 @@ StoreForwardModule::StoreForwardModule() DEBUG_MSG("*** Initializing Store & Forward Module in Client mode\n"); } } else { - setInterval(INT32_MAX); - enabled = false; + disable(); } #endif } diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 8dcf7eb90..4cd6dcee4 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -137,8 +137,7 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), pubSub(mqttClient), mqttQueue(MAX_ // preflightSleepObserver.observe(&preflightSleep); } else { - setInterval(INT32_MAX); - enabled = false; + disable(); } } From 110c80d04585825e752ed3c585bbe986d194d114 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 16:54:39 -0600 Subject: [PATCH 096/119] Make disable return an int32_t for runOnce usage --- src/concurrency/OSThread.cpp | 4 +++- src/concurrency/OSThread.h | 2 +- src/modules/esp32/AudioModule.cpp | 3 +-- src/mqtt/MQTT.cpp | 3 +-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 53058de6a..4e6bf1b5f 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -93,10 +93,12 @@ void OSThread::run() currentThread = NULL; } -void OSThread::disable() +int32_t OSThread::disable() { enabled = false; setInterval(INT32_MAX); + + return INT32_MAX; } /** diff --git a/src/concurrency/OSThread.h b/src/concurrency/OSThread.h index f0071c516..aa8e3e2d8 100644 --- a/src/concurrency/OSThread.h +++ b/src/concurrency/OSThread.h @@ -53,7 +53,7 @@ class OSThread : public Thread static void setup(); - void disable(); + int32_t disable(); /** * Wait a specified number msecs starting from the current time (rather than the last time we were run) diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 25762aa3f..a0dffd0eb 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -260,8 +260,7 @@ int32_t AudioModule::runOnce() return 100; } else { DEBUG_MSG("Audio Module Disabled\n"); - enabled = false; - return INT32_MAX; + return disable(); } } diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 4cd6dcee4..08b16f287 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -244,8 +244,7 @@ bool MQTT::wantsLink() const int32_t MQTT::runOnce() { if(!moduleConfig.mqtt.enabled) { - enabled = false; - return INT32_MAX; + return disable(); } bool wantConnection = wantsLink(); From 979d12d6076e5a80e3166952b3093c191aba71d9 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 16:59:52 -0600 Subject: [PATCH 097/119] Here we go --- src/DebugConfiguration.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/DebugConfiguration.h b/src/DebugConfiguration.h index c1d95256e..0153b2449 100644 --- a/src/DebugConfiguration.h +++ b/src/DebugConfiguration.h @@ -19,11 +19,20 @@ #ifdef USE_SEGGER #define DEBUG_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define INFO_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define WARN_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define ERROR_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) #else #ifdef DEBUG_PORT #define DEBUG_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define INFO_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define WARN_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define ERROR_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) #else #define DEBUG_MSG(...) +#define INFO_MSG(...) +#define WARN_MSG(...) +#define ERROR_MSG(...) #endif #endif From c7c5671cca8e996a1b04465f71e39b51f40a3ca6 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 18:48:33 -0600 Subject: [PATCH 098/119] More disables --- src/modules/RemoteHardwareModule.cpp | 3 +-- src/modules/SerialModule.cpp | 4 +--- src/modules/Telemetry/EnvironmentTelemetry.cpp | 3 +-- src/modules/esp32/RangeTestModule.cpp | 3 +-- src/modules/esp32/StoreForwardModule.cpp | 3 +-- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 419885822..f8f2fecae 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -135,8 +135,7 @@ int32_t RemoteHardwareModule::runOnce() } } else { // No longer watching anything - stop using CPU - enabled = false; - return INT32_MAX; + return disable(); } return 200; // Poll our GPIOs every 200ms (FIXME, make adjustable via protobuf arg) diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 00d8df9d2..fc6448a97 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -221,9 +221,7 @@ int32_t SerialModule::runOnce() return (10); } else { DEBUG_MSG("Serial Module Disabled\n"); - - enabled = false; - return INT32_MAX; + return disable(); } } diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index 500acd7f7..b2b100257 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -67,8 +67,7 @@ int32_t EnvironmentTelemetryModule::runOnce() if (!(moduleConfig.telemetry.environment_measurement_enabled || moduleConfig.telemetry.environment_screen_enabled)) { // If this module is not enabled, and the user doesn't want the display screen don't waste any OSThread time on it - enabled = false; - return result; + return disable(); } if (firstTime) { diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index 5e52fea40..0aa25946d 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -82,8 +82,7 @@ int32_t RangeTestModule::runOnce() return (senderHeartbeat); } else { - enabled = false; - return (INT32_MAX); + return disable(); // This thread does not need to run as a receiver } diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index af0e60ed7..70a28ac68 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -52,8 +52,7 @@ int32_t StoreForwardModule::runOnce() return (this->packetTimeMax); } #endif - enabled = false; // Client doesn't need periodical - return (INT32_MAX); + return disable(); } /* From be91b08b3e0c594fa4b1310876053d0d76865909 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 18:49:40 -0600 Subject: [PATCH 099/119] Missed one --- src/modules/esp32/RangeTestModule.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index 0aa25946d..3db8e55ad 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -94,8 +94,7 @@ int32_t RangeTestModule::runOnce() } #endif - enabled = false; - return (INT32_MAX); + return disable(); } MeshPacket *RangeTestModuleRadio::allocReply() From 0b5cae53933d6d18b28a8ce3a3cb46938a320468 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Thu, 29 Dec 2022 20:41:37 -0600 Subject: [PATCH 100/119] Log levels refactoring --- src/ButtonThread.h | 22 ++-- src/DebugConfiguration.h | 29 ++-- src/FSCommon.cpp | 48 +++---- src/GPSStatus.h | 14 +- src/NodeStatus.h | 2 +- src/Power.cpp | 64 ++++----- src/PowerFSM.cpp | 34 ++--- src/PowerStatus.h | 2 +- src/RedirectablePrint.h | 3 - src/airtime.cpp | 16 +-- src/concurrency/InterruptableDelay.cpp | 4 +- src/concurrency/NotifiedWorkerThread.cpp | 6 +- src/concurrency/OSThread.cpp | 6 +- src/detect/axpDebug.h | 14 +- src/detect/einkScan.h | 4 +- src/detect/i2cScan.h | 84 ++++++------ src/gps/GPS.cpp | 60 ++++----- src/gps/NMEAGPS.cpp | 22 ++-- src/gps/RTC.cpp | 18 +-- src/graphics/EInkDisplay2.cpp | 8 +- src/graphics/Screen.cpp | 48 +++---- src/graphics/TFTDisplay.cpp | 2 +- src/input/RotaryEncoderInterruptBase.cpp | 10 +- src/input/UpDownInterruptBase.cpp | 8 +- src/input/kbI2cBase.cpp | 2 +- src/main.cpp | 46 +++---- src/memtest.cpp | 8 +- src/mesh/Channels.cpp | 20 +-- src/mesh/CryptoEngine.cpp | 6 +- src/mesh/FloodingRouter.cpp | 6 +- src/mesh/MeshModule.cpp | 26 ++-- src/mesh/MeshService.cpp | 18 +-- src/mesh/NodeDB.cpp | 90 ++++++------- src/mesh/PacketHistory.cpp | 8 +- src/mesh/PhoneAPI.cpp | 46 +++---- src/mesh/ProtobufModule.h | 6 +- src/mesh/RF95Interface.cpp | 16 +-- src/mesh/RadioInterface.cpp | 66 +++++----- src/mesh/RadioLibInterface.cpp | 52 ++++---- src/mesh/RadioLibRF95.cpp | 4 +- src/mesh/ReliableRouter.cpp | 18 +-- src/mesh/Router.cpp | 54 ++++---- src/mesh/SX126xInterface.cpp | 22 ++-- src/mesh/SX128xInterface.cpp | 18 +-- src/mesh/StreamAPI.cpp | 4 +- src/mesh/eth/ethClient.cpp | 32 ++--- src/mesh/eth/ethServerAPI.cpp | 8 +- src/mesh/http/ContentHandler.cpp | 42 +++--- src/mesh/http/WebServer.cpp | 38 +++--- src/mesh/http/WiFiAPClient.cpp | 108 +++++++-------- src/mesh/mesh-pb-constants.cpp | 6 +- src/mesh/wifi/WiFiServerAPI.cpp | 8 +- src/modules/AdminModule.cpp | 110 ++++++++-------- src/modules/CannedMessageModule.cpp | 46 +++---- src/modules/ExternalNotificationModule.cpp | 40 +++--- src/modules/NodeInfoModule.cpp | 6 +- src/modules/PositionModule.cpp | 20 +-- src/modules/RemoteHardwareModule.cpp | 8 +- src/modules/ReplyModule.cpp | 2 +- src/modules/SerialModule.cpp | 12 +- src/modules/Telemetry/DeviceTelemetry.cpp | 8 +- .../Telemetry/EnvironmentTelemetry.cpp | 12 +- src/modules/Telemetry/Sensor/BME280Sensor.cpp | 4 +- src/modules/Telemetry/Sensor/BME680Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/BMP280Sensor.cpp | 4 +- src/modules/Telemetry/Sensor/INA219Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/INA260Sensor.cpp | 2 +- .../Telemetry/Sensor/LPS22HBSensor.cpp | 2 +- .../Telemetry/Sensor/MCP9808Sensor.cpp | 4 +- src/modules/Telemetry/Sensor/SHT31Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/SHTC3Sensor.cpp | 2 +- .../Telemetry/Sensor/TelemetrySensor.h | 4 +- src/modules/TextMessageModule.cpp | 2 +- src/modules/TraceRouteModule.cpp | 10 +- src/modules/WaypointModule.cpp | 2 +- src/modules/esp32/AudioModule.cpp | 28 ++-- src/modules/esp32/RangeTestModule.cpp | 124 +++++++++--------- src/modules/esp32/StoreForwardModule.cpp | 76 +++++------ src/mqtt/MQTT.cpp | 62 ++++----- src/nimble/NimbleBluetooth.cpp | 20 +-- src/platform/esp32/ESP32CryptoEngine.cpp | 2 +- src/platform/esp32/main-esp32.cpp | 40 +++--- src/platform/nrf52/NRF52Bluetooth.cpp | 46 +++---- src/platform/nrf52/NRF52CryptoEngine.cpp | 4 +- src/platform/nrf52/hardfault.cpp | 2 +- src/platform/nrf52/main-nrf52.cpp | 16 +-- .../portduino/CrossPlatformCryptoEngine.cpp | 4 +- src/platform/portduino/SimRadio.cpp | 38 +++--- src/shutdown.h | 8 +- src/sleep.cpp | 22 ++-- 90 files changed, 1053 insertions(+), 1051 deletions(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 0e9830f3f..d1076c326 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -98,8 +98,8 @@ class ButtonThread : public concurrency::OSThread userButtonTouch.tick(); canSleep &= userButtonTouch.isIdle(); #endif - // if (!canSleep) DEBUG_MSG("Supressing sleep!\n"); - // else DEBUG_MSG("sleep ok\n"); + // if (!canSleep) LOG_DEBUG("Supressing sleep!\n"); + // else LOG_DEBUG("sleep ok\n"); return 5; } @@ -108,12 +108,12 @@ class ButtonThread : public concurrency::OSThread static void touchPressed() { screen->forceDisplay(); - DEBUG_MSG("touch press!\n"); + LOG_DEBUG("touch press!\n"); } static void userButtonPressed() { - // DEBUG_MSG("press!\n"); + // LOG_DEBUG("press!\n"); #ifdef BUTTON_PIN if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || !moduleConfig.canned_message.enabled) { @@ -123,7 +123,7 @@ class ButtonThread : public concurrency::OSThread } static void userButtonPressedLong() { - // DEBUG_MSG("Long press!\n"); + // LOG_DEBUG("Long press!\n"); #ifdef ARCH_ESP32 screen->adjustBrightness(); #endif @@ -139,7 +139,7 @@ class ButtonThread : public concurrency::OSThread // may wake the board immediatedly. if ((!shutdown_on_long_stop) && (millis() > 30 * 1000)) { screen->startShutdownScreen(); - DEBUG_MSG("Shutdown from long press"); + LOG_DEBUG("Shutdown from long press"); playBeep(); #ifdef PIN_LED1 ledOff(PIN_LED1); @@ -154,7 +154,7 @@ class ButtonThread : public concurrency::OSThread } #endif } else { - // DEBUG_MSG("Long press %u\n", (millis() - longPressTime)); + // LOG_DEBUG("Long press %u\n", (millis() - longPressTime)); } } @@ -166,11 +166,11 @@ class ButtonThread : public concurrency::OSThread #if defined(GPS_POWER_TOGGLE) if(config.position.gps_enabled) { - DEBUG_MSG("Flag set to false for gps power\n"); + LOG_DEBUG("Flag set to false for gps power\n"); } else { - DEBUG_MSG("Flag set to true to restore power\n"); + LOG_DEBUG("Flag set to true to restore power\n"); } config.position.gps_enabled = !(config.position.gps_enabled); doGPSpowersave(config.position.gps_enabled); @@ -187,7 +187,7 @@ class ButtonThread : public concurrency::OSThread static void userButtonPressedLongStart() { if (millis() > 30 * 1000) { - DEBUG_MSG("Long press start!\n"); + LOG_DEBUG("Long press start!\n"); longPressTime = millis(); } } @@ -195,7 +195,7 @@ class ButtonThread : public concurrency::OSThread static void userButtonPressedLongStop() { if (millis() > 30 * 1000) { - DEBUG_MSG("Long press stop!\n"); + LOG_DEBUG("Long press stop!\n"); longPressTime = 0; if (shutdown_on_long_stop) { playShutdownMelody(); diff --git a/src/DebugConfiguration.h b/src/DebugConfiguration.h index 0153b2449..f7733d5b1 100644 --- a/src/DebugConfiguration.h +++ b/src/DebugConfiguration.h @@ -13,26 +13,31 @@ #define SERIAL_BAUD 115200 // Serial debug baud rate #endif +#define LOG_LEVEL_DEBUG "DEBUG" +#define LOG_LEVEL_INFO "INFO " +#define LOG_LEVEL_WARN "WARN " +#define LOG_LEVEL_ERROR "ERROR" + #include "SerialConsole.h" #define DEBUG_PORT (*console) // Serial debug port #ifdef USE_SEGGER -#define DEBUG_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) -#define INFO_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) -#define WARN_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) -#define ERROR_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define LOG_DEBUG(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define LOG_INFO(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define LOG_WARN(...) SEGGER_RTT_printf(0, __VA_ARGS__) +#define LOG_ERROR(...) SEGGER_RTT_printf(0, __VA_ARGS__) #else #ifdef DEBUG_PORT -#define DEBUG_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define INFO_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define WARN_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define ERROR_MSG(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define LOG_DEBUG(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define LOG_INFO(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define LOG_WARN(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define LOG_ERROR(...) DEBUG_PORT.logDebug(__VA_ARGS__) #else -#define DEBUG_MSG(...) -#define INFO_MSG(...) -#define WARN_MSG(...) -#define ERROR_MSG(...) +#define LOG_DEBUG(...) +#define LOG_INFO(...) +#define LOG_WARN(...) +#define LOG_ERROR(...) #endif #endif diff --git a/src/FSCommon.cpp b/src/FSCommon.cpp index 56e551047..2f901d26a 100644 --- a/src/FSCommon.cpp +++ b/src/FSCommon.cpp @@ -21,13 +21,13 @@ bool copyFile(const char* from, const char* to) File f1 = FSCom.open(from, FILE_O_READ); if (!f1){ - DEBUG_MSG("Failed to open source file %s\n", from); + LOG_DEBUG("Failed to open source file %s\n", from); return false; } File f2 = FSCom.open(to, FILE_O_WRITE); if (!f2) { - DEBUG_MSG("Failed to open destination file %s\n", to); + LOG_DEBUG("Failed to open destination file %s\n", to); return false; } @@ -79,7 +79,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) #ifdef ARCH_ESP32 listDir(file.path(), levels -1, del); if(del) { - DEBUG_MSG("Removing %s\n", file.path()); + LOG_DEBUG("Removing %s\n", file.path()); strcpy(buffer, file.path()); file.close(); FSCom.rmdir(buffer); @@ -89,7 +89,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) listDir(file.name(), levels -1, del); if(del) { - DEBUG_MSG("Removing %s\n", file.name()); + LOG_DEBUG("Removing %s\n", file.name()); strcpy(buffer, file.name()); file.close(); FSCom.rmdir(buffer); @@ -104,26 +104,26 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) } else { #ifdef ARCH_ESP32 if(del) { - DEBUG_MSG("Deleting %s\n", file.path()); + LOG_DEBUG("Deleting %s\n", file.path()); strcpy(buffer, file.path()); file.close(); FSCom.remove(buffer); } else { - DEBUG_MSG(" %s (%i Bytes)\n", file.path(), file.size()); + LOG_DEBUG(" %s (%i Bytes)\n", file.path(), file.size()); file.close(); } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) if(del) { - DEBUG_MSG("Deleting %s\n", file.name()); + LOG_DEBUG("Deleting %s\n", file.name()); strcpy(buffer, file.name()); file.close(); FSCom.remove(buffer); } else { - DEBUG_MSG(" %s (%i Bytes)\n", file.name(), file.size()); + LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size()); file.close(); } #else - DEBUG_MSG(" %s (%i Bytes)\n", file.name(), file.size()); + LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size()); file.close(); #endif } @@ -131,7 +131,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) } #ifdef ARCH_ESP32 if(del) { - DEBUG_MSG("Removing %s\n", root.path()); + LOG_DEBUG("Removing %s\n", root.path()); strcpy(buffer, root.path()); root.close(); FSCom.rmdir(buffer); @@ -140,7 +140,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) if(del) { - DEBUG_MSG("Removing %s\n", root.name()); + LOG_DEBUG("Removing %s\n", root.name()); strcpy(buffer, root.name()); root.close(); FSCom.rmdir(buffer); @@ -170,13 +170,13 @@ void fsInit() #ifdef FSCom if (!FSBegin()) { - DEBUG_MSG("ERROR filesystem mount Failed. Formatting...\n"); + LOG_DEBUG("ERROR filesystem mount Failed. Formatting...\n"); assert(0); // FIXME - report failure to phone } #ifdef ARCH_ESP32 - DEBUG_MSG("Filesystem files (%d/%d Bytes):\n", FSCom.usedBytes(), FSCom.totalBytes()); + LOG_DEBUG("Filesystem files (%d/%d Bytes):\n", FSCom.usedBytes(), FSCom.totalBytes()); #else - DEBUG_MSG("Filesystem files:\n"); + LOG_DEBUG("Filesystem files:\n"); #endif listDir("/", 10); #endif @@ -189,29 +189,29 @@ void setupSDCard() SDHandler.begin(SPI_SCK, SPI_MISO, SPI_MOSI); if (!SD.begin(SDCARD_CS, SDHandler)) { - DEBUG_MSG("No SD_MMC card detected\n"); + LOG_DEBUG("No SD_MMC card detected\n"); return ; } uint8_t cardType = SD.cardType(); if (cardType == CARD_NONE) { - DEBUG_MSG("No SD_MMC card attached\n"); + LOG_DEBUG("No SD_MMC card attached\n"); return ; } - DEBUG_MSG("SD_MMC Card Type: "); + LOG_DEBUG("SD_MMC Card Type: "); if (cardType == CARD_MMC) { - DEBUG_MSG("MMC\n"); + LOG_DEBUG("MMC\n"); } else if (cardType == CARD_SD) { - DEBUG_MSG("SDSC\n"); + LOG_DEBUG("SDSC\n"); } else if (cardType == CARD_SDHC) { - DEBUG_MSG("SDHC\n"); + LOG_DEBUG("SDHC\n"); } else { - DEBUG_MSG("UNKNOWN\n"); + LOG_DEBUG("UNKNOWN\n"); } uint64_t cardSize = SD.cardSize() / (1024 * 1024); - DEBUG_MSG("SD Card Size: %lluMB\n", cardSize); - DEBUG_MSG("Total space: %llu MB\n", SD.totalBytes() / (1024 * 1024)); - DEBUG_MSG("Used space: %llu MB\n", SD.usedBytes() / (1024 * 1024)); + LOG_DEBUG("SD Card Size: %lluMB\n", cardSize); + LOG_DEBUG("Total space: %llu MB\n", SD.totalBytes() / (1024 * 1024)); + LOG_DEBUG("Used space: %llu MB\n", SD.usedBytes() / (1024 * 1024)); #endif } diff --git a/src/GPSStatus.h b/src/GPSStatus.h index ef97c59b7..9ada4e66e 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -53,7 +53,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("WARNING: Using fixed latitude\n"); + LOG_WARN("Using fixed latitude\n"); #endif NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.latitude_i; @@ -66,7 +66,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("WARNING: Using fixed longitude\n"); + LOG_WARN("Using fixed longitude\n"); #endif NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.longitude_i; @@ -79,7 +79,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("WARNING: Using fixed altitude\n"); + LOG_WARN("Using fixed altitude\n"); #endif NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.altitude; @@ -97,7 +97,7 @@ class GPSStatus : public Status bool matches(const GPSStatus *newStatus) const { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("GPSStatus.match() new pos@%x to old pos@%x\n", newStatus->p.pos_timestamp, p.pos_timestamp); + LOG_DEBUG("GPSStatus.match() new pos@%x to old pos@%x\n", newStatus->p.pos_timestamp, p.pos_timestamp); #endif return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || newStatus->isPowerSaving !=isPowerSaving || newStatus->p.latitude_i != p.latitude_i || newStatus->p.longitude_i != p.longitude_i || @@ -114,7 +114,7 @@ class GPSStatus : public Status if (isDirty && p.timestamp && (newStatus->p.timestamp == p.timestamp)) { // We can NEVER be in two locations at the same time! (also PR #886) - DEBUG_MSG("BUG!! positional timestamp unchanged from prev solution\n"); + LOG_DEBUG("BUG!! positional timestamp unchanged from prev solution\n"); } initialized = true; @@ -126,11 +126,11 @@ class GPSStatus : public Status if (isDirty) { if (hasLock) { // In debug logs, identify position by @timestamp:stage (stage 3 = notify) - DEBUG_MSG("New GPS pos@%x:3 lat=%f, lon=%f, alt=%d, pdop=%.2f, track=%.2f, speed=%.2f, sats=%d\n", p.timestamp, + LOG_DEBUG("New GPS pos@%x:3 lat=%f, lon=%f, alt=%d, pdop=%.2f, track=%.2f, speed=%.2f, sats=%d\n", p.timestamp, p.latitude_i * 1e-7, p.longitude_i * 1e-7, p.altitude, p.PDOP * 1e-2, p.ground_track * 1e-5, p.ground_speed * 1e-2, p.sats_in_view); } else - DEBUG_MSG("No GPS lock\n"); + LOG_DEBUG("No GPS lock\n"); onNewStatus.notifyObservers(this); } return 0; diff --git a/src/NodeStatus.h b/src/NodeStatus.h index dc567fd2f..7c0477cf6 100644 --- a/src/NodeStatus.h +++ b/src/NodeStatus.h @@ -70,7 +70,7 @@ namespace meshtastic { numTotal = newStatus->getNumTotal(); } if(isDirty || newStatus->forceUpdate) { - DEBUG_MSG("Node status update: %d online, %d total\n", numOnline, numTotal); + LOG_DEBUG("Node status update: %d online, %d total\n", numOnline, numTotal); onNewStatus.notifyObservers(this); } return 0; diff --git a/src/Power.cpp b/src/Power.cpp index d2c5b01a0..bba21549b 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -129,7 +129,7 @@ class AnalogBatteryLevel : public HasBatteryLevel #else scaled = VBAT_RAW_TO_SCALED(raw); // defined in variant.h #endif - // DEBUG_MSG("battery gpio %d raw val=%u scaled=%u\n", BATTERY_PIN, raw, (uint32_t)(scaled)); + // LOG_DEBUG("battery gpio %d raw val=%u scaled=%u\n", BATTERY_PIN, raw, (uint32_t)(scaled)); last_read_value = scaled; return scaled; } else { @@ -190,7 +190,7 @@ Power::Power() : OSThread("Power") bool Power::analogInit() { #ifdef BATTERY_PIN - DEBUG_MSG("Using analog input %d for battery level\n", BATTERY_PIN); + LOG_DEBUG("Using analog input %d for battery level\n", BATTERY_PIN); // disable any internal pullups pinMode(BATTERY_PIN, INPUT); @@ -242,7 +242,7 @@ void Power::shutdown() #endif #ifdef HAS_PMU - DEBUG_MSG("Shutting down\n"); + LOG_DEBUG("Shutting down\n"); if(PMU) { PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF); PMU->shutdown(); @@ -283,12 +283,12 @@ void Power::readPowerStatus() const PowerStatus powerStatus2 = PowerStatus(hasBattery ? OptTrue : OptFalse, batteryLevel->isVbusIn() ? OptTrue : OptFalse, batteryLevel->isCharging() ? OptTrue : OptFalse, batteryVoltageMv, batteryChargePercent); - DEBUG_MSG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d\n", powerStatus2.getHasUSB(), + LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d\n", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP if (lastheap != ESP.getFreeHeap()){ - DEBUG_MSG("Heap status: %d/%d bytes free (%d), running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap , concurrency::mainController.size(false)); + LOG_DEBUG("Heap status: %d/%d bytes free (%d), running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap , concurrency::mainController.size(false)); lastheap = ESP.getFreeHeap(); } #endif @@ -299,11 +299,11 @@ void Power::readPowerStatus() if (powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) { if (batteryLevel->getBattVoltage() < MIN_BAT_MILLIVOLTS) { low_voltage_counter++; - DEBUG_MSG("Warning RAK4631 Low voltage counter: %d/10\n", low_voltage_counter); + LOG_DEBUG("Warning RAK4631 Low voltage counter: %d/10\n", low_voltage_counter); if (low_voltage_counter > 10) { // We can't trigger deep sleep on NRF52, it's freezing the board //powerFSM.trigger(EVENT_LOW_BATTERY); - DEBUG_MSG("Low voltage detected, but not triggering deep sleep\n"); + LOG_DEBUG("Low voltage detected, but not triggering deep sleep\n"); } } else { low_voltage_counter = 0; @@ -333,12 +333,12 @@ int32_t Power::runOnce() PMU->getIrqStatus(); if(PMU->isVbusRemoveIrq()){ - DEBUG_MSG("USB unplugged\n"); + LOG_DEBUG("USB unplugged\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } if (PMU->isVbusInsertIrq()) { - DEBUG_MSG("USB plugged In\n"); + LOG_DEBUG("USB plugged In\n"); powerFSM.trigger(EVENT_POWER_CONNECTED); } @@ -346,20 +346,20 @@ int32_t Power::runOnce() Other things we could check if we cared... if (PMU->isBatChagerStartIrq()) { - DEBUG_MSG("Battery start charging\n"); + LOG_DEBUG("Battery start charging\n"); } if (PMU->isBatChagerDoneIrq()) { - DEBUG_MSG("Battery fully charged\n"); + LOG_DEBUG("Battery fully charged\n"); } if (PMU->isBatInsertIrq()) { - DEBUG_MSG("Battery inserted\n"); + LOG_DEBUG("Battery inserted\n"); } if (PMU->isBatRemoveIrq()) { - DEBUG_MSG("Battery removed\n"); + LOG_DEBUG("Battery removed\n"); } */ if (PMU->isPekeyLongPressIrq()) { - DEBUG_MSG("PEK long button press\n"); + LOG_DEBUG("PEK long button press\n"); screen->setOn(false); } @@ -401,22 +401,22 @@ bool Power::axpChipInit() if (!PMU) { PMU = new XPowersAXP2101(*w); if (!PMU->init()) { - DEBUG_MSG("Warning: Failed to find AXP2101 power management\n"); + LOG_WARN("Failed to find AXP2101 power management\n"); delete PMU; PMU = NULL; } else { - DEBUG_MSG("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); + LOG_DEBUG("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); } } if (!PMU) { PMU = new XPowersAXP192(*w); if (!PMU->init()) { - DEBUG_MSG("Warning: Failed to find AXP192 power management\n"); + LOG_WARN("Failed to find AXP192 power management\n"); delete PMU; PMU = NULL; } else { - DEBUG_MSG("AXP192 PMU init succeeded, using AXP192 PMU\n"); + LOG_DEBUG("AXP192 PMU init succeeded, using AXP192 PMU\n"); } } @@ -538,44 +538,44 @@ bool Power::axpChipInit() PMU->enableVbusVoltageMeasure(); PMU->enableBattVoltageMeasure(); - DEBUG_MSG("=======================================================================\n"); + LOG_DEBUG("=======================================================================\n"); if (PMU->isChannelAvailable(XPOWERS_DCDC1)) { - DEBUG_MSG("DC1 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC1)); + LOG_DEBUG("DC1 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC1)); } if (PMU->isChannelAvailable(XPOWERS_DCDC2)) { - DEBUG_MSG("DC2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC2)); + LOG_DEBUG("DC2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC2)); } if (PMU->isChannelAvailable(XPOWERS_DCDC3)) { - DEBUG_MSG("DC3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC3)); + LOG_DEBUG("DC3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC3)); } if (PMU->isChannelAvailable(XPOWERS_DCDC4)) { - DEBUG_MSG("DC4 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC4)); + LOG_DEBUG("DC4 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC4)); } if (PMU->isChannelAvailable(XPOWERS_LDO2)) { - DEBUG_MSG("LDO2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO2)); + LOG_DEBUG("LDO2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO2)); } if (PMU->isChannelAvailable(XPOWERS_LDO3)) { - DEBUG_MSG("LDO3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO3)); + LOG_DEBUG("LDO3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO3)); } if (PMU->isChannelAvailable(XPOWERS_ALDO1)) { - DEBUG_MSG("ALDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO1)); + LOG_DEBUG("ALDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO1)); } if (PMU->isChannelAvailable(XPOWERS_ALDO2)) { - DEBUG_MSG("ALDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO2)); + LOG_DEBUG("ALDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO2)); } if (PMU->isChannelAvailable(XPOWERS_ALDO3)) { - DEBUG_MSG("ALDO3: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO3)); + LOG_DEBUG("ALDO3: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO3)); } if (PMU->isChannelAvailable(XPOWERS_ALDO4)) { - DEBUG_MSG("ALDO4: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO4)); + LOG_DEBUG("ALDO4: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO4)); } if (PMU->isChannelAvailable(XPOWERS_BLDO1)) { - DEBUG_MSG("BLDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO1)); + LOG_DEBUG("BLDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO1)); } if (PMU->isChannelAvailable(XPOWERS_BLDO2)) { - DEBUG_MSG("BLDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO2)); + LOG_DEBUG("BLDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO2)); } - DEBUG_MSG("=======================================================================\n"); + LOG_DEBUG("=======================================================================\n"); // We can safely ignore this approach for most (or all) boards because MCU turned off // earlier than battery discharged to 2.6V. diff --git a/src/PowerFSM.cpp b/src/PowerFSM.cpp index 5bea8d796..f35e755ca 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -32,7 +32,7 @@ static bool isPowered() static void sdsEnter() { - DEBUG_MSG("Enter state: SDS\n"); + LOG_DEBUG("Enter state: SDS\n"); // FIXME - make sure GPS and LORA radio are off first - because we want close to zero current draw doDeepSleep(getConfiguredOrDefaultMs(config.power.sds_secs)); } @@ -41,7 +41,7 @@ extern Power *power; static void shutdownEnter() { - DEBUG_MSG("Enter state: SHUTDOWN\n"); + LOG_DEBUG("Enter state: SHUTDOWN\n"); power->shutdown(); } @@ -51,16 +51,16 @@ static uint32_t secsSlept; static void lsEnter() { - DEBUG_MSG("lsEnter begin, ls_secs=%u\n", config.power.ls_secs); + LOG_DEBUG("lsEnter begin, ls_secs=%u\n", config.power.ls_secs); screen->setOn(false); secsSlept = 0; // How long have we been sleeping this time - // DEBUG_MSG("lsEnter end\n"); + // LOG_DEBUG("lsEnter end\n"); } static void lsIdle() { - // DEBUG_MSG("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); + // LOG_DEBUG("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); #ifdef ARCH_ESP32 @@ -82,7 +82,7 @@ static void lsIdle() wakeCause2 = doLightSleep(1); // leave led on for 1ms secsSlept += sleepTime; - // DEBUG_MSG("sleeping, flash led!\n"); + // LOG_DEBUG("sleeping, flash led!\n"); break; case ESP_SLEEP_WAKEUP_UART: @@ -93,7 +93,7 @@ static void lsIdle() default: // We woke for some other reason (button press, device interrupt) // uint64_t status = esp_sleep_get_ext1_wakeup_status(); - DEBUG_MSG("wakeCause2 %d\n", wakeCause2); + LOG_DEBUG("wakeCause2 %d\n", wakeCause2); #ifdef BUTTON_PIN bool pressed = !digitalRead(BUTTON_PIN); @@ -117,7 +117,7 @@ static void lsIdle() } else { // Time to stop sleeping! setLed(false); - DEBUG_MSG("reached ls_secs, servicing loop()\n"); + LOG_DEBUG("reached ls_secs, servicing loop()\n"); powerFSM.trigger(EVENT_WAKE_TIMER); } #endif @@ -125,7 +125,7 @@ static void lsIdle() static void lsExit() { - DEBUG_MSG("Exit state: LS\n"); + LOG_DEBUG("Exit state: LS\n"); // setGPSPower(true); // restore GPS power if (gps) gps->forceWake(true); @@ -133,7 +133,7 @@ static void lsExit() static void nbEnter() { - DEBUG_MSG("Enter state: NB\n"); + LOG_DEBUG("Enter state: NB\n"); screen->setOn(false); setBluetoothEnable(false); @@ -148,7 +148,7 @@ static void darkEnter() static void serialEnter() { - DEBUG_MSG("Enter state: SERIAL\n"); + LOG_DEBUG("Enter state: SERIAL\n"); setBluetoothEnable(false); screen->setOn(true); screen->print("Serial connected\n"); @@ -161,10 +161,10 @@ static void serialExit() static void powerEnter() { - DEBUG_MSG("Enter state: POWER\n"); + LOG_DEBUG("Enter state: POWER\n"); if (!isPowered()) { // If we got here, we are in the wrong state - we should be in powered, let that state ahndle things - DEBUG_MSG("Loss of power in Powered\n"); + LOG_DEBUG("Loss of power in Powered\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } else { screen->setOn(true); @@ -177,7 +177,7 @@ static void powerIdle() { if (!isPowered()) { // If we got here, we are in the wrong state - DEBUG_MSG("Loss of power in Powered\n"); + LOG_DEBUG("Loss of power in Powered\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } } @@ -191,7 +191,7 @@ static void powerExit() static void onEnter() { - DEBUG_MSG("Enter state: ON\n"); + LOG_DEBUG("Enter state: ON\n"); screen->setOn(true); setBluetoothEnable(true); @@ -221,7 +221,7 @@ static void screenPress() static void bootEnter() { - DEBUG_MSG("Enter state: BOOT\n"); + LOG_DEBUG("Enter state: BOOT\n"); } State stateSHUTDOWN(shutdownEnter, NULL, NULL, "SHUTDOWN"); @@ -240,7 +240,7 @@ void PowerFSM_setup() bool isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER ? 1 : 0); bool hasPower = isPowered(); - DEBUG_MSG("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); + LOG_DEBUG("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); powerFSM.add_timed_transition(&stateBOOT, hasPower ? &statePOWER : &stateON, 3 * 1000, NULL, "boot timeout"); // wake timer expired or a packet arrived diff --git a/src/PowerStatus.h b/src/PowerStatus.h index a276be59b..56d19b758 100644 --- a/src/PowerStatus.h +++ b/src/PowerStatus.h @@ -82,7 +82,7 @@ class PowerStatus : public Status isCharging = newStatus->isCharging; } if (isDirty) { - // DEBUG_MSG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent); + // LOG_DEBUG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent); onNewStatus.notifyObservers(this); } return 0; diff --git a/src/RedirectablePrint.h b/src/RedirectablePrint.h index b2081d046..9443d1672 100644 --- a/src/RedirectablePrint.h +++ b/src/RedirectablePrint.h @@ -33,9 +33,6 @@ class RedirectablePrint : public Print * If the provide format string ends with a newline we assume it is the final print of a single * log message. Otherwise we assume more prints will come before the log message ends. This * allows you to call logDebug a few times to build up a single log message line if you wish. - * - * FIXME, eventually add log levels (INFO, WARN, ERROR) and subsystems. Move into - * a different class. */ size_t logDebug(const char * format, ...) __attribute__ ((format (printf, 2, 3))); diff --git a/src/airtime.cpp b/src/airtime.cpp index 1c2fb3233..c72a21d54 100644 --- a/src/airtime.cpp +++ b/src/airtime.cpp @@ -10,18 +10,18 @@ void AirTime::logAirtime(reportTypes reportType, uint32_t airtime_ms) { if (reportType == TX_LOG) { - DEBUG_MSG("AirTime - Packet transmitted : %ums\n", airtime_ms); + LOG_DEBUG("AirTime - Packet transmitted : %ums\n", airtime_ms); this->airtimes.periodTX[0] = this->airtimes.periodTX[0] + airtime_ms; myNodeInfo.air_period_tx[0] = myNodeInfo.air_period_tx[0] + airtime_ms; this->utilizationTX[this->getPeriodUtilHour()] = this->utilizationTX[this->getPeriodUtilHour()] + airtime_ms; } else if (reportType == RX_LOG) { - DEBUG_MSG("AirTime - Packet received : %ums\n", airtime_ms); + LOG_DEBUG("AirTime - Packet received : %ums\n", airtime_ms); this->airtimes.periodRX[0] = this->airtimes.periodRX[0] + airtime_ms; myNodeInfo.air_period_rx[0] = myNodeInfo.air_period_rx[0] + airtime_ms; } else if (reportType == RX_ALL_LOG) { - DEBUG_MSG("AirTime - Packet received (noise?) : %ums\n", airtime_ms); + LOG_DEBUG("AirTime - Packet received (noise?) : %ums\n", airtime_ms); this->airtimes.periodRX_ALL[0] = this->airtimes.periodRX_ALL[0] + airtime_ms; } @@ -46,7 +46,7 @@ void AirTime::airtimeRotatePeriod() { if (this->airtimes.lastPeriodIndex != this->currentPeriodIndex()) { - DEBUG_MSG("Rotating airtimes to a new period = %u\n", this->currentPeriodIndex()); + LOG_DEBUG("Rotating airtimes to a new period = %u\n", this->currentPeriodIndex()); for (int i = PERIODS_TO_LOG - 2; i >= 0; --i) { this->airtimes.periodTX[i + 1] = this->airtimes.periodTX[i]; @@ -101,7 +101,7 @@ float AirTime::channelUtilizationPercent() uint32_t sum = 0; for (uint32_t i = 0; i < CHANNEL_UTILIZATION_PERIODS; i++) { sum += this->channelUtilization[i]; - // DEBUG_MSG("ChanUtilArray %u %u\n", i, this->channelUtilization[i]); + // LOG_DEBUG("ChanUtilArray %u %u\n", i, this->channelUtilization[i]); } return (float(sum) / float(CHANNEL_UTILIZATION_PERIODS * 10 * 1000)) * 100; @@ -189,13 +189,13 @@ int32_t AirTime::runOnce() myNodeInfo.air_util_tx = airTime->utilizationTXPercent(); } /* - DEBUG_MSG("utilPeriodTX %d TX Airtime %3.2f%\n", utilPeriodTX, airTime->utilizationTXPercent()); + LOG_DEBUG("utilPeriodTX %d TX Airtime %3.2f%\n", utilPeriodTX, airTime->utilizationTXPercent()); for (uint32_t i = 0; i < MINUTES_IN_HOUR; i++) { - DEBUG_MSG( + LOG_DEBUG( "%d,", this->utilizationTX[i] ); } - DEBUG_MSG("\n"); + LOG_DEBUG("\n"); */ return (1000 * 1); } diff --git a/src/concurrency/InterruptableDelay.cpp b/src/concurrency/InterruptableDelay.cpp index fa664e7bb..7bddea68d 100644 --- a/src/concurrency/InterruptableDelay.cpp +++ b/src/concurrency/InterruptableDelay.cpp @@ -13,12 +13,12 @@ InterruptableDelay::~InterruptableDelay() {} */ bool InterruptableDelay::delay(uint32_t msec) { - // DEBUG_MSG("delay %u ", msec); + // LOG_DEBUG("delay %u ", msec); // sem take will return false if we timed out (i.e. were not interrupted) bool r = semaphore.take(msec); - // DEBUG_MSG("interrupt=%d\n", r); + // LOG_DEBUG("interrupt=%d\n", r); return !r; } diff --git a/src/concurrency/NotifiedWorkerThread.cpp b/src/concurrency/NotifiedWorkerThread.cpp index 9be2bc90d..ac6428f07 100644 --- a/src/concurrency/NotifiedWorkerThread.cpp +++ b/src/concurrency/NotifiedWorkerThread.cpp @@ -33,11 +33,11 @@ IRAM_ATTR bool NotifiedWorkerThread::notifyCommon(uint32_t v, bool overwrite) notification = v; if (debugNotification) - DEBUG_MSG("setting notification %d\n", v); + LOG_DEBUG("setting notification %d\n", v); return true; } else { if (debugNotification) - DEBUG_MSG("dropping notification %d\n", v); + LOG_DEBUG("dropping notification %d\n", v); return false; } } @@ -66,7 +66,7 @@ bool NotifiedWorkerThread::notifyLater(uint32_t delay, uint32_t v, bool overwrit if (didIt) { // If we didn't already have something queued, override the delay to be larger setIntervalFromNow(delay); // a new version of setInterval relative to the current time if (debugNotification) - DEBUG_MSG("delaying notification %u\n", delay); + LOG_DEBUG("delaying notification %u\n", delay); } return didIt; diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 88c21d1c5..560a5cb69 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -61,13 +61,13 @@ bool OSThread::shouldRun(unsigned long time) bool r = Thread::shouldRun(time); if (showRun && r) - DEBUG_MSG("Thread %s: run\n", ThreadName.c_str()); + LOG_DEBUG("Thread %s: run\n", ThreadName.c_str()); if (showWaiting && enabled && !r) - DEBUG_MSG("Thread %s: wait %lu\n", ThreadName.c_str(), interval); + LOG_DEBUG("Thread %s: wait %lu\n", ThreadName.c_str(), interval); if (showDisabled && !enabled) - DEBUG_MSG("Thread %s: disabled\n", ThreadName.c_str()); + LOG_DEBUG("Thread %s: disabled\n", ThreadName.c_str()); return r; } diff --git a/src/detect/axpDebug.h b/src/detect/axpDebug.h index 28e3ee26e..fc95447aa 100644 --- a/src/detect/axpDebug.h +++ b/src/detect/axpDebug.h @@ -3,13 +3,13 @@ uint32_t axpDebugRead() { axp.debugCharging(); - DEBUG_MSG("vbus current %f\n", axp.getVbusCurrent()); - DEBUG_MSG("charge current %f\n", axp.getBattChargeCurrent()); - DEBUG_MSG("bat voltage %f\n", axp.getBattVoltage()); - DEBUG_MSG("batt pct %d\n", axp.getBattPercentage()); - DEBUG_MSG("is battery connected %d\n", axp.isBatteryConnect()); - DEBUG_MSG("is USB connected %d\n", axp.isVBUSPlug()); - DEBUG_MSG("is charging %d\n", axp.isChargeing()); + LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent()); + LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent()); + LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage()); + LOG_DEBUG("batt pct %d\n", axp.getBattPercentage()); + LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect()); + LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug()); + LOG_DEBUG("is charging %d\n", axp.isChargeing()); return 30 * 1000; } diff --git a/src/detect/einkScan.h b/src/detect/einkScan.h index a2509a45a..dd2bf01c2 100644 --- a/src/detect/einkScan.h +++ b/src/detect/einkScan.h @@ -52,9 +52,9 @@ void scanEInkDevice(void) d_writeCommand(0x20); eink_found = (d_waitWhileBusy(150) > 0) ? true : false; if(eink_found) - DEBUG_MSG("EInk display found\n"); + LOG_DEBUG("EInk display found\n"); else - DEBUG_MSG("EInk display not found\n"); + LOG_DEBUG("EInk display not found\n"); SPI1.end(); } #endif diff --git a/src/detect/i2cScan.h b/src/detect/i2cScan.h index 940ebb100..f2ebc18b8 100644 --- a/src/detect/i2cScan.h +++ b/src/detect/i2cScan.h @@ -15,30 +15,30 @@ void printATECCInfo() #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) atecc.readConfigZone(false); - DEBUG_MSG("ATECC608B Serial Number: "); + LOG_DEBUG("ATECC608B Serial Number: "); for (int i = 0 ; i < 9 ; i++) { - DEBUG_MSG("%02x",atecc.serialNumber[i]); + LOG_DEBUG("%02x",atecc.serialNumber[i]); } - DEBUG_MSG(", Rev Number: "); + LOG_DEBUG(", Rev Number: "); for (int i = 0 ; i < 4 ; i++) { - DEBUG_MSG("%02x",atecc.revisionNumber[i]); + LOG_DEBUG("%02x",atecc.revisionNumber[i]); } - DEBUG_MSG("\n"); + LOG_DEBUG("\n"); - DEBUG_MSG("ATECC608B Config %s",atecc.configLockStatus ? "Locked" : "Unlocked"); - DEBUG_MSG(", Data %s",atecc.dataOTPLockStatus ? "Locked" : "Unlocked"); - DEBUG_MSG(", Slot 0 %s\n",atecc.slot0LockStatus ? "Locked" : "Unlocked"); + LOG_DEBUG("ATECC608B Config %s",atecc.configLockStatus ? "Locked" : "Unlocked"); + LOG_DEBUG(", Data %s",atecc.dataOTPLockStatus ? "Locked" : "Unlocked"); + LOG_DEBUG(", Slot 0 %s\n",atecc.slot0LockStatus ? "Locked" : "Unlocked"); if (atecc.configLockStatus && atecc.dataOTPLockStatus && atecc.slot0LockStatus) { if (atecc.generatePublicKey() == false) { - DEBUG_MSG("ATECC608B Error generating public key\n"); + LOG_DEBUG("ATECC608B Error generating public key\n"); } else { - DEBUG_MSG("ATECC608B Public Key: "); + LOG_DEBUG("ATECC608B Public Key: "); for (int i = 0 ; i < 64 ; i++) { - DEBUG_MSG("%02x",atecc.publicKey64Bytes[i]); + LOG_DEBUG("%02x",atecc.publicKey64Bytes[i]); } - DEBUG_MSG("\n"); + LOG_DEBUG("\n"); } } #endif @@ -51,7 +51,7 @@ uint16_t getRegisterValue(uint8_t address, uint8_t reg, uint8_t length) { Wire.endTransmission(); delay(20); Wire.requestFrom(address, length); - DEBUG_MSG("Wire.available() = %d\n", Wire.available()); + LOG_DEBUG("Wire.available() = %d\n", Wire.available()); if (Wire.available() == 2) { // Read MSB, then LSB value = (uint16_t)Wire.read() << 8; @@ -86,7 +86,7 @@ uint8_t oled_probe(byte addr) } c++; } while ((r != r_prev) && (c < 4)); - DEBUG_MSG("0x%x subtype probed in %i tries \n", r, c); + LOG_DEBUG("0x%x subtype probed in %i tries \n", r, c); return o_probe; } @@ -99,7 +99,7 @@ void scanI2Cdevice() Wire.beginTransmission(addr); err = Wire.endTransmission(); if (err == 0) { - DEBUG_MSG("I2C device found at address 0x%x\n", addr); + LOG_DEBUG("I2C device found at address 0x%x\n", addr); nDevices++; @@ -107,20 +107,20 @@ void scanI2Cdevice() screen_found = addr; screen_model = oled_probe(addr); if (screen_model == 1) { - DEBUG_MSG("ssd1306 display found\n"); + LOG_DEBUG("ssd1306 display found\n"); } else if (screen_model == 2) { - DEBUG_MSG("sh1106 display found\n"); + LOG_DEBUG("sh1106 display found\n"); } else { - DEBUG_MSG("unknown display found\n"); + LOG_DEBUG("unknown display found\n"); } } #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) if (addr == ATECC608B_ADDR) { keystore_found = addr; if (atecc.begin(keystore_found) == true) { - DEBUG_MSG("ATECC608B initialized\n"); + LOG_DEBUG("ATECC608B initialized\n"); } else { - DEBUG_MSG("ATECC608B initialization failed\n"); + LOG_DEBUG("ATECC608B initialization failed\n"); } printATECCInfo(); } @@ -128,7 +128,7 @@ void scanI2Cdevice() #ifdef RV3028_RTC if (addr == RV3028_RTC){ rtc_found = addr; - DEBUG_MSG("RV3028 RTC found\n"); + LOG_DEBUG("RV3028 RTC found\n"); Melopero_RV3028 rtc; rtc.initI2C(); rtc.writeToRegister(0x35,0x07); // no Clkout @@ -138,7 +138,7 @@ void scanI2Cdevice() #ifdef PCF8563_RTC if (addr == PCF8563_RTC){ rtc_found = addr; - DEBUG_MSG("PCF8563 RTC found\n"); + LOG_DEBUG("PCF8563 RTC found\n"); } #endif if (addr == CARDKB_ADDR) { @@ -146,86 +146,86 @@ void scanI2Cdevice() // Do we have the RAK14006 instead? registerValue = getRegisterValue(addr, 0x04, 1); if (registerValue == 0x02) { // KEYPAD_VERSION - DEBUG_MSG("RAK14004 found\n"); + LOG_DEBUG("RAK14004 found\n"); kb_model = 0x02; } else { - DEBUG_MSG("m5 cardKB found\n"); + LOG_DEBUG("m5 cardKB found\n"); kb_model = 0x00; } } if (addr == ST7567_ADDRESS) { screen_found = addr; - DEBUG_MSG("st7567 display found\n"); + LOG_DEBUG("st7567 display found\n"); } #ifdef HAS_PMU if (addr == XPOWERS_AXP192_AXP2101_ADDRESS) { pmu_found = true; - DEBUG_MSG("axp192/axp2101 PMU found\n"); + LOG_DEBUG("axp192/axp2101 PMU found\n"); } #endif if (addr == BME_ADDR || addr == BME_ADDR_ALTERNATE) { registerValue = getRegisterValue(addr, 0xD0, 1); // GET_ID if (registerValue == 0x61) { - DEBUG_MSG("BME-680 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_DEBUG("BME-680 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BME680] = addr; } else if (registerValue == 0x60) { - DEBUG_MSG("BME-280 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_DEBUG("BME-280 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BME280] = addr; } else { - DEBUG_MSG("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_DEBUG("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BMP280] = addr; } } if (addr == INA_ADDR || addr == INA_ADDR_ALTERNATE) { registerValue = getRegisterValue(addr, 0xFE, 2); - DEBUG_MSG("Register MFG_UID: 0x%x\n", registerValue); + LOG_DEBUG("Register MFG_UID: 0x%x\n", registerValue); if (registerValue == 0x5449) { - DEBUG_MSG("INA260 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_DEBUG("INA260 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_INA260] = addr; } else { // Assume INA219 if INA260 ID is not found - DEBUG_MSG("INA219 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_DEBUG("INA219 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_INA219] = addr; } } if (addr == MCP9808_ADDR) { nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr; - DEBUG_MSG("MCP9808 sensor found\n"); + LOG_DEBUG("MCP9808 sensor found\n"); } if (addr == SHT31_ADDR) { - DEBUG_MSG("SHT31 sensor found\n"); + LOG_DEBUG("SHT31 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; } if (addr == SHTC3_ADDR) { - DEBUG_MSG("SHTC3 sensor found\n"); + LOG_DEBUG("SHTC3 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; } if (addr == LPS22HB_ADDR || addr == LPS22HB_ADDR_ALT) { - DEBUG_MSG("LPS22HB sensor found\n"); + LOG_DEBUG("LPS22HB sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_LPS22] = addr; } // High rate sensors, will be processed internally if (addr == QMC6310_ADDR) { - DEBUG_MSG("QMC6310 Highrate 3-Axis magnetic sensor found\n"); + LOG_DEBUG("QMC6310 Highrate 3-Axis magnetic sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMC6310] = addr; } if (addr == QMI8658_ADDR) { - DEBUG_MSG("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); + LOG_DEBUG("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMI8658] = addr; } if (addr == QMC5883L_ADDR) { - DEBUG_MSG("QMC5883L Highrate 3-Axis magnetic sensor found\n"); + LOG_DEBUG("QMC5883L Highrate 3-Axis magnetic sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMC5883L] = addr; } } else if (err == 4) { - DEBUG_MSG("Unknow error at address 0x%x\n", addr); + LOG_DEBUG("Unknow error at address 0x%x\n", addr); } } if (nDevices == 0) - DEBUG_MSG("No I2C devices found\n"); + LOG_DEBUG("No I2C devices found\n"); else - DEBUG_MSG("%i I2C devices found\n",nDevices); + LOG_DEBUG("%i I2C devices found\n",nDevices); } #else void scanI2Cdevice() {} diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 7e860cdd0..d8c33a5ea 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -203,7 +203,7 @@ if (!config.position.tx_gpio) 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0xAF}; _serial_gps->write(_message_nmea, sizeof(_message_nmea)); if (!getACK(0x06, 0x00)) { - DEBUG_MSG("WARNING: Unable to enable NMEA Mode.\n"); + LOG_WARN("Unable to enable NMEA Mode.\n"); return true; } */ @@ -214,7 +214,7 @@ if (!config.position.tx_gpio) byte _message_GGL[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x05, 0x3A}; _serial_gps->write(_message_GGL, sizeof(_message_GGL)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to disable NMEA GGL.\n"); + LOG_WARN("Unable to disable NMEA GGL.\n"); return true; } @@ -222,7 +222,7 @@ if (!config.position.tx_gpio) byte _message_GSA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x02, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x06, 0x41}; _serial_gps->write(_message_GSA, sizeof(_message_GSA)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to disable NMEA GSA.\n"); + LOG_WARN("Unable to disable NMEA GSA.\n"); return true; } @@ -230,7 +230,7 @@ if (!config.position.tx_gpio) byte _message_GSV[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x07, 0x48}; _serial_gps->write(_message_GSV, sizeof(_message_GSV)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to disable NMEA GSV.\n"); + LOG_WARN("Unable to disable NMEA GSV.\n"); return true; } @@ -238,7 +238,7 @@ if (!config.position.tx_gpio) byte _message_VTG[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x05, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x09, 0x56}; _serial_gps->write(_message_VTG, sizeof(_message_VTG)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to disable NMEA VTG.\n"); + LOG_WARN("Unable to disable NMEA VTG.\n"); return true; } @@ -246,7 +246,7 @@ if (!config.position.tx_gpio) byte _message_RMC[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x09, 0x54}; _serial_gps->write(_message_RMC, sizeof(_message_RMC)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to enable NMEA RMC.\n"); + LOG_WARN("Unable to enable NMEA RMC.\n"); return true; } @@ -254,7 +254,7 @@ if (!config.position.tx_gpio) byte _message_GGA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, 0x38}; _serial_gps->write(_message_GGA, sizeof(_message_GGA)); if (!getACK(0x06, 0x01)) { - DEBUG_MSG("WARNING: Unable to enable NMEA GGA.\n"); + LOG_WARN("Unable to enable NMEA GGA.\n"); } } } @@ -361,12 +361,12 @@ void GPS::setNumSatellites(uint8_t n) void GPS::setAwake(bool on) { if (!wakeAllowed && on) { - DEBUG_MSG("Inhibiting because !wakeAllowed\n"); + LOG_DEBUG("Inhibiting because !wakeAllowed\n"); on = false; } if (isAwake != on) { - DEBUG_MSG("WANT GPS=%d\n", on); + LOG_DEBUG("WANT GPS=%d\n", on); if (on) { lastWakeStartMsec = millis(); wake(); @@ -412,7 +412,7 @@ void GPS::publishUpdate() shouldPublish = false; // In debug logs, identify position by @timestamp:stage (stage 2 = publish) - DEBUG_MSG("publishing pos@%x:2, hasVal=%d, GPSlock=%d\n", p.timestamp, hasValidLocation, hasLock()); + LOG_DEBUG("publishing pos@%x:2, hasVal=%d, GPSlock=%d\n", p.timestamp, hasValidLocation, hasLock()); // Notify any status instances that are observing us const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasValidLocation, isConnected(), isPowerSaving(), p); @@ -429,7 +429,7 @@ int32_t GPS::runOnce() if((config.position.gps_enabled == 1) && (gnssModel == GNSS_MODEL_UBLOX)){ // reset the GPS on next bootup if(devicestate.did_gps_reset && (millis() > 60000) && !hasFlow()) { - DEBUG_MSG("GPS is not communicating, trying factory reset on next bootup.\n"); + LOG_DEBUG("GPS is not communicating, trying factory reset on next bootup.\n"); devicestate.did_gps_reset = false; nodeDB.saveDeviceStateToDisk(); } @@ -447,7 +447,7 @@ int32_t GPS::runOnce() // While we are awake if (isAwake) { - // DEBUG_MSG("looking for location\n"); + // LOG_DEBUG("looking for location\n"); if ((now - lastWhileActiveMsec) > 5000) { lastWhileActiveMsec = now; whileActive(); @@ -462,7 +462,7 @@ int32_t GPS::runOnce() bool gotLoc = lookForLocation(); if (gotLoc && !hasValidLocation) { // declare that we have location ASAP - DEBUG_MSG("hasValidLocation RISING EDGE\n"); + LOG_DEBUG("hasValidLocation RISING EDGE\n"); hasValidLocation = true; shouldPublish = true; } @@ -473,13 +473,13 @@ int32_t GPS::runOnce() bool tooLong = wakeTime != UINT32_MAX && (now - lastWakeStartMsec) > wakeTime; // Once we get a location we no longer desperately want an update - // DEBUG_MSG("gotLoc %d, tooLong %d, gotTime %d\n", gotLoc, tooLong, gotTime); + // LOG_DEBUG("gotLoc %d, tooLong %d, gotTime %d\n", gotLoc, tooLong, gotTime); if ((gotLoc && gotTime) || tooLong) { if (tooLong) { // we didn't get a location during this ack window, therefore declare loss of lock if (hasValidLocation) { - DEBUG_MSG("hasValidLocation FALLING EDGE (last read: %d)\n", gotLoc); + LOG_DEBUG("hasValidLocation FALLING EDGE (last read: %d)\n", gotLoc); } p = Position_init_default; hasValidLocation = false; @@ -501,7 +501,7 @@ int32_t GPS::runOnce() void GPS::forceWake(bool on) { if (on) { - DEBUG_MSG("Allowing GPS lock\n"); + LOG_DEBUG("Allowing GPS lock\n"); // lastSleepStartMsec = 0; // Force an update ASAP wakeAllowed = true; } else { @@ -516,7 +516,7 @@ void GPS::forceWake(bool on) /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs int GPS::prepareSleep(void *unused) { - DEBUG_MSG("GPS prepare sleep!\n"); + LOG_DEBUG("GPS prepare sleep!\n"); forceWake(false); return 0; @@ -525,7 +525,7 @@ int GPS::prepareSleep(void *unused) /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs int GPS::prepareDeepSleep(void *unused) { - DEBUG_MSG("GPS deep sleep!\n"); + LOG_DEBUG("GPS deep sleep!\n"); // For deep sleep we also want abandon any lock attempts (because we want minimum power) getSleepTime(); @@ -568,7 +568,7 @@ GnssModel_t GPS::probe() if(index != -1){ ver = ver.substring(index); if (ver.startsWith("$GPTXT,01,01,02")) { - DEBUG_MSG("L76K GNSS init succeeded, using L76K GNSS Module\n"); + LOG_DEBUG("L76K GNSS init succeeded, using L76K GNSS Module\n"); return GNSS_MODEL_MTK; } } @@ -580,7 +580,7 @@ GnssModel_t GPS::probe() _serial_gps->write(cfg_rate, sizeof(cfg_rate)); // Check that the returned response class and message ID are correct if (!getAck(buffer, 256, 0x06, 0x08)) { - DEBUG_MSG("Warning: Failed to find UBlox & MTK GNSS Module\n"); + LOG_WARN("Failed to find UBlox & MTK GNSS Module\n"); return GNSS_MODEL_UNKONW; } @@ -611,12 +611,12 @@ GnssModel_t GPS::probe() break; } - DEBUG_MSG("Module Info : \n"); - DEBUG_MSG("Soft version: %s\n",info.swVersion); - DEBUG_MSG("Hard version: %s\n",info.hwVersion); - DEBUG_MSG("Extensions:%d\n",info.extensionNo); + LOG_DEBUG("Module Info : \n"); + LOG_DEBUG("Soft version: %s\n",info.swVersion); + LOG_DEBUG("Hard version: %s\n",info.hwVersion); + LOG_DEBUG("Extensions:%d\n",info.extensionNo); for (int i = 0; i < info.extensionNo; i++) { - DEBUG_MSG(" %s\n",info.extension[i]); + LOG_DEBUG(" %s\n",info.extension[i]); } memset(buffer,0,sizeof(buffer)); @@ -625,15 +625,15 @@ GnssModel_t GPS::probe() for (int i = 0; i < info.extensionNo; ++i) { if (!strncmp(info.extension[i], "OD=", 3)) { strcpy((char *)buffer, &(info.extension[i][3])); - DEBUG_MSG("GetModel:%s\n",(char *)buffer); + LOG_DEBUG("GetModel:%s\n",(char *)buffer); } } } if (strlen((char*)buffer)) { - DEBUG_MSG("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n" , buffer); + LOG_DEBUG("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n" , buffer); }else{ - DEBUG_MSG("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); + LOG_DEBUG("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); } return GNSS_MODEL_UBLOX; @@ -652,9 +652,9 @@ GPS *createGps() #else if (config.position.gps_enabled) { #ifdef GPS_ALTITUDE_HAE - DEBUG_MSG("Using HAE altitude model\n"); + LOG_DEBUG("Using HAE altitude model\n"); #else - DEBUG_MSG("Using MSL altitude model\n"); + LOG_DEBUG("Using MSL altitude model\n"); #endif if (GPS::_serial_gps) { // Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just diff --git a/src/gps/NMEAGPS.cpp b/src/gps/NMEAGPS.cpp index 0ff302bab..a99b55873 100644 --- a/src/gps/NMEAGPS.cpp +++ b/src/gps/NMEAGPS.cpp @@ -53,9 +53,9 @@ bool NMEAGPS::setupGPS() // see NMEAGPS.h gsafixtype.begin(reader, NMEA_MSG_GXGSA, 2); gsapdop.begin(reader, NMEA_MSG_GXGSA, 15); - DEBUG_MSG("Using " NMEA_MSG_GXGSA " for 3DFIX and PDOP\n"); + LOG_DEBUG("Using " NMEA_MSG_GXGSA " for 3DFIX and PDOP\n"); #else - DEBUG_MSG("GxGSA NOT available\n"); + LOG_DEBUG("GxGSA NOT available\n"); #endif return true; @@ -85,7 +85,7 @@ The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of s t.tm_year = d.year() - 1900; t.tm_isdst = false; if (t.tm_mon > -1){ - DEBUG_MSG("NMEA GPS time %02d-%02d-%02d %02d:%02d:%02d\n", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); + LOG_DEBUG("NMEA GPS time %02d-%02d-%02d %02d:%02d:%02d\n", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); perhapsSetRTC(RTCQualityGPS, t); return true; } else @@ -109,7 +109,7 @@ bool NMEAGPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS fixType = atoi(gsafixtype.value()); // will set to zero if no data - // DEBUG_MSG("FIX QUAL=%d, TYPE=%d\n", fixQual, fixType); + // LOG_DEBUG("FIX QUAL=%d, TYPE=%d\n", fixQual, fixType); #endif // check if GPS has an acceptable lock @@ -117,7 +117,7 @@ bool NMEAGPS::lookForLocation() return false; #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("AGE: LOC=%d FIX=%d DATE=%d TIME=%d\n", + LOG_DEBUG("AGE: LOC=%d FIX=%d DATE=%d TIME=%d\n", reader.location.age(), #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS gsafixtype.age(), @@ -137,7 +137,7 @@ bool NMEAGPS::lookForLocation() (reader.time.age() < GPS_SOL_EXPIRY_MS) && (reader.date.age() < GPS_SOL_EXPIRY_MS))) { - DEBUG_MSG("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age()); + LOG_DEBUG("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age()); return false; } @@ -151,13 +151,13 @@ bool NMEAGPS::lookForLocation() // Bail out EARLY to avoid overwriting previous good data (like #857) if (toDegInt(loc.lat) > 900000000) { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("Bail out EARLY on LAT %i\n",toDegInt(loc.lat)); + LOG_DEBUG("Bail out EARLY on LAT %i\n",toDegInt(loc.lat)); #endif return false; } if (toDegInt(loc.lng) > 1800000000) { #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("Bail out EARLY on LNG %i\n",toDegInt(loc.lng)); + LOG_DEBUG("Bail out EARLY on LNG %i\n",toDegInt(loc.lng)); #endif return false; } @@ -168,7 +168,7 @@ bool NMEAGPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS p.HDOP = reader.hdop.value(); p.PDOP = TinyGPSPlus::parseDecimal(gsapdop.value()); - // DEBUG_MSG("PDOP=%d, HDOP=%d\n", p.PDOP, p.HDOP); + // LOG_DEBUG("PDOP=%d, HDOP=%d\n", p.PDOP, p.HDOP); #else // FIXME! naive PDOP emulation (assumes VDOP==HDOP) // correct formula is PDOP = SQRT(HDOP^2 + VDOP^2) @@ -212,7 +212,7 @@ bool NMEAGPS::lookForLocation() if (reader.course.value() < 36000) { // sanity check p.ground_track = reader.course.value() * 1e3; // Scale the heading (in degrees * 10^-2) to match the expected degrees * 10^-5 } else { - DEBUG_MSG("BOGUS course.value() REJECTED: %d\n", + LOG_DEBUG("BOGUS course.value() REJECTED: %d\n", reader.course.value()); } } @@ -251,7 +251,7 @@ bool NMEAGPS::whileIdle() // First consume any chars that have piled up at the receiver while (_serial_gps->available() > 0) { int c = _serial_gps->read(); - // DEBUG_MSG("%c", c); + // LOG_DEBUG("%c", c); isValid |= reader.encode(c); } diff --git a/src/gps/RTC.cpp b/src/gps/RTC.cpp index e04f903ee..e61991917 100644 --- a/src/gps/RTC.cpp +++ b/src/gps/RTC.cpp @@ -33,7 +33,7 @@ void readFromRTC() t.tm_sec = rtc.getSecond(); tv.tv_sec = mktime(&t); tv.tv_usec = 0; - DEBUG_MSG("Read RTC time from RV3028 as %ld\n", tv.tv_sec); + LOG_DEBUG("Read RTC time from RV3028 as %ld\n", tv.tv_sec); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; if (currentQuality == RTCQualityNone) { @@ -59,7 +59,7 @@ void readFromRTC() t.tm_sec = tc.second; tv.tv_sec = mktime(&t); tv.tv_usec = 0; - DEBUG_MSG("Read RTC time from PCF8563 as %ld\n", tv.tv_sec); + LOG_DEBUG("Read RTC time from PCF8563 as %ld\n", tv.tv_sec); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; if (currentQuality == RTCQualityNone) { @@ -69,7 +69,7 @@ void readFromRTC() #else if (!gettimeofday(&tv, NULL)) { uint32_t now = millis(); - DEBUG_MSG("Read RTC time as %ld\n", tv.tv_sec); + LOG_DEBUG("Read RTC time as %ld\n", tv.tv_sec); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; } @@ -86,11 +86,11 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv) if (q > currentQuality) { currentQuality = q; shouldSet = true; - DEBUG_MSG("Upgrading time to RTC %ld secs (quality %d)\n", tv->tv_sec, q); + LOG_DEBUG("Upgrading time to RTC %ld secs (quality %d)\n", tv->tv_sec, q); } else if(q == RTCQualityGPS && (now - lastSetMsec) > (12 * 60 * 60 * 1000UL)) { // Every 12 hrs we will slam in a new GPS time, to correct for local RTC clock drift shouldSet = true; - DEBUG_MSG("Reapplying external time to correct clock drift %ld secs\n", tv->tv_sec); + LOG_DEBUG("Reapplying external time to correct clock drift %ld secs\n", tv->tv_sec); } else shouldSet = false; @@ -109,7 +109,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv) rtc.initI2C(); tm *t = localtime(&tv->tv_sec); rtc.setTime(t->tm_year + 1900, t->tm_mon + 1, t->tm_wday, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - DEBUG_MSG("RV3028_RTC setTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); + LOG_DEBUG("RV3028_RTC setTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); } #elif defined(PCF8563_RTC) if(rtc_found == PCF8563_RTC) { @@ -121,7 +121,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv) #endif tm *t = localtime(&tv->tv_sec); rtc.setDateTime(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - DEBUG_MSG("PCF8563_RTC setDateTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); + LOG_DEBUG("PCF8563_RTC setDateTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); } #elif defined(ARCH_ESP32) settimeofday(tv, NULL); @@ -149,9 +149,9 @@ bool perhapsSetRTC(RTCQuality q, struct tm &t) tv.tv_sec = res; tv.tv_usec = 0; // time.centisecond() * (10 / 1000); - // DEBUG_MSG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); + // LOG_DEBUG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); if (t.tm_year < 0 || t.tm_year >= 300) { - // DEBUG_MSG("Ignoring invalid GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); + // LOG_DEBUG("Ignoring invalid GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); return false; } else { return perhapsSetRTC(q, &tv); diff --git a/src/graphics/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp index 9e0834954..a7ec5e056 100644 --- a/src/graphics/EInkDisplay2.cpp +++ b/src/graphics/EInkDisplay2.cpp @@ -103,7 +103,7 @@ bool EInkDisplay::forceDisplay(uint32_t msecLimit) } } - DEBUG_MSG("Updating E-Paper... "); + LOG_DEBUG("Updating E-Paper... "); #if defined(TTGO_T_ECHO) // ePaper.Reset(); // wake the screen from sleep @@ -128,11 +128,11 @@ bool EInkDisplay::forceDisplay(uint32_t msecLimit) // Put screen to sleep to save power (possibly not necessary because we already did poweroff inside of display) adafruitDisplay->hibernate(); - DEBUG_MSG("done\n"); + LOG_DEBUG("done\n"); return true; } else { - // DEBUG_MSG("Skipping eink display\n"); + // LOG_DEBUG("Skipping eink display\n"); return false; } } @@ -162,7 +162,7 @@ void EInkDisplay::setDetected(uint8_t detected) // Connect to the display bool EInkDisplay::connect() { - DEBUG_MSG("Doing EInk init\n"); + LOG_DEBUG("Doing EInk init\n"); #ifdef PIN_EINK_PWR_ON digitalWrite(PIN_EINK_PWR_ON, HIGH); // If we need to assert a pin to power external peripherals diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 02159940a..426d5f2cd 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -276,9 +276,9 @@ static void drawModuleFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int } else { // otherwise, just display the module frame that's aligned with the current frame module_frame = state->currentFrame; - // DEBUG_MSG("Screen is not in transition. Frame: %d\n\n", module_frame); + // LOG_DEBUG("Screen is not in transition. Frame: %d\n\n", module_frame); } - // DEBUG_MSG("Drawing Module Frame %d\n\n", module_frame); + // LOG_DEBUG("Drawing Module Frame %d\n\n", module_frame); MeshModule &pi = *moduleFrames.at(module_frame); pi.drawFrame(display, state, x, y); } @@ -368,7 +368,7 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state MeshPacket &mp = devicestate.rx_text_message; NodeInfo *node = nodeDB.getNode(getFrom(&mp)); - // DEBUG_MSG("drawing text message from 0x%x: %s\n", mp.from, + // LOG_DEBUG("drawing text message from 0x%x: %s\n", mp.from, // mp.decoded.variant.data.decoded.bytes); // Demo for drawStringMaxWidth: @@ -882,7 +882,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ if (!hasNodeHeading) { // direction to node is unknown so display question mark // Debug info for gps lock errors - // DEBUG_MSG("ourNode %d, ourPos %d, theirPos %d\n", !!ourNode, ourNode && hasPosition(ourNode), hasPosition(node)); + // LOG_DEBUG("ourNode %d, ourPos %d, theirPos %d\n", !!ourNode, ourNode && hasPosition(ourNode), hasPosition(node)); display->drawString(compassX - FONT_HEIGHT_SMALL / 4, compassY - FONT_HEIGHT_SMALL / 2, "?"); } display->drawCircle(compassX, compassY, getCompassDiam(display) / 2); @@ -936,14 +936,14 @@ void Screen::handleSetOn(bool on) if (on != screenOn) { if (on) { - DEBUG_MSG("Turning on screen\n"); + LOG_DEBUG("Turning on screen\n"); dispdev.displayOn(); dispdev.displayOn(); enabled = true; setInterval(0); // Draw ASAP runASAP = true; } else { - DEBUG_MSG("Turning off screen\n"); + LOG_DEBUG("Turning off screen\n"); dispdev.displayOff(); enabled = false; } @@ -1056,7 +1056,7 @@ int32_t Screen::runOnce() // serialSinceMsec adjusts for additional serial wait time during nRF52 bootup static bool showingBootScreen = true; if (showingBootScreen && (millis() > (logo_timeout + serialSinceMsec))) { - DEBUG_MSG("Done with boot screen...\n"); + LOG_DEBUG("Done with boot screen...\n"); stopBootScreen(); showingBootScreen = false; } @@ -1065,7 +1065,7 @@ int32_t Screen::runOnce() if (strlen(oemStore.oem_text) > 0) { static bool showingOEMBootScreen = true; if (showingOEMBootScreen && (millis() > ((logo_timeout / 2) + serialSinceMsec))) { - DEBUG_MSG("Switch to OEM screen...\n"); + LOG_DEBUG("Switch to OEM screen...\n"); // Change frames. static FrameCallback bootOEMFrames[] = {drawOEMBootScreen}; static const int bootOEMFrameCount = sizeof(bootOEMFrames) / sizeof(bootOEMFrames[0]); @@ -1127,7 +1127,7 @@ int32_t Screen::runOnce() handleRebootScreen(); break; default: - DEBUG_MSG("BUG: invalid cmd\n"); + LOG_DEBUG("BUG: invalid cmd\n"); } } @@ -1158,12 +1158,12 @@ int32_t Screen::runOnce() // standard screen loop handling here if (config.display.auto_screen_carousel_secs > 0 && (millis() - lastScreenTransition) > (config.display.auto_screen_carousel_secs * 1000)) { - DEBUG_MSG("LastScreenTransition exceeded %ums transitioning to next frame\n", (millis() - lastScreenTransition)); + LOG_DEBUG("LastScreenTransition exceeded %ums transitioning to next frame\n", (millis() - lastScreenTransition)); handleOnPress(); } } - // DEBUG_MSG("want fps %d, fixed=%d\n", targetFramerate, + // LOG_DEBUG("want fps %d, fixed=%d\n", targetFramerate, // ui.getUiState()->frameState); If we are scrolling we need to be called // soon, otherwise just 1 fps (to save CPU) We also ask to be called twice // as fast as we really need so that any rounding errors still result with @@ -1194,7 +1194,7 @@ void Screen::drawDebugInfoWiFiTrampoline(OLEDDisplay *display, OLEDDisplayUiStat void Screen::setSSLFrames() { if (address_found) { - // DEBUG_MSG("showing SSL frames\n"); + // LOG_DEBUG("showing SSL frames\n"); static FrameCallback sslFrames[] = {drawSSLScreen}; ui.setFrames(sslFrames, 1); ui.update(); @@ -1206,7 +1206,7 @@ void Screen::setSSLFrames() void Screen::setWelcomeFrames() { if (address_found) { - // DEBUG_MSG("showing Welcome frames\n"); + // LOG_DEBUG("showing Welcome frames\n"); ui.disableAllIndicators(); static FrameCallback welcomeFrames[] = {drawWelcomeScreen}; @@ -1218,13 +1218,13 @@ void Screen::setWelcomeFrames() // restore our regular frame list void Screen::setFrames() { - DEBUG_MSG("showing standard frames\n"); + LOG_DEBUG("showing standard frames\n"); showingNormalScreen = true; moduleFrames = MeshModule::GetMeshModulesWithUIFrames(); - DEBUG_MSG("Showing %d module frames\n", moduleFrames.size()); + LOG_DEBUG("Showing %d module frames\n", moduleFrames.size()); int totalFrameCount = MAX_NUM_NODES + NUM_EXTRA_FRAMES + moduleFrames.size(); - DEBUG_MSG("Total frame count: %d\n", totalFrameCount); + LOG_DEBUG("Total frame count: %d\n", totalFrameCount); // We don't show the node info our our node (if we have it yet - we should) size_t numnodes = nodeStatus->getNumTotal(); @@ -1243,7 +1243,7 @@ void Screen::setFrames() normalFrames[numframes++] = drawModuleFrame; } - DEBUG_MSG("Added modules. numframes: %d\n", numframes); + LOG_DEBUG("Added modules. numframes: %d\n", numframes); // If we have a critical fault, show it first if (myNodeInfo.error_code) @@ -1276,7 +1276,7 @@ void Screen::setFrames() } #endif - DEBUG_MSG("Finished building frames. numframes: %d\n", numframes); + LOG_DEBUG("Finished building frames. numframes: %d\n", numframes); ui.setFrames(normalFrames, numframes); ui.enableAllIndicators(); @@ -1289,7 +1289,7 @@ void Screen::setFrames() void Screen::handleStartBluetoothPinScreen(uint32_t pin) { - DEBUG_MSG("showing bluetooth screen\n"); + LOG_DEBUG("showing bluetooth screen\n"); showingNormalScreen = false; static FrameCallback btFrames[] = {drawFrameBluetooth}; @@ -1303,7 +1303,7 @@ void Screen::handleStartBluetoothPinScreen(uint32_t pin) void Screen::handleShutdownScreen() { - DEBUG_MSG("showing shutdown screen\n"); + LOG_DEBUG("showing shutdown screen\n"); showingNormalScreen = false; static FrameCallback shutdownFrames[] = {drawFrameShutdown}; @@ -1315,7 +1315,7 @@ void Screen::handleShutdownScreen() void Screen::handleRebootScreen() { - DEBUG_MSG("showing reboot screen\n"); + LOG_DEBUG("showing reboot screen\n"); showingNormalScreen = false; static FrameCallback rebootFrames[] = {drawFrameReboot}; @@ -1327,7 +1327,7 @@ void Screen::handleRebootScreen() void Screen::handleStartFirmwareUpdateScreen() { - DEBUG_MSG("showing firmware screen\n"); + LOG_DEBUG("showing firmware screen\n"); showingNormalScreen = false; static FrameCallback btFrames[] = {drawFrameFirmware}; @@ -1358,7 +1358,7 @@ void Screen::handlePrint(const char *text) { // the string passed into us probably has a newline, but that would confuse the logging system // so strip it - DEBUG_MSG("Screen: %.*s\n", strlen(text) - 1, text); + LOG_DEBUG("Screen: %.*s\n", strlen(text) - 1, text); if (!useDisplay || !showingNormalScreen) return; @@ -1778,7 +1778,7 @@ void Screen::adjustBrightness() int Screen::handleStatusUpdate(const meshtastic::Status *arg) { - // DEBUG_MSG("Screen got status update %d\n", arg->getStatusType()); + // LOG_DEBUG("Screen got status update %d\n", arg->getStatusType()); switch (arg->getStatusType()) { case STATUS_TYPE_NODE: if (showingNormalScreen && nodeStatus->getLastNumTotal() != nodeStatus->getNumTotal()) { diff --git a/src/graphics/TFTDisplay.cpp b/src/graphics/TFTDisplay.cpp index 1d5f43cd1..083ee273c 100644 --- a/src/graphics/TFTDisplay.cpp +++ b/src/graphics/TFTDisplay.cpp @@ -59,7 +59,7 @@ void TFTDisplay::setDetected(uint8_t detected) bool TFTDisplay::connect() { concurrency::LockGuard g(spiLock); - DEBUG_MSG("Doing TFT init\n"); + LOG_DEBUG("Doing TFT init\n"); #ifdef TFT_BL digitalWrite(TFT_BL, HIGH); diff --git a/src/input/RotaryEncoderInterruptBase.cpp b/src/input/RotaryEncoderInterruptBase.cpp index 6914824fd..0f75c3a5a 100644 --- a/src/input/RotaryEncoderInterruptBase.cpp +++ b/src/input/RotaryEncoderInterruptBase.cpp @@ -28,7 +28,7 @@ void RotaryEncoderInterruptBase::init( this->rotaryLevelA = digitalRead(this->_pinA); this->rotaryLevelB = digitalRead(this->_pinB); - DEBUG_MSG("Rotary initialized (%d, %d, %d)\n", this->_pinA, this->_pinB, pinPress); + LOG_DEBUG("Rotary initialized (%d, %d, %d)\n", this->_pinA, this->_pinB, pinPress); } int32_t RotaryEncoderInterruptBase::runOnce() @@ -38,13 +38,13 @@ int32_t RotaryEncoderInterruptBase::runOnce() e.source = this->_originName; if (this->action == ROTARY_ACTION_PRESSED) { - DEBUG_MSG("Rotary event Press\n"); + LOG_DEBUG("Rotary event Press\n"); e.inputEvent = this->_eventPressed; } else if (this->action == ROTARY_ACTION_CW) { - DEBUG_MSG("Rotary event CW\n"); + LOG_DEBUG("Rotary event CW\n"); e.inputEvent = this->_eventCw; } else if (this->action == ROTARY_ACTION_CCW) { - DEBUG_MSG("Rotary event CCW\n"); + LOG_DEBUG("Rotary event CCW\n"); e.inputEvent = this->_eventCcw; } @@ -104,7 +104,7 @@ RotaryEncoderInterruptBaseStateType RotaryEncoderInterruptBase::intHandler(bool newState = ROTARY_EVENT_OCCURRED; if ((this->action != ROTARY_ACTION_PRESSED) && (this->action != action)) { this->action = action; - DEBUG_MSG("Rotary action\n"); + LOG_DEBUG("Rotary action\n"); } } } else if (!actualPinRaising && (otherPinLevel == HIGH)) { diff --git a/src/input/UpDownInterruptBase.cpp b/src/input/UpDownInterruptBase.cpp index 31edc848b..5a0f25158 100644 --- a/src/input/UpDownInterruptBase.cpp +++ b/src/input/UpDownInterruptBase.cpp @@ -26,7 +26,7 @@ void UpDownInterruptBase::init( attachInterrupt(this->_pinDown, onIntDown, RISING); attachInterrupt(this->_pinUp, onIntUp, RISING); - DEBUG_MSG("GPIO initialized (%d, %d, %d)\n", + LOG_DEBUG("GPIO initialized (%d, %d, %d)\n", this->_pinDown, this->_pinUp, pinPress); } @@ -34,7 +34,7 @@ void UpDownInterruptBase::intPressHandler() { InputEvent e; e.source = this->_originName; - DEBUG_MSG("GPIO event Press\n"); + LOG_DEBUG("GPIO event Press\n"); e.inputEvent = this->_eventPressed; this->notifyObservers(&e); } @@ -43,7 +43,7 @@ void UpDownInterruptBase::intDownHandler() { InputEvent e; e.source = this->_originName; - DEBUG_MSG("GPIO event Down\n"); + LOG_DEBUG("GPIO event Down\n"); e.inputEvent = this->_eventDown; this->notifyObservers(&e); } @@ -52,7 +52,7 @@ void UpDownInterruptBase::intUpHandler() { InputEvent e; e.source = this->_originName; - DEBUG_MSG("GPIO event Up\n"); + LOG_DEBUG("GPIO event Up\n"); e.inputEvent = this->_eventUp; this->notifyObservers(&e); } diff --git a/src/input/kbI2cBase.cpp b/src/input/kbI2cBase.cpp index 332dfde0d..a857bae77 100644 --- a/src/input/kbI2cBase.cpp +++ b/src/input/kbI2cBase.cpp @@ -56,7 +56,7 @@ int32_t KbI2cBase::runOnce() } } if (PrintDataBuf != 0) { - DEBUG_MSG("RAK14004 key 0x%x pressed\n", PrintDataBuf); + LOG_DEBUG("RAK14004 key 0x%x pressed\n", PrintDataBuf); InputEvent e; e.inputEvent = MATRIXKEY; e.source = this->_originName; diff --git a/src/main.cpp b/src/main.cpp index f999ac708..6f25ac1f7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -174,7 +174,7 @@ void setup() serialSinceMsec = millis(); - DEBUG_MSG("\n\n//\\ E S H T /\\ S T / C\n\n"); + LOG_INFO("\n\n//\\ E S H T /\\ S T / C\n\n"); initDeepSleep(); @@ -256,7 +256,7 @@ void setup() Wire1.beginTransmission(PCF8563_RTC); if (Wire1.endTransmission() == 0){ rtc_found = PCF8563_RTC; - DEBUG_MSG("PCF8563 RTC found\n"); + LOG_DEBUG("PCF8563 RTC found\n"); } #endif @@ -282,7 +282,7 @@ void setup() #endif // Hello - DEBUG_MSG("Meshtastic hwvendor=%d, swver=%s\n", HW_VENDOR, optstr(APP_VERSION)); + LOG_INFO("Meshtastic hwvendor=%d, swver=%s\n", HW_VENDOR, optstr(APP_VERSION)); #ifdef ARCH_ESP32 // Don't init display if we don't have one or we are waking headless due to a timer event @@ -325,7 +325,7 @@ void setup() if (gps) gpsStatus->observe(&gps->newStatus); else - DEBUG_MSG("Warning: No GPS found - running without GPS\n"); + LOG_WARN("No GPS found - running without GPS\n"); nodeStatus->observe(&nodeDB.newStatus); @@ -355,7 +355,7 @@ void setup() // ONCE we will factory reset the GPS for bug #327 if (gps && !devicestate.did_gps_reset) { - DEBUG_MSG("GPS FactoryReset requested\n"); + LOG_WARN("GPS FactoryReset requested\n"); if (gps->factoryReset()) { // If we don't succeed try again next time devicestate.did_gps_reset = true; nodeDB.saveToDisk(SEGMENT_DEVICESTATE); @@ -374,11 +374,11 @@ void setup() if (!rIf) { rIf = new RF95Interface(RF95_NSS, RF95_IRQ, RF95_RESET, SPI); if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find RF95 radio\n"); + LOG_WARN("Failed to find RF95 radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("RF95 Radio init succeeded, using RF95 radio\n"); + LOG_DEBUG("RF95 Radio init succeeded, using RF95 radio\n"); } } #endif @@ -387,11 +387,11 @@ void setup() if (!rIf) { rIf = new SX1280Interface(SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY, SPI); if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find SX1280 radio\n"); + LOG_WARN("Failed to find SX1280 radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("SX1280 Radio init succeeded, using SX1280 radio\n"); + LOG_DEBUG("SX1280 Radio init succeeded, using SX1280 radio\n"); } } #endif @@ -400,11 +400,11 @@ void setup() if (!rIf) { rIf = new SX1262Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find SX1262 radio\n"); + LOG_WARN("Failed to find SX1262 radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("SX1262 Radio init succeeded, using SX1262 radio\n"); + LOG_DEBUG("SX1262 Radio init succeeded, using SX1262 radio\n"); } } #endif @@ -413,11 +413,11 @@ void setup() if (!rIf) { rIf = new SX1268Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find SX1268 radio\n"); + LOG_WARN("Failed to find SX1268 radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("SX1268 Radio init succeeded, using SX1268 radio\n"); + LOG_DEBUG("SX1268 Radio init succeeded, using SX1268 radio\n"); } } #endif @@ -426,11 +426,11 @@ void setup() if (!rIf) { rIf = new LLCC68Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find LLCC68 radio\n"); + LOG_WARN("Failed to find LLCC68 radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("LLCC68 Radio init succeeded, using LLCC68 radio\n"); + LOG_DEBUG("LLCC68 Radio init succeeded, using LLCC68 radio\n"); } } #endif @@ -439,11 +439,11 @@ void setup() if (!rIf) { rIf = new SimRadio; if (!rIf->init()) { - DEBUG_MSG("Warning: Failed to find simulated radio\n"); + LOG_WARN("Failed to find simulated radio\n"); delete rIf; rIf = NULL; } else { - DEBUG_MSG("Using SIMULATED radio!\n"); + LOG_DEBUG("Using SIMULATED radio!\n"); } } #endif @@ -451,11 +451,11 @@ void setup() // check if the radio chip matches the selected region if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLora())){ - DEBUG_MSG("Warning: Radio chip does not support 2.4GHz LoRa. Reverting to unset.\n"); + LOG_WARN("Radio chip does not support 2.4GHz LoRa. Reverting to unset.\n"); config.lora.region = Config_LoRaConfig_RegionCode_UNSET; nodeDB.saveToDisk(SEGMENT_CONFIG); if(!rIf->reconfigure()) { - DEBUG_MSG("Reconfigure failed, rebooting\n"); + LOG_WARN("Reconfigure failed, rebooting\n"); screen->startRebootScreen(); rebootAtMsec = millis() + 5000; } @@ -493,7 +493,7 @@ if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLo // Calculate and save the bit rate to myNodeInfo // TODO: This needs to be added what ever method changes the channel from the phone. myNodeInfo.bitrate = (float(Constants_DATA_PAYLOAD_LEN) / (float(rIf->getPacketTime(Constants_DATA_PAYLOAD_LEN)))) * 1000; - DEBUG_MSG("myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); + LOG_DEBUG("myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); } // This must be _after_ service.init because we need our preferences loaded from flash to have proper timeout values @@ -546,13 +546,13 @@ void loop() long delayMsec = mainController.runOrDelay(); /* if (mainController.nextThread && delayMsec) - DEBUG_MSG("Next %s in %ld\n", mainController.nextThread->ThreadName.c_str(), + LOG_DEBUG("Next %s in %ld\n", mainController.nextThread->ThreadName.c_str(), mainController.nextThread->tillRun(millis())); */ // We want to sleep as long as possible here - because it saves power if (!runASAP && loopCanSleep()) { - // if(delayMsec > 100) DEBUG_MSG("sleeping %ld\n", delayMsec); + // if(delayMsec > 100) LOG_DEBUG("sleeping %ld\n", delayMsec); mainDelay.delay(delayMsec); } - // if (didWake) DEBUG_MSG("wake!\n"); + // if (didWake) LOG_DEBUG("wake!\n"); } diff --git a/src/memtest.cpp b/src/memtest.cpp index d5d073998..f5fe3d7d2 100644 --- a/src/memtest.cpp +++ b/src/memtest.cpp @@ -255,10 +255,10 @@ static int mem_test(uint32_t *_start, size_t len, bool doRead = true, bool doWri int rcode = 0; incr = 1; - //DEBUG_MSG("memtest read=%d, write=%d\n", doRead, doWrite); + //LOG_DEBUG("memtest read=%d, write=%d\n", doRead, doWrite); if (doWrite) { - //DEBUG_MSG("writing\n"); + //LOG_DEBUG("writing\n"); for (addr = start, val = pattern; addr < end; addr++) { *addr = val; val += incr; @@ -266,11 +266,11 @@ static int mem_test(uint32_t *_start, size_t len, bool doRead = true, bool doWri } if (doRead) { - //DEBUG_MSG("reading\n"); + //LOG_DEBUG("reading\n"); for (addr = start, val = pattern; addr < end; addr++) { readback = *addr; if (readback != val) { - DEBUG_MSG("Mem error @ 0x%08X: " + LOG_DEBUG("Mem error @ 0x%08X: " "found 0x%08lX, expected 0x%08lX\n", addr, readback, val); rcode++; diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index e7f1cb3ed..97f2c1448 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -106,30 +106,30 @@ CryptoKey Channels::getKey(ChannelIndex chIndex) k.length = channelSettings.psk.size; if (k.length == 0) { if (ch.role == Channel_Role_SECONDARY) { - DEBUG_MSG("Unset PSK for secondary channel %s. using primary key\n", ch.settings.name); + LOG_DEBUG("Unset PSK for secondary channel %s. using primary key\n", ch.settings.name); k = getKey(primaryIndex); } else - DEBUG_MSG("Warning: User disabled encryption\n"); + LOG_WARN("User disabled encryption\n"); } else if (k.length == 1) { // Convert the short single byte variants of psk into variant that can be used more generally uint8_t pskIndex = k.bytes[0]; - DEBUG_MSG("Expanding short PSK #%d\n", pskIndex); + LOG_DEBUG("Expanding short PSK #%d\n", pskIndex); if (pskIndex == 0) k.length = 0; // Turn off encryption else if (oemStore.oem_aes_key.size > 1) { // Use the OEM key - DEBUG_MSG("Using OEM Key with %d bytes\n", oemStore.oem_aes_key.size); + LOG_DEBUG("Using OEM Key with %d bytes\n", oemStore.oem_aes_key.size); memcpy(k.bytes, oemStore.oem_aes_key.bytes , oemStore.oem_aes_key.size); k.length = oemStore.oem_aes_key.size; // Bump up the last byte of PSK as needed uint8_t *last = k.bytes + oemStore.oem_aes_key.size - 1; *last = *last + pskIndex - 1; // index of 1 means no change vs defaultPSK if (k.length < 16) { - DEBUG_MSG("Warning: OEM provided a too short AES128 key - padding\n"); + LOG_WARN("OEM provided a too short AES128 key - padding\n"); k.length = 16; } else if (k.length < 32 && k.length != 16) { - DEBUG_MSG("Warning: OEM provided a too short AES256 key - padding\n"); + LOG_WARN("OEM provided a too short AES256 key - padding\n"); k.length = 32; } } else { @@ -142,12 +142,12 @@ CryptoKey Channels::getKey(ChannelIndex chIndex) } else if (k.length < 16) { // Error! The user specified only the first few bits of an AES128 key. So by convention we just pad the rest of the // key with zeros - DEBUG_MSG("Warning: User provided a too short AES128 key - padding\n"); + LOG_WARN("User provided a too short AES128 key - padding\n"); k.length = 16; } else if (k.length < 32 && k.length != 16) { // Error! The user specified only the first few bits of an AES256 key. So by convention we just pad the rest of the // key with zeros - DEBUG_MSG("Warning: User provided a too short AES256 key - padding\n"); + LOG_WARN("User provided a too short AES256 key - padding\n"); k.length = 32; } } @@ -308,11 +308,11 @@ const char *Channels::getPrimaryName() bool Channels::decryptForHash(ChannelIndex chIndex, ChannelHash channelHash) { if (chIndex > getNumChannels() || getHash(chIndex) != channelHash) { - // DEBUG_MSG("Skipping channel %d (hash %x) due to invalid hash/index, want=%x\n", chIndex, getHash(chIndex), + // LOG_DEBUG("Skipping channel %d (hash %x) due to invalid hash/index, want=%x\n", chIndex, getHash(chIndex), // channelHash); return false; } else { - DEBUG_MSG("Using channel %d (hash 0x%x)\n", chIndex, channelHash); + LOG_DEBUG("Using channel %d (hash 0x%x)\n", chIndex, channelHash); setCrypto(chIndex); return true; } diff --git a/src/mesh/CryptoEngine.cpp b/src/mesh/CryptoEngine.cpp index 5e73e3921..55535a0a8 100644 --- a/src/mesh/CryptoEngine.cpp +++ b/src/mesh/CryptoEngine.cpp @@ -3,7 +3,7 @@ void CryptoEngine::setKey(const CryptoKey &k) { - DEBUG_MSG("Using AES%d key!\n", k.length * 8); + LOG_DEBUG("Using AES%d key!\n", k.length * 8); key = k; } @@ -14,12 +14,12 @@ void CryptoEngine::setKey(const CryptoKey &k) */ void CryptoEngine::encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) { - DEBUG_MSG("WARNING: noop encryption!\n"); + LOG_WARN("noop encryption!\n"); } void CryptoEngine::decrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) { - DEBUG_MSG("WARNING: noop decryption!\n"); + LOG_WARN("noop decryption!\n"); } /** diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index e21820305..568af182d 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -32,7 +32,7 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK if (isAck && p->to != getNodeNum()) { // do not flood direct message that is ACKed - DEBUG_MSG("Receiving an ACK not for me, but don't need to rebroadcast this direct message anymore.\n"); + LOG_DEBUG("Receiving an ACK not for me, but don't need to rebroadcast this direct message anymore.\n"); Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM } if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) { @@ -53,11 +53,11 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) Router::send(tosend); } else { - DEBUG_MSG("Not rebroadcasting. Role = Role_ClientMute\n"); + LOG_DEBUG("Not rebroadcasting. Role = Role_ClientMute\n"); } } else { - DEBUG_MSG("Ignoring a simple (0 id) broadcast\n"); + LOG_DEBUG("Ignoring a simple (0 id) broadcast\n"); } } diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index 8019cda1e..fe5e3d81e 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -52,7 +52,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr p->to = to; p->decoded.request_id = idFrom; p->channel = chIndex; - DEBUG_MSG("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id); + LOG_DEBUG("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id); return p; } @@ -68,7 +68,7 @@ MeshPacket *MeshModule::allocErrorResponse(Routing_Error err, const MeshPacket * void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) { - // DEBUG_MSG("In call modules\n"); + // LOG_DEBUG("In call modules\n"); bool moduleFound = false; // We now allow **encrypted** packets to pass through the modules @@ -96,7 +96,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) assert(!pi.myReply); // If it is !null it means we have a bug, because it should have been sent the previous time if (wantsPacket) { - DEBUG_MSG("Module '%s' wantsPacket=%d\n", pi.name, wantsPacket); + LOG_DEBUG("Module '%s' wantsPacket=%d\n", pi.name, wantsPacket); moduleFound = true; @@ -134,20 +134,20 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) // any other node. if (mp.decoded.want_response && toUs && (getFrom(&mp) != ourNodeNum || mp.to == ourNodeNum) && !currentReply) { pi.sendResponse(mp); - DEBUG_MSG("Module '%s' sent a response\n", pi.name); + LOG_DEBUG("Module '%s' sent a response\n", pi.name); } else { - DEBUG_MSG("Module '%s' considered\n", pi.name); + LOG_DEBUG("Module '%s' considered\n", pi.name); } // If the requester didn't ask for a response we might need to discard unused replies to prevent memory leaks if (pi.myReply) { - DEBUG_MSG("Discarding an unneeded response\n"); + LOG_DEBUG("Discarding an unneeded response\n"); packetPool.release(pi.myReply); pi.myReply = NULL; } if (handled == ProcessMessage::STOP) { - DEBUG_MSG("Module '%s' handled and skipped other processing\n", pi.name); + LOG_DEBUG("Module '%s' handled and skipped other processing\n", pi.name); break; } } @@ -165,7 +165,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) // Note: if the message started with the local node we don't want to send a no response reply // No one wanted to reply to this requst, tell the requster that happened - DEBUG_MSG("No one responded, send a nak\n"); + LOG_DEBUG("No one responded, send a nak\n"); // SECURITY NOTE! I considered sending back a different error code if we didn't find the psk (i.e. !isDecoded) // but opted NOT TO. Because it is not a good idea to let remote nodes 'probe' to find out which PSKs were "good" vs @@ -175,7 +175,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) } if (!moduleFound) - DEBUG_MSG("No modules interested in portnum=%d, src=%s\n", + LOG_DEBUG("No modules interested in portnum=%d, src=%s\n", mp.decoded.portnum, (src == RX_SRC_LOCAL) ? "LOCAL":"REMOTE"); } @@ -199,7 +199,7 @@ void MeshModule::sendResponse(const MeshPacket &req) currentReply = r; } else { // Ignore - this is now expected behavior for routing module (because it ignores some replies) - // DEBUG_MSG("WARNING: Client requested response but this module did not provide\n"); + // LOG_WARN("Client requested response but this module did not provide\n"); } } @@ -227,7 +227,7 @@ std::vector MeshModule::GetMeshModulesWithUIFrames() for (auto i = modules->begin(); i != modules->end(); ++i) { auto &pi = **i; if (pi.wantUIFrame()) { - DEBUG_MSG("Module wants a UI Frame\n"); + LOG_DEBUG("Module wants a UI Frame\n"); modulesWithUIFrames.push_back(&pi); } } @@ -244,7 +244,7 @@ void MeshModule::observeUIEvents( Observable *observable = pi.getUIFrameObservable(); if (observable != NULL) { - DEBUG_MSG("Module wants a UI Frame\n"); + LOG_DEBUG("Module wants a UI Frame\n"); observer->observe(observable); } } @@ -261,7 +261,7 @@ AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const MeshP if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) { // In case we have a response it always has priority. - DEBUG_MSG("Reply prepared by module '%s' of variant: %d\n", + LOG_DEBUG("Reply prepared by module '%s' of variant: %d\n", pi.name, response->which_payload_variant); handled = h; diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index b4a4a171f..6ac7321da 100644 --- a/src/mesh/MeshService.cpp +++ b/src/mesh/MeshService.cpp @@ -106,7 +106,7 @@ bool MeshService::reloadConfig(int saveWhat) /// The owner User record just got updated, update our node DB and broadcast the info into the mesh void MeshService::reloadOwner(bool shouldSave) { - // DEBUG_MSG("reloadOwner()\n"); + // LOG_DEBUG("reloadOwner()\n"); // update our local data directly nodeDB.updateUser(nodeDB.getNodeNum(), owner); assert(nodeInfoModule); @@ -140,7 +140,7 @@ void MeshService::handleToRadio(MeshPacket &p) // Switch the port from PortNum_SIMULATOR_APP back to the original PortNum p.decoded.portnum = decoded->portnum; } else - DEBUG_MSG("Error decoding protobuf for simulator message!\n"); + LOG_DEBUG("Error decoding protobuf for simulator message!\n"); } // Let SimRadio receive as if it did via its LoRa chip SimRadio::instance->startReceive(&p); @@ -148,7 +148,7 @@ void MeshService::handleToRadio(MeshPacket &p) } #endif if (p.from != 0) { // We don't let phones assign nodenums to their sent messages - DEBUG_MSG("Warning: phone tried to pick a nodenum, we don't allow that.\n"); + LOG_WARN("phone tried to pick a nodenum, we don't allow that.\n"); p.from = 0; } else { // p.from = nodeDB.getNodeNum(); @@ -198,12 +198,12 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) if (node->has_position && (node->position.latitude_i != 0 || node->position.longitude_i != 0)) { if (positionModule) { - DEBUG_MSG("Sending position ping to 0x%x, wantReplies=%d\n", dest, wantReplies); + LOG_DEBUG("Sending position ping to 0x%x, wantReplies=%d\n", dest, wantReplies); positionModule->sendOurPosition(dest, wantReplies); } } else { if (nodeInfoModule) { - DEBUG_MSG("Sending nodeinfo ping to 0x%x, wantReplies=%d\n", dest, wantReplies); + LOG_DEBUG("Sending nodeinfo ping to 0x%x, wantReplies=%d\n", dest, wantReplies); nodeInfoModule->sendOurNodeInfo(dest, wantReplies); } } @@ -212,7 +212,7 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) void MeshService::sendToPhone(MeshPacket *p) { if (toPhoneQueue.numFree() == 0) { - DEBUG_MSG("NOTE: tophone queue is full, discarding oldest\n"); + LOG_DEBUG("NOTE: tophone queue is full, discarding oldest\n"); MeshPacket *d = toPhoneQueue.dequeuePtr(0); if (d) releaseToPool(d); @@ -262,10 +262,10 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) // The GPS has lost lock, if we are fixed position we should just keep using // the old position #ifdef GPS_EXTRAVERBOSE - DEBUG_MSG("onGPSchanged() - lost validLocation\n"); + LOG_DEBUG("onGPSchanged() - lost validLocation\n"); #endif if (config.position.fixed_position) { - DEBUG_MSG("WARNING: Using fixed position\n"); + LOG_WARN("Using fixed position\n"); pos = node->position; } } @@ -276,7 +276,7 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) pos.time = getValidTime(RTCQualityGPS); // In debug logs, identify position by @timestamp:stage (stage 4 = nodeDB) - DEBUG_MSG("onGPSChanged() pos@%x, time=%u, lat=%d, lon=%d, alt=%d\n", pos.timestamp, pos.time, pos.latitude_i, + LOG_DEBUG("onGPSChanged() pos@%x, time=%u, lat=%d, lon=%d, alt=%d\n", pos.timestamp, pos.time, pos.latitude_i, pos.longitude_i, pos.altitude); // Update our current position in the local DB diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index f2139b82b..57d462da2 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -86,7 +86,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) } if (channelFile.channels_count != MAX_NUM_CHANNELS) { - DEBUG_MSG("Setting default channel and radio preferences!\n"); + LOG_DEBUG("Setting default channel and radio preferences!\n"); channels.initDefaults(); } @@ -96,7 +96,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) // temp hack for quicker testing // devicestate.no_save = true; if (devicestate.no_save) { - DEBUG_MSG("***** DEVELOPMENT MODE - DO NOT RELEASE *****\n"); + LOG_DEBUG("***** DEVELOPMENT MODE - DO NOT RELEASE *****\n"); // Sleep quite frequently to stress test the BLE comms, broadcast position every 6 mins config.display.screen_on_secs = 10; @@ -114,7 +114,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) initRegion(); if (didFactoryReset) { - DEBUG_MSG("Rebooting due to factory reset"); + LOG_DEBUG("Rebooting due to factory reset"); screen->startRebootScreen(); rebootAtMsec = millis() + (5 * 1000); } @@ -124,7 +124,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) bool NodeDB::factoryReset() { - DEBUG_MSG("Performing factory reset!\n"); + LOG_DEBUG("Performing factory reset!\n"); // first, remove the "/prefs" (this removes most prefs) rmDir("/prefs"); // second, install default state (this will deal with the duplicate mac address issue) @@ -140,7 +140,7 @@ bool NodeDB::factoryReset() #endif #ifdef ARCH_NRF52 Bluefruit.begin(); - DEBUG_MSG("Clearing bluetooth bonds!\n"); + LOG_DEBUG("Clearing bluetooth bonds!\n"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); Bluefruit.Periph.clearBonds(); @@ -151,7 +151,7 @@ bool NodeDB::factoryReset() void NodeDB::installDefaultConfig() { - DEBUG_MSG("Installing default LocalConfig\n"); + LOG_DEBUG("Installing default LocalConfig\n"); memset(&config, 0, sizeof(LocalConfig)); config.version = DEVICESTATE_CUR_VER; config.has_device = true; @@ -203,7 +203,7 @@ void NodeDB::initConfigIntervals() void NodeDB::installDefaultModuleConfig() { - DEBUG_MSG("Installing default ModuleConfig\n"); + LOG_DEBUG("Installing default ModuleConfig\n"); memset(&moduleConfig, 0, sizeof(ModuleConfig)); moduleConfig.version = DEVICESTATE_CUR_VER; @@ -230,7 +230,7 @@ void NodeDB::initModuleConfigIntervals() void NodeDB::installDefaultChannels() { - DEBUG_MSG("Installing default ChannelFile\n"); + LOG_DEBUG("Installing default ChannelFile\n"); memset(&channelFile, 0, sizeof(ChannelFile)); channelFile.version = DEVICESTATE_CUR_VER; } @@ -244,7 +244,7 @@ void NodeDB::resetNodes() void NodeDB::installDefaultDeviceState() { - DEBUG_MSG("Installing default DeviceState\n"); + LOG_DEBUG("Installing default DeviceState\n"); memset(&devicestate, 0, sizeof(DeviceState)); *numNodes = 0; @@ -275,7 +275,7 @@ void NodeDB::installDefaultDeviceState() void NodeDB::init() { - DEBUG_MSG("Initializing NodeDB\n"); + LOG_DEBUG("Initializing NodeDB\n"); loadFromDisk(); uint32_t devicestateCRC = crc32Buffer(&devicestate, sizeof(devicestate)); @@ -311,7 +311,7 @@ void NodeDB::init() preferences.begin("meshtastic", false); myNodeInfo.reboot_count = preferences.getUInt("rebootCounter", 0); preferences.end(); - DEBUG_MSG("Number of Device Reboots: %d\n", myNodeInfo.reboot_count); + LOG_DEBUG("Number of Device Reboots: %d\n", myNodeInfo.reboot_count); /* The ESP32 has a wifi radio. This will need to be modified at some point so * the test isn't so simplistic. @@ -320,7 +320,7 @@ void NodeDB::init() #endif resetRadioConfig(); // If bogus settings got saved, then fix them - DEBUG_MSG("region=%d, NODENUM=0x%x, dbsize=%d\n", config.lora.region, myNodeInfo.my_node_num, *numNodes); + LOG_DEBUG("region=%d, NODENUM=0x%x, dbsize=%d\n", config.lora.region, myNodeInfo.my_node_num, *numNodes); if (devicestateCRC != crc32Buffer(&devicestate, sizeof(devicestate))) saveWhat |= SEGMENT_DEVICESTATE; @@ -352,7 +352,7 @@ void NodeDB::pickNewNodeNum() NodeInfo *found; while ((found = getNode(r)) && memcmp(found->user.macaddr, owner.macaddr, sizeof(owner.macaddr))) { NodeNum n = random(NUM_RESERVED, NODENUM_BROADCAST); // try a new random choice - DEBUG_MSG("NOTE! Our desired nodenum 0x%x is in use, so trying for 0x%x\n", r, n); + LOG_DEBUG("NOTE! Our desired nodenum 0x%x is in use, so trying for 0x%x\n", r, n); r = n; } @@ -376,24 +376,24 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c auto f = FSCom.open(filename, FILE_O_READ); if (f) { - DEBUG_MSG("Loading %s\n", filename); + LOG_DEBUG("Loading %s\n", filename); pb_istream_t stream = {&readcb, &f, protoSize}; - // DEBUG_MSG("Preload channel name=%s\n", channelSettings.name); + // LOG_DEBUG("Preload channel name=%s\n", channelSettings.name); memset(dest_struct, 0, objSize); if (!pb_decode(&stream, fields, dest_struct)) { - DEBUG_MSG("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_DEBUG("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); } else { okay = true; } f.close(); } else { - DEBUG_MSG("No %s preferences found\n", filename); + LOG_DEBUG("No %s preferences found\n", filename); } #else - DEBUG_MSG("ERROR: Filesystem not implemented\n"); + LOG_DEBUG("ERROR: Filesystem not implemented\n"); #endif return okay; } @@ -405,10 +405,10 @@ void NodeDB::loadFromDisk() installDefaultDeviceState(); // Our in RAM copy might now be corrupt } else { if (devicestate.version < DEVICESTATE_MIN_VER) { - DEBUG_MSG("Warn: devicestate %d is old, discarding\n", devicestate.version); + LOG_DEBUG("Warn: devicestate %d is old, discarding\n", devicestate.version); factoryReset(); } else { - DEBUG_MSG("Loaded saved devicestate version %d\n", devicestate.version); + LOG_DEBUG("Loaded saved devicestate version %d\n", devicestate.version); } } @@ -416,10 +416,10 @@ void NodeDB::loadFromDisk() installDefaultConfig(); // Our in RAM copy might now be corrupt } else { if (config.version < DEVICESTATE_MIN_VER) { - DEBUG_MSG("Warn: config %d is old, discarding\n", config.version); + LOG_DEBUG("Warn: config %d is old, discarding\n", config.version); installDefaultConfig(); } else { - DEBUG_MSG("Loaded saved config version %d\n", config.version); + LOG_DEBUG("Loaded saved config version %d\n", config.version); } } @@ -427,10 +427,10 @@ void NodeDB::loadFromDisk() installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { - DEBUG_MSG("Warn: moduleConfig %d is old, discarding\n", moduleConfig.version); + LOG_DEBUG("Warn: moduleConfig %d is old, discarding\n", moduleConfig.version); installDefaultModuleConfig(); } else { - DEBUG_MSG("Loaded saved moduleConfig version %d\n", moduleConfig.version); + LOG_DEBUG("Loaded saved moduleConfig version %d\n", moduleConfig.version); } } @@ -438,15 +438,15 @@ void NodeDB::loadFromDisk() installDefaultChannels(); // Our in RAM copy might now be corrupt } else { if (channelFile.version < DEVICESTATE_MIN_VER) { - DEBUG_MSG("Warn: channelFile %d is old, discarding\n", channelFile.version); + LOG_DEBUG("Warn: channelFile %d is old, discarding\n", channelFile.version); installDefaultChannels(); } else { - DEBUG_MSG("Loaded saved channelFile version %d\n", channelFile.version); + LOG_DEBUG("Loaded saved channelFile version %d\n", channelFile.version); } } if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), &OEMStore_msg, &oemStore)) - DEBUG_MSG("Loaded OEMStore\n"); + LOG_DEBUG("Loaded OEMStore\n"); } /** Save a protobuf from a file, return true for success */ @@ -459,11 +459,11 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ filenameTmp += ".tmp"; auto f = FSCom.open(filenameTmp.c_str(), FILE_O_WRITE); if (f) { - DEBUG_MSG("Saving %s\n", filename); + LOG_DEBUG("Saving %s\n", filename); pb_ostream_t stream = {&writecb, &f, protoSize}; if (!pb_encode(&stream, fields, dest_struct)) { - DEBUG_MSG("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_DEBUG("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); } else { okay = true; } @@ -471,11 +471,11 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ // brief window of risk here ;-) if (FSCom.exists(filename) && !FSCom.remove(filename)) - DEBUG_MSG("Warning: Can't remove old pref file\n"); + LOG_WARN("Can't remove old pref file\n"); if (!renameFile(filenameTmp.c_str(), filename)) - DEBUG_MSG("Error: can't rename new pref file\n"); + LOG_DEBUG("Error: can't rename new pref file\n"); } else { - DEBUG_MSG("Can't write prefs\n"); + LOG_DEBUG("Can't write prefs\n"); #ifdef ARCH_NRF52 static uint8_t failedCounter = 0; failedCounter++; @@ -487,7 +487,7 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ #endif } #else - DEBUG_MSG("ERROR: Filesystem not implemented\n"); + LOG_DEBUG("ERROR: Filesystem not implemented\n"); #endif return okay; } @@ -548,7 +548,7 @@ void NodeDB::saveToDisk(int saveWhat) saveChannelsToDisk(); } } else { - DEBUG_MSG("***** DEVELOPMENT MODE - DO NOT RELEASE - not saving to flash *****\n"); + LOG_DEBUG("***** DEVELOPMENT MODE - DO NOT RELEASE - not saving to flash *****\n"); } } @@ -599,14 +599,14 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative - DEBUG_MSG("updatePosition LOCAL pos@%x, time=%u, latI=%d, lonI=%d, alt=%d\n", p.timestamp, p.time, p.latitude_i, + LOG_DEBUG("updatePosition LOCAL pos@%x, time=%u, latI=%d, lonI=%d, alt=%d\n", p.timestamp, p.time, p.latitude_i, p.longitude_i, p.altitude); info->position = p; } else if ((p.time > 0) && !p.latitude_i && !p.longitude_i && !p.timestamp && !p.location_source) { // FIXME SPECIAL TIME SETTING PACKET FROM EUD TO RADIO // (stop-gap fix for issue #900) - DEBUG_MSG("updatePosition SPECIAL time setting time=%u\n", p.time); + LOG_DEBUG("updatePosition SPECIAL time setting time=%u\n", p.time); info->position.time = p.time; } else { @@ -615,7 +615,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) // recorded based on the packet rxTime // // FIXME perhaps handle RX_SRC_USER separately? - DEBUG_MSG("updatePosition REMOTE node=0x%x time=%u, latI=%d, lonI=%d\n", nodeId, p.time, p.latitude_i, p.longitude_i); + LOG_DEBUG("updatePosition REMOTE node=0x%x time=%u, latI=%d, lonI=%d\n", nodeId, p.time, p.latitude_i, p.longitude_i); // First, back up fields that we want to protect from overwrite uint32_t tmp_time = info->position.time; @@ -645,9 +645,9 @@ void NodeDB::updateTelemetry(uint32_t nodeId, const Telemetry &t, RxSource src) if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative - DEBUG_MSG("updateTelemetry LOCAL\n"); + LOG_DEBUG("updateTelemetry LOCAL\n"); } else { - DEBUG_MSG("updateTelemetry REMOTE node=0x%x \n", nodeId); + LOG_DEBUG("updateTelemetry REMOTE node=0x%x \n", nodeId); } info->device_metrics = t.variant.device_metrics; info->has_device_metrics = true; @@ -664,13 +664,13 @@ void NodeDB::updateUser(uint32_t nodeId, const User &p) return; } - DEBUG_MSG("old user %s/%s/%s\n", info->user.id, info->user.long_name, info->user.short_name); + LOG_DEBUG("old user %s/%s/%s\n", info->user.id, info->user.long_name, info->user.short_name); bool changed = memcmp(&info->user, &p, sizeof(info->user)); // Both of these blocks start as filled with zero so I think this is okay info->user = p; - DEBUG_MSG("updating changed=%d user %s/%s/%s\n", changed, info->user.id, info->user.long_name, info->user.short_name); + LOG_DEBUG("updating changed=%d user %s/%s/%s\n", changed, info->user.id, info->user.long_name, info->user.short_name); info->has_user = true; if (changed) { @@ -689,7 +689,7 @@ void NodeDB::updateUser(uint32_t nodeId, const User &p) void NodeDB::updateFrom(const MeshPacket &mp) { if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.from) { - DEBUG_MSG("Update DB node 0x%x, rx_time=%u\n", mp.from, mp.rx_time); + LOG_DEBUG("Update DB node 0x%x, rx_time=%u\n", mp.from, mp.rx_time); NodeInfo *info = getOrCreateNode(getFrom(&mp)); if (!info) { @@ -756,9 +756,9 @@ void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *f String lcd = String("Critical error ") + code + "!\n"; screen->print(lcd.c_str()); if (filename) - DEBUG_MSG("NOTE! Recording critical error %d at %s:%lu\n", code, filename, address); + LOG_DEBUG("NOTE! Recording critical error %d at %s:%lu\n", code, filename, address); else - DEBUG_MSG("NOTE! Recording critical error %d, address=0x%lx\n", code, address); + LOG_DEBUG("NOTE! Recording critical error %d, address=0x%lx\n", code, address); // Record error to DB myNodeInfo.error_code = code; @@ -767,7 +767,7 @@ void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *f // Currently portuino is mostly used for simulation. Make sue the user notices something really bad happend #ifdef ARCH_PORTDUINO - DEBUG_MSG("A critical failure occurred, portduino is exiting..."); + LOG_DEBUG("A critical failure occurred, portduino is exiting..."); exit(2); #endif } diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index c8008689d..e46adfc9e 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -14,7 +14,7 @@ PacketHistory::PacketHistory() bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) { if (p->id == 0) { - DEBUG_MSG("Ignoring message with zero id\n"); + LOG_DEBUG("Ignoring message with zero id\n"); return false; // Not a floodable message ID, so we don't care } @@ -35,7 +35,7 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) } if (seenRecently) { - DEBUG_MSG("Found existing packet record for fr=0x%x,to=0x%x,id=0x%x\n", p->from, p->to, p->id); + LOG_DEBUG("Found existing packet record for fr=0x%x,to=0x%x,id=0x%x\n", p->from, p->to, p->id); } if (withUpdate) { @@ -61,7 +61,7 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) void PacketHistory::clearExpiredRecentPackets() { uint32_t now = millis(); - DEBUG_MSG("recentPackets size=%ld\n", recentPackets.size()); + LOG_DEBUG("recentPackets size=%ld\n", recentPackets.size()); for (auto it = recentPackets.begin(); it != recentPackets.end(); ) { if ((now - it->rxTimeMsec) >= FLOOD_EXPIRE_TIME) { @@ -71,5 +71,5 @@ void PacketHistory::clearExpiredRecentPackets() { } } - DEBUG_MSG("recentPackets size=%ld (after clearing expired packets)\n", recentPackets.size()); + LOG_DEBUG("recentPackets size=%ld (after clearing expired packets)\n", recentPackets.size()); } \ No newline at end of file diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index ac134f352..75805c11c 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -37,7 +37,7 @@ void PhoneAPI::handleStartConfig() // even if we were already connected - restart our state machine state = STATE_SEND_MY_INFO; - DEBUG_MSG("Starting API client config\n"); + LOG_DEBUG("Starting API client config\n"); nodeInfoForPhone = NULL; // Don't keep returning old nodeinfos nodeDB.resetReadPointer(); // FIXME, this read pointer should be moved out of nodeDB and into this class - because // this will break once we have multiple instances of PhoneAPI running independently @@ -60,7 +60,7 @@ void PhoneAPI::checkConnectionTimeout() if (isConnected()) { bool newContact = checkIsConnected(); if (!newContact) { - DEBUG_MSG("Lost phone connection\n"); + LOG_DEBUG("Lost phone connection\n"); close(); } } @@ -83,20 +83,20 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) return handleToRadioPacket(toRadioScratch.packet); case ToRadio_want_config_id_tag: config_nonce = toRadioScratch.want_config_id; - DEBUG_MSG("Client wants config, nonce=%u\n", config_nonce); + LOG_DEBUG("Client wants config, nonce=%u\n", config_nonce); handleStartConfig(); break; case ToRadio_disconnect_tag: - DEBUG_MSG("Disconnecting from phone\n"); + LOG_DEBUG("Disconnecting from phone\n"); close(); break; default: // Ignore nop messages - // DEBUG_MSG("Error: unexpected ToRadio variant\n"); + // LOG_DEBUG("Error: unexpected ToRadio variant\n"); break; } } else { - DEBUG_MSG("Error: ignoring malformed toradio\n"); + LOG_DEBUG("Error: ignoring malformed toradio\n"); } return false; @@ -119,7 +119,7 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) size_t PhoneAPI::getFromRadio(uint8_t *buf) { if (!available()) { - // DEBUG_MSG("getFromRadio=not available\n"); + // LOG_DEBUG("getFromRadio=not available\n"); return 0; } // In case we send a FromRadio packet @@ -128,11 +128,11 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Advance states as needed switch (state) { case STATE_SEND_NOTHING: - DEBUG_MSG("getFromRadio=STATE_SEND_NOTHING\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_NOTHING\n"); break; case STATE_SEND_MY_INFO: - DEBUG_MSG("getFromRadio=STATE_SEND_MY_INFO\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_MY_INFO\n"); // If the user has specified they don't want our node to share its location, make sure to tell the phone // app not to send locations on our behalf. myNodeInfo.has_gps = gps && gps->isConnected(); // Update with latest GPS connect info @@ -144,18 +144,18 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_NODEINFO: { - DEBUG_MSG("getFromRadio=STATE_SEND_NODEINFO\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_NODEINFO\n"); const NodeInfo *info = nodeInfoForPhone; nodeInfoForPhone = NULL; // We just consumed a nodeinfo, will need a new one next time if (info) { - DEBUG_MSG("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->last_heard, info->user.id, + LOG_DEBUG("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->last_heard, info->user.id, info->user.long_name); fromRadioScratch.which_payload_variant = FromRadio_node_info_tag; fromRadioScratch.node_info = *info; // Stay in current state until done sending nodeinfos } else { - DEBUG_MSG("Done sending nodeinfos\n"); + LOG_DEBUG("Done sending nodeinfos\n"); state = STATE_SEND_CHANNELS; // Go ahead and send that ID right now return getFromRadio(buf); @@ -164,7 +164,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) } case STATE_SEND_CHANNELS: - DEBUG_MSG("getFromRadio=STATE_SEND_CHANNELS\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_CHANNELS\n"); fromRadioScratch.which_payload_variant = FromRadio_channel_tag; fromRadioScratch.channel = channels.getByIndex(config_state); config_state++; @@ -176,7 +176,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_CONFIG: - DEBUG_MSG("getFromRadio=STATE_SEND_CONFIG\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_CONFIG\n"); fromRadioScratch.which_payload_variant = FromRadio_config_tag; switch (config_state) { case Config_device_tag: @@ -222,7 +222,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_MODULECONFIG: - DEBUG_MSG("getFromRadio=STATE_SEND_MODULECONFIG\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_MODULECONFIG\n"); fromRadioScratch.which_payload_variant = FromRadio_moduleConfig_tag; switch (config_state) { case ModuleConfig_mqtt_tag: @@ -272,7 +272,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_COMPLETE_ID: - DEBUG_MSG("getFromRadio=STATE_SEND_COMPLETE_ID\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_COMPLETE_ID\n"); fromRadioScratch.which_payload_variant = FromRadio_config_complete_id_tag; fromRadioScratch.config_complete_id = config_nonce; config_nonce = 0; @@ -281,7 +281,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_PACKETS: // Do we have a message from the mesh? - DEBUG_MSG("getFromRadio=STATE_SEND_PACKETS\n"); + LOG_DEBUG("getFromRadio=STATE_SEND_PACKETS\n"); if (packetForPhone) { printPacket("phone downloaded packet", packetForPhone); @@ -301,17 +301,17 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Encapsulate as a FromRadio packet size_t numbytes = pb_encode_to_bytes(buf, FromRadio_size, &FromRadio_msg, &fromRadioScratch); - DEBUG_MSG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes); + LOG_DEBUG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes); return numbytes; } - DEBUG_MSG("no FromRadio packet available\n"); + LOG_DEBUG("no FromRadio packet available\n"); return 0; } void PhoneAPI::handleDisconnect() { - DEBUG_MSG("PhoneAPI disconnect\n"); + LOG_DEBUG("PhoneAPI disconnect\n"); } void PhoneAPI::releasePhonePacket() @@ -345,7 +345,7 @@ bool PhoneAPI::available() if (!packetForPhone) packetForPhone = service.getForPhone(); bool hasPacket = !!packetForPhone; - // DEBUG_MSG("available hasPacket=%d\n", hasPacket); + // LOG_DEBUG("available hasPacket=%d\n", hasPacket); return hasPacket; } default: @@ -373,10 +373,10 @@ int PhoneAPI::onNotify(uint32_t newValue) // from idle) if (state == STATE_SEND_PACKETS) { - DEBUG_MSG("Telling client we have new packets %u\n", newValue); + LOG_DEBUG("Telling client we have new packets %u\n", newValue); onNowHasData(newValue); } else - DEBUG_MSG("(Client not yet interested in packets)\n"); + LOG_DEBUG("(Client not yet interested in packets)\n"); return 0; } diff --git a/src/mesh/ProtobufModule.h b/src/mesh/ProtobufModule.h index 9905d2250..bac38b786 100644 --- a/src/mesh/ProtobufModule.h +++ b/src/mesh/ProtobufModule.h @@ -44,7 +44,7 @@ template class ProtobufModule : protected SinglePortModule p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), fields, &payload); - // DEBUG_MSG("did encode\n"); + // LOG_DEBUG("did encode\n"); return p; } @@ -70,7 +70,7 @@ template class ProtobufModule : protected SinglePortModule // it would be better to update even if the message was destined to others. auto &p = mp.decoded; - DEBUG_MSG("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, + LOG_DEBUG("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, p.payload.size); T scratch; @@ -80,7 +80,7 @@ template class ProtobufModule : protected SinglePortModule if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { decoded = &scratch; } else { - DEBUG_MSG("Error decoding protobuf module!\n"); + LOG_DEBUG("Error decoding protobuf module!\n"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } diff --git a/src/mesh/RF95Interface.cpp b/src/mesh/RF95Interface.cpp index 5b88d45ed..e679775c3 100644 --- a/src/mesh/RF95Interface.cpp +++ b/src/mesh/RF95Interface.cpp @@ -68,17 +68,17 @@ bool RF95Interface::init() setTransmitEnable(false); int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, currentLimit, preambleLength); - DEBUG_MSG("RF95 init result %d\n", res); + LOG_DEBUG("RF95 init result %d\n", res); - DEBUG_MSG("Frequency set to %f\n", getFreq()); - DEBUG_MSG("Bandwidth set to %f\n", bw); - DEBUG_MSG("Power output set to %d\n", power); + LOG_DEBUG("Frequency set to %f\n", getFreq()); + LOG_DEBUG("Bandwidth set to %f\n", bw); + LOG_DEBUG("Power output set to %d\n", power); // current limit was removed from module' ctor // override default value (60 mA) res = lora->setCurrentLimit(currentLimit); - DEBUG_MSG("Current limit set to %f\n", currentLimit); - DEBUG_MSG("Current limit set result %d\n", res); + LOG_DEBUG("Current limit set to %f\n", currentLimit); + LOG_DEBUG("Current limit set result %d\n", res); if (res == RADIOLIB_ERR_NONE) res = lora->setCRC(RADIOLIB_SX126X_LORA_CRC_ON); @@ -190,12 +190,12 @@ bool RF95Interface::isChannelActive() result = lora->scanChannel(); if (result == RADIOLIB_PREAMBLE_DETECTED) { - // DEBUG_MSG("Channel is busy!\n"); + // LOG_DEBUG("Channel is busy!\n"); return true; } assert(result != RADIOLIB_ERR_WRONG_MODEM); - // DEBUG_MSG("Channel is free!\n"); + // LOG_DEBUG("Channel is free!\n"); return false; } diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 222e5d14b..f3971ddb0 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -117,7 +117,7 @@ void initRegion() for (; r->code != Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) ; myRegion = r; - DEBUG_MSG("Wanted region %d, using %s\n", config.lora.region, r->name); + LOG_DEBUG("Wanted region %d, using %s\n", config.lora.region, r->name); } /** @@ -157,7 +157,7 @@ uint32_t RadioInterface::getPacketTime(uint32_t pl) uint32_t msecs = tPacket * 1000; - DEBUG_MSG("(bw=%d, sf=%d, cr=4/%d) packet symLen=%d ms, payloadSize=%u, time %d ms\n", (int)bw, sf, cr, (int)(tSym * 1000), + LOG_DEBUG("(bw=%d, sf=%d, cr=4/%d) packet symLen=%d ms, payloadSize=%u, time %d ms\n", (int)bw, sf, cr, (int)(tSym * 1000), pl, msecs); return msecs; } @@ -178,7 +178,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); uint32_t packetAirtime = getPacketTime(numbytes + sizeof(PacketHeader)); // Make sure enough time has elapsed for this packet to be sent and an ACK is received. - // DEBUG_MSG("Waiting for flooding message with airtime %d and slotTime is %d\n", packetAirtime, slotTimeMsec); + // LOG_DEBUG("Waiting for flooding message with airtime %d and slotTime is %d\n", packetAirtime, slotTimeMsec); float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); // Assuming we pick max. of CWsize and there will be a receiver with SNR at half the range @@ -193,7 +193,7 @@ uint32_t RadioInterface::getTxDelayMsec() current channel utilization. */ float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); - // DEBUG_MSG("Current channel utilization is %f so setting CWsize to %d\n", channelUtil, CWsize); + // LOG_DEBUG("Current channel utilization is %f so setting CWsize to %d\n", channelUtil, CWsize); return random(0, pow(2, CWsize)) * slotTimeMsec; } @@ -210,14 +210,14 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr) // low SNR = small CW size (Short Delay) uint32_t delay = 0; uint8_t CWsize = map(snr, SNR_MIN, SNR_MAX, CWmin, CWmax); - // DEBUG_MSG("rx_snr of %f so setting CWsize to:%d\n", snr, CWsize); + // LOG_DEBUG("rx_snr of %f so setting CWsize to:%d\n", snr, CWsize); if (config.device.role == Config_DeviceConfig_Role_ROUTER || config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT) { delay = random(0, 2*CWsize) * slotTimeMsec; - DEBUG_MSG("rx_snr found in packet. As a router, setting tx delay:%d\n", delay); + LOG_DEBUG("rx_snr found in packet. As a router, setting tx delay:%d\n", delay); } else { delay = random(0, pow(2, CWsize)) * slotTimeMsec; - DEBUG_MSG("rx_snr found in packet. Setting tx delay:%d\n", delay); + LOG_DEBUG("rx_snr found in packet. Setting tx delay:%d\n", delay); } return delay; @@ -225,47 +225,47 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr) void printPacket(const char *prefix, const MeshPacket *p) { - DEBUG_MSG("%s (id=0x%08x fr=0x%02x to=0x%02x, WantAck=%d, HopLim=%d Ch=0x%x", prefix, p->id, p->from & 0xff, p->to & 0xff, + LOG_DEBUG("%s (id=0x%08x fr=0x%02x to=0x%02x, WantAck=%d, HopLim=%d Ch=0x%x", prefix, p->id, p->from & 0xff, p->to & 0xff, p->want_ack, p->hop_limit, p->channel); if (p->which_payload_variant == MeshPacket_decoded_tag) { auto &s = p->decoded; - DEBUG_MSG(" Portnum=%d", s.portnum); + LOG_DEBUG(" Portnum=%d", s.portnum); if (s.want_response) - DEBUG_MSG(" WANTRESP"); + LOG_DEBUG(" WANTRESP"); if (s.source != 0) - DEBUG_MSG(" source=%08x", s.source); + LOG_DEBUG(" source=%08x", s.source); if (s.dest != 0) - DEBUG_MSG(" dest=%08x", s.dest); + LOG_DEBUG(" dest=%08x", s.dest); if (s.request_id) - DEBUG_MSG(" requestId=%0x", s.request_id); + LOG_DEBUG(" requestId=%0x", s.request_id); /* now inside Data and therefore kinda opaque if (s.which_ackVariant == SubPacket_success_id_tag) - DEBUG_MSG(" successId=%08x", s.ackVariant.success_id); + LOG_DEBUG(" successId=%08x", s.ackVariant.success_id); else if (s.which_ackVariant == SubPacket_fail_id_tag) - DEBUG_MSG(" failId=%08x", s.ackVariant.fail_id); */ + LOG_DEBUG(" failId=%08x", s.ackVariant.fail_id); */ } else { - DEBUG_MSG(" encrypted"); + LOG_DEBUG(" encrypted"); } if (p->rx_time != 0) { - DEBUG_MSG(" rxtime=%u", p->rx_time); + LOG_DEBUG(" rxtime=%u", p->rx_time); } if (p->rx_snr != 0.0) { - DEBUG_MSG(" rxSNR=%g", p->rx_snr); + LOG_DEBUG(" rxSNR=%g", p->rx_snr); } if (p->rx_rssi != 0) { - DEBUG_MSG(" rxRSSI=%g", p->rx_rssi); + LOG_DEBUG(" rxRSSI=%g", p->rx_rssi); } if (p->priority != 0) - DEBUG_MSG(" priority=%d", p->priority); + LOG_DEBUG(" priority=%d", p->priority); - DEBUG_MSG(")\n"); + LOG_DEBUG(")\n"); } RadioInterface::RadioInterface() @@ -273,7 +273,7 @@ RadioInterface::RadioInterface() assert(sizeof(PacketHeader) == 16); // make sure the compiler did what we expected // Can't print strings this early - serial not setup yet - // DEBUG_MSG("Set meshradio defaults name=%s\n", channelSettings.name); + // LOG_DEBUG("Set meshradio defaults name=%s\n", channelSettings.name); } bool RadioInterface::reconfigure() @@ -284,7 +284,7 @@ bool RadioInterface::reconfigure() bool RadioInterface::init() { - DEBUG_MSG("Starting meshradio init...\n"); + LOG_DEBUG("Starting meshradio init...\n"); configChangedObserver.observe(&service.configChanged); preflightSleepObserver.observe(&preflightSleep); @@ -449,13 +449,13 @@ void RadioInterface::applyModemConfig() saveChannelNum(channel_num); saveFreq(freq + config.lora.frequency_offset); - DEBUG_MSG("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); - DEBUG_MSG("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); - DEBUG_MSG("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); - DEBUG_MSG("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw); - DEBUG_MSG("Radio channel_num: %d\n", channel_num); - DEBUG_MSG("Radio frequency: %f\n", getFreq()); - DEBUG_MSG("Slot time: %u msec\n", slotTimeMsec); + LOG_DEBUG("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); + LOG_DEBUG("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); + LOG_DEBUG("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); + LOG_DEBUG("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw); + LOG_DEBUG("Radio channel_num: %d\n", channel_num); + LOG_DEBUG("Radio frequency: %f\n", getFreq()); + LOG_DEBUG("Slot time: %u msec\n", slotTimeMsec); } /** @@ -470,11 +470,11 @@ void RadioInterface::limitPower() maxPower = myRegion->powerLimit; if ((power > maxPower) && !devicestate.owner.is_licensed) { - DEBUG_MSG("Lowering transmit power because of regulatory limits\n"); + LOG_DEBUG("Lowering transmit power because of regulatory limits\n"); power = maxPower; } - DEBUG_MSG("Set radio: final power level=%d\n", power); + LOG_DEBUG("Set radio: final power level=%d\n", power); } @@ -491,7 +491,7 @@ size_t RadioInterface::beginSending(MeshPacket *p) { assert(!sendingPacket); - // DEBUG_MSG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad()); + // LOG_DEBUG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad()); assert(p->which_payload_variant == MeshPacket_encrypted_tag); // It should have already been encoded by now lastTxStart = millis(); diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 18f2ef2f1..127a246c0 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -82,17 +82,17 @@ bool RadioLibInterface::canSendImmediately() if (busyTx || busyRx) { if (busyTx) - DEBUG_MSG("Can not send yet, busyTx\n"); + LOG_DEBUG("Can not send yet, busyTx\n"); // If we've been trying to send the same packet more than one minute and we haven't gotten a // TX IRQ from the radio, the radio is probably broken. if (busyTx && (millis() - lastTxStart > 60000)) { - DEBUG_MSG("Hardware Failure! busyTx for more than 60s\n"); + LOG_DEBUG("Hardware Failure! busyTx for more than 60s\n"); RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED); // reboot in 5 seconds when this condition occurs. rebootAtMsec = lastTxStart + 65000; } if (busyRx) - DEBUG_MSG("Can not send yet, busyRx\n"); + LOG_DEBUG("Can not send yet, busyRx\n"); return false; } else return true; @@ -111,13 +111,13 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) { if (disabled || !config.lora.tx_enabled) { - DEBUG_MSG("send - !config.lora.tx_enabled\n"); + LOG_DEBUG("send - !config.lora.tx_enabled\n"); packetPool.release(p); return ERRNO_DISABLED; } } else { - DEBUG_MSG("send - lora tx disable because RegionCode_Unset\n"); + LOG_DEBUG("send - lora tx disable because RegionCode_Unset\n"); packetPool.release(p); return ERRNO_DISABLED; } @@ -127,7 +127,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) #else if (disabled || !config.lora.tx_enabled) { - DEBUG_MSG("send - !config.lora.tx_enabled\n"); + LOG_DEBUG("send - !config.lora.tx_enabled\n"); packetPool.release(p); return ERRNO_DISABLED; } @@ -138,7 +138,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) #ifndef LORA_DISABLE_SENDING printPacket("enqueuing for send", p); - DEBUG_MSG("txGood=%d,rxGood=%d,rxBad=%d\n", txGood, rxGood, rxBad); + LOG_DEBUG("txGood=%d,rxGood=%d,rxBad=%d\n", txGood, rxGood, rxBad); ErrorCode res = txQueue.enqueue(p) ? ERRNO_OK : ERRNO_UNKNOWN; if (res != ERRNO_OK) { // we weren't able to queue it, so we must drop it to prevent leaks @@ -148,7 +148,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // set (random) transmit delay to let others reconfigure their radio, // to avoid collisions and implement timing-based flooding - // DEBUG_MSG("Set random delay before transmitting.\n"); + // LOG_DEBUG("Set random delay before transmitting.\n"); setTransmitDelay(); return res; @@ -162,7 +162,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) { bool res = txQueue.empty(); if (!res) // only print debug messages if we are vetoing sleep - DEBUG_MSG("radio wait to sleep, txEmpty=%d\n", res); + LOG_DEBUG("radio wait to sleep, txEmpty=%d\n", res); return res; } @@ -175,7 +175,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) packetPool.release(p); // free the packet we just removed bool result = (p != NULL); - DEBUG_MSG("cancelSending id=0x%x, removed=%d\n", id, result); + LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); return result; } @@ -192,27 +192,27 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) case ISR_TX: handleTransmitInterrupt(); startReceive(); - // DEBUG_MSG("tx complete - starting timer\n"); + // LOG_DEBUG("tx complete - starting timer\n"); startTransmitTimer(); break; case ISR_RX: handleReceiveInterrupt(); startReceive(); - // DEBUG_MSG("rx complete - starting timer\n"); + // LOG_DEBUG("rx complete - starting timer\n"); startTransmitTimer(); break; case TRANSMIT_DELAY_COMPLETED: - // DEBUG_MSG("delay done\n"); + // LOG_DEBUG("delay done\n"); // If we are not currently in receive mode, then restart the random delay (this can happen if the main thread // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode? if (!txQueue.empty()) { if (!canSendImmediately()) { - // DEBUG_MSG("Currently Rx/Tx-ing: set random delay\n"); + // LOG_DEBUG("Currently Rx/Tx-ing: set random delay\n"); setTransmitDelay(); // currently Rx/Tx-ing: reset random delay } else { if (isChannelActive()) { // check if there is currently a LoRa packet on the channel - // DEBUG_MSG("Channel is active: set random delay\n"); + // LOG_DEBUG("Channel is active: set random delay\n"); setTransmitDelay(); // reset random delay } else { // Send any outgoing packets we have ready @@ -226,7 +226,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) } } } else { - // DEBUG_MSG("done with txqueue\n"); + // LOG_DEBUG("done with txqueue\n"); } break; default: @@ -249,7 +249,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) startTransmitTimer(true); } else { // If there is a SNR, start a timer scaled based on that SNR. - DEBUG_MSG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); + LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); startTransmitTimerSNR(p->rx_snr); } } @@ -259,7 +259,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delay = !withDelay ? 1 : getTxDelayMsec(); - // DEBUG_MSG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d\n", delay); notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable } } @@ -269,14 +269,14 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delay = getTxDelayMsecWeighted(snr); - // DEBUG_MSG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d\n", delay); notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable } } void RadioLibInterface::handleTransmitInterrupt() { - // DEBUG_MSG("handling lora TX interrupt\n"); + // LOG_DEBUG("handling lora TX interrupt\n"); // This can be null if we forced the device to enter standby mode. In that case // ignore the transmit interrupt if (sendingPacket) @@ -296,7 +296,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // We are done sending that packet, release it packetPool.release(p); - // DEBUG_MSG("Done with send\n"); + // LOG_DEBUG("Done with send\n"); } } @@ -306,7 +306,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // when this is called, we should be in receive mode - if we are not, just jump out instead of bombing. Possible Race Condition? if (!isReceiving) { - DEBUG_MSG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode\n"); + LOG_DEBUG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode\n"); return; } @@ -319,7 +319,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) int state = iface->readData(radiobuf, length); if (state != RADIOLIB_ERR_NONE) { - DEBUG_MSG("ignoring received packet due to error=%d\n", state); + LOG_DEBUG("ignoring received packet due to error=%d\n", state); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); @@ -331,7 +331,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // check for short packets if (payloadLen < 0) { - DEBUG_MSG("ignoring received packet too short\n"); + LOG_DEBUG("ignoring received packet too short\n"); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); } else { @@ -374,7 +374,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) { printPacket("Starting low level send", txp); if (disabled || !config.lora.tx_enabled) { - DEBUG_MSG("startSend is dropping tx packet because we are disabled\n"); + LOG_DEBUG("startSend is dropping tx packet because we are disabled\n"); packetPool.release(txp); } else { setStandby(); // Cancel any already in process receives @@ -385,7 +385,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) int res = iface->startTransmit(radiobuf, numbytes); if (res != RADIOLIB_ERR_NONE) { - DEBUG_MSG("startTransmit failed, error=%d\n", res); + LOG_DEBUG("startTransmit failed, error=%d\n", res); RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG); // This send failed, but make sure to 'complete' it properly diff --git a/src/mesh/RadioLibRF95.cpp b/src/mesh/RadioLibRF95.cpp index 93f078918..6067f59b6 100644 --- a/src/mesh/RadioLibRF95.cpp +++ b/src/mesh/RadioLibRF95.cpp @@ -22,8 +22,8 @@ int16_t RadioLibRF95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_ // current limit was removed from module' ctor // override default value (60 mA) state = setCurrentLimit(currentLimit); - DEBUG_MSG("Current limit set to %f\n", currentLimit); - DEBUG_MSG("Current limit set result %d\n", state); + LOG_DEBUG("Current limit set to %f\n", currentLimit); + LOG_DEBUG("Current limit set result %d\n", state); // configure settings not accessible by API state = config(); diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index 22f3692b9..a7e80e8a1 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -42,14 +42,14 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) auto key = GlobalPacketId(getFrom(p), p->id); auto old = findPendingPacket(key); if (old) { - DEBUG_MSG("generating implicit ack\n"); + LOG_DEBUG("generating implicit ack\n"); // NOTE: we do NOT check p->wantAck here because p is the INCOMING rebroadcast and that packet is not expected to be // marked as wantAck sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); stopRetransmission(key); } else { - DEBUG_MSG("didn't find pending packet\n"); + LOG_DEBUG("didn't find pending packet\n"); } } @@ -59,7 +59,7 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) * flooding this ACK back to the original sender already adds redundancy. */ if (wasSeenRecently(p, false) && p->hop_limit == HOP_RELIABLE && !MeshModule::currentReply && p->to != nodeDB.getNodeNum()) { // retransmission on broadcast has hop_limit still equal to HOP_RELIABLE - DEBUG_MSG("Resending implicit ack for a repeated floodmsg\n"); + LOG_DEBUG("Resending implicit ack for a repeated floodmsg\n"); MeshPacket *tosend = packetPool.allocCopy(*p); tosend->hop_limit--; // bump down the hop count Router::send(tosend); @@ -87,7 +87,7 @@ void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) if (p->to == ourNode) { // ignore ack/nak/want_ack packets that are not address to us (we only handle 0 hop reliability) if (p->want_ack) { if (MeshModule::currentReply) - DEBUG_MSG("Some other module has replied to this message, no need for a 2nd ack\n"); + LOG_DEBUG("Some other module has replied to this message, no need for a 2nd ack\n"); else if (p->which_payload_variant == MeshPacket_decoded_tag) sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); @@ -105,10 +105,10 @@ void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) // We intentionally don't check wasSeenRecently, because it is harmless to delete non existent retransmission records if (ackId || nakId) { if (ackId) { - DEBUG_MSG("Received an ack for 0x%x, stopping retransmissions\n", ackId); + LOG_DEBUG("Received an ack for 0x%x, stopping retransmissions\n", ackId); stopRetransmission(p->to, ackId); } else { - DEBUG_MSG("Received a nak for 0x%x, stopping retransmissions\n", nakId); + LOG_DEBUG("Received a nak for 0x%x, stopping retransmissions\n", nakId); stopRetransmission(p->to, nakId); } } @@ -190,14 +190,14 @@ int32_t ReliableRouter::doRetransmissions() // FIXME, handle 51 day rolloever here!!! if (p.nextTxMsec <= now) { if (p.numRetransmissions == 0) { - DEBUG_MSG("Reliable send failed, returning a nak for fr=0x%x,to=0x%x,id=0x%x\n", p.packet->from, p.packet->to, + LOG_DEBUG("Reliable send failed, returning a nak for fr=0x%x,to=0x%x,id=0x%x\n", p.packet->from, p.packet->to, p.packet->id); sendAckNak(Routing_Error_MAX_RETRANSMIT, getFrom(p.packet), p.packet->id, p.packet->channel); // Note: we don't stop retransmission here, instead the Nak packet gets processed in sniffReceived stopRetransmission(it->first); stillValid = false; // just deleted it } else { - DEBUG_MSG("Sending reliable retransmission fr=0x%x,to=0x%x,id=0x%x, tries left=%d\n", p.packet->from, + LOG_DEBUG("Sending reliable retransmission fr=0x%x,to=0x%x,id=0x%x, tries left=%d\n", p.packet->from, p.packet->to, p.packet->id, p.numRetransmissions); // Note: we call the superclass version because we don't want to have our version of send() add a new @@ -226,7 +226,7 @@ void ReliableRouter::setNextTx(PendingPacket *pending) assert(iface); auto d = iface->getRetransmissionMsec(pending->packet); pending->nextTxMsec = millis() + d; - DEBUG_MSG("Setting next retransmission in %u msecs: ", d); + LOG_DEBUG("Setting next retransmission in %u msecs: ", d); printPacket("", pending->packet); setReceivedMessage(); // Run ASAP, so we can figure out our correct sleep time } diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 66e21d21d..826a3f089 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -48,9 +48,9 @@ Router::Router() : concurrency::OSThread("Router"), fromRadioQueue(MAX_RX_FROMRA { // This is called pre main(), don't touch anything here, the following code is not safe - /* DEBUG_MSG("Size of NodeInfo %d\n", sizeof(NodeInfo)); - DEBUG_MSG("Size of SubPacket %d\n", sizeof(SubPacket)); - DEBUG_MSG("Size of MeshPacket %d\n", sizeof(MeshPacket)); */ + /* LOG_DEBUG("Size of NodeInfo %d\n", sizeof(NodeInfo)); + LOG_DEBUG("Size of SubPacket %d\n", sizeof(SubPacket)); + LOG_DEBUG("Size of MeshPacket %d\n", sizeof(MeshPacket)); */ fromRadioQueue.setReader(this); } @@ -67,7 +67,7 @@ int32_t Router::runOnce() perhapsHandleReceived(mp); } - // DEBUG_MSG("sleeping forever!\n"); + // LOG_DEBUG("sleeping forever!\n"); return INT32_MAX; // Wait a long time - until we get woken for the message queue } @@ -103,7 +103,7 @@ PacketId generatePacketId() // pick a random initial sequence number at boot (to prevent repeated reboots always starting at 0) // Note: we mask the high order bit to ensure that we never pass a 'negative' number to random i = random(numPacketId & 0x7fffffff); - DEBUG_MSG("Initial packet id %u, numPacketId %u\n", i, numPacketId); + LOG_DEBUG("Initial packet id %u, numPacketId %u\n", i, numPacketId); } i++; @@ -136,14 +136,14 @@ void Router::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelI void Router::abortSendAndNak(Routing_Error err, MeshPacket *p) { - DEBUG_MSG("Error=%d, returning NAK and dropping packet.\n", err); + LOG_DEBUG("Error=%d, returning NAK and dropping packet.\n", err); sendAckNak(Routing_Error_NO_INTERFACE, getFrom(p), p->id, p->channel); packetPool.release(p); } void Router::setReceivedMessage() { - // DEBUG_MSG("set interval to ASAP\n"); + // LOG_DEBUG("set interval to ASAP\n"); setInterval(0); // Run ASAP, so we can figure out our correct sleep time runASAP = true; } @@ -173,10 +173,10 @@ ErrorCode Router::sendLocal(MeshPacket *p, RxSource src) void printBytes(const char *label, const uint8_t *p, size_t numbytes) { - DEBUG_MSG("%s: ", label); + LOG_DEBUG("%s: ", label); for (size_t i = 0; i < numbytes; i++) - DEBUG_MSG("%02x ", p[i]); - DEBUG_MSG("\n"); + LOG_DEBUG("%02x ", p[i]); + LOG_DEBUG("\n"); } /** @@ -193,7 +193,7 @@ ErrorCode Router::send(MeshPacket *p) float hourlyTxPercent = airTime->utilizationTXPercent(); if (hourlyTxPercent > myRegion->dutyCycle) { uint8_t silentMinutes = airTime->getSilentMinutes(hourlyTxPercent, myRegion->dutyCycle); - DEBUG_MSG("WARNING: Duty cycle limit exceeded. Aborting send for now, you can send again in %d minutes.\n", silentMinutes); + LOG_WARN("Duty cycle limit exceeded. Aborting send for now, you can send again in %d minutes.\n", silentMinutes); Routing_Error err = Routing_Error_DUTY_CYCLE_LIMIT; abortSendAndNak(err, p); return err; @@ -239,7 +239,7 @@ ErrorCode Router::send(MeshPacket *p) shouldActuallyEncrypt = false; } - DEBUG_MSG("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); + LOG_DEBUG("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); // the packet is currently in a decrypted state. send it now if they want decrypted packets if (mqtt && !shouldActuallyEncrypt) @@ -276,14 +276,14 @@ bool Router::cancelSending(NodeNum from, PacketId id) */ void Router::sniffReceived(const MeshPacket *p, const Routing *c) { - DEBUG_MSG("FIXME-update-db Sniffing packet\n"); + LOG_DEBUG("FIXME-update-db Sniffing packet\n"); // FIXME, update nodedb here for any packet that passes through us } bool perhapsDecode(MeshPacket *p) { - // DEBUG_MSG("\n\n** perhapsDecode payloadVariant - %d\n\n", p->which_payloadVariant); + // LOG_DEBUG("\n\n** perhapsDecode payloadVariant - %d\n\n", p->which_payloadVariant); if (p->which_payload_variant == MeshPacket_decoded_tag) return true; // If packet was already decoded just return @@ -307,9 +307,9 @@ bool perhapsDecode(MeshPacket *p) // Take those raw bytes and convert them back into a well structured protobuf we can understand memset(&p->decoded, 0, sizeof(p->decoded)); if (!pb_decode_from_bytes(bytes, rawSize, &Data_msg, &p->decoded)) { - DEBUG_MSG("Invalid protobufs in received mesh packet (bad psk?)!\n"); + LOG_DEBUG("Invalid protobufs in received mesh packet (bad psk?)!\n"); } else if (p->decoded.portnum == PortNum_UNKNOWN_APP) { - DEBUG_MSG("Invalid portnum (bad psk?)!\n"); + LOG_DEBUG("Invalid portnum (bad psk?)!\n"); } else { // parsing was successful p->which_payload_variant = MeshPacket_decoded_tag; // change type to decoded @@ -317,9 +317,9 @@ bool perhapsDecode(MeshPacket *p) /* if (p->decoded.portnum == PortNum_TEXT_MESSAGE_APP) { - DEBUG_MSG("\n\n** TEXT_MESSAGE_APP\n"); + LOG_DEBUG("\n\n** TEXT_MESSAGE_APP\n"); } else if (p->decoded.portnum == PortNum_TEXT_MESSAGE_COMPRESSED_APP) { - DEBUG_MSG("\n\n** PortNum_TEXT_MESSAGE_COMPRESSED_APP\n"); + LOG_DEBUG("\n\n** PortNum_TEXT_MESSAGE_COMPRESSED_APP\n"); } */ @@ -334,7 +334,7 @@ bool perhapsDecode(MeshPacket *p) decompressed_len = unishox2_decompress_simple(compressed_in, p->decoded.payload.size, decompressed_out); - // DEBUG_MSG("\n\n**\n\nDecompressed length - %d \n", decompressed_len); + // LOG_DEBUG("\n\n**\n\nDecompressed length - %d \n", decompressed_len); memcpy(p->decoded.payload.bytes, decompressed_out, decompressed_len); @@ -348,7 +348,7 @@ bool perhapsDecode(MeshPacket *p) } } - DEBUG_MSG("No suitable channel found for decoding, hash was 0x%x!\n", p->channel); + LOG_DEBUG("No suitable channel found for decoding, hash was 0x%x!\n", p->channel); return false; } @@ -374,20 +374,20 @@ Routing_Error perhapsEncode(MeshPacket *p) int compressed_len; compressed_len = unishox2_compress_simple(original_payload, p->decoded.payload.size, compressed_out); - DEBUG_MSG("Original length - %d \n", p->decoded.payload.size); - DEBUG_MSG("Compressed length - %d \n", compressed_len); - DEBUG_MSG("Original message - %s \n", p->decoded.payload.bytes); + LOG_DEBUG("Original length - %d \n", p->decoded.payload.size); + LOG_DEBUG("Compressed length - %d \n", compressed_len); + LOG_DEBUG("Original message - %s \n", p->decoded.payload.bytes); // If the compressed length is greater than or equal to the original size, don't use the compressed form if (compressed_len >= p->decoded.payload.size) { - DEBUG_MSG("Not using compressing message.\n"); + LOG_DEBUG("Not using compressing message.\n"); // Set the uncompressed payload varient anyway. Shouldn't hurt? // p->decoded.which_payloadVariant = Data_payload_tag; // Otherwise we use the compressor } else { - DEBUG_MSG("Using compressed message.\n"); + LOG_DEBUG("Using compressed message.\n"); // Copy the compressed data into the meshpacket p->decoded.payload.size = compressed_len; @@ -459,9 +459,9 @@ void Router::perhapsHandleReceived(MeshPacket *p) bool ignore = is_in_repeated(config.lora.ignore_incoming, p->from); if (ignore) - DEBUG_MSG("Ignoring incoming message, 0x%x is in our ignore list\n", p->from); + LOG_DEBUG("Ignoring incoming message, 0x%x is in our ignore list\n", p->from); else if (ignore |= shouldFilterReceived(p)) { - DEBUG_MSG("Incoming message was filtered 0x%x\n", p->from); + LOG_DEBUG("Incoming message was filtered 0x%x\n", p->from); } // Note: we avoid calling shouldFilterReceived if we are supposed to ignore certain nodes - because some overrides might diff --git a/src/mesh/SX126xInterface.cpp b/src/mesh/SX126xInterface.cpp index ea7600dfc..1caf8c9d8 100644 --- a/src/mesh/SX126xInterface.cpp +++ b/src/mesh/SX126xInterface.cpp @@ -12,7 +12,7 @@ SX126xInterface::SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, SPIClass &spi) : RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module) { - DEBUG_MSG("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_DEBUG("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); } /// Initialise the Driver transport hardware and software. @@ -55,17 +55,17 @@ bool SX126xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage, useRegulatorLDO); // \todo Display actual typename of the adapter, not just `SX126x` - DEBUG_MSG("SX126x init result %d\n", res); + LOG_DEBUG("SX126x init result %d\n", res); - DEBUG_MSG("Frequency set to %f\n", getFreq()); - DEBUG_MSG("Bandwidth set to %f\n", bw); - DEBUG_MSG("Power output set to %d\n", power); + LOG_DEBUG("Frequency set to %f\n", getFreq()); + LOG_DEBUG("Bandwidth set to %f\n", bw); + LOG_DEBUG("Power output set to %d\n", power); // current limit was removed from module' ctor // override default value (60 mA) res = lora.setCurrentLimit(currentLimit); - DEBUG_MSG("Current limit set to %f\n", currentLimit); - DEBUG_MSG("Current limit set result %d\n", res); + LOG_DEBUG("Current limit set to %f\n", currentLimit); + LOG_DEBUG("Current limit set result %d\n", res); #if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) // lora.begin sets Dio2 as RF switch control, which is not true if we are manually controlling RX and TX @@ -170,7 +170,7 @@ void SX126xInterface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) - DEBUG_MSG("SX126x standby failed with error %d\n", err); + LOG_DEBUG("SX126x standby failed with error %d\n", err); assert(err == RADIOLIB_ERR_NONE); @@ -192,7 +192,7 @@ void SX126xInterface::setStandby() template void SX126xInterface::addReceiveMetadata(MeshPacket *mp) { - // DEBUG_MSG("PacketStatus %x\n", lora.getPacketStatus()); + // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); mp->rx_rssi = lround(lora.getRSSI()); } @@ -275,7 +275,7 @@ bool SX126xInterface::isActivelyReceiving() // this is not correct - often always true - need to add an extra conditional // size_t bytesPending = lora.getPacketLength(); - // if (hasPreamble) DEBUG_MSG("rx hasPreamble\n"); + // if (hasPreamble) LOG_DEBUG("rx hasPreamble\n"); return hasPreamble; } @@ -284,7 +284,7 @@ bool SX126xInterface::sleep() { // Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // \todo Display actual typename of the adapter, not just `SX126x` - DEBUG_MSG("sx126x entering sleep mode (FIXME, don't keep config)\n"); + LOG_DEBUG("sx126x entering sleep mode (FIXME, don't keep config)\n"); setStandby(); // Stop any pending operations // turn off TCXO if it was powered diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index d056ab8dd..b96801794 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -49,10 +49,10 @@ bool SX128xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength); // \todo Display actual typename of the adapter, not just `SX128x` - DEBUG_MSG("SX128x init result %d\n", res); + LOG_DEBUG("SX128x init result %d\n", res); if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (res == RADIOLIB_ERR_INVALID_FREQUENCY)) { - DEBUG_MSG("Warning: Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting.\n"); + LOG_WARN("Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting.\n"); config.lora.region = Config_LoRaConfig_RegionCode_LORA_24; nodeDB.saveToDisk(SEGMENT_CONFIG); delay(2000); @@ -61,13 +61,13 @@ bool SX128xInterface::init() #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else - DEBUG_MSG("FIXME implement reboot for this platform. Skipping for now.\n"); + LOG_DEBUG("FIXME implement reboot for this platform. Skipping for now.\n"); #endif } - DEBUG_MSG("Frequency set to %f\n", getFreq()); - DEBUG_MSG("Bandwidth set to %f\n", bw); - DEBUG_MSG("Power output set to %d\n", power); + LOG_DEBUG("Frequency set to %f\n", getFreq()); + LOG_DEBUG("Bandwidth set to %f\n", bw); + LOG_DEBUG("Power output set to %d\n", power); if (res == RADIOLIB_ERR_NONE) res = lora.setCRC(2); @@ -145,7 +145,7 @@ void SX128xInterface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) - DEBUG_MSG("SX128x standby failed with error %d\n", err); + LOG_DEBUG("SX128x standby failed with error %d\n", err); assert(err == RADIOLIB_ERR_NONE); @@ -167,7 +167,7 @@ void SX128xInterface::setStandby() template void SX128xInterface::addReceiveMetadata(MeshPacket *mp) { - // DEBUG_MSG("PacketStatus %x\n", lora.getPacketStatus()); + // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); mp->rx_rssi = lround(lora.getRSSI()); } @@ -248,7 +248,7 @@ bool SX128xInterface::sleep() { // Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // \todo Display actual typename of the adapter, not just `SX128x` - DEBUG_MSG("SX128x entering sleep mode (FIXME, don't keep config)\n"); + LOG_DEBUG("SX128x entering sleep mode (FIXME, don't keep config)\n"); setStandby(); // Stop any pending operations // turn off TCXO if it was powered diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index 57911cf77..9be24cac9 100644 --- a/src/mesh/StreamAPI.cpp +++ b/src/mesh/StreamAPI.cpp @@ -95,7 +95,7 @@ void StreamAPI::writeStream() void StreamAPI::emitTxBuffer(size_t len) { if (len != 0) { - // DEBUG_MSG("emit tx %d\n", len); + // LOG_DEBUG("emit tx %d\n", len); txBuf[0] = START1; txBuf[1] = START2; txBuf[2] = (len >> 8) & 0xff; @@ -114,7 +114,7 @@ void StreamAPI::emitRebooted() fromRadioScratch.which_payload_variant = FromRadio_rebooted_tag; fromRadioScratch.rebooted = true; - // DEBUG_MSG("Emitting reboot packet for serial shell\n"); + // LOG_DEBUG("Emitting reboot packet for serial shell\n"); emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, &FromRadio_msg, &fromRadioScratch)); } diff --git a/src/mesh/eth/ethClient.cpp b/src/mesh/eth/ethClient.cpp index 793a86125..57decacdc 100644 --- a/src/mesh/eth/ethClient.cpp +++ b/src/mesh/eth/ethClient.cpp @@ -29,10 +29,10 @@ static int32_t reconnectETH() Ethernet.maintain(); if (!ethStartupComplete) { // Start web server - DEBUG_MSG("... Starting network services\n"); + LOG_DEBUG("... Starting network services\n"); #ifndef DISABLE_NTP - DEBUG_MSG("Starting NTP time client\n"); + LOG_DEBUG("Starting NTP time client\n"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif @@ -51,9 +51,9 @@ static int32_t reconnectETH() #ifndef DISABLE_NTP if (isEthernetAvailable() && (ntp_renew < millis())) { - DEBUG_MSG("Updating NTP time from %s\n", config.network.ntp_server); + LOG_DEBUG("Updating NTP time from %s\n", config.network.ntp_server); if (timeClient.update()) { - DEBUG_MSG("NTP Request Success - Setting RTCQualityNTP if needed\n"); + LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); struct timeval tv; tv.tv_sec = timeClient.getEpochTime(); @@ -64,7 +64,7 @@ static int32_t reconnectETH() ntp_renew = millis() + 43200 * 1000; // success, refresh every 12 hours } else { - DEBUG_MSG("NTP Update failed\n"); + LOG_DEBUG("NTP Update failed\n"); ntp_renew = millis() + 300 * 1000; // failure, retry every 5 minutes } } @@ -96,32 +96,32 @@ bool initEthernet() getMacAddr(mac); // FIXME use the BLE MAC for now... if (config.network.eth_mode == Config_NetworkConfig_EthMode_DHCP) { - DEBUG_MSG("starting Ethernet DHCP\n"); + LOG_DEBUG("starting Ethernet DHCP\n"); status = Ethernet.begin(mac); } else if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC) { - DEBUG_MSG("starting Ethernet Static\n"); + LOG_DEBUG("starting Ethernet Static\n"); Ethernet.begin(mac, config.network.ipv4_config.ip, config.network.ipv4_config.dns, config.network.ipv4_config.subnet); } else { - DEBUG_MSG("Ethernet Disabled\n"); + LOG_DEBUG("Ethernet Disabled\n"); return false; } if (status == 0) { if (Ethernet.hardwareStatus() == EthernetNoHardware) { - DEBUG_MSG("Ethernet shield was not found.\n"); + LOG_DEBUG("Ethernet shield was not found.\n"); return false; } else if (Ethernet.linkStatus() == LinkOFF) { - DEBUG_MSG("Ethernet cable is not connected.\n"); + LOG_DEBUG("Ethernet cable is not connected.\n"); return false; } else{ - DEBUG_MSG("Unknown Ethernet error.\n"); + LOG_DEBUG("Unknown Ethernet error.\n"); return false; } } else { - DEBUG_MSG("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); - DEBUG_MSG("Subnet Mask %u.%u.%u.%u\n",Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); - DEBUG_MSG("Gateway IP %u.%u.%u.%u\n",Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); - DEBUG_MSG("DNS Server IP %u.%u.%u.%u\n",Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); + LOG_DEBUG("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); + LOG_DEBUG("Subnet Mask %u.%u.%u.%u\n",Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); + LOG_DEBUG("Gateway IP %u.%u.%u.%u\n",Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); + LOG_DEBUG("DNS Server IP %u.%u.%u.%u\n",Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); } ethEvent = new Periodic("ethConnect", reconnectETH); @@ -129,7 +129,7 @@ bool initEthernet() return true; } else { - DEBUG_MSG("Not using Ethernet\n"); + LOG_DEBUG("Not using Ethernet\n"); return false; } } diff --git a/src/mesh/eth/ethServerAPI.cpp b/src/mesh/eth/ethServerAPI.cpp index 3b3b6bbc8..4159d285a 100644 --- a/src/mesh/eth/ethServerAPI.cpp +++ b/src/mesh/eth/ethServerAPI.cpp @@ -9,14 +9,14 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new ethServerPort(port); - DEBUG_MSG("API server listening on TCP port %d\n", port); + LOG_DEBUG("API server listening on TCP port %d\n", port); apiPort->init(); } } ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), concurrency::OSThread("ethServerAPI"), client(_client) { - DEBUG_MSG("Incoming ethernet connection\n"); + LOG_DEBUG("Incoming ethernet connection\n"); } ethServerAPI::~ethServerAPI() @@ -44,7 +44,7 @@ int32_t ethServerAPI::runOnce() if (client.connected()) { return StreamAPI::runOncePart(); } else { - DEBUG_MSG("Client dropped connection, suspending API service\n"); + LOG_DEBUG("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run return 0; } @@ -71,7 +71,7 @@ int32_t ethServerPort::runOnce() if (client) { // Close any previous connection (see FIXME in header file) if (openAPI) { - DEBUG_MSG("Force closing previous TCP connection\n"); + LOG_DEBUG("Force closing previous TCP connection\n"); delete openAPI; } diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index d01f3c4a5..22d97a2b6 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -140,7 +140,7 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("webAPI handleAPIv1FromRadio\n"); + LOG_DEBUG("webAPI handleAPIv1FromRadio\n"); /* For documentation, see: @@ -185,12 +185,12 @@ void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) res->write(txBuf, len); } - DEBUG_MSG("webAPI handleAPIv1FromRadio, len %d\n", len); + LOG_DEBUG("webAPI handleAPIv1FromRadio, len %d\n", len); } void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); + LOG_DEBUG("webAPI handleAPIv1ToRadio\n"); /* For documentation, see: @@ -213,11 +213,11 @@ void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) byte buffer[MAX_TO_FROM_RADIO_SIZE]; size_t s = req->readBytes(buffer, MAX_TO_FROM_RADIO_SIZE); - DEBUG_MSG("Received %d bytes from PUT request\n", s); + LOG_DEBUG("Received %d bytes from PUT request\n", s); webAPI.handleToRadio(buffer, s); res->write(buffer, s); - DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); + LOG_DEBUG("webAPI handleAPIv1ToRadio\n"); } void htmlDeleteDir(const char *dirname) @@ -238,7 +238,7 @@ void htmlDeleteDir(const char *dirname) } else { String fileName = String(file.name()); file.close(); - DEBUG_MSG(" %s\n", fileName.c_str()); + LOG_DEBUG(" %s\n", fileName.c_str()); FSCom.remove(fileName); } file = root.openNextFile(); @@ -379,13 +379,13 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) if (FSCom.exists(filename.c_str())) { file = FSCom.open(filename.c_str()); if (!file.available()) { - DEBUG_MSG("File not available - %s\n", filename.c_str()); + LOG_DEBUG("File not available - %s\n", filename.c_str()); } } else if (FSCom.exists(filenameGzip.c_str())) { file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Encoding", "gzip"); if (!file.available()) { - DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); + LOG_DEBUG("File not available - %s\n", filenameGzip.c_str()); } } else { has_set_content_type = true; @@ -393,7 +393,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Type", "text/html"); if (!file.available()) { - DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); + LOG_DEBUG("File not available - %s\n", filenameGzip.c_str()); res->println("Web server is running.

The content you are looking for can't be found. Please see: FAQ.

admin"); @@ -437,7 +437,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) return; } else { - DEBUG_MSG("ERROR: This should not have happened...\n"); + LOG_DEBUG("ERROR: This should not have happened...\n"); res->println("ERROR: This should not have happened..."); } } @@ -445,7 +445,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) void handleFormUpload(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("Form Upload - Disabling keep-alive\n"); + LOG_DEBUG("Form Upload - Disabling keep-alive\n"); res->setHeader("Connection", "close"); // First, we need to check the encoding of the form that we have received. @@ -453,7 +453,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // Then we select the body parser based on the encoding. // Actually we do this only for documentary purposes, we know the form is going // to be multipart/form-data. - DEBUG_MSG("Form Upload - Creating body parser reference\n"); + LOG_DEBUG("Form Upload - Creating body parser reference\n"); HTTPBodyParser *parser; std::string contentType = req->getHeader("Content-Type"); @@ -469,7 +469,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // Now, we can decide based on the content type: if (contentType == "multipart/form-data") { - DEBUG_MSG("Form Upload - multipart/form-data\n"); + LOG_DEBUG("Form Upload - multipart/form-data\n"); parser = new HTTPMultipartBodyParser(req); } else { Serial.printf("Unknown POST Content-Type: %s\n", contentType.c_str()); @@ -499,19 +499,19 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) std::string filename = parser->getFieldFilename(); std::string mimeType = parser->getFieldMimeType(); // We log all three values, so that you can observe the upload on the serial monitor: - DEBUG_MSG("handleFormUpload: field name='%s', filename='%s', mimetype='%s'\n", name.c_str(), filename.c_str(), + LOG_DEBUG("handleFormUpload: field name='%s', filename='%s', mimetype='%s'\n", name.c_str(), filename.c_str(), mimeType.c_str()); // Double check that it is what we expect if (name != "file") { - DEBUG_MSG("Skipping unexpected field\n"); + LOG_DEBUG("Skipping unexpected field\n"); res->println("

No file found.

"); return; } // Double check that it is what we expect if (filename == "") { - DEBUG_MSG("Skipping unexpected field\n"); + LOG_DEBUG("Skipping unexpected field\n"); res->println("

No file found.

"); return; } @@ -532,7 +532,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) byte buf[512]; size_t readLength = parser->read(buf, 512); - // DEBUG_MSG("\n\nreadLength - %i\n", readLength); + // LOG_DEBUG("\n\nreadLength - %i\n", readLength); // Abort the transfer if there is less than 50k space left on the filesystem. if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { @@ -548,7 +548,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // if (readLength) { file.write(buf, readLength); fileLength += readLength; - DEBUG_MSG("File Length %i\n", fileLength); + LOG_DEBUG("File Length %i\n", fileLength); //} } // enableLoopWDT(); @@ -671,7 +671,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res) */ void handleHotspot(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("Hotspot Request\n"); + LOG_DEBUG("Hotspot Request\n"); /* If we don't do a redirect, be sure to return a "Success" message @@ -697,7 +697,7 @@ void handleDeleteFsContent(HTTPRequest *req, HTTPResponse *res) res->println("

Meshtastic

\n"); res->println("Deleting Content in /static/*"); - DEBUG_MSG("Deleting files from /static/* : \n"); + LOG_DEBUG("Deleting files from /static/* : \n"); htmlDeleteDir("/static"); @@ -771,7 +771,7 @@ void handleRestart(HTTPRequest *req, HTTPResponse *res) res->println("

Meshtastic

\n"); res->println("Restarting"); - DEBUG_MSG("***** Restarted on HTTP(s) Request *****\n"); + LOG_DEBUG("***** Restarted on HTTP(s) Request *****\n"); webServerThread->requestRestart = (millis() / 1000) + 5; } diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index c1844b0cb..10f8067f6 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -68,19 +68,19 @@ static void taskCreateCert(void *parameter) #if 0 // Delete the saved certs (used in debugging) - DEBUG_MSG("Deleting any saved SSL keys ...\n"); + LOG_DEBUG("Deleting any saved SSL keys ...\n"); // prefs.clear(); prefs.remove("PK"); prefs.remove("cert"); #endif - DEBUG_MSG("Checking if we have a previously saved SSL Certificate.\n"); + LOG_DEBUG("Checking if we have a previously saved SSL Certificate.\n"); size_t pkLen = prefs.getBytesLength("PK"); size_t certLen = prefs.getBytesLength("cert"); if (pkLen && certLen) { - DEBUG_MSG("Existing SSL Certificate found!\n"); + LOG_DEBUG("Existing SSL Certificate found!\n"); uint8_t *pkBuffer = new uint8_t[pkLen]; prefs.getBytes("PK", pkBuffer, pkLen); @@ -90,12 +90,12 @@ static void taskCreateCert(void *parameter) cert = new SSLCert(certBuffer, certLen, pkBuffer, pkLen); - DEBUG_MSG("Retrieved Private Key: %d Bytes\n", cert->getPKLength()); - DEBUG_MSG("Retrieved Certificate: %d Bytes\n", cert->getCertLength()); + LOG_DEBUG("Retrieved Private Key: %d Bytes\n", cert->getPKLength()); + LOG_DEBUG("Retrieved Certificate: %d Bytes\n", cert->getCertLength()); } else { - DEBUG_MSG("Creating the certificate. This may take a while. Please wait...\n"); + LOG_DEBUG("Creating the certificate. This may take a while. Please wait...\n"); yield(); cert = new SSLCert(); yield(); @@ -104,14 +104,14 @@ static void taskCreateCert(void *parameter) yield(); if (createCertResult != 0) { - DEBUG_MSG("Creating the certificate failed\n"); + LOG_DEBUG("Creating the certificate failed\n"); } else { - DEBUG_MSG("Creating the certificate was successful\n"); + LOG_DEBUG("Creating the certificate was successful\n"); - DEBUG_MSG("Created Private Key: %d Bytes\n", cert->getPKLength()); + LOG_DEBUG("Created Private Key: %d Bytes\n", cert->getPKLength()); - DEBUG_MSG("Created Certificate: %d Bytes\n", cert->getCertLength()); + LOG_DEBUG("Created Certificate: %d Bytes\n", cert->getCertLength()); prefs.putBytes("PK", (uint8_t *)cert->getPKData(), cert->getPKLength()); prefs.putBytes("cert", (uint8_t *)cert->getCertData(), cert->getCertLength()); @@ -140,11 +140,11 @@ void createSSLCert() 16, /* Priority of the task. */ NULL); /* Task handle. */ - DEBUG_MSG("Waiting for SSL Cert to be generated.\n"); + LOG_DEBUG("Waiting for SSL Cert to be generated.\n"); while (!isCertReady) { if ((millis() / 500) % 2) { if (runLoop) { - DEBUG_MSG("."); + LOG_DEBUG("."); yield(); esp_task_wdt_reset(); @@ -159,7 +159,7 @@ void createSSLCert() runLoop = true; } } - DEBUG_MSG("SSL Cert Ready!\n"); + LOG_DEBUG("SSL Cert Ready!\n"); } } @@ -169,7 +169,7 @@ WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") {} int32_t WebServerThread::runOnce() { - // DEBUG_MSG("WebServerThread::runOnce()\n"); + // LOG_DEBUG("WebServerThread::runOnce()\n"); handleWebResponse(); if (requestRestart && (millis() / 1000) > requestRestart) { @@ -182,7 +182,7 @@ int32_t WebServerThread::runOnce() void initWebServer() { - DEBUG_MSG("Initializing Web Server ...\n"); + LOG_DEBUG("Initializing Web Server ...\n"); // We can now use the new certificate to setup our server as usual. secureServer = new HTTPSServer(cert); @@ -191,15 +191,15 @@ void initWebServer() registerHandlers(insecureServer, secureServer); if (secureServer) { - DEBUG_MSG("Starting Secure Web Server...\n"); + LOG_DEBUG("Starting Secure Web Server...\n"); secureServer->start(); } - DEBUG_MSG("Starting Insecure Web Server...\n"); + LOG_DEBUG("Starting Insecure Web Server...\n"); insecureServer->start(); if (insecureServer->isRunning()) { - DEBUG_MSG("Web Servers Ready! :-) \n"); + LOG_DEBUG("Web Servers Ready! :-) \n"); isWebServerReady = true; } else { - DEBUG_MSG("Web Servers Failed! ;-( \n"); + LOG_DEBUG("Web Servers Failed! ;-( \n"); } } diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 731197e60..13e127756 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -56,7 +56,7 @@ static int32_t reconnectWiFi() // Make sure we clear old connection credentials WiFi.disconnect(false, true); - DEBUG_MSG("Reconnecting to WiFi access point %s\n",wifiName); + LOG_DEBUG("Reconnecting to WiFi access point %s\n",wifiName); WiFi.mode(WIFI_MODE_STA); WiFi.begin(wifiName, wifiPsw); @@ -64,9 +64,9 @@ static int32_t reconnectWiFi() #ifndef DISABLE_NTP if (WiFi.isConnected() && (((millis() - lastrun_ntp) > 43200000) || (lastrun_ntp == 0))) { // every 12 hours - DEBUG_MSG("Updating NTP time from %s\n",config.network.ntp_server); + LOG_DEBUG("Updating NTP time from %s\n",config.network.ntp_server); if (timeClient.update()) { - DEBUG_MSG("NTP Request Success - Setting RTCQualityNTP if needed\n"); + LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); struct timeval tv; tv.tv_sec = timeClient.getEpochTime(); @@ -76,7 +76,7 @@ static int32_t reconnectWiFi() lastrun_ntp = millis(); } else { - DEBUG_MSG("NTP Update failed\n"); + LOG_DEBUG("NTP Update failed\n"); } } #endif @@ -101,12 +101,12 @@ bool isWifiAvailable() // Disable WiFi void deinitWifi() { - DEBUG_MSG("WiFi deinit\n"); + LOG_DEBUG("WiFi deinit\n"); if (isWifiAvailable()) { WiFi.disconnect(true); WiFi.mode(WIFI_MODE_NULL); - DEBUG_MSG("WiFi Turned Off\n"); + LOG_DEBUG("WiFi Turned Off\n"); // WiFi.printDiag(Serial); } } @@ -115,20 +115,20 @@ static void onNetworkConnected() { if (!APStartupComplete) { // Start web server - DEBUG_MSG("Starting network services\n"); + LOG_DEBUG("Starting network services\n"); // start mdns if (!MDNS.begin("Meshtastic")) { - DEBUG_MSG("Error setting up MDNS responder!\n"); + LOG_DEBUG("Error setting up MDNS responder!\n"); } else { - DEBUG_MSG("mDNS responder started\n"); - DEBUG_MSG("mDNS Host: Meshtastic.local\n"); + LOG_DEBUG("mDNS responder started\n"); + LOG_DEBUG("mDNS Host: Meshtastic.local\n"); MDNS.addService("http", "tcp", 80); MDNS.addService("https", "tcp", 443); } #ifndef DISABLE_NTP - DEBUG_MSG("Starting NTP time client\n"); + LOG_DEBUG("Starting NTP time client\n"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif @@ -196,12 +196,12 @@ bool initWifi() }, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); - DEBUG_MSG("JOINING WIFI soon: ssid=%s\n", wifiName); + LOG_DEBUG("JOINING WIFI soon: ssid=%s\n", wifiName); wifiReconnect = new Periodic("WifiConnect", reconnectWiFi); } return true; } else { - DEBUG_MSG("Not using WIFI\n"); + LOG_DEBUG("Not using WIFI\n"); return false; } } @@ -209,137 +209,137 @@ bool initWifi() // Called by the Espressif SDK to static void WiFiEvent(WiFiEvent_t event) { - DEBUG_MSG("WiFi-Event %d: ", event); + LOG_DEBUG("WiFi-Event %d: ", event); switch (event) { case ARDUINO_EVENT_WIFI_READY: - DEBUG_MSG("WiFi interface ready\n"); + LOG_DEBUG("WiFi interface ready\n"); break; case ARDUINO_EVENT_WIFI_SCAN_DONE: - DEBUG_MSG("Completed scan for access points\n"); + LOG_DEBUG("Completed scan for access points\n"); break; case ARDUINO_EVENT_WIFI_STA_START: - DEBUG_MSG("WiFi station started\n"); + LOG_DEBUG("WiFi station started\n"); break; case ARDUINO_EVENT_WIFI_STA_STOP: - DEBUG_MSG("WiFi station stopped\n"); + LOG_DEBUG("WiFi station stopped\n"); break; case ARDUINO_EVENT_WIFI_STA_CONNECTED: - DEBUG_MSG("Connected to access point\n"); + LOG_DEBUG("Connected to access point\n"); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - DEBUG_MSG("Disconnected from WiFi access point\n"); + LOG_DEBUG("Disconnected from WiFi access point\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: - DEBUG_MSG("Authentication mode of access point has changed\n"); + LOG_DEBUG("Authentication mode of access point has changed\n"); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: - DEBUG_MSG("Obtained IP address: "); + LOG_DEBUG("Obtained IP address: "); Serial.println(WiFi.localIP()); onNetworkConnected(); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP6: - DEBUG_MSG("Obtained IP6 address: "); + LOG_DEBUG("Obtained IP6 address: "); Serial.println(WiFi.localIPv6()); break; case ARDUINO_EVENT_WIFI_STA_LOST_IP: - DEBUG_MSG("Lost IP address and IP address is reset to 0\n"); + LOG_DEBUG("Lost IP address and IP address is reset to 0\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; case ARDUINO_EVENT_WPS_ER_SUCCESS: - DEBUG_MSG("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); + LOG_DEBUG("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_FAILED: - DEBUG_MSG("WiFi Protected Setup (WPS): failed in enrollee mode\n"); + LOG_DEBUG("WiFi Protected Setup (WPS): failed in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_TIMEOUT: - DEBUG_MSG("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); + LOG_DEBUG("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_PIN: - DEBUG_MSG("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); + LOG_DEBUG("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP: - DEBUG_MSG("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); + LOG_DEBUG("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); break; case ARDUINO_EVENT_WIFI_AP_START: - DEBUG_MSG("WiFi access point started\n"); + LOG_DEBUG("WiFi access point started\n"); break; case ARDUINO_EVENT_WIFI_AP_STOP: - DEBUG_MSG("WiFi access point stopped\n"); + LOG_DEBUG("WiFi access point stopped\n"); break; case ARDUINO_EVENT_WIFI_AP_STACONNECTED: - DEBUG_MSG("Client connected\n"); + LOG_DEBUG("Client connected\n"); break; case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: - DEBUG_MSG("Client disconnected\n"); + LOG_DEBUG("Client disconnected\n"); break; case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: - DEBUG_MSG("Assigned IP address to client\n"); + LOG_DEBUG("Assigned IP address to client\n"); break; case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: - DEBUG_MSG("Received probe request\n"); + LOG_DEBUG("Received probe request\n"); break; case ARDUINO_EVENT_WIFI_AP_GOT_IP6: - DEBUG_MSG("IPv6 is preferred\n"); + LOG_DEBUG("IPv6 is preferred\n"); break; case ARDUINO_EVENT_WIFI_FTM_REPORT: - DEBUG_MSG("Fast Transition Management report\n"); + LOG_DEBUG("Fast Transition Management report\n"); break; case ARDUINO_EVENT_ETH_START: - DEBUG_MSG("Ethernet started\n"); + LOG_DEBUG("Ethernet started\n"); break; case ARDUINO_EVENT_ETH_STOP: - DEBUG_MSG("Ethernet stopped\n"); + LOG_DEBUG("Ethernet stopped\n"); break; case ARDUINO_EVENT_ETH_CONNECTED: - DEBUG_MSG("Ethernet connected\n"); + LOG_DEBUG("Ethernet connected\n"); break; case ARDUINO_EVENT_ETH_DISCONNECTED: - DEBUG_MSG("Ethernet disconnected\n"); + LOG_DEBUG("Ethernet disconnected\n"); break; case ARDUINO_EVENT_ETH_GOT_IP: - DEBUG_MSG("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); + LOG_DEBUG("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); break; case ARDUINO_EVENT_ETH_GOT_IP6: - DEBUG_MSG("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); + LOG_DEBUG("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); break; case ARDUINO_EVENT_SC_SCAN_DONE: - DEBUG_MSG("SmartConfig: Scan done\n"); + LOG_DEBUG("SmartConfig: Scan done\n"); break; case ARDUINO_EVENT_SC_FOUND_CHANNEL: - DEBUG_MSG("SmartConfig: Found channel\n"); + LOG_DEBUG("SmartConfig: Found channel\n"); break; case ARDUINO_EVENT_SC_GOT_SSID_PSWD: - DEBUG_MSG("SmartConfig: Got SSID and password\n"); + LOG_DEBUG("SmartConfig: Got SSID and password\n"); break; case ARDUINO_EVENT_SC_SEND_ACK_DONE: - DEBUG_MSG("SmartConfig: Send ACK done\n"); + LOG_DEBUG("SmartConfig: Send ACK done\n"); break; case ARDUINO_EVENT_PROV_INIT: - DEBUG_MSG("Provisioning: Init\n"); + LOG_DEBUG("Provisioning: Init\n"); break; case ARDUINO_EVENT_PROV_DEINIT: - DEBUG_MSG("Provisioning: Stopped\n"); + LOG_DEBUG("Provisioning: Stopped\n"); break; case ARDUINO_EVENT_PROV_START: - DEBUG_MSG("Provisioning: Started\n"); + LOG_DEBUG("Provisioning: Started\n"); break; case ARDUINO_EVENT_PROV_END: - DEBUG_MSG("Provisioning: End\n"); + LOG_DEBUG("Provisioning: End\n"); break; case ARDUINO_EVENT_PROV_CRED_RECV: - DEBUG_MSG("Provisioning: Credentials received\n"); + LOG_DEBUG("Provisioning: Credentials received\n"); break; case ARDUINO_EVENT_PROV_CRED_FAIL: - DEBUG_MSG("Provisioning: Credentials failed\n"); + LOG_DEBUG("Provisioning: Credentials failed\n"); break; case ARDUINO_EVENT_PROV_CRED_SUCCESS: - DEBUG_MSG("Provisioning: Credentials success\n"); + LOG_DEBUG("Provisioning: Credentials success\n"); break; default: break; diff --git a/src/mesh/mesh-pb-constants.cpp b/src/mesh/mesh-pb-constants.cpp index b2b99644c..cbf4c76d3 100644 --- a/src/mesh/mesh-pb-constants.cpp +++ b/src/mesh/mesh-pb-constants.cpp @@ -12,7 +12,7 @@ size_t pb_encode_to_bytes(uint8_t *destbuf, size_t destbufsize, const pb_msgdesc { pb_ostream_t stream = pb_ostream_from_buffer(destbuf, destbufsize); if (!pb_encode(&stream, fields, src_struct)) { - DEBUG_MSG("Panic: can't encode protobuf reason='%s'\n", PB_GET_ERROR(&stream)); + LOG_DEBUG("Panic: can't encode protobuf reason='%s'\n", PB_GET_ERROR(&stream)); assert(0); // If this asser fails it probably means you made a field too large for the max limits specified in mesh.options } else { return stream.bytes_written; @@ -24,7 +24,7 @@ bool pb_decode_from_bytes(const uint8_t *srcbuf, size_t srcbufsize, const pb_msg { pb_istream_t stream = pb_istream_from_buffer(srcbuf, srcbufsize); if (!pb_decode(&stream, fields, dest_struct)) { - DEBUG_MSG("Error: can't decode protobuf reason='%s', pb_msgdesc 0x%p\n", PB_GET_ERROR(&stream), fields); + LOG_DEBUG("Error: can't decode protobuf reason='%s', pb_msgdesc 0x%p\n", PB_GET_ERROR(&stream), fields); return false; } else { return true; @@ -56,7 +56,7 @@ bool readcb(pb_istream_t *stream, uint8_t *buf, size_t count) bool writecb(pb_ostream_t *stream, const uint8_t *buf, size_t count) { File *file = (File *)stream->state; - // DEBUG_MSG("writing %d bytes to protobuf file\n", count); + // LOG_DEBUG("writing %d bytes to protobuf file\n", count); return file->write(buf, count) == count; } #endif diff --git a/src/mesh/wifi/WiFiServerAPI.cpp b/src/mesh/wifi/WiFiServerAPI.cpp index 78936176b..98e38f926 100644 --- a/src/mesh/wifi/WiFiServerAPI.cpp +++ b/src/mesh/wifi/WiFiServerAPI.cpp @@ -9,14 +9,14 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new WiFiServerPort(port); - DEBUG_MSG("API server listening on TCP port %d\n", port); + LOG_DEBUG("API server listening on TCP port %d\n", port); apiPort->init(); } } WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), concurrency::OSThread("WiFiServerAPI"), client(_client) { - DEBUG_MSG("Incoming wifi connection\n"); + LOG_DEBUG("Incoming wifi connection\n"); } WiFiServerAPI::~WiFiServerAPI() @@ -44,7 +44,7 @@ int32_t WiFiServerAPI::runOnce() if (client.connected()) { return StreamAPI::runOncePart(); } else { - DEBUG_MSG("Client dropped connection, suspending API service\n"); + LOG_DEBUG("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run return 0; } @@ -71,7 +71,7 @@ int32_t WiFiServerPort::runOnce() if (client) { // Close any previous connection (see FIXME in header file) if (openAPI) { - DEBUG_MSG("Force closing previous TCP connection\n"); + LOG_DEBUG("Force closing previous TCP connection\n"); delete openAPI; } diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 023cf7396..30bff79b6 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -50,23 +50,23 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) * Getters */ case AdminMessage_get_owner_request_tag: - DEBUG_MSG("Client is getting owner\n"); + LOG_DEBUG("Client is getting owner\n"); handleGetOwner(mp); break; case AdminMessage_get_config_request_tag: - DEBUG_MSG("Client is getting config\n"); + LOG_DEBUG("Client is getting config\n"); handleGetConfig(mp, r->get_config_request); break; case AdminMessage_get_module_config_request_tag: - DEBUG_MSG("Client is getting module config\n"); + LOG_DEBUG("Client is getting module config\n"); handleGetModuleConfig(mp, r->get_module_config_request); break; case AdminMessage_get_channel_request_tag: { uint32_t i = r->get_channel_request - 1; - DEBUG_MSG("Client is getting channel %u\n", i); + LOG_DEBUG("Client is getting channel %u\n", i); if (i >= MAX_NUM_CHANNELS) myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); else @@ -78,22 +78,22 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) * Setters */ case AdminMessage_set_owner_tag: - DEBUG_MSG("Client is setting owner\n"); + LOG_DEBUG("Client is setting owner\n"); handleSetOwner(r->set_owner); break; case AdminMessage_set_config_tag: - DEBUG_MSG("Client is setting the config\n"); + LOG_DEBUG("Client is setting the config\n"); handleSetConfig(r->set_config); break; case AdminMessage_set_module_config_tag: - DEBUG_MSG("Client is setting the module config\n"); + LOG_DEBUG("Client is setting the module config\n"); handleSetModuleConfig(r->set_module_config); break; case AdminMessage_set_channel_tag: - DEBUG_MSG("Client is setting channel %d\n", r->set_channel.index); + LOG_DEBUG("Client is setting channel %d\n", r->set_channel.index); if (r->set_channel.index < 0 || r->set_channel.index >= (int)MAX_NUM_CHANNELS) myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); else @@ -111,15 +111,15 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) int32_t s = r->reboot_ota_seconds; #ifdef ARCH_ESP32 if (BleOta::getOtaAppVersion().isEmpty()) { - DEBUG_MSG("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); + LOG_DEBUG("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); screen->startRebootScreen(); }else{ screen->startFirmwareUpdateScreen(); BleOta::switchToOtaApp(); - DEBUG_MSG("Rebooting to OTA in %d seconds\n", s); + LOG_DEBUG("Rebooting to OTA in %d seconds\n", s); } #else - DEBUG_MSG("Not on ESP32, scheduling regular reboot in %d seconds\n", s); + LOG_DEBUG("Not on ESP32, scheduling regular reboot in %d seconds\n", s); screen->startRebootScreen(); #endif rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); @@ -127,40 +127,40 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) } case AdminMessage_shutdown_seconds_tag: { int32_t s = r->shutdown_seconds; - DEBUG_MSG("Shutdown in %d seconds\n", s); + LOG_DEBUG("Shutdown in %d seconds\n", s); shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } case AdminMessage_get_device_metadata_request_tag: { - DEBUG_MSG("Client is getting device metadata\n"); + LOG_DEBUG("Client is getting device metadata\n"); handleGetDeviceMetadata(mp); break; } case AdminMessage_factory_reset_tag: { - DEBUG_MSG("Initiating factory reset\n"); + LOG_DEBUG("Initiating factory reset\n"); nodeDB.factoryReset(); reboot(DEFAULT_REBOOT_SECONDS); break; } case AdminMessage_nodedb_reset_tag: { - DEBUG_MSG("Initiating node-db reset\n"); + LOG_DEBUG("Initiating node-db reset\n"); nodeDB.resetNodes(); reboot(DEFAULT_REBOOT_SECONDS); break; } case AdminMessage_begin_edit_settings_tag: { - DEBUG_MSG("Beginning transaction for editing settings\n"); + LOG_DEBUG("Beginning transaction for editing settings\n"); hasOpenEditTransaction = true; break; } case AdminMessage_commit_edit_settings_tag: { - DEBUG_MSG("Committing transaction for edited settings\n"); + LOG_DEBUG("Committing transaction for edited settings\n"); hasOpenEditTransaction = false; saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); break; } #ifdef ARCH_PORTDUINO case AdminMessage_exit_simulator_tag: - DEBUG_MSG("Exiting simulator\n"); + LOG_DEBUG("Exiting simulator\n"); _exit(0); break; #endif @@ -172,10 +172,10 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) if (handleResult == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) { myReply = allocDataProtobuf(res); } else if (mp.decoded.want_response) { - DEBUG_MSG("We did not responded to a request that wanted a respond. req.variant=%d\n", r->which_payload_variant); + LOG_DEBUG("We did not responded to a request that wanted a respond. req.variant=%d\n", r->which_payload_variant); } else if (handleResult != AdminMessageHandleResult::HANDLED) { // Probably a message sent by us or sent to our local node. FIXME, we should avoid scanning these messages - DEBUG_MSG("Ignoring nonrelevant admin %d\n", r->which_payload_variant); + LOG_DEBUG("Ignoring nonrelevant admin %d\n", r->which_payload_variant); } break; } @@ -229,7 +229,7 @@ void AdminModule::handleSetConfig(const Config &c) switch (c.which_payload_variant) { case Config_device_tag: - DEBUG_MSG("Setting config: Device\n"); + LOG_DEBUG("Setting config: Device\n"); config.has_device = true; config.device = c.payload_variant.device; // If we're setting router role for the first time, install its intervals @@ -240,29 +240,29 @@ void AdminModule::handleSetConfig(const Config &c) } break; case Config_position_tag: - DEBUG_MSG("Setting config: Position\n"); + LOG_DEBUG("Setting config: Position\n"); config.has_position = true; config.position = c.payload_variant.position; // Save nodedb as well in case we got a fixed position packet saveChanges(SEGMENT_DEVICESTATE, false); break; case Config_power_tag: - DEBUG_MSG("Setting config: Power\n"); + LOG_DEBUG("Setting config: Power\n"); config.has_power = true; config.power = c.payload_variant.power; break; case Config_network_tag: - DEBUG_MSG("Setting config: WiFi\n"); + LOG_DEBUG("Setting config: WiFi\n"); config.has_network = true; config.network = c.payload_variant.network; break; case Config_display_tag: - DEBUG_MSG("Setting config: Display\n"); + LOG_DEBUG("Setting config: Display\n"); config.has_display = true; config.display = c.payload_variant.display; break; case Config_lora_tag: - DEBUG_MSG("Setting config: LoRa\n"); + LOG_DEBUG("Setting config: LoRa\n"); config.has_lora = true; config.lora = c.payload_variant.lora; if (isRegionUnset && @@ -271,7 +271,7 @@ void AdminModule::handleSetConfig(const Config &c) } break; case Config_bluetooth_tag: - DEBUG_MSG("Setting config: Bluetooth\n"); + LOG_DEBUG("Setting config: Bluetooth\n"); config.has_bluetooth = true; config.bluetooth = c.payload_variant.bluetooth; break; @@ -284,47 +284,47 @@ void AdminModule::handleSetModuleConfig(const ModuleConfig &c) { switch (c.which_payload_variant) { case ModuleConfig_mqtt_tag: - DEBUG_MSG("Setting module config: MQTT\n"); + LOG_DEBUG("Setting module config: MQTT\n"); moduleConfig.has_mqtt = true; moduleConfig.mqtt = c.payload_variant.mqtt; break; case ModuleConfig_serial_tag: - DEBUG_MSG("Setting module config: Serial\n"); + LOG_DEBUG("Setting module config: Serial\n"); moduleConfig.has_serial = true; moduleConfig.serial = c.payload_variant.serial; break; case ModuleConfig_external_notification_tag: - DEBUG_MSG("Setting module config: External Notification\n"); + LOG_DEBUG("Setting module config: External Notification\n"); moduleConfig.has_external_notification = true; moduleConfig.external_notification = c.payload_variant.external_notification; break; case ModuleConfig_store_forward_tag: - DEBUG_MSG("Setting module config: Store & Forward\n"); + LOG_DEBUG("Setting module config: Store & Forward\n"); moduleConfig.has_store_forward = true; moduleConfig.store_forward = c.payload_variant.store_forward; break; case ModuleConfig_range_test_tag: - DEBUG_MSG("Setting module config: Range Test\n"); + LOG_DEBUG("Setting module config: Range Test\n"); moduleConfig.has_range_test = true; moduleConfig.range_test = c.payload_variant.range_test; break; case ModuleConfig_telemetry_tag: - DEBUG_MSG("Setting module config: Telemetry\n"); + LOG_DEBUG("Setting module config: Telemetry\n"); moduleConfig.has_telemetry = true; moduleConfig.telemetry = c.payload_variant.telemetry; break; case ModuleConfig_canned_message_tag: - DEBUG_MSG("Setting module config: Canned Message\n"); + LOG_DEBUG("Setting module config: Canned Message\n"); moduleConfig.has_canned_message = true; moduleConfig.canned_message = c.payload_variant.canned_message; break; case ModuleConfig_audio_tag: - DEBUG_MSG("Setting module config: Audio\n"); + LOG_DEBUG("Setting module config: Audio\n"); moduleConfig.has_audio = true; moduleConfig.audio = c.payload_variant.audio; break; case ModuleConfig_remote_hardware_tag: - DEBUG_MSG("Setting module config: Remote Hardware\n"); + LOG_DEBUG("Setting module config: Remote Hardware\n"); moduleConfig.has_remote_hardware = true; moduleConfig.remote_hardware = c.payload_variant.remote_hardware; break; @@ -363,38 +363,38 @@ void AdminModule::handleGetConfig(const MeshPacket &req, const uint32_t configTy if (req.decoded.want_response) { switch (configType) { case AdminMessage_ConfigType_DEVICE_CONFIG: - DEBUG_MSG("Getting config: Device\n"); + LOG_DEBUG("Getting config: Device\n"); res.get_config_response.which_payload_variant = Config_device_tag; res.get_config_response.payload_variant.device = config.device; break; case AdminMessage_ConfigType_POSITION_CONFIG: - DEBUG_MSG("Getting config: Position\n"); + LOG_DEBUG("Getting config: Position\n"); res.get_config_response.which_payload_variant = Config_position_tag; res.get_config_response.payload_variant.position = config.position; break; case AdminMessage_ConfigType_POWER_CONFIG: - DEBUG_MSG("Getting config: Power\n"); + LOG_DEBUG("Getting config: Power\n"); res.get_config_response.which_payload_variant = Config_power_tag; res.get_config_response.payload_variant.power = config.power; break; case AdminMessage_ConfigType_NETWORK_CONFIG: - DEBUG_MSG("Getting config: Network\n"); + LOG_DEBUG("Getting config: Network\n"); res.get_config_response.which_payload_variant = Config_network_tag; res.get_config_response.payload_variant.network = config.network; writeSecret(res.get_config_response.payload_variant.network.wifi_psk, config.network.wifi_psk); break; case AdminMessage_ConfigType_DISPLAY_CONFIG: - DEBUG_MSG("Getting config: Display\n"); + LOG_DEBUG("Getting config: Display\n"); res.get_config_response.which_payload_variant = Config_display_tag; res.get_config_response.payload_variant.display = config.display; break; case AdminMessage_ConfigType_LORA_CONFIG: - DEBUG_MSG("Getting config: LoRa\n"); + LOG_DEBUG("Getting config: LoRa\n"); res.get_config_response.which_payload_variant = Config_lora_tag; res.get_config_response.payload_variant.lora = config.lora; break; case AdminMessage_ConfigType_BLUETOOTH_CONFIG: - DEBUG_MSG("Getting config: Bluetooth\n"); + LOG_DEBUG("Getting config: Bluetooth\n"); res.get_config_response.which_payload_variant = Config_bluetooth_tag; res.get_config_response.payload_variant.bluetooth = config.bluetooth; break; @@ -418,48 +418,48 @@ void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t co if (req.decoded.want_response) { switch (configType) { case AdminMessage_ModuleConfigType_MQTT_CONFIG: - DEBUG_MSG("Getting module config: MQTT\n"); + LOG_DEBUG("Getting module config: MQTT\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_mqtt_tag; res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt; break; case AdminMessage_ModuleConfigType_SERIAL_CONFIG: - DEBUG_MSG("Getting module config: Serial\n"); + LOG_DEBUG("Getting module config: Serial\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_serial_tag; res.get_module_config_response.payload_variant.serial = moduleConfig.serial; break; case AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: - DEBUG_MSG("Getting module config: External Notification\n"); + LOG_DEBUG("Getting module config: External Notification\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_external_notification_tag; res.get_module_config_response.payload_variant.external_notification = moduleConfig.external_notification; break; case AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: - DEBUG_MSG("Getting module config: Store & Forward\n"); + LOG_DEBUG("Getting module config: Store & Forward\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_store_forward_tag; res.get_module_config_response.payload_variant.store_forward = moduleConfig.store_forward; break; case AdminMessage_ModuleConfigType_RANGETEST_CONFIG: - DEBUG_MSG("Getting module config: Range Test\n"); + LOG_DEBUG("Getting module config: Range Test\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_range_test_tag; res.get_module_config_response.payload_variant.range_test = moduleConfig.range_test; break; case AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: - DEBUG_MSG("Getting module config: Telemetry\n"); + LOG_DEBUG("Getting module config: Telemetry\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_telemetry_tag; res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry; break; case AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: - DEBUG_MSG("Getting module config: Canned Message\n"); + LOG_DEBUG("Getting module config: Canned Message\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_canned_message_tag; res.get_module_config_response.payload_variant.canned_message = moduleConfig.canned_message; break; case AdminMessage_ModuleConfigType_AUDIO_CONFIG: - DEBUG_MSG("Getting module config: Audio\n"); + LOG_DEBUG("Getting module config: Audio\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_audio_tag; res.get_module_config_response.payload_variant.audio = moduleConfig.audio; break; case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: - DEBUG_MSG("Getting module config: Remote Hardware\n"); + LOG_DEBUG("Getting module config: Remote Hardware\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_remote_hardware_tag; res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware; break; @@ -506,7 +506,7 @@ void AdminModule::handleGetChannel(const MeshPacket &req, uint32_t channelIndex) void AdminModule::reboot(int32_t seconds) { - DEBUG_MSG("Rebooting in %d seconds\n", seconds); + LOG_DEBUG("Rebooting in %d seconds\n", seconds); screen->startRebootScreen(); rebootAtMsec = (seconds < 0) ? 0 : (millis() + seconds * 1000); } @@ -514,10 +514,10 @@ void AdminModule::reboot(int32_t seconds) void AdminModule::saveChanges(int saveWhat, bool shouldReboot) { if (!hasOpenEditTransaction) { - DEBUG_MSG("Saving changes to disk\n"); + LOG_DEBUG("Saving changes to disk\n"); service.reloadConfig(saveWhat); // Calls saveToDisk among other things } else { - DEBUG_MSG("Delaying save of changes to disk until the open transaction is committed\n"); + LOG_DEBUG("Delaying save of changes to disk until the open transaction is committed\n"); } if (shouldReboot) { diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index c0563f666..f1a9e099f 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -49,10 +49,10 @@ CannedMessageModule::CannedMessageModule() if (moduleConfig.canned_message.enabled) { this->loadProtoForModule(); if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) { - DEBUG_MSG("CannedMessageModule: No messages are configured. Module is disabled\n"); + LOG_DEBUG("CannedMessageModule: No messages are configured. Module is disabled\n"); this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; } else { - DEBUG_MSG("CannedMessageModule is enabled\n"); + LOG_DEBUG("CannedMessageModule is enabled\n"); this->inputObserver.observe(inputBroker); } } @@ -81,7 +81,7 @@ int CannedMessageModule::splitConfiguredMessages() if (this->messageStore[i] == '|') { // Message ending found, replace it with string-end character. this->messageStore[i] = '\0'; - DEBUG_MSG("CannedMessage %d is: '%s'\n", messageIndex - 1, this->messages[messageIndex - 1]); + LOG_DEBUG("CannedMessage %d is: '%s'\n", messageIndex - 1, this->messages[messageIndex - 1]); // hit our max messages, bail if (messageIndex >= CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT) { @@ -96,7 +96,7 @@ int CannedMessageModule::splitConfiguredMessages() } if (strlen(this->messages[messageIndex - 1]) > 0) { // We have a last message. - DEBUG_MSG("CannedMessage %d is: '%s'\n", messageIndex - 1, this->messages[messageIndex - 1]); + LOG_DEBUG("CannedMessage %d is: '%s'\n", messageIndex - 1, this->messages[messageIndex - 1]); this->messagesCount = messageIndex; } else { this->messagesCount = messageIndex - 1; @@ -119,17 +119,17 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) bool validEvent = false; if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_UP)) { - DEBUG_MSG("Canned message event UP\n"); + LOG_DEBUG("Canned message event UP\n"); this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_UP; validEvent = true; } if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_DOWN)) { - DEBUG_MSG("Canned message event DOWN\n"); + LOG_DEBUG("Canned message event DOWN\n"); this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_DOWN; validEvent = true; } if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_SELECT)) { - DEBUG_MSG("Canned message event Select\n"); + LOG_DEBUG("Canned message event Select\n"); // when inactive, call the onebutton shortpress instead. Activate Module only on up/down if ((this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_DISABLED)) { powerFSM.trigger(EVENT_PRESS); @@ -140,7 +140,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) } } if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL)) { - DEBUG_MSG("Canned message event Cancel\n"); + LOG_DEBUG("Canned message event Cancel\n"); // emulate a timeout. Same result this->lastTouchMillis = 0; validEvent = true; @@ -148,7 +148,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) if ((event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_BACK)) || (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_LEFT)) || (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT))) { - DEBUG_MSG("Canned message event (%x)\n",event->kbchar); + LOG_DEBUG("Canned message event (%x)\n",event->kbchar); if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) { // pass the pressed key this->payload = event->kbchar; @@ -157,7 +157,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) } } if (event->inputEvent == static_cast(ANYKEY)) { - DEBUG_MSG("Canned message event any key pressed\n"); + LOG_DEBUG("Canned message event any key pressed\n"); // when inactive, this will switch to the freetext mode if ((this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_DISABLED)) { this->runState = CANNED_MESSAGE_RUN_STATE_FREETEXT; @@ -168,7 +168,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) validEvent = true; } if (event->inputEvent == static_cast(MATRIXKEY)) { - DEBUG_MSG("Canned message event Matrix key pressed\n"); + LOG_DEBUG("Canned message event Matrix key pressed\n"); // this will send the text immediately on matrix press this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_SELECT; this->payload = MATRIXKEY; @@ -198,7 +198,7 @@ void CannedMessageModule::sendText(NodeNum dest, const char *message, bool wantR p->decoded.payload.size++; } - DEBUG_MSG("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); + LOG_DEBUG("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); service.sendToMesh(p); } @@ -209,7 +209,7 @@ int32_t CannedMessageModule::runOnce() (this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE)) { return INT32_MAX; } - DEBUG_MSG("Check status\n"); + LOG_DEBUG("Check status\n"); UIFrameEvent e = {false, true}; if (this->runState == CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE) { // TODO: might have some feedback of sendig state @@ -222,7 +222,7 @@ int32_t CannedMessageModule::runOnce() this->notifyObservers(&e); } else if (((this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT)) && ((millis() - this->lastTouchMillis) > INACTIVATE_AFTER_MS)) { // Reset module - DEBUG_MSG("Reset due to lack of activity.\n"); + LOG_DEBUG("Reset due to lack of activity.\n"); e.frameChanged = true; this->currentMessageIndex = -1; this->freetext = ""; // clear freetext @@ -236,7 +236,7 @@ int32_t CannedMessageModule::runOnce() sendText(this->dest, this->freetext.c_str(), true); this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE; } else { - DEBUG_MSG("Reset message is empty.\n"); + LOG_DEBUG("Reset message is empty.\n"); this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; } } else { @@ -249,7 +249,7 @@ int32_t CannedMessageModule::runOnce() } this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE; } else { - DEBUG_MSG("Reset message is empty.\n"); + LOG_DEBUG("Reset message is empty.\n"); this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; } } @@ -262,7 +262,7 @@ int32_t CannedMessageModule::runOnce() return 2000; } else if ((this->runState != CANNED_MESSAGE_RUN_STATE_FREETEXT) && (this->currentMessageIndex == -1)) { this->currentMessageIndex = 0; - DEBUG_MSG("First touch (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("First touch (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); e.frameChanged = true; this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_UP) { @@ -272,7 +272,7 @@ int32_t CannedMessageModule::runOnce() this->cursor = 0; this->destSelect = false; this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; - DEBUG_MSG("MOVE UP (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("MOVE UP (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); } } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_DOWN) { if (this->messagesCount > 0) { @@ -281,7 +281,7 @@ int32_t CannedMessageModule::runOnce() this->cursor = 0; this->destSelect = false; this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; - DEBUG_MSG("MOVE DOWN (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("MOVE DOWN (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); } } else if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) { e.frameChanged = true; @@ -524,13 +524,13 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const switch (request->which_payload_variant) { case AdminMessage_get_canned_message_module_messages_request_tag: - DEBUG_MSG("Client is getting radio canned messages\n"); + LOG_DEBUG("Client is getting radio canned messages\n"); this->handleGetCannedMessageModuleMessages(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; case AdminMessage_set_canned_message_module_messages_tag: - DEBUG_MSG("Client is setting radio canned messages\n"); + LOG_DEBUG("Client is setting radio canned messages\n"); this->handleSetCannedMessageModuleMessages(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; break; @@ -544,7 +544,7 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const void CannedMessageModule::handleGetCannedMessageModuleMessages(const MeshPacket &req, AdminMessage *response) { - DEBUG_MSG("*** handleGetCannedMessageModuleMessages\n"); + LOG_DEBUG("*** handleGetCannedMessageModuleMessages\n"); assert(req.decoded.want_response); response->which_payload_variant = AdminMessage_get_canned_message_module_messages_response_tag; @@ -559,7 +559,7 @@ void CannedMessageModule::handleSetCannedMessageModuleMessages(const char *from_ if (*from_msg) { changed |= strcmp(cannedMessageModuleConfig.messages, from_msg); strcpy(cannedMessageModuleConfig.messages, from_msg); - DEBUG_MSG("*** from_msg.text:%s\n", from_msg); + LOG_DEBUG("*** from_msg.text:%s\n", from_msg); } if (changed) { diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index c042aa966..cabed32e3 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -48,15 +48,15 @@ int32_t ExternalNotificationModule::runOnce() if (nagCycleCutoff < millis()) { #endif nagCycleCutoff = UINT32_MAX; - DEBUG_MSG("Turning off external notification: "); + LOG_DEBUG("Turning off external notification: "); for (int i = 0; i < 2; i++) { if (getExternal(i)) { setExternalOff(i); externalTurnedOn[i] = 0; - DEBUG_MSG("%d ", i); + LOG_DEBUG("%d ", i); } } - DEBUG_MSG("\n"); + LOG_DEBUG("\n"); return INT32_MAX; // save cycles till we're needed again } @@ -175,26 +175,26 @@ ExternalNotificationModule::ExternalNotificationModule() strncpy(rtttlConfig.ringtone, "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#", sizeof(rtttlConfig.ringtone)); } - DEBUG_MSG("Initializing External Notification Module\n"); + LOG_DEBUG("Initializing External Notification Module\n"); output = moduleConfig.external_notification.output ? moduleConfig.external_notification.output : EXT_NOTIFICATION_MODULE_OUTPUT; // Set the direction of a pin - DEBUG_MSG("Using Pin %i in digital mode\n", output); + LOG_DEBUG("Using Pin %i in digital mode\n", output); pinMode(output, OUTPUT); setExternalOff(0); externalTurnedOn[0] = 0; if(moduleConfig.external_notification.output_vibra) { - DEBUG_MSG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); + LOG_DEBUG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); setExternalOff(1); externalTurnedOn[1] = 0; } if(moduleConfig.external_notification.output_buzzer) { if (!moduleConfig.external_notification.use_pwm) { - DEBUG_MSG("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); + LOG_DEBUG("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT); setExternalOff(2); externalTurnedOn[2] = 0; @@ -203,11 +203,11 @@ ExternalNotificationModule::ExternalNotificationModule() ? config.device.buzzer_gpio : PIN_BUZZER; // in PWM Mode we force the buzzer pin if it is set - DEBUG_MSG("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); + LOG_DEBUG("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); } } } else { - DEBUG_MSG("External Notification Module Disabled\n"); + LOG_DEBUG("External Notification Module Disabled\n"); enabled = false; } } @@ -229,7 +229,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell) { if (containsBell) { - DEBUG_MSG("externalNotificationModule - Notification Bell\n"); + LOG_DEBUG("externalNotificationModule - Notification Bell\n"); setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -241,7 +241,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell_vibra) { if (containsBell) { - DEBUG_MSG("externalNotificationModule - Notification Bell (Vibra)\n"); + LOG_DEBUG("externalNotificationModule - Notification Bell (Vibra)\n"); setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -253,7 +253,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell_buzzer) { if (containsBell) { - DEBUG_MSG("externalNotificationModule - Notification Bell (Buzzer)\n"); + LOG_DEBUG("externalNotificationModule - Notification Bell (Buzzer)\n"); if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { @@ -270,7 +270,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } if (moduleConfig.external_notification.alert_message) { - DEBUG_MSG("externalNotificationModule - Notification Module\n"); + LOG_DEBUG("externalNotificationModule - Notification Module\n"); setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -281,7 +281,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (!moduleConfig.external_notification.use_pwm) { if (moduleConfig.external_notification.alert_message_vibra) { - DEBUG_MSG("externalNotificationModule - Notification Module (Vibra)\n"); + LOG_DEBUG("externalNotificationModule - Notification Module (Vibra)\n"); setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -291,7 +291,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } if (moduleConfig.external_notification.alert_message_buzzer) { - DEBUG_MSG("externalNotificationModule - Notification Module (Buzzer)\n"); + LOG_DEBUG("externalNotificationModule - Notification Module (Buzzer)\n"); if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { @@ -310,7 +310,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } } else { - DEBUG_MSG("External Notification Module Disabled\n"); + LOG_DEBUG("External Notification Module Disabled\n"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want @@ -331,13 +331,13 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule switch (request->which_payload_variant) { case AdminMessage_get_ringtone_request_tag: - DEBUG_MSG("Client is getting ringtone\n"); + LOG_DEBUG("Client is getting ringtone\n"); this->handleGetRingtone(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; case AdminMessage_set_ringtone_message_tag: - DEBUG_MSG("Client is setting ringtone\n"); + LOG_DEBUG("Client is setting ringtone\n"); this->handleSetRingtone(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; break; @@ -351,7 +351,7 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response) { - DEBUG_MSG("*** handleGetRingtone\n"); + LOG_DEBUG("*** handleGetRingtone\n"); assert(req.decoded.want_response); response->which_payload_variant = AdminMessage_get_ringtone_response_tag; @@ -366,7 +366,7 @@ void ExternalNotificationModule::handleSetRingtone(const char *from_msg) if (*from_msg) { changed |= strcmp(rtttlConfig.ringtone, from_msg); strcpy(rtttlConfig.ringtone, from_msg); - DEBUG_MSG("*** from_msg.text:%s\n", from_msg); + LOG_DEBUG("*** from_msg.text:%s\n", from_msg); } if (changed) { diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index 1ce1acf33..b4e054717 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -23,7 +23,7 @@ bool NodeInfoModule::handleReceivedProtobuf(const MeshPacket &mp, User *pptr) screen->print(lcd.c_str()); } - // DEBUG_MSG("did handleReceived\n"); + // LOG_DEBUG("did handleReceived\n"); return false; // Let others look at this message also if they want } @@ -46,7 +46,7 @@ MeshPacket *NodeInfoModule::allocReply() { User &u = owner; - DEBUG_MSG("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); + LOG_DEBUG("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); return allocDataProtobuf(u); } @@ -65,7 +65,7 @@ int32_t NodeInfoModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - DEBUG_MSG("Sending our nodeinfo to mesh (wantReplies=%d)\n", requestReplies); + LOG_DEBUG("Sending our nodeinfo to mesh (wantReplies=%d)\n", requestReplies); sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies) return default_broadcast_interval_secs * 1000; diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 013f2ee44..2df3b029b 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -26,13 +26,13 @@ bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr // FIXME this can in fact happen with packets sent from EUD (src=RX_SRC_USER) // to set fixed location, EUD-GPS location or just the time (see also issue #900) if (nodeDB.getNodeNum() == getFrom(&mp)) { - DEBUG_MSG("Incoming update from MYSELF\n"); - // DEBUG_MSG("Ignored an incoming update from MYSELF\n"); + LOG_DEBUG("Incoming update from MYSELF\n"); + // LOG_DEBUG("Ignored an incoming update from MYSELF\n"); // return false; } // Log packet size and list of fields - DEBUG_MSG("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size, + LOG_DEBUG("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size, p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "", p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "", p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "", @@ -109,12 +109,12 @@ MeshPacket *PositionModule::allocReply() // nodes shouldn't trust it anyways) Note: we allow a device with a local GPS to include the time, so that gpsless // devices can get time. if (getRTCQuality() < RTCQualityDevice) { - DEBUG_MSG("Stripping time %u from position send\n", p.time); + LOG_DEBUG("Stripping time %u from position send\n", p.time); p.time = 0; } else - DEBUG_MSG("Providing time to mesh %u\n", p.time); + LOG_DEBUG("Providing time to mesh %u\n", p.time); - DEBUG_MSG("Position reply: time=%i, latI=%i, lonI=-%i\n", p.time, p.latitude_i, p.longitude_i); + LOG_DEBUG("Position reply: time=%i, latI=%i, lonI=-%i\n", p.time, p.latitude_i, p.longitude_i); return allocDataProtobuf(p); } @@ -155,11 +155,11 @@ int32_t PositionModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - DEBUG_MSG("Sending pos@%x:6 to mesh (wantReplies=%d)\n", node->position.timestamp, requestReplies); + LOG_DEBUG("Sending pos@%x:6 to mesh (wantReplies=%d)\n", node->position.timestamp, requestReplies); sendOurPosition(NODENUM_BROADCAST, requestReplies); } } else { - DEBUG_MSG("Channel utilization is >40 percent. Skipping this opportunity to send.\n"); + LOG_DEBUG("Channel utilization is >40 percent. Skipping this opportunity to send.\n"); } } else if (config.position.position_broadcast_smart_enabled) { @@ -194,7 +194,7 @@ int32_t PositionModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - DEBUG_MSG("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp, + LOG_DEBUG("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp, requestReplies, distance, distanceTravelThreshold, timeTravel); sendOurPosition(NODENUM_BROADCAST, requestReplies); @@ -209,7 +209,7 @@ int32_t PositionModule::runOnce() } } } else { - DEBUG_MSG("Channel utilization is >25 percent. Skipping this opportunity to send.\n"); + LOG_DEBUG("Channel utilization is >25 percent. Skipping this opportunity to send.\n"); } } diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 26f1c4dba..9958fbe39 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -55,7 +55,7 @@ RemoteHardwareModule::RemoteHardwareModule() bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr) { auto p = *pptr; - DEBUG_MSG("Received RemoteHardware typ=%d\n", p.type); + LOG_DEBUG("Received RemoteHardware typ=%d\n", p.type); switch (p.type) { case HardwareMessage_Type_WRITE_GPIOS: @@ -95,7 +95,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar lastWatchMsec = 0; // Force a new publish soon previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) enabled = true; // Let our thread run at least once - DEBUG_MSG("Now watching GPIOs 0x%llx\n", watchGpios); + LOG_DEBUG("Now watching GPIOs 0x%llx\n", watchGpios); break; } @@ -104,7 +104,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar break; // Ignore - we might see our own replies default: - DEBUG_MSG("Hardware operation %d not yet implemented! FIXME\n", p.type); + LOG_DEBUG("Hardware operation %d not yet implemented! FIXME\n", p.type); break; } @@ -121,7 +121,7 @@ int32_t RemoteHardwareModule::runOnce() if (curVal != previousWatch) { previousWatch = curVal; - DEBUG_MSG("Broadcasting GPIOS 0x%llx changed!\n", curVal); + LOG_DEBUG("Broadcasting GPIOS 0x%llx changed!\n", curVal); // Something changed! Tell the world with a broadcast message HardwareMessage r = HardwareMessage_init_default; diff --git a/src/modules/ReplyModule.cpp b/src/modules/ReplyModule.cpp index af7232895..cd0dbec3a 100644 --- a/src/modules/ReplyModule.cpp +++ b/src/modules/ReplyModule.cpp @@ -11,7 +11,7 @@ MeshPacket *ReplyModule::allocReply() auto req = *currentRequest; auto &p = req.decoded; // The incoming message is in p.payload - DEBUG_MSG("Received message from=0x%0x, id=%d, msg=%.*s\n", req.from, req.id, p.payload.size, p.payload.bytes); + LOG_DEBUG("Received message from=0x%0x, id=%d, msg=%.*s\n", req.from, req.id, p.payload.size, p.payload.bytes); screen->print("Sending reply\n"); diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index eb8f0986b..f3708a704 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -109,7 +109,7 @@ int32_t SerialModule::runOnce() if (firstTime) { // Interface with the serial peripheral from in here. - DEBUG_MSG("Initializing serial peripheral interface\n"); + LOG_DEBUG("Initializing serial peripheral interface\n"); uint32_t baud = 0; @@ -213,14 +213,14 @@ int32_t SerialModule::runOnce() serialModuleRadio->sendPayload(); - DEBUG_MSG("Received: %s\n", serialStringChar); + LOG_DEBUG("Received: %s\n", serialStringChar); } } } return (10); } else { - DEBUG_MSG("Serial Module Disabled\n"); + LOG_DEBUG("Serial Module Disabled\n"); return INT32_MAX; } @@ -256,7 +256,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } auto &p = mp.decoded; - // DEBUG_MSG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", + // LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", // nodeDB.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); if (getFrom(&mp) == nodeDB.getNodeNum()) { @@ -271,7 +271,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) // TODO: need to find out why. if (lastRxID != mp.id) { lastRxID = mp.id; - // DEBUG_MSG("* * Message came this device\n"); + // LOG_DEBUG("* * Message came this device\n"); // Serial2.println("* * Message came this device"); Serial2.printf("%s", p.payload.bytes); } @@ -305,7 +305,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } } else { - DEBUG_MSG("Serial Module Disabled\n"); + LOG_DEBUG("Serial Module Disabled\n"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want } diff --git a/src/modules/Telemetry/DeviceTelemetry.cpp b/src/modules/Telemetry/DeviceTelemetry.cpp index f3d787682..301aa1797 100644 --- a/src/modules/Telemetry/DeviceTelemetry.cpp +++ b/src/modules/Telemetry/DeviceTelemetry.cpp @@ -34,7 +34,7 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemet if (t->which_variant == Telemetry_device_metrics_tag) { const char *sender = getSenderShortName(mp); - DEBUG_MSG("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", + LOG_DEBUG("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", sender, t->variant.device_metrics.air_util_tx, t->variant.device_metrics.channel_utilization, @@ -60,7 +60,7 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) t.variant.device_metrics.channel_utilization = myNodeInfo.channel_utilization; t.variant.device_metrics.voltage = powerStatus->getBatteryVoltageMv() / 1000.0; - DEBUG_MSG("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", + LOG_DEBUG("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", t.variant.device_metrics.air_util_tx, t.variant.device_metrics.channel_utilization, t.variant.device_metrics.battery_level, @@ -74,10 +74,10 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); nodeDB.updateTelemetry(nodeDB.getNodeNum(), t, RX_SRC_LOCAL); if (phoneOnly) { - DEBUG_MSG("Sending packet to phone\n"); + LOG_DEBUG("Sending packet to phone\n"); service.sendToPhone(p); } else { - DEBUG_MSG("Sending packet to mesh\n"); + LOG_DEBUG("Sending packet to mesh\n"); service.sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index 11955f3f6..fa90dc7cf 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -75,7 +75,7 @@ int32_t EnvironmentTelemetryModule::runOnce() firstTime = 0; if (moduleConfig.telemetry.environment_measurement_enabled) { - DEBUG_MSG("Environment Telemetry: Initializing\n"); + LOG_DEBUG("Environment Telemetry: Initializing\n"); // it's possible to have this module enabled, only for displaying values on the screen. // therefore, we should only enable the sensor loop if measurement is also enabled if (bmp280Sensor.hasSensor()) @@ -162,7 +162,7 @@ void EnvironmentTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiSt if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Telemetry_msg, &lastMeasurement)) { display->setFont(FONT_SMALL); display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error"); - DEBUG_MSG("Unable to decode last packet"); + LOG_DEBUG("Unable to decode last packet"); return; } @@ -187,7 +187,7 @@ bool EnvironmentTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Te if (t->which_variant == Telemetry_environment_metrics_tag) { const char *sender = getSenderShortName(mp); - DEBUG_MSG("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", + LOG_DEBUG("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", sender, t->variant.environment_metrics.barometric_pressure, t->variant.environment_metrics.current, @@ -234,7 +234,7 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) if (ina260Sensor.hasSensor()) ina260Sensor.getMetrics(&m); - DEBUG_MSG("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", + LOG_DEBUG("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", m.variant.environment_metrics.barometric_pressure, m.variant.environment_metrics.current, m.variant.environment_metrics.gas_resistance, @@ -251,10 +251,10 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { - DEBUG_MSG("Sending packet to phone\n"); + LOG_DEBUG("Sending packet to phone\n"); service.sendToPhone(p); } else { - DEBUG_MSG("Sending packet to mesh\n"); + LOG_DEBUG("Sending packet to mesh\n"); service.sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/Sensor/BME280Sensor.cpp b/src/modules/Telemetry/Sensor/BME280Sensor.cpp index 4b6a50091..e33c1e014 100644 --- a/src/modules/Telemetry/Sensor/BME280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME280Sensor.cpp @@ -11,7 +11,7 @@ BME280Sensor::BME280Sensor() : } int32_t BME280Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -30,7 +30,7 @@ int32_t BME280Sensor::runOnce() { void BME280Sensor::setup() { } bool BME280Sensor::getMetrics(Telemetry *measurement) { - DEBUG_MSG("BME280Sensor::getMetrics\n"); + LOG_DEBUG("BME280Sensor::getMetrics\n"); bme280.takeForcedMeasurement(); measurement->variant.environment_metrics.temperature = bme280.readTemperature(); measurement->variant.environment_metrics.relative_humidity = bme280.readHumidity(); diff --git a/src/modules/Telemetry/Sensor/BME680Sensor.cpp b/src/modules/Telemetry/Sensor/BME680Sensor.cpp index a9171facf..f07de0d8d 100644 --- a/src/modules/Telemetry/Sensor/BME680Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME680Sensor.cpp @@ -10,7 +10,7 @@ BME680Sensor::BME680Sensor() : } int32_t BME680Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp index 917c40d6f..29a73e282 100644 --- a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp @@ -11,7 +11,7 @@ BMP280Sensor::BMP280Sensor() : } int32_t BMP280Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -29,7 +29,7 @@ int32_t BMP280Sensor::runOnce() { void BMP280Sensor::setup() { } bool BMP280Sensor::getMetrics(Telemetry *measurement) { - DEBUG_MSG("BMP280Sensor::getMetrics\n"); + LOG_DEBUG("BMP280Sensor::getMetrics\n"); bmp280.takeForcedMeasurement(); measurement->variant.environment_metrics.temperature = bmp280.readTemperature(); measurement->variant.environment_metrics.barometric_pressure = bmp280.readPressure() / 100.0F; diff --git a/src/modules/Telemetry/Sensor/INA219Sensor.cpp b/src/modules/Telemetry/Sensor/INA219Sensor.cpp index 3e280c526..9ae886f15 100644 --- a/src/modules/Telemetry/Sensor/INA219Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA219Sensor.cpp @@ -10,7 +10,7 @@ INA219Sensor::INA219Sensor() : } int32_t INA219Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/INA260Sensor.cpp b/src/modules/Telemetry/Sensor/INA260Sensor.cpp index 1c924ad71..e648cd824 100644 --- a/src/modules/Telemetry/Sensor/INA260Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA260Sensor.cpp @@ -10,7 +10,7 @@ INA260Sensor::INA260Sensor() : } int32_t INA260Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp index 1209c1435..295fccdfc 100644 --- a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp +++ b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp @@ -11,7 +11,7 @@ LPS22HBSensor::LPS22HBSensor() : } int32_t LPS22HBSensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp index 57092d285..3f0cafdfe 100644 --- a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp @@ -10,7 +10,7 @@ MCP9808Sensor::MCP9808Sensor() : } int32_t MCP9808Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -23,7 +23,7 @@ void MCP9808Sensor::setup() { } bool MCP9808Sensor::getMetrics(Telemetry *measurement) { - DEBUG_MSG("MCP9808Sensor::getMetrics\n"); + LOG_DEBUG("MCP9808Sensor::getMetrics\n"); measurement->variant.environment_metrics.temperature = mcp9808.readTempC(); return true; } \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp index 94591e6cb..4d367823d 100644 --- a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp @@ -10,7 +10,7 @@ SHT31Sensor::SHT31Sensor() : } int32_t SHT31Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp index b3a76ba91..b19d12692 100644 --- a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp @@ -10,7 +10,7 @@ SHTC3Sensor::SHTC3Sensor() : } int32_t SHTC3Sensor::runOnce() { - DEBUG_MSG("Init sensor: %s\n", sensorName); + LOG_DEBUG("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/TelemetrySensor.h b/src/modules/Telemetry/Sensor/TelemetrySensor.h index 12bf17e56..642c82b3a 100644 --- a/src/modules/Telemetry/Sensor/TelemetrySensor.h +++ b/src/modules/Telemetry/Sensor/TelemetrySensor.h @@ -21,10 +21,10 @@ class TelemetrySensor int32_t initI2CSensor() { if (!status) { - DEBUG_MSG("Could not connect to detected %s sensor.\n Removing from nodeTelemetrySensorsMap.\n", sensorName); + LOG_DEBUG("Could not connect to detected %s sensor.\n Removing from nodeTelemetrySensorsMap.\n", sensorName); nodeTelemetrySensorsMap[sensorType] = 0; } else { - DEBUG_MSG("Opened %s sensor on default i2c bus\n", sensorName); + LOG_DEBUG("Opened %s sensor on default i2c bus\n", sensorName); setup(); } return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; diff --git a/src/modules/TextMessageModule.cpp b/src/modules/TextMessageModule.cpp index abccc0ae8..7e7115b8d 100644 --- a/src/modules/TextMessageModule.cpp +++ b/src/modules/TextMessageModule.cpp @@ -8,7 +8,7 @@ TextMessageModule *textMessageModule; ProcessMessage TextMessageModule::handleReceived(const MeshPacket &mp) { auto &p = mp.decoded; - DEBUG_MSG("Received text msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); + LOG_DEBUG("Received text msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); // We only store/display messages destined for us. // Keep a copy of the most recent text message. diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index fcb234664..4558c5957 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -43,19 +43,19 @@ void TraceRouteModule::appendMyID(RouteDiscovery* updated) updated->route[updated->route_count] = myNodeInfo.my_node_num; updated->route_count += 1; } else { - DEBUG_MSG("WARNING: Route exceeded maximum hop limit, are you bridging networks?\n"); + LOG_WARN("Route exceeded maximum hop limit, are you bridging networks?\n"); } } void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest) { - DEBUG_MSG("Route traced:\n"); - DEBUG_MSG("0x%x --> ", origin); + LOG_DEBUG("Route traced:\n"); + LOG_DEBUG("0x%x --> ", origin); for (uint8_t i=0; iroute_count; i++) { - DEBUG_MSG("0x%x --> ", r->route[i]); + LOG_DEBUG("0x%x --> ", r->route[i]); } - if (dest != NODENUM_BROADCAST) DEBUG_MSG("0x%x\n", dest); else DEBUG_MSG("...\n"); + if (dest != NODENUM_BROADCAST) LOG_DEBUG("0x%x\n", dest); else LOG_DEBUG("...\n"); } diff --git a/src/modules/WaypointModule.cpp b/src/modules/WaypointModule.cpp index fbc519d58..9ab9a5879 100644 --- a/src/modules/WaypointModule.cpp +++ b/src/modules/WaypointModule.cpp @@ -8,7 +8,7 @@ WaypointModule *waypointModule; ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp) { auto &p = mp.decoded; - DEBUG_MSG("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); + LOG_DEBUG("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); notifyObservers(&mp); diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index e7132fcc4..8a9dbcf7f 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -71,7 +71,7 @@ void run_codec2(void* parameter) // 4 bytes of header in each frame hex c0 de c2 plus the bitrate memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); - DEBUG_MSG("Starting codec2 task\n"); + LOG_DEBUG("Starting codec2 task\n"); while (true) { uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); @@ -86,7 +86,7 @@ void run_codec2(void* parameter) if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) { - DEBUG_MSG("Sending %d codec2 bytes\n", audioModule->encode_frame_size); + LOG_DEBUG("Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); } @@ -127,7 +127,7 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), // moduleConfig.audio.ptt_pin = 39; if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - DEBUG_MSG("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + LOG_DEBUG("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; @@ -136,10 +136,10 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), encode_frame_num = (Constants_DATA_PAYLOAD_LEN - sizeof(tx_header)) / encode_codec_size; encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes adc_buffer_size = codec2_samples_per_frame(codec2); - DEBUG_MSG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); + LOG_DEBUG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { - DEBUG_MSG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); + LOG_DEBUG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -173,7 +173,7 @@ int32_t AudioModule::runOnce() esp_err_t res; if (firstTime) { // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC - DEBUG_MSG("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); + LOG_DEBUG("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), .sample_rate = 8000, @@ -189,7 +189,7 @@ int32_t AudioModule::runOnce() }; res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); if(res != ESP_OK) - DEBUG_MSG("Failed to install I2S driver: %d\n", res); + LOG_DEBUG("Failed to install I2S driver: %d\n", res); const i2s_pin_config_t pin_config = { .bck_io_num = moduleConfig.audio.i2s_sck, @@ -199,16 +199,16 @@ int32_t AudioModule::runOnce() }; res = i2s_set_pin(I2S_PORT, &pin_config); if(res != ESP_OK) - DEBUG_MSG("Failed to set I2S pin config: %d\n", res); + LOG_DEBUG("Failed to set I2S pin config: %d\n", res); res = i2s_start(I2S_PORT); if(res != ESP_OK) - DEBUG_MSG("Failed to start I2S: %d\n", res); + LOG_DEBUG("Failed to start I2S: %d\n", res); radio_state = RadioState::rx; // Configure PTT input - DEBUG_MSG("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + LOG_DEBUG("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; @@ -217,17 +217,17 @@ int32_t AudioModule::runOnce() // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { - DEBUG_MSG("PTT pressed, switching to TX\n"); + LOG_DEBUG("PTT pressed, switching to TX\n"); radio_state = RadioState::tx; e.frameChanged = true; this->notifyObservers(&e); } } else { if (radio_state == RadioState::tx) { - DEBUG_MSG("PTT released, switching to RX\n"); + LOG_DEBUG("PTT released, switching to RX\n"); if (tx_encode_frame_index > sizeof(tx_header)) { // Send the incomplete frame - DEBUG_MSG("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); + LOG_DEBUG("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } tx_encode_frame_index = sizeof(tx_header); @@ -258,7 +258,7 @@ int32_t AudioModule::runOnce() } return 100; } else { - DEBUG_MSG("Audio Module Disabled\n"); + LOG_DEBUG("Audio Module Disabled\n"); return INT32_MAX; } diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index d706f8ed3..e8e9f62dd 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -53,10 +53,10 @@ int32_t RangeTestModule::runOnce() firstTime = 0; if (moduleConfig.range_test.sender) { - DEBUG_MSG("Initializing Range Test Module -- Sender\n"); + LOG_DEBUG("Initializing Range Test Module -- Sender\n"); return (5000); // Sending first message 5 seconds after initilization. } else { - DEBUG_MSG("Initializing Range Test Module -- Receiver\n"); + LOG_DEBUG("Initializing Range Test Module -- Receiver\n"); return (INT32_MAX); // This thread does not need to run as a receiver } @@ -65,19 +65,19 @@ int32_t RangeTestModule::runOnce() if (moduleConfig.range_test.sender) { // If sender - DEBUG_MSG("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); + LOG_DEBUG("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); - DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - DEBUG_MSG("fixed_position() %d\n", config.position.fixed_position); + LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); + LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); + LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); + LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); + LOG_DEBUG("fixed_position() %d\n", config.position.fixed_position); // Only send packets if the channel is less than 25% utilized. if (airTime->channelUtilizationPercent() < 25) { rangeTestModuleRadio->sendPayload(); } else { - DEBUG_MSG("rangeTest - Channel utilization is >25 percent. Skipping this opportunity to send.\n"); + LOG_DEBUG("rangeTest - Channel utilization is >25 percent. Skipping this opportunity to send.\n"); } return (senderHeartbeat); @@ -90,7 +90,7 @@ int32_t RangeTestModule::runOnce() } } else { - DEBUG_MSG("Range Test Module - Disabled\n"); + LOG_DEBUG("Range Test Module - Disabled\n"); } #endif @@ -135,7 +135,7 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) /* auto &p = mp.decoded; - DEBUG_MSG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", + LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", nodeDB.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); */ @@ -148,33 +148,33 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) /* NodeInfo *n = nodeDB.getNode(getFrom(&mp)); - DEBUG_MSG("-----------------------------------------\n"); - DEBUG_MSG("p.payload.bytes \"%s\"\n", p.payload.bytes); - DEBUG_MSG("p.payload.size %d\n", p.payload.size); - DEBUG_MSG("---- Received Packet:\n"); - DEBUG_MSG("mp.from %d\n", mp.from); - DEBUG_MSG("mp.rx_snr %f\n", mp.rx_snr); - DEBUG_MSG("mp.hop_limit %d\n", mp.hop_limit); - // DEBUG_MSG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated - // DEBUG_MSG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated - DEBUG_MSG("---- Node Information of Received Packet (mp.from):\n"); - DEBUG_MSG("n->user.long_name %s\n", n->user.long_name); - DEBUG_MSG("n->user.short_name %s\n", n->user.short_name); - DEBUG_MSG("n->user.macaddr %X\n", n->user.macaddr); - DEBUG_MSG("n->has_position %d\n", n->has_position); - DEBUG_MSG("n->position.latitude_i %d\n", n->position.latitude_i); - DEBUG_MSG("n->position.longitude_i %d\n", n->position.longitude_i); - DEBUG_MSG("---- Current device location information:\n"); - DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - DEBUG_MSG("-----------------------------------------\n"); + LOG_DEBUG("-----------------------------------------\n"); + LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes); + LOG_DEBUG("p.payload.size %d\n", p.payload.size); + LOG_DEBUG("---- Received Packet:\n"); + LOG_DEBUG("mp.from %d\n", mp.from); + LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr); + LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit); + // LOG_DEBUG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated + // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated + LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n"); + LOG_DEBUG("n->user.long_name %s\n", n->user.long_name); + LOG_DEBUG("n->user.short_name %s\n", n->user.short_name); + LOG_DEBUG("n->user.macaddr %X\n", n->user.macaddr); + LOG_DEBUG("n->has_position %d\n", n->has_position); + LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i); + LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i); + LOG_DEBUG("---- Current device location information:\n"); + LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); + LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); + LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); + LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); + LOG_DEBUG("-----------------------------------------\n"); */ } } else { - DEBUG_MSG("Range Test Module Disabled\n"); + LOG_DEBUG("Range Test Module Disabled\n"); } #endif @@ -188,36 +188,36 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) NodeInfo *n = nodeDB.getNode(getFrom(&mp)); /* - DEBUG_MSG("-----------------------------------------\n"); - DEBUG_MSG("p.payload.bytes \"%s\"\n", p.payload.bytes); - DEBUG_MSG("p.payload.size %d\n", p.payload.size); - DEBUG_MSG("---- Received Packet:\n"); - DEBUG_MSG("mp.from %d\n", mp.from); - DEBUG_MSG("mp.rx_snr %f\n", mp.rx_snr); - DEBUG_MSG("mp.hop_limit %d\n", mp.hop_limit); - // DEBUG_MSG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated - // DEBUG_MSG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated - DEBUG_MSG("---- Node Information of Received Packet (mp.from):\n"); - DEBUG_MSG("n->user.long_name %s\n", n->user.long_name); - DEBUG_MSG("n->user.short_name %s\n", n->user.short_name); - DEBUG_MSG("n->user.macaddr %X\n", n->user.macaddr); - DEBUG_MSG("n->has_position %d\n", n->has_position); - DEBUG_MSG("n->position.latitude_i %d\n", n->position.latitude_i); - DEBUG_MSG("n->position.longitude_i %d\n", n->position.longitude_i); - DEBUG_MSG("---- Current device location information:\n"); - DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - DEBUG_MSG("-----------------------------------------\n"); + LOG_DEBUG("-----------------------------------------\n"); + LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes); + LOG_DEBUG("p.payload.size %d\n", p.payload.size); + LOG_DEBUG("---- Received Packet:\n"); + LOG_DEBUG("mp.from %d\n", mp.from); + LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr); + LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit); + // LOG_DEBUG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated + // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated + LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n"); + LOG_DEBUG("n->user.long_name %s\n", n->user.long_name); + LOG_DEBUG("n->user.short_name %s\n", n->user.short_name); + LOG_DEBUG("n->user.macaddr %X\n", n->user.macaddr); + LOG_DEBUG("n->has_position %d\n", n->has_position); + LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i); + LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i); + LOG_DEBUG("---- Current device location information:\n"); + LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); + LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); + LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); + LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); + LOG_DEBUG("-----------------------------------------\n"); */ if (!FSBegin()) { - DEBUG_MSG("An Error has occurred while mounting the filesystem\n"); + LOG_DEBUG("An Error has occurred while mounting the filesystem\n"); return 0; } if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { - DEBUG_MSG("Filesystem doesn't have enough free space. Aborting write.\n"); + LOG_DEBUG("Filesystem doesn't have enough free space. Aborting write.\n"); return 0; } @@ -229,16 +229,16 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) File fileToWrite = FSCom.open("/static/rangetest.csv", FILE_WRITE); if (!fileToWrite) { - DEBUG_MSG("There was an error opening the file for writing\n"); + LOG_DEBUG("There was an error opening the file for writing\n"); return 0; } // Print the CSV header if (fileToWrite.println( "time,from,sender name,sender lat,sender long,rx lat,rx long,rx elevation,rx snr,distance,hop limit,payload")) { - DEBUG_MSG("File was written\n"); + LOG_DEBUG("File was written\n"); } else { - DEBUG_MSG("File write failed\n"); + LOG_DEBUG("File write failed\n"); } fileToWrite.close(); @@ -248,7 +248,7 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) File fileToAppend = FSCom.open("/static/rangetest.csv", FILE_APPEND); if (!fileToAppend) { - DEBUG_MSG("There was an error opening the file for appending\n"); + LOG_DEBUG("There was an error opening the file for appending\n"); return 0; } diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 54a250d2a..524aa0670 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -28,20 +28,20 @@ int32_t StoreForwardModule::runOnce() StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_PING; storeForwardModule->sendMessage(this->busyTo, sf); - DEBUG_MSG("*** S&F - Done. (ROUTER_PING)\n"); + LOG_DEBUG("*** S&F - Done. (ROUTER_PING)\n"); this->packetHistoryTXQueue_index = 0; this->busy = false; } else { this->packetHistoryTXQueue_index++; } } else { - DEBUG_MSG("*** Channel utilization is too high. Retrying later.\n"); + LOG_DEBUG("*** Channel utilization is too high. Retrying later.\n"); } - DEBUG_MSG("*** SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); + LOG_DEBUG("*** SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && (airTime->channelUtilizationPercent() < polite_channel_util_percent)) { lastHeartbeat = millis(); - DEBUG_MSG("*** Sending heartbeat\n"); + LOG_DEBUG("*** Sending heartbeat\n"); StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; sf.which_variant = StoreAndForward_heartbeat_tag; @@ -65,7 +65,7 @@ void StoreForwardModule::populatePSRAM() https://learn.upesy.com/en/programmation/psram.html#psram-tab */ - DEBUG_MSG("*** Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + LOG_DEBUG("*** Before PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); this->packetHistoryTXQueue = static_cast(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct))); @@ -78,8 +78,8 @@ void StoreForwardModule::populatePSRAM() this->packetHistory = static_cast(ps_calloc(numberOfPackets, sizeof(PacketHistoryStruct))); - DEBUG_MSG("*** After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); - DEBUG_MSG("*** numberOfPackets for packetHistory - %u\n", numberOfPackets); + LOG_DEBUG("*** After PSRAM initilization: heap %d/%d PSRAM %d/%d\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreePsram(), ESP.getPsramSize()); + LOG_DEBUG("*** numberOfPackets for packetHistory - %u\n", numberOfPackets); } void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) @@ -87,11 +87,11 @@ void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) uint32_t queueSize = storeForwardModule->historyQueueCreate(msAgo, to); if (queueSize) { - DEBUG_MSG ("*** S&F - Sending %u message(s)\n", queueSize); + LOG_DEBUG ("*** S&F - Sending %u message(s)\n", queueSize); this->busy = true; // runOnce() will pickup the next steps once busy = true. this->busyTo = to; } else { - DEBUG_MSG ("*** S&F - No history to send\n"); + LOG_DEBUG ("*** S&F - No history to send\n"); } StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; @@ -108,13 +108,13 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) for (int i = 0; i < this->packetHistoryCurrent; i++) { /* - DEBUG_MSG("SF historyQueueCreate\n"); - DEBUG_MSG("SF historyQueueCreate - time %d\n", this->packetHistory[i].time); - DEBUG_MSG("SF historyQueueCreate - millis %d\n", millis()); - DEBUG_MSG("SF historyQueueCreate - math %d\n", (millis() - msAgo)); + LOG_DEBUG("SF historyQueueCreate\n"); + LOG_DEBUG("SF historyQueueCreate - time %d\n", this->packetHistory[i].time); + LOG_DEBUG("SF historyQueueCreate - millis %d\n", millis()); + LOG_DEBUG("SF historyQueueCreate - math %d\n", (millis() - msAgo)); */ if (this->packetHistory[i].time && (this->packetHistory[i].time < (millis() - msAgo))) { - DEBUG_MSG("*** SF historyQueueCreate - Time matches - ok\n"); + LOG_DEBUG("*** SF historyQueueCreate - Time matches - ok\n"); /* Copy the messages that were received by the router in the last msAgo to the packetHistoryTXQueue structure. @@ -133,8 +133,8 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) Constants_DATA_PAYLOAD_LEN); this->packetHistoryTXQueue_size++; - DEBUG_MSG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time); - DEBUG_MSG("*** PacketHistoryStruct msg=%s\n", this->packetHistory[i].payload); + LOG_DEBUG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time); + LOG_DEBUG("*** PacketHistoryStruct msg=%s\n", this->packetHistory[i].payload); } } } @@ -164,7 +164,7 @@ MeshPacket *StoreForwardModule::allocReply() void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) { - DEBUG_MSG("*** Sending S&F Payload\n"); + LOG_DEBUG("*** Sending S&F Payload\n"); MeshPacket *p = allocReply(); p->to = dest; @@ -227,7 +227,7 @@ void StoreForwardModule::statsSend(uint32_t to) sf.variant.stats.return_max = this->historyReturnMax; sf.variant.stats.return_window = this->historyReturnWindow; - DEBUG_MSG("*** Sending S&F Stats\n"); + LOG_DEBUG("*** Sending S&F Stats\n"); storeForwardModule->sendMessage(to, sf); } @@ -241,7 +241,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { storeForwardModule->historyAdd(mp); - DEBUG_MSG("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); + LOG_DEBUG("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { auto &p = mp.decoded; @@ -251,7 +251,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &StoreAndForward_msg, &scratch)) { decoded = &scratch; } else { - DEBUG_MSG("Error decoding protobuf module!\n"); + LOG_DEBUG("Error decoding protobuf module!\n"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } @@ -281,7 +281,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_server) { // stop sending stuff, the client wants to abort or has another error if ((this->busy) && (this->busyTo == getFrom(&mp))) { - DEBUG_MSG("*** Client in ERROR or ABORT requested\n"); + LOG_DEBUG("*** Client in ERROR or ABORT requested\n"); this->packetHistoryTXQueue_index = 0; this->busy = false; } @@ -291,11 +291,11 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_HISTORY: if(is_server) { requests_history++; - DEBUG_MSG("*** Client Request to send HISTORY\n"); + LOG_DEBUG("*** Client Request to send HISTORY\n"); // Send the last 60 minutes of messages. if (this->busy) { storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); - DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); + LOG_DEBUG("*** S&F - Busy. Try again shortly.\n"); } else { if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)){ storeForwardModule->historySend(p->variant.history.window * 60000, getFrom(&mp)); // window is in minutes @@ -308,7 +308,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_PING: if(is_server) { - DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); + LOG_DEBUG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); // respond with a ROUTER PONG storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_PONG); } @@ -316,7 +316,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_PONG: if(is_server) { - DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); + LOG_DEBUG("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); // The Client is alive, update NodeDB nodeDB.updateFrom(mp); } @@ -324,10 +324,10 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_STATS: if(is_server) { - DEBUG_MSG("*** Client Request to send STATS\n"); + LOG_DEBUG("*** Client Request to send STATS\n"); if (this->busy) { storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); - DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); + LOG_DEBUG("*** S&F - Busy. Try again shortly.\n"); } else { storeForwardModule->statsSend(getFrom(&mp)); } @@ -337,7 +337,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_ROUTER_ERROR: case StoreAndForward_RequestResponse_ROUTER_BUSY: if(is_client) { - DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); // retry in messages_saved * packetTimeMax ms retry_delay = millis() + packetHistoryCurrent * packetTimeMax * (StoreAndForward_RequestResponse_ROUTER_ERROR ? 2 : 1); } @@ -352,13 +352,13 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo heartbeatInterval = p->variant.heartbeat.period; } lastHeartbeat = millis(); - DEBUG_MSG("*** StoreAndForward Heartbeat received\n"); + LOG_DEBUG("*** StoreAndForward Heartbeat received\n"); } break; case StoreAndForward_RequestResponse_ROUTER_PING: if(is_client) { - DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); + LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); // respond with a CLIENT PONG storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_CLIENT_PONG); } @@ -366,7 +366,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_ROUTER_STATS: if(is_client) { - DEBUG_MSG("*** Router Response STATS\n"); + LOG_DEBUG("*** Router Response STATS\n"); // These fields only have informational purpose on a client. Fill them to consume later. if (p->which_variant == StoreAndForward_stats_tag) { this->packetHistoryMax = p->variant.stats.messages_total; @@ -386,7 +386,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo // These fields only have informational purpose on a client. Fill them to consume later. if (p->which_variant == StoreAndForward_history_tag) { this->historyReturnWindow = p->variant.history.window / 60000; - DEBUG_MSG("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); + LOG_DEBUG("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); } } break; @@ -418,7 +418,7 @@ StoreForwardModule::StoreForwardModule() // Router if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { - DEBUG_MSG("*** Initializing Store & Forward Module in Router mode\n"); + LOG_DEBUG("*** Initializing Store & Forward Module in Router mode\n"); if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { @@ -444,19 +444,19 @@ StoreForwardModule::StoreForwardModule() this->populatePSRAM(); is_server = true; } else { - DEBUG_MSG("*** Device has less than 1M of PSRAM free.\n"); - DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); + LOG_DEBUG("*** Device has less than 1M of PSRAM free.\n"); + LOG_DEBUG("*** Store & Forward Module - disabling server.\n"); } } else { - DEBUG_MSG("*** Device doesn't have PSRAM.\n"); - DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); + LOG_DEBUG("*** Device doesn't have PSRAM.\n"); + LOG_DEBUG("*** Store & Forward Module - disabling server.\n"); } // Client } if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { is_client = true; - DEBUG_MSG("*** Initializing Store & Forward Module in Client mode\n"); + LOG_DEBUG("*** Initializing Store & Forward Module in Client mode\n"); } } #endif diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index df2d9b093..33122d091 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -42,7 +42,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) payloadStr[length] = 0; // null terminated string JSONValue *json_value = JSON::Parse(payloadStr); if (json_value != NULL) { - DEBUG_MSG("JSON Received on MQTT, parsing..\n"); + LOG_DEBUG("JSON Received on MQTT, parsing..\n"); // check if it is a valid envelope JSONObject json; json = json_value->AsObject(); @@ -50,7 +50,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) // this is a valid envelope if (json["payload"]->IsString() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) { std::string jsonPayloadStr = json["payload"]->AsString(); - DEBUG_MSG("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); + LOG_DEBUG("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); // construct protobuf data packet using TEXT_MESSAGE, send it to the mesh MeshPacket *p = router->allocForSending(); @@ -61,10 +61,10 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) MeshPacket *packet = packetPool.allocCopy(*p); service.sendToMesh(packet, RX_SRC_LOCAL); } else { - DEBUG_MSG("Received MQTT json payload too long, dropping\n"); + LOG_DEBUG("Received MQTT json payload too long, dropping\n"); } } else { - DEBUG_MSG("JSON Ignoring downlink message we originally sent.\n"); + LOG_DEBUG("JSON Ignoring downlink message we originally sent.\n"); } } else if ((json.find("sender") != json.end()) && (json.find("payload") != json.end()) && (json.find("type") != json.end()) && json["type"]->IsString() && (json["type"]->AsString().compare("sendposition") == 0)) { //invent the "sendposition" type for a valid envelope @@ -84,26 +84,26 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) service.sendToMesh(p, RX_SRC_LOCAL); } else { - DEBUG_MSG("JSON Ignoring downlink message we originally sent.\n"); + LOG_DEBUG("JSON Ignoring downlink message we originally sent.\n"); } } else{ - DEBUG_MSG("JSON Received payload on MQTT but not a valid envelope\n"); + LOG_DEBUG("JSON Received payload on MQTT but not a valid envelope\n"); } } else { // no json, this is an invalid payload - DEBUG_MSG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_DEBUG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); } delete json_value; } else { if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) { - DEBUG_MSG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_DEBUG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); return; }else { if (strcmp(e.gateway_id, owner.id) == 0) - DEBUG_MSG("Ignoring downlink message we originally sent.\n"); + LOG_DEBUG("Ignoring downlink message we originally sent.\n"); else { if (e.packet) { - DEBUG_MSG("Received MQTT topic %s, len=%u\n", topic, length); + LOG_DEBUG("Received MQTT topic %s, len=%u\n", topic, length); MeshPacket *p = packetPool.allocCopy(*e.packet); // ignore messages sent by us or if we don't have the channel key @@ -166,22 +166,22 @@ void MQTT::reconnect() } pubSub.setServer(serverAddr, serverPort); - DEBUG_MSG("Connecting to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, serverPort, mqttUsername, mqttPassword); + LOG_DEBUG("Connecting to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, serverPort, mqttUsername, mqttPassword); auto myStatus = (statusTopic + owner.id); bool connected = pubSub.connect(owner.id, mqttUsername, mqttPassword, myStatus.c_str(), 1, true, "offline"); if (connected) { - DEBUG_MSG("MQTT connected\n"); + LOG_DEBUG("MQTT connected\n"); enabled = true; // Start running background process again runASAP = true; reconnectCount = 0; /// FIXME, include more information in the status text bool ok = pubSub.publish(myStatus.c_str(), "online", true); - DEBUG_MSG("published %d\n", ok); + LOG_DEBUG("published %d\n", ok); sendSubscriptions(); } else { - DEBUG_MSG("Failed to contact MQTT server (%d/10)...\n",reconnectCount); + LOG_DEBUG("Failed to contact MQTT server (%d/10)...\n",reconnectCount); #if HAS_WIFI && !defined(ARCH_PORTDUINO) if (reconnectCount > 9) { needReconnect = true; @@ -200,11 +200,11 @@ void MQTT::sendSubscriptions() auto &ch = channels.getByIndex(i); if (ch.settings.downlink_enabled) { String topic = cryptTopic + channels.getGlobalId(i) + "/#"; - DEBUG_MSG("Subscribing to %s\n", topic.c_str()); + LOG_DEBUG("Subscribing to %s\n", topic.c_str()); pubSub.subscribe(topic.c_str(), 1); // FIXME, is QOS 1 right? if (moduleConfig.mqtt.json_enabled == true) { String topicDecoded = jsonTopic + channels.getGlobalId(i) + "/#"; - DEBUG_MSG("Subscribing to %s\n", topicDecoded.c_str()); + LOG_DEBUG("Subscribing to %s\n", topicDecoded.c_str()); pubSub.subscribe(topicDecoded.c_str(), 1); // FIXME, is QOS 1 right? } } @@ -254,7 +254,7 @@ int32_t MQTT::runOnce() size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); String topic = cryptTopic + env->channel_id + "/" + owner.id; - DEBUG_MSG("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); + LOG_DEBUG("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); pubSub.publish(topic.c_str(), bytes, numBytes, false); @@ -264,7 +264,7 @@ int32_t MQTT::runOnce() auto jsonString = this->downstreamPacketToJson(env->packet); if (jsonString.length() != 0) { String topicJson = jsonTopic + env->channel_id + "/" + owner.id; - DEBUG_MSG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + LOG_DEBUG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); } } @@ -279,7 +279,7 @@ int32_t MQTT::runOnce() } else { // we are connected to server, check often for new requests on the TCP port if (!wantConnection) { - DEBUG_MSG("MQTT link not needed, dropping\n"); + LOG_DEBUG("MQTT link not needed, dropping\n"); pubSub.disconnect(); } @@ -308,7 +308,7 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); String topic = cryptTopic + channelId + "/" + owner.id; - DEBUG_MSG("publish %s, %u bytes\n", topic.c_str(), numBytes); + LOG_DEBUG("publish %s, %u bytes\n", topic.c_str(), numBytes); pubSub.publish(topic.c_str(), bytes, numBytes, false); @@ -317,14 +317,14 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp); if (jsonString.length() != 0) { String topicJson = jsonTopic + channelId + "/" + owner.id; - DEBUG_MSG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + LOG_DEBUG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); } } } else { - DEBUG_MSG("MQTT not connected, queueing packet\n"); + LOG_DEBUG("MQTT not connected, queueing packet\n"); if (mqttQueue.numFree() == 0) { - DEBUG_MSG("NOTE: MQTT queue is full, discarding oldest\n"); + LOG_DEBUG("NOTE: MQTT queue is full, discarding oldest\n"); ServiceEnvelope *d = mqttQueue.dequeuePtr(0); if (d) mqttPool.release(d); @@ -350,20 +350,20 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) case PortNum_TEXT_MESSAGE_APP: { msgType = "text"; // convert bytes to string - DEBUG_MSG("got text message of size %u\n", mp->decoded.payload.size); + LOG_DEBUG("got text message of size %u\n", mp->decoded.payload.size); char payloadStr[(mp->decoded.payload.size) + 1]; memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size); payloadStr[mp->decoded.payload.size] = 0; // null terminated string // check if this is a JSON payload JSONValue *json_value = JSON::Parse(payloadStr); if (json_value != NULL) { - DEBUG_MSG("text message payload is of type json\n"); + LOG_DEBUG("text message payload is of type json\n"); // if it is, then we can just use the json object jsonObj["payload"] = json_value; } else { // if it isn't, then we need to create a json object // with the string as the value - DEBUG_MSG("text message payload is of type plaintext\n"); + LOG_DEBUG("text message payload is of type plaintext\n"); msgPayload["text"] = new JSONValue(payloadStr); jsonObj["payload"] = new JSONValue(msgPayload); } @@ -392,7 +392,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) } jsonObj["payload"] = new JSONValue(msgPayload); } else - DEBUG_MSG("Error decoding protobuf for telemetry message!\n"); + LOG_DEBUG("Error decoding protobuf for telemetry message!\n"); }; break; } @@ -410,7 +410,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) msgPayload["hardware"] = new JSONValue(decoded->hw_model); jsonObj["payload"] = new JSONValue(msgPayload); } else - DEBUG_MSG("Error decoding protobuf for nodeinfo message!\n"); + LOG_DEBUG("Error decoding protobuf for nodeinfo message!\n"); }; break; } @@ -429,7 +429,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) if((int)decoded->altitude){msgPayload["altitude"] = new JSONValue((int)decoded->altitude);} jsonObj["payload"] = new JSONValue(msgPayload); } else { - DEBUG_MSG("Error decoding protobuf for position message!\n"); + LOG_DEBUG("Error decoding protobuf for position message!\n"); } }; break; @@ -452,7 +452,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) msgPayload["longitude_i"] = new JSONValue((int)decoded->longitude_i); jsonObj["payload"] = new JSONValue(msgPayload); } else { - DEBUG_MSG("Error decoding protobuf for position message!\n"); + LOG_DEBUG("Error decoding protobuf for position message!\n"); } }; break; @@ -474,7 +474,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) JSONValue *value = new JSONValue(jsonObj); std::string jsonStr = value->Stringify(); - DEBUG_MSG("serialized json message: %s\n", jsonStr.c_str()); + LOG_DEBUG("serialized json message: %s\n", jsonStr.c_str()); delete value; return jsonStr; diff --git a/src/nimble/NimbleBluetooth.cpp b/src/nimble/NimbleBluetooth.cpp index c74c73316..ae33e4702 100644 --- a/src/nimble/NimbleBluetooth.cpp +++ b/src/nimble/NimbleBluetooth.cpp @@ -22,7 +22,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - DEBUG_MSG("BLE notify fromNum\n"); + LOG_DEBUG("BLE notify fromNum\n"); uint8_t val[4]; put_le32(val, fromRadioNum); @@ -46,7 +46,7 @@ static BluetoothPhoneAPI *bluetoothPhoneAPI; class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks { virtual void onWrite(NimBLECharacteristic *pCharacteristic) { - DEBUG_MSG("To Radio onwrite\n"); + LOG_DEBUG("To Radio onwrite\n"); auto val = pCharacteristic->getValue(); bluetoothPhoneAPI->handleToRadio(val.data(), val.length()); @@ -56,7 +56,7 @@ class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks { virtual void onRead(NimBLECharacteristic *pCharacteristic) { - DEBUG_MSG("From Radio onread\n"); + LOG_DEBUG("From Radio onread\n"); uint8_t fromRadioBytes[FromRadio_size]; size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes); @@ -72,11 +72,11 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks uint32_t passkey = config.bluetooth.fixed_pin; if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_RANDOM_PIN) { - DEBUG_MSG("Using random passkey\n"); + LOG_DEBUG("Using random passkey\n"); // This is the passkey to be entered on peer - we pick a number >100,000 to ensure 6 digits passkey = random(100000, 999999); } - DEBUG_MSG("*** Enter passkey %d on the peer side ***\n", passkey); + LOG_DEBUG("*** Enter passkey %d on the peer side ***\n", passkey); powerFSM.trigger(EVENT_BLUETOOTH_PAIR); screen->startBluetoothPinScreen(passkey); @@ -87,7 +87,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) { - DEBUG_MSG("BLE authentication complete\n"); + LOG_DEBUG("BLE authentication complete\n"); if (passkeyShowing) { passkeyShowing = false; @@ -98,7 +98,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onDisconnect(NimBLEServer* pServer, ble_gap_conn_desc *desc) { - DEBUG_MSG("BLE disconnect\n"); + LOG_DEBUG("BLE disconnect\n"); } }; @@ -108,7 +108,7 @@ static NimbleBluetoothFromRadioCallback *fromRadioCallbacks; void NimbleBluetooth::shutdown() { // Shutdown bluetooth for minimum power draw - DEBUG_MSG("Disable bluetooth\n"); + LOG_DEBUG("Disable bluetooth\n"); //Bluefruit.Advertising.stop(); NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); pAdvertising->reset(); @@ -125,7 +125,7 @@ void NimbleBluetooth::setup() // Uncomment for testing // NimbleBluetooth::clearBonds(); - DEBUG_MSG("Initialise the NimBLE bluetooth module\n"); + LOG_DEBUG("Initialise the NimBLE bluetooth module\n"); NimBLEDevice::init(getDeviceName()); NimBLEDevice::setPower(ESP_PWR_LVL_P9); @@ -186,7 +186,7 @@ void updateBatteryLevel(uint8_t level) void NimbleBluetooth::clearBonds() { - DEBUG_MSG("Clearing bluetooth bonds!\n"); + LOG_DEBUG("Clearing bluetooth bonds!\n"); NimBLEDevice::deleteAllBonds(); } diff --git a/src/platform/esp32/ESP32CryptoEngine.cpp b/src/platform/esp32/ESP32CryptoEngine.cpp index 4bbbc4ad4..93eb76dbd 100644 --- a/src/platform/esp32/ESP32CryptoEngine.cpp +++ b/src/platform/esp32/ESP32CryptoEngine.cpp @@ -46,7 +46,7 @@ class ESP32CryptoEngine : public CryptoEngine static uint8_t scratch[MAX_BLOCKSIZE]; size_t nc_off = 0; - DEBUG_MSG("ESP32 crypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("ESP32 crypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); initNonce(fromNode, packetId); assert(numBytes <= MAX_BLOCKSIZE); memcpy(scratch, bytes, numBytes); diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index 2fcdf9318..f141ff3be 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -66,17 +66,17 @@ void enableSlowCLK() uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL); if (cal_32k == 0) { - DEBUG_MSG("32K XTAL OSC has not started up\n"); + LOG_DEBUG("32K XTAL OSC has not started up\n"); } else { rtc_clk_slow_freq_set(RTC_SLOW_FREQ_32K_XTAL); - DEBUG_MSG("Switching RTC Source to 32.768Khz succeeded, using 32K XTAL\n"); + LOG_DEBUG("Switching RTC Source to 32.768Khz succeeded, using 32K XTAL\n"); CALIBRATE_ONE(RTC_CAL_RTC_MUX); CALIBRATE_ONE(RTC_CAL_32K_XTAL); } CALIBRATE_ONE(RTC_CAL_RTC_MUX); CALIBRATE_ONE(RTC_CAL_32K_XTAL); if (rtc_clk_slow_freq_get() != RTC_SLOW_FREQ_32K_XTAL) { - DEBUG_MSG("Warning: Failed to switch 32K XTAL RTC source to 32.768Khz !!! \n"); return; + LOG_WARN("Failed to switch 32K XTAL RTC source to 32.768Khz !!! \n"); return; } } #endif @@ -85,21 +85,21 @@ void enableSlowCLK() void esp32Setup() { uint32_t seed = esp_random(); - DEBUG_MSG("Setting random seed %u\n", seed); + LOG_DEBUG("Setting random seed %u\n", seed); randomSeed(seed); // ESP docs say this is fairly random - DEBUG_MSG("Total heap: %d\n", ESP.getHeapSize()); - DEBUG_MSG("Free heap: %d\n", ESP.getFreeHeap()); - DEBUG_MSG("Total PSRAM: %d\n", ESP.getPsramSize()); - DEBUG_MSG("Free PSRAM: %d\n", ESP.getFreePsram()); + LOG_DEBUG("Total heap: %d\n", ESP.getHeapSize()); + LOG_DEBUG("Free heap: %d\n", ESP.getFreeHeap()); + LOG_DEBUG("Total PSRAM: %d\n", ESP.getPsramSize()); + LOG_DEBUG("Free PSRAM: %d\n", ESP.getFreePsram()); nvs_stats_t nvs_stats; auto res = nvs_get_stats(NULL, &nvs_stats); assert(res == ESP_OK); - DEBUG_MSG("NVS: UsedEntries %d, FreeEntries %d, AllEntries %d, NameSpaces %d\n", nvs_stats.used_entries, nvs_stats.free_entries, + LOG_DEBUG("NVS: UsedEntries %d, FreeEntries %d, AllEntries %d, NameSpaces %d\n", nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.total_entries, nvs_stats.namespace_count); - DEBUG_MSG("Setup Preferences in Flash Storage\n"); + LOG_DEBUG("Setup Preferences in Flash Storage\n"); // Create object to store our persistant data Preferences preferences; @@ -109,12 +109,12 @@ void esp32Setup() rebootCounter++; preferences.putUInt("rebootCounter", rebootCounter); preferences.end(); - DEBUG_MSG("Number of Device Reboots: %d\n", rebootCounter); + LOG_DEBUG("Number of Device Reboots: %d\n", rebootCounter); String BLEOTA=BleOta::getOtaAppVersion(); if (BLEOTA.isEmpty()) { - DEBUG_MSG("No OTA firmware available\n"); + LOG_DEBUG("No OTA firmware available\n"); }else{ - DEBUG_MSG("OTA firmware version %s\n", BLEOTA.c_str()); + LOG_DEBUG("OTA firmware version %s\n", BLEOTA.c_str()); } // enableModemSleep(); @@ -141,13 +141,13 @@ void esp32Setup() uint32_t axpDebugRead() { axp.debugCharging(); - DEBUG_MSG("vbus current %f\n", axp.getVbusCurrent()); - DEBUG_MSG("charge current %f\n", axp.getBattChargeCurrent()); - DEBUG_MSG("bat voltage %f\n", axp.getBattVoltage()); - DEBUG_MSG("batt pct %d\n", axp.getBattPercentage()); - DEBUG_MSG("is battery connected %d\n", axp.isBatteryConnect()); - DEBUG_MSG("is USB connected %d\n", axp.isVBUSPlug()); - DEBUG_MSG("is charging %d\n", axp.isChargeing()); + LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent()); + LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent()); + LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage()); + LOG_DEBUG("batt pct %d\n", axp.getBattPercentage()); + LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect()); + LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug()); + LOG_DEBUG("is charging %d\n", axp.isChargeing()); return 30 * 1000; } diff --git a/src/platform/nrf52/NRF52Bluetooth.cpp b/src/platform/nrf52/NRF52Bluetooth.cpp index acb26071f..950d6b7a4 100644 --- a/src/platform/nrf52/NRF52Bluetooth.cpp +++ b/src/platform/nrf52/NRF52Bluetooth.cpp @@ -33,7 +33,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - DEBUG_MSG("BLE notify fromNum\n"); + LOG_DEBUG("BLE notify fromNum\n"); fromNum.notify32(fromRadioNum); } @@ -55,7 +55,7 @@ void onConnect(uint16_t conn_handle) char central_name[32] = {0}; connection->getPeerName(central_name, sizeof(central_name)); - DEBUG_MSG("BLE Connected to %s\n", central_name); + LOG_DEBUG("BLE Connected to %s\n", central_name); } /** @@ -66,21 +66,21 @@ void onConnect(uint16_t conn_handle) void onDisconnect(uint16_t conn_handle, uint8_t reason) { // FIXME - we currently assume only one active connection - DEBUG_MSG("BLE Disconnected, reason = 0x%x\n", reason); + LOG_DEBUG("BLE Disconnected, reason = 0x%x\n", reason); } void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value) { // Display the raw request packet - DEBUG_MSG("CCCD Updated: %u\n", cccd_value); + LOG_DEBUG("CCCD Updated: %u\n", cccd_value); // Check the characteristic this CCCD update is associated with in case // this handler is used for multiple CCCD records. if (chr->uuid == fromNum.uuid) { if (chr->notifyEnabled(conn_hdl)) { - DEBUG_MSG("fromNum 'Notify' enabled\n"); + LOG_DEBUG("fromNum 'Notify' enabled\n"); } else { - DEBUG_MSG("fromNum 'Notify' disabled\n"); + LOG_DEBUG("fromNum 'Notify' disabled\n"); } } } @@ -135,14 +135,14 @@ void onFromRadioAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_e // or make empty if the queue is empty fromRadio.write(fromRadioBytes, numBytes); } else { - // DEBUG_MSG("Ignoring successor read\n"); + // LOG_DEBUG("Ignoring successor read\n"); } authorizeRead(conn_hdl); } void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, uint16_t len) { - DEBUG_MSG("toRadioWriteCb data %p, len %u\n", data, len); + LOG_DEBUG("toRadioWriteCb data %p, len %u\n", data, len); bluetoothPhoneAPI->handleToRadio(data, len); } @@ -152,7 +152,7 @@ void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, ui */ void onFromNumAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_evt_read_t *request) { - DEBUG_MSG("fromNumAuthorizeCb\n"); + LOG_DEBUG("fromNumAuthorizeCb\n"); authorizeRead(conn_hdl); } @@ -204,14 +204,14 @@ static uint32_t configuredPasskey; void NRF52Bluetooth::shutdown() { // Shutdown bluetooth for minimum power draw - DEBUG_MSG("Disable NRF52 bluetooth\n"); + LOG_DEBUG("Disable NRF52 bluetooth\n"); Bluefruit.Advertising.stop(); } void NRF52Bluetooth::setup() { // Initialise the Bluefruit module - DEBUG_MSG("Initialize the Bluefruit nRF52 module\n"); + LOG_DEBUG("Initialize the Bluefruit nRF52 module\n"); Bluefruit.autoConnLed(false); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.begin(); @@ -225,7 +225,7 @@ void NRF52Bluetooth::setup() configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ? config.bluetooth.fixed_pin : random(100000, 999999); auto pinString = std::to_string(configuredPasskey); - DEBUG_MSG("Bluetooth pin set to '%i'\n", configuredPasskey); + LOG_DEBUG("Bluetooth pin set to '%i'\n", configuredPasskey); Bluefruit.Security.setPIN(pinString.c_str()); Bluefruit.Security.setIOCaps(true, false, false); Bluefruit.Security.setPairPasskeyCallback(NRF52Bluetooth::onPairingPasskey); @@ -248,30 +248,30 @@ void NRF52Bluetooth::setup() bledfu.begin(); // Install the DFU helper // Configure and Start the Device Information Service - DEBUG_MSG("Configuring the Device Information Service\n"); + LOG_DEBUG("Configuring the Device Information Service\n"); bledis.setModel(optstr(HW_VERSION)); bledis.setFirmwareRev(optstr(APP_VERSION)); bledis.begin(); // Start the BLE Battery Service and set it to 100% - DEBUG_MSG("Configuring the Battery Service\n"); + LOG_DEBUG("Configuring the Battery Service\n"); blebas.begin(); blebas.write(0); // Unknown battery level for now // Setup the Heart Rate Monitor service using // BLEService and BLECharacteristic classes - DEBUG_MSG("Configuring the Mesh bluetooth service\n"); + LOG_DEBUG("Configuring the Mesh bluetooth service\n"); setupMeshService(); // Supposedly debugging works with soft device if you disable advertising if (isSoftDeviceAllowed) { // Setup the advertising packet(s) - DEBUG_MSG("Setting up the advertising payload(s)\n"); + LOG_DEBUG("Setting up the advertising payload(s)\n"); startAdv(); - DEBUG_MSG("Advertising\n"); + LOG_DEBUG("Advertising\n"); } } @@ -283,7 +283,7 @@ void updateBatteryLevel(uint8_t level) void NRF52Bluetooth::clearBonds() { - DEBUG_MSG("Clearing bluetooth bonds!\n"); + LOG_DEBUG("Clearing bluetooth bonds!\n"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); @@ -293,12 +293,12 @@ void NRF52Bluetooth::clearBonds() void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle) { - DEBUG_MSG("BLE connection secured\n"); + LOG_DEBUG("BLE connection secured\n"); } bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passkey[6], bool match_request) { - DEBUG_MSG("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3); + LOG_DEBUG("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3); screen->startBluetoothPinScreen(configuredPasskey); if (match_request) @@ -309,16 +309,16 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke if (!Bluefruit.connected(conn_handle)) break; } } - DEBUG_MSG("BLE passkey pairing: match_request=%i\n", match_request); + LOG_DEBUG("BLE passkey pairing: match_request=%i\n", match_request); return true; } void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_status) { if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS) - DEBUG_MSG("BLE pairing success\n"); + LOG_DEBUG("BLE pairing success\n"); else - DEBUG_MSG("BLE pairing failed\n"); + LOG_DEBUG("BLE pairing failed\n"); screen->stopBluetoothPinScreen(); } diff --git a/src/platform/nrf52/NRF52CryptoEngine.cpp b/src/platform/nrf52/NRF52CryptoEngine.cpp index 42eacfc27..73add2c3b 100644 --- a/src/platform/nrf52/NRF52CryptoEngine.cpp +++ b/src/platform/nrf52/NRF52CryptoEngine.cpp @@ -17,13 +17,13 @@ class NRF52CryptoEngine : public CryptoEngine virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) override { if (key.length > 16) { - DEBUG_MSG("Software encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("Software encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); AES_ctx ctx; initNonce(fromNode, packetId); AES_init_ctx_iv(&ctx, key.bytes, nonce); AES_CTR_xcrypt_buffer(&ctx, bytes, numBytes); } else if (key.length > 0) { - DEBUG_MSG("nRF52 encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("nRF52 encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); nRFCrypto.begin(); nRFCrypto_AES ctx; uint8_t myLen = ctx.blockLen(numBytes); diff --git a/src/platform/nrf52/hardfault.cpp b/src/platform/nrf52/hardfault.cpp index d63829072..fb27c3550 100644 --- a/src/platform/nrf52/hardfault.cpp +++ b/src/platform/nrf52/hardfault.cpp @@ -5,7 +5,7 @@ enum { r0, r1, r2, r3, r12, lr, pc, psr }; -// we can't use the regular DEBUG_MSG for these crash dumps because it depends on threading still being running. Instead use the +// we can't use the regular LOG_DEBUG for these crash dumps because it depends on threading still being running. Instead use the // segger in memory tool #define FAULT_MSG(...) SEGGER_MSG(__VA_ARGS__) diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp index 254ab695b..c53c548b5 100644 --- a/src/platform/nrf52/main-nrf52.cpp +++ b/src/platform/nrf52/main-nrf52.cpp @@ -32,7 +32,7 @@ bool loopCanSleep() { // handle standard gcc assert failures void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *failedexpr) { - DEBUG_MSG("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr); + LOG_DEBUG("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr); // debugger_break(); FIXME doesn't work, possibly not for segger // Reboot cpu NVIC_SystemReset(); @@ -73,7 +73,7 @@ void setBluetoothEnable(bool on) if (on) { if (!nrf52Bluetooth) { if (!useSoftDevice) - DEBUG_MSG("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); + LOG_DEBUG("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); else { nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth->setup(); @@ -112,7 +112,7 @@ void checkSDEvents() break; default: - DEBUG_MSG("Unexpected SDevt %d\n", evt); + LOG_DEBUG("Unexpected SDevt %d\n", evt); break; } } @@ -132,7 +132,7 @@ void nrf52Setup() auto why = NRF_POWER->RESETREAS; // per // https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.nrf52832.ps.v1.1%2Fpower.html - DEBUG_MSG("Reset reason: 0x%x\n", why); + LOG_DEBUG("Reset reason: 0x%x\n", why); // Per // https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/monitor-mode-debugging-with-j-link-and-gdbeclipse @@ -142,7 +142,7 @@ void nrf52Setup() #ifdef BQ25703A_ADDR auto *bq = new BQ25713(); if (!bq->setup()) - DEBUG_MSG("ERROR! Charge controller init failed\n"); + LOG_DEBUG("ERROR! Charge controller init failed\n"); #endif // Init random seed @@ -152,7 +152,7 @@ void nrf52Setup() } seed; nRFCrypto.begin(); nRFCrypto.Random.generate(seed.seed8, sizeof(seed.seed8)); - DEBUG_MSG("Setting random seed %u\n", seed.seed32); + LOG_DEBUG("Setting random seed %u\n", seed.seed32); randomSeed(seed.seed32); nRFCrypto.end(); } @@ -178,7 +178,7 @@ void cpuDeepSleep(uint64_t msecToWake) auto ok = sd_power_system_off(); if (ok != NRF_SUCCESS) { - DEBUG_MSG("FIXME: Ignoring soft device (EasyDMA pending?) and forcing " + LOG_DEBUG("FIXME: Ignoring soft device (EasyDMA pending?) and forcing " "system-off!\n"); NRF_POWER->SYSTEMOFF = 1; } @@ -186,7 +186,7 @@ void cpuDeepSleep(uint64_t msecToWake) // The following code should not be run, because we are off while (1) { delay(5000); - DEBUG_MSG("."); + LOG_DEBUG("."); } } diff --git a/src/platform/portduino/CrossPlatformCryptoEngine.cpp b/src/platform/portduino/CrossPlatformCryptoEngine.cpp index b3b3853c3..7bd021a42 100644 --- a/src/platform/portduino/CrossPlatformCryptoEngine.cpp +++ b/src/platform/portduino/CrossPlatformCryptoEngine.cpp @@ -27,7 +27,7 @@ class CrossPlatformCryptoEngine : public CryptoEngine virtual void setKey(const CryptoKey &k) override { CryptoEngine::setKey(k); - DEBUG_MSG("Installing AES%d key!\n", key.length * 8); + LOG_DEBUG("Installing AES%d key!\n", key.length * 8); if (ctr) { delete ctr; ctr = NULL; @@ -54,7 +54,7 @@ class CrossPlatformCryptoEngine : public CryptoEngine static uint8_t scratch[MAX_BLOCKSIZE]; //size_t nc_off = 0; - // DEBUG_MSG("ESP32 encrypt!\n"); + // LOG_DEBUG("ESP32 encrypt!\n"); initNonce(fromNode, packetId); assert(numBytes <= MAX_BLOCKSIZE); memcpy(scratch, bytes, numBytes); diff --git a/src/platform/portduino/SimRadio.cpp b/src/platform/portduino/SimRadio.cpp index 06427a6d5..016b91045 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -22,7 +22,7 @@ ErrorCode SimRadio::send(MeshPacket *p) // set (random) transmit delay to let others reconfigure their radio, // to avoid collisions and implement timing-based flooding - DEBUG_MSG("Set random delay before transmitting.\n"); + LOG_DEBUG("Set random delay before transmitting.\n"); setTransmitDelay(); return res; } @@ -42,7 +42,7 @@ void SimRadio::setTransmitDelay() startTransmitTimer(true); } else { // If there is a SNR, start a timer scaled based on that SNR. - DEBUG_MSG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); + LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); startTransmitTimerSNR(p->rx_snr); } } @@ -52,11 +52,11 @@ void SimRadio::startTransmitTimer(bool withDelay) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delayMsec = !withDelay ? 1 : getTxDelayMsec(); - // DEBUG_MSG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d\n", delay); delay(delayMsec); onNotify(TRANSMIT_DELAY_COMPLETED); } else { - DEBUG_MSG("TX QUEUE EMPTY!\n"); + LOG_DEBUG("TX QUEUE EMPTY!\n"); } } @@ -65,7 +65,7 @@ void SimRadio::startTransmitTimerSNR(float snr) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delayMsec = getTxDelayMsecWeighted(snr); - // DEBUG_MSG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d\n", delay); delay(delayMsec); onNotify(TRANSMIT_DELAY_COMPLETED); } @@ -92,7 +92,7 @@ void SimRadio::completeSending() // We are done sending that packet, release it packetPool.release(p); - // DEBUG_MSG("Done with send\n"); + // LOG_DEBUG("Done with send\n"); } } @@ -108,9 +108,9 @@ bool SimRadio::canSendImmediately() if (busyTx || busyRx) { if (busyTx) - DEBUG_MSG("Can not send yet, busyTx\n"); + LOG_DEBUG("Can not send yet, busyTx\n"); if (busyRx) - DEBUG_MSG("Can not send yet, busyRx\n"); + LOG_DEBUG("Can not send yet, busyRx\n"); return false; } else return true; @@ -134,7 +134,7 @@ bool SimRadio::cancelSending(NodeNum from, PacketId id) packetPool.release(p); // free the packet we just removed bool result = (p != NULL); - DEBUG_MSG("cancelSending id=0x%x, removed=%d\n", id, result); + LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); return result; } @@ -144,24 +144,24 @@ void SimRadio::onNotify(uint32_t notification) switch (notification) { case ISR_TX: handleTransmitInterrupt(); - DEBUG_MSG("tx complete - starting timer\n"); + LOG_DEBUG("tx complete - starting timer\n"); startTransmitTimer(); break; case ISR_RX: - DEBUG_MSG("rx complete - starting timer\n"); + LOG_DEBUG("rx complete - starting timer\n"); break; case TRANSMIT_DELAY_COMPLETED: - DEBUG_MSG("delay done\n"); + LOG_DEBUG("delay done\n"); // If we are not currently in receive mode, then restart the random delay (this can happen if the main thread // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode? if (!txQueue.empty()) { if (!canSendImmediately()) { - // DEBUG_MSG("Currently Rx/Tx-ing: set random delay\n"); + // LOG_DEBUG("Currently Rx/Tx-ing: set random delay\n"); setTransmitDelay(); // currently Rx/Tx-ing: reset random delay } else { if (isChannelActive()) { // check if there is currently a LoRa packet on the channel - // DEBUG_MSG("Channel is active: set random delay\n"); + // LOG_DEBUG("Channel is active: set random delay\n"); setTransmitDelay(); // reset random delay } else { // Send any outgoing packets we have ready @@ -177,7 +177,7 @@ void SimRadio::onNotify(uint32_t notification) } } } else { - // DEBUG_MSG("done with txqueue\n"); + // LOG_DEBUG("done with txqueue\n"); } break; default: @@ -194,12 +194,12 @@ void SimRadio::startSend(MeshPacket * txp) perhapsDecode(p); Compressed c = Compressed_init_default; c.portnum = p->decoded.portnum; - // DEBUG_MSG("Sending back to simulator with portNum %d\n", p->decoded.portnum); + // LOG_DEBUG("Sending back to simulator with portNum %d\n", p->decoded.portnum); if (p->decoded.payload.size <= sizeof(c.data.bytes)) { memcpy(&c.data.bytes, p->decoded.payload.bytes, p->decoded.payload.size); c.data.size = p->decoded.payload.size; } else { - DEBUG_MSG("Payload size is larger than compressed message allows! Sending empty payload.\n"); + LOG_DEBUG("Payload size is larger than compressed message allows! Sending empty payload.\n"); } p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Compressed_msg, &c); p->decoded.portnum = PortNum_SIMULATOR_APP; @@ -218,7 +218,7 @@ void SimRadio::startReceive(MeshPacket *p) { void SimRadio::handleReceiveInterrupt(MeshPacket *p) { - DEBUG_MSG("HANDLE RECEIVE INTERRUPT\n"); + LOG_DEBUG("HANDLE RECEIVE INTERRUPT\n"); uint32_t xmitMsec; assert(isReceiving); isReceiving = false; @@ -226,7 +226,7 @@ void SimRadio::handleReceiveInterrupt(MeshPacket *p) // read the number of actually received bytes size_t length = getPacketLength(p); xmitMsec = getPacketTime(length); - // DEBUG_MSG("Payload size %d vs length (includes header) %d\n", p->decoded.payload.size, length); + // LOG_DEBUG("Payload size %d vs length (includes header) %d\n", p->decoded.payload.size, length); MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packtPool mp->which_payload_variant = MeshPacket_decoded_tag; // Mark that the payload is already decoded diff --git a/src/shutdown.h b/src/shutdown.h index 3927825fb..23f5d7252 100644 --- a/src/shutdown.h +++ b/src/shutdown.h @@ -7,14 +7,14 @@ void powerCommandsCheck() { if (rebootAtMsec && millis() > rebootAtMsec) { - DEBUG_MSG("Rebooting\n"); + LOG_DEBUG("Rebooting\n"); #if defined(ARCH_ESP32) ESP.restart(); #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else rebootAtMsec = -1; - DEBUG_MSG("FIXME implement reboot for this platform. Skipping for now.\n"); + LOG_DEBUG("FIXME implement reboot for this platform. Skipping for now.\n"); #endif } @@ -35,7 +35,7 @@ void powerCommandsCheck() #endif if (shutdownAtMsec && millis() > shutdownAtMsec) { - DEBUG_MSG("Shutting down from admin command\n"); + LOG_DEBUG("Shutting down from admin command\n"); #ifdef HAS_PMU if (pmu_found == true) { playShutdownMelody(); @@ -45,7 +45,7 @@ void powerCommandsCheck() playShutdownMelody(); power->shutdown(); #else - DEBUG_MSG("FIXME implement shutdown for this platform"); + LOG_DEBUG("FIXME implement shutdown for this platform"); #endif } } diff --git a/src/sleep.cpp b/src/sleep.cpp index 40426a777..ee38da699 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -60,7 +60,7 @@ void setCPUFast(bool on) * all WiFi use cases. * (Added: Dec 23, 2021 by Jm Casler) */ - DEBUG_MSG("Setting CPU to 240mhz because WiFi is in use.\n"); + LOG_DEBUG("Setting CPU to 240mhz because WiFi is in use.\n"); setCpuFrequencyMhz(240); return; } @@ -90,7 +90,7 @@ void setLed(bool ledOn) void setGPSPower(bool on) { - DEBUG_MSG("Setting GPS power=%d\n", on); + LOG_DEBUG("Setting GPS power=%d\n", on); #ifdef HAS_PMU if (pmu_found && PMU){ @@ -136,7 +136,7 @@ void initDeepSleep() if (wakeCause == ESP_SLEEP_WAKEUP_TIMER) reason = "timeout"; - DEBUG_MSG("booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason); + LOG_DEBUG("booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason); #endif } @@ -174,13 +174,13 @@ void doGPSpowersave(bool on) #ifdef HAS_PMU if (on) { - DEBUG_MSG("Turning GPS back on\n"); + LOG_DEBUG("Turning GPS back on\n"); gps->forceWake(1); setGPSPower(1); } else { - DEBUG_MSG("Turning off GPS chip\n"); + LOG_DEBUG("Turning off GPS chip\n"); notifyGPSSleep.notifyObservers(NULL); setGPSPower(0); } @@ -188,12 +188,12 @@ void doGPSpowersave(bool on) #ifdef PIN_GPS_WAKE if (on) { - DEBUG_MSG("Waking GPS"); + LOG_DEBUG("Waking GPS"); gps->forceWake(1); } else { - DEBUG_MSG("GPS entering sleep"); + LOG_DEBUG("GPS entering sleep"); notifyGPSSleep.notifyObservers(NULL); } #endif @@ -201,7 +201,7 @@ void doGPSpowersave(bool on) void doDeepSleep(uint64_t msecToWake) { - DEBUG_MSG("Entering deep sleep for %lu seconds\n", msecToWake / 1000); + LOG_DEBUG("Entering deep sleep for %lu seconds\n", msecToWake / 1000); // not using wifi yet, but once we are this is needed to shutoff the radio hw // esp_wifi_stop(); @@ -258,7 +258,7 @@ void doDeepSleep(uint64_t msecToWake) */ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more reasonable default { - // DEBUG_MSG("Enter light sleep\n"); + // LOG_DEBUG("Enter light sleep\n"); waitEnterSleep(); @@ -310,7 +310,7 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more r esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause(); #ifdef BUTTON_PIN if (cause == ESP_SLEEP_WAKEUP_GPIO) - DEBUG_MSG("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN)); + LOG_DEBUG("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN)); #endif return cause; @@ -340,6 +340,6 @@ void enableModemSleep() esp32_config.min_freq_mhz = 20; // 10Mhz is minimum recommended esp32_config.light_sleep_enable = false; int rv = esp_pm_configure(&esp32_config); - DEBUG_MSG("Sleep request result %x\n", rv); + LOG_DEBUG("Sleep request result %x\n", rv); } #endif From 115cb05d3bf1316054c60dba6431257bd54fc6a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 30 Dec 2022 14:22:08 +0100 Subject: [PATCH 101/119] less verbose logging and heap free printing --- src/concurrency/OSThread.cpp | 4 +++- src/modules/SerialModule.cpp | 1 - src/modules/esp32/AudioModule.cpp | 2 -- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 4e6bf1b5f..8862fa68b 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -82,7 +82,9 @@ void OSThread::run() #ifdef DEBUG_HEAP auto newHeap = ESP.getFreeHeap(); if (newHeap < heap) - DEBUG_MSG("Thread %s leaked heap %d -> %d (%d)\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + DEBUG_MSG("------ Thread %s leaked heap %d -> %d (%d) ------\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + if (heap < newHeap) + DEBUG_MSG("++++++ Thread %s freed heap %d -> %d (%d) ++++++\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); #endif runned(); diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index fc6448a97..11347c910 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -220,7 +220,6 @@ int32_t SerialModule::runOnce() return (10); } else { - DEBUG_MSG("Serial Module Disabled\n"); return disable(); } } diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index a0dffd0eb..548464392 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -140,7 +140,6 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { disable(); - DEBUG_MSG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -259,7 +258,6 @@ int32_t AudioModule::runOnce() } return 100; } else { - DEBUG_MSG("Audio Module Disabled\n"); return disable(); } From 3eefd46ca1f0a7bb322194e39db27c04afe54b50 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Fri, 30 Dec 2022 07:48:59 -0600 Subject: [PATCH 102/119] Log levels log function --- src/DebugConfiguration.h | 8 ++++---- src/RedirectablePrint.cpp | 7 +++---- src/RedirectablePrint.h | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/DebugConfiguration.h b/src/DebugConfiguration.h index f7733d5b1..d82ea186c 100644 --- a/src/DebugConfiguration.h +++ b/src/DebugConfiguration.h @@ -29,10 +29,10 @@ #define LOG_ERROR(...) SEGGER_RTT_printf(0, __VA_ARGS__) #else #ifdef DEBUG_PORT -#define LOG_DEBUG(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define LOG_INFO(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define LOG_WARN(...) DEBUG_PORT.logDebug(__VA_ARGS__) -#define LOG_ERROR(...) DEBUG_PORT.logDebug(__VA_ARGS__) +#define LOG_DEBUG(...) DEBUG_PORT.log(LOG_LEVEL_DEBUG, __VA_ARGS__) +#define LOG_INFO(...) DEBUG_PORT.log(LOG_LEVEL_INFO, __VA_ARGS__) +#define LOG_WARN(...) DEBUG_PORT.log(LOG_LEVEL_WARN, __VA_ARGS__) +#define LOG_ERROR(...) DEBUG_PORT.log(LOG_LEVEL_ERROR, __VA_ARGS__) #else #define LOG_DEBUG(...) #define LOG_INFO(...) diff --git a/src/RedirectablePrint.cpp b/src/RedirectablePrint.cpp index 66c83171a..e7f305e19 100644 --- a/src/RedirectablePrint.cpp +++ b/src/RedirectablePrint.cpp @@ -58,7 +58,7 @@ size_t RedirectablePrint::vprintf(const char *format, va_list arg) return len; } -size_t RedirectablePrint::logDebug(const char *format, ...) +size_t RedirectablePrint::log(const char *logLevel, const char *format, ...) { size_t r = 0; @@ -86,9 +86,9 @@ size_t RedirectablePrint::logDebug(const char *format, ...) int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN; int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN - r += printf("%02d:%02d:%02d %u ", hour, min, sec, millis() / 1000); + r += printf("%s | %02d:%02d:%02d %u ", logLevel, hour, min, sec, millis() / 1000); } else - r += printf("??:??:?? %u ", millis() / 1000); + r += printf("%s | ??:??:?? %u ", logLevel, millis() / 1000); auto thread = concurrency::OSThread::currentThread; if (thread) { @@ -99,7 +99,6 @@ size_t RedirectablePrint::logDebug(const char *format, ...) print("] "); } } - r += vprintf(format, arg); va_end(arg); diff --git a/src/RedirectablePrint.h b/src/RedirectablePrint.h index 9443d1672..8fabd4a72 100644 --- a/src/RedirectablePrint.h +++ b/src/RedirectablePrint.h @@ -34,7 +34,7 @@ class RedirectablePrint : public Print * log message. Otherwise we assume more prints will come before the log message ends. This * allows you to call logDebug a few times to build up a single log message line if you wish. */ - size_t logDebug(const char * format, ...) __attribute__ ((format (printf, 2, 3))); + size_t log(const char *logLevel, const char *format, ...) __attribute__ ((format (printf, 3, 4))); /** like printf but va_list based */ size_t vprintf(const char *format, va_list arg); From 65aad62702167c6a7c0125d70337e226fa6784bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 30 Dec 2022 14:51:00 +0100 Subject: [PATCH 103/119] tryfix - no mqtt if no mqtt wanted... --- src/mesh/Router.cpp | 50 ++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 66e21d21d..4f60360ce 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -222,28 +222,30 @@ ErrorCode Router::send(MeshPacket *p) ChannelIndex chIndex = p->channel; // keep as a local because we are about to change it #if HAS_WIFI || HAS_ETHERNET - // check if we should send decrypted packets to mqtt + if(moduleConfig.mqtt.enabled) { + // check if we should send decrypted packets to mqtt - // truth table: - /* mqtt_server mqtt_encryption_enabled should_encrypt - * not set 0 1 - * not set 1 1 - * set 0 0 - * set 1 1 - * - * => so we only decrypt mqtt if they have a custom mqtt server AND mqtt_encryption_enabled is FALSE - */ + // truth table: + /* mqtt_server mqtt_encryption_enabled should_encrypt + * not set 0 1 + * not set 1 1 + * set 0 0 + * set 1 1 + * + * => so we only decrypt mqtt if they have a custom mqtt server AND mqtt_encryption_enabled is FALSE + */ - bool shouldActuallyEncrypt = true; - if (*moduleConfig.mqtt.address && !moduleConfig.mqtt.encryption_enabled) { - shouldActuallyEncrypt = false; + bool shouldActuallyEncrypt = true; + if (*moduleConfig.mqtt.address && !moduleConfig.mqtt.encryption_enabled) { + shouldActuallyEncrypt = false; + } + + DEBUG_MSG("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); + + // the packet is currently in a decrypted state. send it now if they want decrypted packets + if (mqtt && !shouldActuallyEncrypt) + mqtt->onSend(*p, chIndex); } - - DEBUG_MSG("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); - - // the packet is currently in a decrypted state. send it now if they want decrypted packets - if (mqtt && !shouldActuallyEncrypt) - mqtt->onSend(*p, chIndex); #endif auto encodeResult = perhapsEncode(p); @@ -253,10 +255,12 @@ ErrorCode Router::send(MeshPacket *p) } #if HAS_WIFI || HAS_ETHERNET - // the packet is now encrypted. - // check if we should send encrypted packets to mqtt - if (mqtt && shouldActuallyEncrypt) - mqtt->onSend(*p, chIndex); + if(moduleConfig.mqtt.enabled) { + // the packet is now encrypted. + // check if we should send encrypted packets to mqtt + if (mqtt && shouldActuallyEncrypt) + mqtt->onSend(*p, chIndex); + } #endif } From e73ae7cdacdad0d3eb1ce5d06991d60d52af5cd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 30 Dec 2022 14:53:34 +0100 Subject: [PATCH 104/119] woops - was too fast there --- src/mesh/Router.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 4f60360ce..ee6473b2b 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -221,6 +221,8 @@ ErrorCode Router::send(MeshPacket *p) if (p->which_payload_variant == MeshPacket_decoded_tag) { ChannelIndex chIndex = p->channel; // keep as a local because we are about to change it + bool shouldActuallyEncrypt = true; + #if HAS_WIFI || HAS_ETHERNET if(moduleConfig.mqtt.enabled) { // check if we should send decrypted packets to mqtt @@ -235,7 +237,6 @@ ErrorCode Router::send(MeshPacket *p) * => so we only decrypt mqtt if they have a custom mqtt server AND mqtt_encryption_enabled is FALSE */ - bool shouldActuallyEncrypt = true; if (*moduleConfig.mqtt.address && !moduleConfig.mqtt.encryption_enabled) { shouldActuallyEncrypt = false; } @@ -255,7 +256,7 @@ ErrorCode Router::send(MeshPacket *p) } #if HAS_WIFI || HAS_ETHERNET - if(moduleConfig.mqtt.enabled) { + if (moduleConfig.mqtt.enabled) { // the packet is now encrypted. // check if we should send encrypted packets to mqtt if (mqtt && shouldActuallyEncrypt) From 819321529494fe66e510eec97497de69f628ec24 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Fri, 30 Dec 2022 08:14:37 -0600 Subject: [PATCH 105/119] Trace --- src/DebugConfiguration.h | 2 ++ src/mesh/NodeDB.cpp | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/DebugConfiguration.h b/src/DebugConfiguration.h index d82ea186c..cae83cb18 100644 --- a/src/DebugConfiguration.h +++ b/src/DebugConfiguration.h @@ -17,6 +17,7 @@ #define LOG_LEVEL_INFO "INFO " #define LOG_LEVEL_WARN "WARN " #define LOG_LEVEL_ERROR "ERROR" +#define LOG_LEVEL_TRACE "TRACE" #include "SerialConsole.h" @@ -33,6 +34,7 @@ #define LOG_INFO(...) DEBUG_PORT.log(LOG_LEVEL_INFO, __VA_ARGS__) #define LOG_WARN(...) DEBUG_PORT.log(LOG_LEVEL_WARN, __VA_ARGS__) #define LOG_ERROR(...) DEBUG_PORT.log(LOG_LEVEL_ERROR, __VA_ARGS__) +#define LOG_TRACE(...) DEBUG_PORT.log(LOG_TRACE, __VA_ARGS__) #else #define LOG_DEBUG(...) #define LOG_INFO(...) diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 57d462da2..e198c7065 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -203,7 +203,7 @@ void NodeDB::initConfigIntervals() void NodeDB::installDefaultModuleConfig() { - LOG_DEBUG("Installing default ModuleConfig\n"); + LOG_INFO("Installing default ModuleConfig\n"); memset(&moduleConfig, 0, sizeof(ModuleConfig)); moduleConfig.version = DEVICESTATE_CUR_VER; @@ -230,7 +230,7 @@ void NodeDB::initModuleConfigIntervals() void NodeDB::installDefaultChannels() { - LOG_DEBUG("Installing default ChannelFile\n"); + LOG_INFO("Installing default ChannelFile\n"); memset(&channelFile, 0, sizeof(ChannelFile)); channelFile.version = DEVICESTATE_CUR_VER; } @@ -244,7 +244,7 @@ void NodeDB::resetNodes() void NodeDB::installDefaultDeviceState() { - LOG_DEBUG("Installing default DeviceState\n"); + LOG_INFO("Installing default DeviceState\n"); memset(&devicestate, 0, sizeof(DeviceState)); *numNodes = 0; @@ -275,7 +275,7 @@ void NodeDB::installDefaultDeviceState() void NodeDB::init() { - LOG_DEBUG("Initializing NodeDB\n"); + LOG_INFO("Initializing NodeDB\n"); loadFromDisk(); uint32_t devicestateCRC = crc32Buffer(&devicestate, sizeof(devicestate)); @@ -383,7 +383,7 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c memset(dest_struct, 0, objSize); if (!pb_decode(&stream, fields, dest_struct)) { - LOG_DEBUG("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); } else { okay = true; } @@ -393,7 +393,7 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c LOG_DEBUG("No %s preferences found\n", filename); } #else - LOG_DEBUG("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented\n"); #endif return okay; } @@ -405,7 +405,7 @@ void NodeDB::loadFromDisk() installDefaultDeviceState(); // Our in RAM copy might now be corrupt } else { if (devicestate.version < DEVICESTATE_MIN_VER) { - LOG_DEBUG("Warn: devicestate %d is old, discarding\n", devicestate.version); + LOG_WARN("Devicestate %d is old, discarding\n", devicestate.version); factoryReset(); } else { LOG_DEBUG("Loaded saved devicestate version %d\n", devicestate.version); @@ -416,7 +416,7 @@ void NodeDB::loadFromDisk() installDefaultConfig(); // Our in RAM copy might now be corrupt } else { if (config.version < DEVICESTATE_MIN_VER) { - LOG_DEBUG("Warn: config %d is old, discarding\n", config.version); + LOG_WARN("config %d is old, discarding\n", config.version); installDefaultConfig(); } else { LOG_DEBUG("Loaded saved config version %d\n", config.version); @@ -427,7 +427,7 @@ void NodeDB::loadFromDisk() installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { - LOG_DEBUG("Warn: moduleConfig %d is old, discarding\n", moduleConfig.version); + LOG_WARN("moduleConfig %d is old, discarding\n", moduleConfig.version); installDefaultModuleConfig(); } else { LOG_DEBUG("Loaded saved moduleConfig version %d\n", moduleConfig.version); @@ -438,7 +438,7 @@ void NodeDB::loadFromDisk() installDefaultChannels(); // Our in RAM copy might now be corrupt } else { if (channelFile.version < DEVICESTATE_MIN_VER) { - LOG_DEBUG("Warn: channelFile %d is old, discarding\n", channelFile.version); + LOG_WARN("channelFile %d is old, discarding\n", channelFile.version); installDefaultChannels(); } else { LOG_DEBUG("Loaded saved channelFile version %d\n", channelFile.version); From 8364c2b1471771b630e17030eb436302213079d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 30 Dec 2022 17:03:48 +0100 Subject: [PATCH 106/119] more verbose thread debug --- src/Power.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Power.cpp b/src/Power.cpp index d2c5b01a0..550c8ad37 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -287,8 +287,18 @@ void Power::readPowerStatus() powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP - if (lastheap != ESP.getFreeHeap()){ - DEBUG_MSG("Heap status: %d/%d bytes free (%d), running %d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap , concurrency::mainController.size(false)); + if (lastheap != ESP.getFreeHeap()) { + DEBUG_MSG("Threads running:"); + int running = 0; + for(int i = 0; i < MAX_THREADS; i++){ + auto thread = concurrency::mainController.get(i); + if((thread != nullptr) && (thread->enabled)) { + DEBUG_MSG(" %s", thread->ThreadName.c_str()); + running++; + } + } + DEBUG_MSG("\n"); + DEBUG_MSG("Heap status: %d/%d bytes free (%d), running %d/%d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap, running, concurrency::mainController.size(false)); lastheap = ESP.getFreeHeap(); } #endif From f1cdfd163df371a0fd3926535e508556175f230d Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Fri, 30 Dec 2022 10:27:07 -0600 Subject: [PATCH 107/119] Replaced all of the logging with proper log levels --- src/ButtonThread.h | 2 +- src/FSCommon.cpp | 6 +- src/GPSStatus.h | 2 +- src/Power.cpp | 10 +- src/PowerFSM.cpp | 34 +++--- src/detect/einkScan.h | 4 +- src/detect/i2cScan.h | 52 ++++----- src/gps/GPS.cpp | 12 +- src/gps/NMEAGPS.cpp | 4 +- src/graphics/EInkDisplay2.cpp | 2 +- src/graphics/Screen.cpp | 10 +- src/graphics/TFTDisplay.cpp | 2 +- src/input/RotaryEncoderInterruptBase.cpp | 2 +- src/main.cpp | 14 +-- src/memtest.cpp | 2 +- src/mesh/FloodingRouter.cpp | 2 +- src/mesh/MeshModule.cpp | 4 +- src/mesh/MeshService.cpp | 8 +- src/mesh/NodeDB.cpp | 44 +++---- src/mesh/PhoneAPI.cpp | 34 +++--- src/mesh/ProtobufModule.h | 4 +- src/mesh/RF95Interface.cpp | 8 +- src/mesh/RadioInterface.cpp | 22 ++-- src/mesh/RadioLibInterface.cpp | 20 ++-- src/mesh/Router.cpp | 10 +- src/mesh/SX126xInterface.cpp | 10 +- src/mesh/SX128xInterface.cpp | 12 +- src/mesh/eth/ethClient.cpp | 30 ++--- src/mesh/eth/ethServerAPI.cpp | 8 +- src/mesh/http/ContentHandler.cpp | 18 +-- src/mesh/http/WebServer.cpp | 20 ++-- src/mesh/http/WiFiAPClient.cpp | 103 ++++++++--------- src/mesh/mesh-pb-constants.cpp | 4 +- src/mesh/wifi/WiFiServerAPI.cpp | 8 +- src/modules/AdminModule.cpp | 108 +++++++++--------- src/modules/CannedMessageModule.cpp | 6 +- src/modules/ExternalNotificationModule.cpp | 40 +++---- src/modules/NodeInfoModule.cpp | 4 +- src/modules/PositionModule.cpp | 16 +-- src/modules/RemoteHardwareModule.cpp | 8 +- src/modules/ReplyModule.cpp | 2 +- src/modules/SerialModule.cpp | 8 +- src/modules/Telemetry/DeviceTelemetry.cpp | 8 +- .../Telemetry/EnvironmentTelemetry.cpp | 12 +- src/modules/Telemetry/Sensor/BME280Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/BME680Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/BMP280Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/INA219Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/INA260Sensor.cpp | 2 +- .../Telemetry/Sensor/LPS22HBSensor.cpp | 2 +- .../Telemetry/Sensor/MCP9808Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/SHT31Sensor.cpp | 2 +- src/modules/Telemetry/Sensor/SHTC3Sensor.cpp | 2 +- .../Telemetry/Sensor/TelemetrySensor.h | 4 +- src/modules/TextMessageModule.cpp | 2 +- src/modules/TraceRouteModule.cpp | 8 +- src/modules/WaypointModule.cpp | 2 +- src/modules/esp32/AudioModule.cpp | 28 ++--- src/modules/esp32/RangeTestModule.cpp | 33 +++--- src/modules/esp32/StoreForwardModule.cpp | 46 ++++---- src/mqtt/MQTT.cpp | 54 ++++----- src/nimble/NimbleBluetooth.cpp | 20 ++-- src/platform/esp32/SimpleAllocator.cpp | 4 +- src/platform/nrf52/NRF52Bluetooth.cpp | 46 ++++---- src/platform/nrf52/main-nrf52.cpp | 9 +- src/platform/portduino/SimRadio.cpp | 6 +- src/shutdown.h | 8 +- src/sleep.cpp | 16 +-- 68 files changed, 519 insertions(+), 524 deletions(-) diff --git a/src/ButtonThread.h b/src/ButtonThread.h index d1076c326..d94b6a769 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -139,7 +139,7 @@ class ButtonThread : public concurrency::OSThread // may wake the board immediatedly. if ((!shutdown_on_long_stop) && (millis() > 30 * 1000)) { screen->startShutdownScreen(); - LOG_DEBUG("Shutdown from long press"); + LOG_INFO("Shutdown from long press"); playBeep(); #ifdef PIN_LED1 ledOff(PIN_LED1); diff --git a/src/FSCommon.cpp b/src/FSCommon.cpp index 2f901d26a..73d5d92b3 100644 --- a/src/FSCommon.cpp +++ b/src/FSCommon.cpp @@ -21,13 +21,13 @@ bool copyFile(const char* from, const char* to) File f1 = FSCom.open(from, FILE_O_READ); if (!f1){ - LOG_DEBUG("Failed to open source file %s\n", from); + LOG_ERROR("Failed to open source file %s\n", from); return false; } File f2 = FSCom.open(to, FILE_O_WRITE); if (!f2) { - LOG_DEBUG("Failed to open destination file %s\n", to); + LOG_ERROR("Failed to open destination file %s\n", to); return false; } @@ -170,7 +170,7 @@ void fsInit() #ifdef FSCom if (!FSBegin()) { - LOG_DEBUG("ERROR filesystem mount Failed. Formatting...\n"); + LOG_ERROR("Filesystem mount Failed. Formatting...\n"); assert(0); // FIXME - report failure to phone } #ifdef ARCH_ESP32 diff --git a/src/GPSStatus.h b/src/GPSStatus.h index 9ada4e66e..c76b66103 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -114,7 +114,7 @@ class GPSStatus : public Status if (isDirty && p.timestamp && (newStatus->p.timestamp == p.timestamp)) { // We can NEVER be in two locations at the same time! (also PR #886) - LOG_DEBUG("BUG!! positional timestamp unchanged from prev solution\n"); + LOG_ERROR("BUG: Positional timestamp unchanged from prev solution\n"); } initialized = true; diff --git a/src/Power.cpp b/src/Power.cpp index bba21549b..7f6dd92a0 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -242,7 +242,7 @@ void Power::shutdown() #endif #ifdef HAS_PMU - LOG_DEBUG("Shutting down\n"); + LOG_INFO("Shutting down\n"); if(PMU) { PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF); PMU->shutdown(); @@ -333,12 +333,12 @@ int32_t Power::runOnce() PMU->getIrqStatus(); if(PMU->isVbusRemoveIrq()){ - LOG_DEBUG("USB unplugged\n"); + LOG_INFO("USB unplugged\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } if (PMU->isVbusInsertIrq()) { - LOG_DEBUG("USB plugged In\n"); + LOG_INFO("USB plugged In\n"); powerFSM.trigger(EVENT_POWER_CONNECTED); } @@ -405,7 +405,7 @@ bool Power::axpChipInit() delete PMU; PMU = NULL; } else { - LOG_DEBUG("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); + LOG_INFO("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); } } @@ -416,7 +416,7 @@ bool Power::axpChipInit() delete PMU; PMU = NULL; } else { - LOG_DEBUG("AXP192 PMU init succeeded, using AXP192 PMU\n"); + LOG_INFO("AXP192 PMU init succeeded, using AXP192 PMU\n"); } } diff --git a/src/PowerFSM.cpp b/src/PowerFSM.cpp index f35e755ca..d5235c00b 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -32,7 +32,7 @@ static bool isPowered() static void sdsEnter() { - LOG_DEBUG("Enter state: SDS\n"); + LOG_INFO("Enter state: SDS\n"); // FIXME - make sure GPS and LORA radio are off first - because we want close to zero current draw doDeepSleep(getConfiguredOrDefaultMs(config.power.sds_secs)); } @@ -41,7 +41,7 @@ extern Power *power; static void shutdownEnter() { - LOG_DEBUG("Enter state: SHUTDOWN\n"); + LOG_INFO("Enter state: SHUTDOWN\n"); power->shutdown(); } @@ -51,16 +51,16 @@ static uint32_t secsSlept; static void lsEnter() { - LOG_DEBUG("lsEnter begin, ls_secs=%u\n", config.power.ls_secs); + LOG_INFO("lsEnter begin, ls_secs=%u\n", config.power.ls_secs); screen->setOn(false); secsSlept = 0; // How long have we been sleeping this time - // LOG_DEBUG("lsEnter end\n"); + // LOG_INFO("lsEnter end\n"); } static void lsIdle() { - // LOG_DEBUG("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); + // LOG_INFO("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); #ifdef ARCH_ESP32 @@ -82,7 +82,7 @@ static void lsIdle() wakeCause2 = doLightSleep(1); // leave led on for 1ms secsSlept += sleepTime; - // LOG_DEBUG("sleeping, flash led!\n"); + // LOG_INFO("sleeping, flash led!\n"); break; case ESP_SLEEP_WAKEUP_UART: @@ -93,7 +93,7 @@ static void lsIdle() default: // We woke for some other reason (button press, device interrupt) // uint64_t status = esp_sleep_get_ext1_wakeup_status(); - LOG_DEBUG("wakeCause2 %d\n", wakeCause2); + LOG_INFO("wakeCause2 %d\n", wakeCause2); #ifdef BUTTON_PIN bool pressed = !digitalRead(BUTTON_PIN); @@ -117,7 +117,7 @@ static void lsIdle() } else { // Time to stop sleeping! setLed(false); - LOG_DEBUG("reached ls_secs, servicing loop()\n"); + LOG_INFO("Reached ls_secs, servicing loop()\n"); powerFSM.trigger(EVENT_WAKE_TIMER); } #endif @@ -125,7 +125,7 @@ static void lsIdle() static void lsExit() { - LOG_DEBUG("Exit state: LS\n"); + LOG_INFO("Exit state: LS\n"); // setGPSPower(true); // restore GPS power if (gps) gps->forceWake(true); @@ -133,7 +133,7 @@ static void lsExit() static void nbEnter() { - LOG_DEBUG("Enter state: NB\n"); + LOG_INFO("Enter state: NB\n"); screen->setOn(false); setBluetoothEnable(false); @@ -148,7 +148,7 @@ static void darkEnter() static void serialEnter() { - LOG_DEBUG("Enter state: SERIAL\n"); + LOG_INFO("Enter state: SERIAL\n"); setBluetoothEnable(false); screen->setOn(true); screen->print("Serial connected\n"); @@ -161,10 +161,10 @@ static void serialExit() static void powerEnter() { - LOG_DEBUG("Enter state: POWER\n"); + LOG_INFO("Enter state: POWER\n"); if (!isPowered()) { // If we got here, we are in the wrong state - we should be in powered, let that state ahndle things - LOG_DEBUG("Loss of power in Powered\n"); + LOG_INFO("Loss of power in Powered\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } else { screen->setOn(true); @@ -177,7 +177,7 @@ static void powerIdle() { if (!isPowered()) { // If we got here, we are in the wrong state - LOG_DEBUG("Loss of power in Powered\n"); + LOG_INFO("Loss of power in Powered\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } } @@ -191,7 +191,7 @@ static void powerExit() static void onEnter() { - LOG_DEBUG("Enter state: ON\n"); + LOG_INFO("Enter state: ON\n"); screen->setOn(true); setBluetoothEnable(true); @@ -221,7 +221,7 @@ static void screenPress() static void bootEnter() { - LOG_DEBUG("Enter state: BOOT\n"); + LOG_INFO("Enter state: BOOT\n"); } State stateSHUTDOWN(shutdownEnter, NULL, NULL, "SHUTDOWN"); @@ -240,7 +240,7 @@ void PowerFSM_setup() bool isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER ? 1 : 0); bool hasPower = isPowered(); - LOG_DEBUG("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); + LOG_INFO("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); powerFSM.add_timed_transition(&stateBOOT, hasPower ? &statePOWER : &stateON, 3 * 1000, NULL, "boot timeout"); // wake timer expired or a packet arrived diff --git a/src/detect/einkScan.h b/src/detect/einkScan.h index dd2bf01c2..a7a855709 100644 --- a/src/detect/einkScan.h +++ b/src/detect/einkScan.h @@ -52,9 +52,9 @@ void scanEInkDevice(void) d_writeCommand(0x20); eink_found = (d_waitWhileBusy(150) > 0) ? true : false; if(eink_found) - LOG_DEBUG("EInk display found\n"); + LOG_DEBUG("EInk display found\n"); else - LOG_DEBUG("EInk display not found\n"); + LOG_DEBUG("EInk display not found\n"); SPI1.end(); } #endif diff --git a/src/detect/i2cScan.h b/src/detect/i2cScan.h index f2ebc18b8..77d1fff17 100644 --- a/src/detect/i2cScan.h +++ b/src/detect/i2cScan.h @@ -107,20 +107,20 @@ void scanI2Cdevice() screen_found = addr; screen_model = oled_probe(addr); if (screen_model == 1) { - LOG_DEBUG("ssd1306 display found\n"); + LOG_INFO("ssd1306 display found\n"); } else if (screen_model == 2) { - LOG_DEBUG("sh1106 display found\n"); + LOG_INFO("sh1106 display found\n"); } else { - LOG_DEBUG("unknown display found\n"); + LOG_INFO("unknown display found\n"); } } #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) if (addr == ATECC608B_ADDR) { keystore_found = addr; if (atecc.begin(keystore_found) == true) { - LOG_DEBUG("ATECC608B initialized\n"); + LOG_INFO("ATECC608B initialized\n"); } else { - LOG_DEBUG("ATECC608B initialization failed\n"); + LOG_WARN("ATECC608B initialization failed\n"); } printATECCInfo(); } @@ -128,7 +128,7 @@ void scanI2Cdevice() #ifdef RV3028_RTC if (addr == RV3028_RTC){ rtc_found = addr; - LOG_DEBUG("RV3028 RTC found\n"); + LOG_INFO("RV3028 RTC found\n"); Melopero_RV3028 rtc; rtc.initI2C(); rtc.writeToRegister(0x35,0x07); // no Clkout @@ -138,7 +138,7 @@ void scanI2Cdevice() #ifdef PCF8563_RTC if (addr == PCF8563_RTC){ rtc_found = addr; - LOG_DEBUG("PCF8563 RTC found\n"); + LOG_INFO("PCF8563 RTC found\n"); } #endif if (addr == CARDKB_ADDR) { @@ -146,33 +146,33 @@ void scanI2Cdevice() // Do we have the RAK14006 instead? registerValue = getRegisterValue(addr, 0x04, 1); if (registerValue == 0x02) { // KEYPAD_VERSION - LOG_DEBUG("RAK14004 found\n"); + LOG_INFO("RAK14004 found\n"); kb_model = 0x02; } else { - LOG_DEBUG("m5 cardKB found\n"); + LOG_INFO("m5 cardKB found\n"); kb_model = 0x00; } } if (addr == ST7567_ADDRESS) { screen_found = addr; - LOG_DEBUG("st7567 display found\n"); + LOG_INFO("st7567 display found\n"); } #ifdef HAS_PMU if (addr == XPOWERS_AXP192_AXP2101_ADDRESS) { pmu_found = true; - LOG_DEBUG("axp192/axp2101 PMU found\n"); + LOG_INFO("axp192/axp2101 PMU found\n"); } #endif if (addr == BME_ADDR || addr == BME_ADDR_ALTERNATE) { registerValue = getRegisterValue(addr, 0xD0, 1); // GET_ID if (registerValue == 0x61) { - LOG_DEBUG("BME-680 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_INFO("BME-680 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BME680] = addr; } else if (registerValue == 0x60) { - LOG_DEBUG("BME-280 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_INFO("BME-280 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BME280] = addr; } else { - LOG_DEBUG("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_INFO("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_BMP280] = addr; } } @@ -180,52 +180,52 @@ void scanI2Cdevice() registerValue = getRegisterValue(addr, 0xFE, 2); LOG_DEBUG("Register MFG_UID: 0x%x\n", registerValue); if (registerValue == 0x5449) { - LOG_DEBUG("INA260 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_INFO("INA260 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_INA260] = addr; } else { // Assume INA219 if INA260 ID is not found - LOG_DEBUG("INA219 sensor found at address 0x%x\n", (uint8_t)addr); + LOG_INFO("INA219 sensor found at address 0x%x\n", (uint8_t)addr); nodeTelemetrySensorsMap[TelemetrySensorType_INA219] = addr; } } if (addr == MCP9808_ADDR) { nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr; - LOG_DEBUG("MCP9808 sensor found\n"); + LOG_INFO("MCP9808 sensor found\n"); } if (addr == SHT31_ADDR) { - LOG_DEBUG("SHT31 sensor found\n"); + LOG_INFO("SHT31 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; } if (addr == SHTC3_ADDR) { - LOG_DEBUG("SHTC3 sensor found\n"); + LOG_INFO("SHTC3 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; } if (addr == LPS22HB_ADDR || addr == LPS22HB_ADDR_ALT) { - LOG_DEBUG("LPS22HB sensor found\n"); + LOG_INFO("LPS22HB sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_LPS22] = addr; } // High rate sensors, will be processed internally if (addr == QMC6310_ADDR) { - LOG_DEBUG("QMC6310 Highrate 3-Axis magnetic sensor found\n"); + LOG_INFO("QMC6310 Highrate 3-Axis magnetic sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMC6310] = addr; } if (addr == QMI8658_ADDR) { - LOG_DEBUG("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); + LOG_INFO("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMI8658] = addr; } if (addr == QMC5883L_ADDR) { - LOG_DEBUG("QMC5883L Highrate 3-Axis magnetic sensor found\n"); + LOG_INFO("QMC5883L Highrate 3-Axis magnetic sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_QMC5883L] = addr; } } else if (err == 4) { - LOG_DEBUG("Unknow error at address 0x%x\n", addr); + LOG_ERROR("Unknow error at address 0x%x\n", addr); } } if (nDevices == 0) - LOG_DEBUG("No I2C devices found\n"); + LOG_INFO("No I2C devices found\n"); else - LOG_DEBUG("%i I2C devices found\n",nDevices); + LOG_INFO("%i I2C devices found\n",nDevices); } #else void scanI2Cdevice() {} diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index d8c33a5ea..7eec13228 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -361,7 +361,7 @@ void GPS::setNumSatellites(uint8_t n) void GPS::setAwake(bool on) { if (!wakeAllowed && on) { - LOG_DEBUG("Inhibiting because !wakeAllowed\n"); + LOG_WARN("Inhibiting because !wakeAllowed\n"); on = false; } @@ -516,7 +516,7 @@ void GPS::forceWake(bool on) /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs int GPS::prepareSleep(void *unused) { - LOG_DEBUG("GPS prepare sleep!\n"); + LOG_INFO("GPS prepare sleep!\n"); forceWake(false); return 0; @@ -525,7 +525,7 @@ int GPS::prepareSleep(void *unused) /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs int GPS::prepareDeepSleep(void *unused) { - LOG_DEBUG("GPS deep sleep!\n"); + LOG_INFO("GPS deep sleep!\n"); // For deep sleep we also want abandon any lock attempts (because we want minimum power) getSleepTime(); @@ -568,7 +568,7 @@ GnssModel_t GPS::probe() if(index != -1){ ver = ver.substring(index); if (ver.startsWith("$GPTXT,01,01,02")) { - LOG_DEBUG("L76K GNSS init succeeded, using L76K GNSS Module\n"); + LOG_INFO("L76K GNSS init succeeded, using L76K GNSS Module\n"); return GNSS_MODEL_MTK; } } @@ -631,9 +631,9 @@ GnssModel_t GPS::probe() } if (strlen((char*)buffer)) { - LOG_DEBUG("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n" , buffer); + LOG_INFO("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n" , buffer); }else{ - LOG_DEBUG("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); + LOG_INFO("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); } return GNSS_MODEL_UBLOX; diff --git a/src/gps/NMEAGPS.cpp b/src/gps/NMEAGPS.cpp index a99b55873..a89083c0e 100644 --- a/src/gps/NMEAGPS.cpp +++ b/src/gps/NMEAGPS.cpp @@ -137,7 +137,7 @@ bool NMEAGPS::lookForLocation() (reader.time.age() < GPS_SOL_EXPIRY_MS) && (reader.date.age() < GPS_SOL_EXPIRY_MS))) { - LOG_DEBUG("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age()); + LOG_WARN("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age()); return false; } @@ -212,7 +212,7 @@ bool NMEAGPS::lookForLocation() if (reader.course.value() < 36000) { // sanity check p.ground_track = reader.course.value() * 1e3; // Scale the heading (in degrees * 10^-2) to match the expected degrees * 10^-5 } else { - LOG_DEBUG("BOGUS course.value() REJECTED: %d\n", + LOG_WARN("BOGUS course.value() REJECTED: %d\n", reader.course.value()); } } diff --git a/src/graphics/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp index a7ec5e056..07fcd2c46 100644 --- a/src/graphics/EInkDisplay2.cpp +++ b/src/graphics/EInkDisplay2.cpp @@ -162,7 +162,7 @@ void EInkDisplay::setDetected(uint8_t detected) // Connect to the display bool EInkDisplay::connect() { - LOG_DEBUG("Doing EInk init\n"); + LOG_INFO("Doing EInk init\n"); #ifdef PIN_EINK_PWR_ON digitalWrite(PIN_EINK_PWR_ON, HIGH); // If we need to assert a pin to power external peripherals diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 426d5f2cd..53ca75a51 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -936,14 +936,14 @@ void Screen::handleSetOn(bool on) if (on != screenOn) { if (on) { - LOG_DEBUG("Turning on screen\n"); + LOG_INFO("Turning on screen\n"); dispdev.displayOn(); dispdev.displayOn(); enabled = true; setInterval(0); // Draw ASAP runASAP = true; } else { - LOG_DEBUG("Turning off screen\n"); + LOG_INFO("Turning off screen\n"); dispdev.displayOff(); enabled = false; } @@ -1056,7 +1056,7 @@ int32_t Screen::runOnce() // serialSinceMsec adjusts for additional serial wait time during nRF52 bootup static bool showingBootScreen = true; if (showingBootScreen && (millis() > (logo_timeout + serialSinceMsec))) { - LOG_DEBUG("Done with boot screen...\n"); + LOG_INFO("Done with boot screen...\n"); stopBootScreen(); showingBootScreen = false; } @@ -1065,7 +1065,7 @@ int32_t Screen::runOnce() if (strlen(oemStore.oem_text) > 0) { static bool showingOEMBootScreen = true; if (showingOEMBootScreen && (millis() > ((logo_timeout / 2) + serialSinceMsec))) { - LOG_DEBUG("Switch to OEM screen...\n"); + LOG_INFO("Switch to OEM screen...\n"); // Change frames. static FrameCallback bootOEMFrames[] = {drawOEMBootScreen}; static const int bootOEMFrameCount = sizeof(bootOEMFrames) / sizeof(bootOEMFrames[0]); @@ -1127,7 +1127,7 @@ int32_t Screen::runOnce() handleRebootScreen(); break; default: - LOG_DEBUG("BUG: invalid cmd\n"); + LOG_ERROR("Invalid screen cmd\n"); } } diff --git a/src/graphics/TFTDisplay.cpp b/src/graphics/TFTDisplay.cpp index 083ee273c..670c0f162 100644 --- a/src/graphics/TFTDisplay.cpp +++ b/src/graphics/TFTDisplay.cpp @@ -59,7 +59,7 @@ void TFTDisplay::setDetected(uint8_t detected) bool TFTDisplay::connect() { concurrency::LockGuard g(spiLock); - LOG_DEBUG("Doing TFT init\n"); + LOG_INFO("Doing TFT init\n"); #ifdef TFT_BL digitalWrite(TFT_BL, HIGH); diff --git a/src/input/RotaryEncoderInterruptBase.cpp b/src/input/RotaryEncoderInterruptBase.cpp index 0f75c3a5a..7a71e5d96 100644 --- a/src/input/RotaryEncoderInterruptBase.cpp +++ b/src/input/RotaryEncoderInterruptBase.cpp @@ -28,7 +28,7 @@ void RotaryEncoderInterruptBase::init( this->rotaryLevelA = digitalRead(this->_pinA); this->rotaryLevelB = digitalRead(this->_pinB); - LOG_DEBUG("Rotary initialized (%d, %d, %d)\n", this->_pinA, this->_pinB, pinPress); + LOG_INFO("Rotary initialized (%d, %d, %d)\n", this->_pinA, this->_pinB, pinPress); } int32_t RotaryEncoderInterruptBase::runOnce() diff --git a/src/main.cpp b/src/main.cpp index 6f25ac1f7..af7f28b50 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -256,7 +256,7 @@ void setup() Wire1.beginTransmission(PCF8563_RTC); if (Wire1.endTransmission() == 0){ rtc_found = PCF8563_RTC; - LOG_DEBUG("PCF8563 RTC found\n"); + LOG_INFO("PCF8563 RTC found\n"); } #endif @@ -378,7 +378,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("RF95 Radio init succeeded, using RF95 radio\n"); + LOG_INFO("RF95 Radio init succeeded, using RF95 radio\n"); } } #endif @@ -391,7 +391,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("SX1280 Radio init succeeded, using SX1280 radio\n"); + LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio\n"); } } #endif @@ -404,7 +404,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("SX1262 Radio init succeeded, using SX1262 radio\n"); + LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio\n"); } } #endif @@ -417,7 +417,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("SX1268 Radio init succeeded, using SX1268 radio\n"); + LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio\n"); } } #endif @@ -430,7 +430,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("LLCC68 Radio init succeeded, using LLCC68 radio\n"); + LOG_INFO("LLCC68 Radio init succeeded, using LLCC68 radio\n"); } } #endif @@ -443,7 +443,7 @@ void setup() delete rIf; rIf = NULL; } else { - LOG_DEBUG("Using SIMULATED radio!\n"); + LOG_INFO("Using SIMULATED radio!\n"); } } #endif diff --git a/src/memtest.cpp b/src/memtest.cpp index f5fe3d7d2..20a4bfa53 100644 --- a/src/memtest.cpp +++ b/src/memtest.cpp @@ -270,7 +270,7 @@ static int mem_test(uint32_t *_start, size_t len, bool doRead = true, bool doWri for (addr = start, val = pattern; addr < end; addr++) { readback = *addr; if (readback != val) { - LOG_DEBUG("Mem error @ 0x%08X: " + LOG_ERROR("Mem error @ 0x%08X: " "found 0x%08lX, expected 0x%08lX\n", addr, readback, val); rcode++; diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 568af182d..b6c093e22 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -47,7 +47,7 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) traceRouteModule->updateRoute(tosend); } - printPacket("Rebroadcasting received floodmsg to neighbors", p); + LOG_INFO("Rebroadcasting received floodmsg to neighbors", p); // Note: we are careful to resend using the original senders node id // We are careful not to call our hooked version of send() - because we don't want to check this again Router::send(tosend); diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index fe5e3d81e..34a40d795 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -52,7 +52,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr p->to = to; p->decoded.request_id = idFrom; p->channel = chIndex; - LOG_DEBUG("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id); + LOG_ERROR("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id); return p; } @@ -134,7 +134,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) // any other node. if (mp.decoded.want_response && toUs && (getFrom(&mp) != ourNodeNum || mp.to == ourNodeNum) && !currentReply) { pi.sendResponse(mp); - LOG_DEBUG("Module '%s' sent a response\n", pi.name); + LOG_INFO("Module '%s' sent a response\n", pi.name); } else { LOG_DEBUG("Module '%s' considered\n", pi.name); } diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index 6ac7321da..c300104a4 100644 --- a/src/mesh/MeshService.cpp +++ b/src/mesh/MeshService.cpp @@ -140,7 +140,7 @@ void MeshService::handleToRadio(MeshPacket &p) // Switch the port from PortNum_SIMULATOR_APP back to the original PortNum p.decoded.portnum = decoded->portnum; } else - LOG_DEBUG("Error decoding protobuf for simulator message!\n"); + LOG_ERROR("Error decoding protobuf for simulator message!\n"); } // Let SimRadio receive as if it did via its LoRa chip SimRadio::instance->startReceive(&p); @@ -198,12 +198,12 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) if (node->has_position && (node->position.latitude_i != 0 || node->position.longitude_i != 0)) { if (positionModule) { - LOG_DEBUG("Sending position ping to 0x%x, wantReplies=%d\n", dest, wantReplies); + LOG_INFO("Sending position ping to 0x%x, wantReplies=%d\n", dest, wantReplies); positionModule->sendOurPosition(dest, wantReplies); } } else { if (nodeInfoModule) { - LOG_DEBUG("Sending nodeinfo ping to 0x%x, wantReplies=%d\n", dest, wantReplies); + LOG_INFO("Sending nodeinfo ping to 0x%x, wantReplies=%d\n", dest, wantReplies); nodeInfoModule->sendOurNodeInfo(dest, wantReplies); } } @@ -212,7 +212,7 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) void MeshService::sendToPhone(MeshPacket *p) { if (toPhoneQueue.numFree() == 0) { - LOG_DEBUG("NOTE: tophone queue is full, discarding oldest\n"); + LOG_WARN("ToPhone queue is full, discarding oldest\n"); MeshPacket *d = toPhoneQueue.dequeuePtr(0); if (d) releaseToPool(d); diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index e198c7065..e995e0b22 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -86,7 +86,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) } if (channelFile.channels_count != MAX_NUM_CHANNELS) { - LOG_DEBUG("Setting default channel and radio preferences!\n"); + LOG_INFO("Setting default channel and radio preferences!\n"); channels.initDefaults(); } @@ -114,7 +114,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) initRegion(); if (didFactoryReset) { - LOG_DEBUG("Rebooting due to factory reset"); + LOG_INFO("Rebooting due to factory reset"); screen->startRebootScreen(); rebootAtMsec = millis() + (5 * 1000); } @@ -124,7 +124,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) bool NodeDB::factoryReset() { - LOG_DEBUG("Performing factory reset!\n"); + LOG_INFO("Performing factory reset!\n"); // first, remove the "/prefs" (this removes most prefs) rmDir("/prefs"); // second, install default state (this will deal with the duplicate mac address issue) @@ -140,7 +140,7 @@ bool NodeDB::factoryReset() #endif #ifdef ARCH_NRF52 Bluefruit.begin(); - LOG_DEBUG("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!\n"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); Bluefruit.Periph.clearBonds(); @@ -151,7 +151,7 @@ bool NodeDB::factoryReset() void NodeDB::installDefaultConfig() { - LOG_DEBUG("Installing default LocalConfig\n"); + LOG_INFO("Installing default LocalConfig\n"); memset(&config, 0, sizeof(LocalConfig)); config.version = DEVICESTATE_CUR_VER; config.has_device = true; @@ -376,7 +376,7 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c auto f = FSCom.open(filename, FILE_O_READ); if (f) { - LOG_DEBUG("Loading %s\n", filename); + LOG_INFO("Loading %s\n", filename); pb_istream_t stream = {&readcb, &f, protoSize}; // LOG_DEBUG("Preload channel name=%s\n", channelSettings.name); @@ -390,7 +390,7 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c f.close(); } else { - LOG_DEBUG("No %s preferences found\n", filename); + LOG_INFO("No %s preferences found\n", filename); } #else LOG_ERROR("ERROR: Filesystem not implemented\n"); @@ -408,7 +408,7 @@ void NodeDB::loadFromDisk() LOG_WARN("Devicestate %d is old, discarding\n", devicestate.version); factoryReset(); } else { - LOG_DEBUG("Loaded saved devicestate version %d\n", devicestate.version); + LOG_INFO("Loaded saved devicestate version %d\n", devicestate.version); } } @@ -419,7 +419,7 @@ void NodeDB::loadFromDisk() LOG_WARN("config %d is old, discarding\n", config.version); installDefaultConfig(); } else { - LOG_DEBUG("Loaded saved config version %d\n", config.version); + LOG_INFO("Loaded saved config version %d\n", config.version); } } @@ -430,7 +430,7 @@ void NodeDB::loadFromDisk() LOG_WARN("moduleConfig %d is old, discarding\n", moduleConfig.version); installDefaultModuleConfig(); } else { - LOG_DEBUG("Loaded saved moduleConfig version %d\n", moduleConfig.version); + LOG_INFO("Loaded saved moduleConfig version %d\n", moduleConfig.version); } } @@ -441,12 +441,12 @@ void NodeDB::loadFromDisk() LOG_WARN("channelFile %d is old, discarding\n", channelFile.version); installDefaultChannels(); } else { - LOG_DEBUG("Loaded saved channelFile version %d\n", channelFile.version); + LOG_INFO("Loaded saved channelFile version %d\n", channelFile.version); } } if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), &OEMStore_msg, &oemStore)) - LOG_DEBUG("Loaded OEMStore\n"); + LOG_INFO("Loaded OEMStore\n"); } /** Save a protobuf from a file, return true for success */ @@ -459,11 +459,11 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ filenameTmp += ".tmp"; auto f = FSCom.open(filenameTmp.c_str(), FILE_O_WRITE); if (f) { - LOG_DEBUG("Saving %s\n", filename); + LOG_INFO("Saving %s\n", filename); pb_ostream_t stream = {&writecb, &f, protoSize}; if (!pb_encode(&stream, fields, dest_struct)) { - LOG_DEBUG("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); } else { okay = true; } @@ -473,9 +473,9 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ if (FSCom.exists(filename) && !FSCom.remove(filename)) LOG_WARN("Can't remove old pref file\n"); if (!renameFile(filenameTmp.c_str(), filename)) - LOG_DEBUG("Error: can't rename new pref file\n"); + LOG_ERROR("Error: can't rename new pref file\n"); } else { - LOG_DEBUG("Can't write prefs\n"); + LOG_ERROR("Can't write prefs\n"); #ifdef ARCH_NRF52 static uint8_t failedCounter = 0; failedCounter++; @@ -487,7 +487,7 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ #endif } #else - LOG_DEBUG("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented\n"); #endif return okay; } @@ -599,7 +599,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative - LOG_DEBUG("updatePosition LOCAL pos@%x, time=%u, latI=%d, lonI=%d, alt=%d\n", p.timestamp, p.time, p.latitude_i, + LOG_INFO("updatePosition LOCAL pos@%x, time=%u, latI=%d, lonI=%d, alt=%d\n", p.timestamp, p.time, p.latitude_i, p.longitude_i, p.altitude); info->position = p; @@ -615,7 +615,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) // recorded based on the packet rxTime // // FIXME perhaps handle RX_SRC_USER separately? - LOG_DEBUG("updatePosition REMOTE node=0x%x time=%u, latI=%d, lonI=%d\n", nodeId, p.time, p.latitude_i, p.longitude_i); + LOG_INFO("updatePosition REMOTE node=0x%x time=%u, latI=%d, lonI=%d\n", nodeId, p.time, p.latitude_i, p.longitude_i); // First, back up fields that we want to protect from overwrite uint32_t tmp_time = info->position.time; @@ -756,9 +756,9 @@ void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *f String lcd = String("Critical error ") + code + "!\n"; screen->print(lcd.c_str()); if (filename) - LOG_DEBUG("NOTE! Recording critical error %d at %s:%lu\n", code, filename, address); + LOG_ERROR("NOTE! Recording critical error %d at %s:%lu\n", code, filename, address); else - LOG_DEBUG("NOTE! Recording critical error %d, address=0x%lx\n", code, address); + LOG_ERROR("NOTE! Recording critical error %d, address=0x%lx\n", code, address); // Record error to DB myNodeInfo.error_code = code; @@ -767,7 +767,7 @@ void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *f // Currently portuino is mostly used for simulation. Make sue the user notices something really bad happend #ifdef ARCH_PORTDUINO - LOG_DEBUG("A critical failure occurred, portduino is exiting..."); + LOG_ERROR("A critical failure occurred, portduino is exiting..."); exit(2); #endif } diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index 75805c11c..897ddfe8a 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -37,7 +37,7 @@ void PhoneAPI::handleStartConfig() // even if we were already connected - restart our state machine state = STATE_SEND_MY_INFO; - LOG_DEBUG("Starting API client config\n"); + LOG_INFO("Starting API client config\n"); nodeInfoForPhone = NULL; // Don't keep returning old nodeinfos nodeDB.resetReadPointer(); // FIXME, this read pointer should be moved out of nodeDB and into this class - because // this will break once we have multiple instances of PhoneAPI running independently @@ -60,7 +60,7 @@ void PhoneAPI::checkConnectionTimeout() if (isConnected()) { bool newContact = checkIsConnected(); if (!newContact) { - LOG_DEBUG("Lost phone connection\n"); + LOG_INFO("Lost phone connection\n"); close(); } } @@ -83,11 +83,11 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) return handleToRadioPacket(toRadioScratch.packet); case ToRadio_want_config_id_tag: config_nonce = toRadioScratch.want_config_id; - LOG_DEBUG("Client wants config, nonce=%u\n", config_nonce); + LOG_INFO("Client wants config, nonce=%u\n", config_nonce); handleStartConfig(); break; case ToRadio_disconnect_tag: - LOG_DEBUG("Disconnecting from phone\n"); + LOG_INFO("Disconnecting from phone\n"); close(); break; default: @@ -96,7 +96,7 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) break; } } else { - LOG_DEBUG("Error: ignoring malformed toradio\n"); + LOG_ERROR("Error: ignoring malformed toradio\n"); } return false; @@ -128,11 +128,11 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Advance states as needed switch (state) { case STATE_SEND_NOTHING: - LOG_DEBUG("getFromRadio=STATE_SEND_NOTHING\n"); + LOG_INFO("getFromRadio=STATE_SEND_NOTHING\n"); break; case STATE_SEND_MY_INFO: - LOG_DEBUG("getFromRadio=STATE_SEND_MY_INFO\n"); + LOG_INFO("getFromRadio=STATE_SEND_MY_INFO\n"); // If the user has specified they don't want our node to share its location, make sure to tell the phone // app not to send locations on our behalf. myNodeInfo.has_gps = gps && gps->isConnected(); // Update with latest GPS connect info @@ -144,18 +144,18 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_NODEINFO: { - LOG_DEBUG("getFromRadio=STATE_SEND_NODEINFO\n"); + LOG_INFO("getFromRadio=STATE_SEND_NODEINFO\n"); const NodeInfo *info = nodeInfoForPhone; nodeInfoForPhone = NULL; // We just consumed a nodeinfo, will need a new one next time if (info) { - LOG_DEBUG("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->last_heard, info->user.id, + LOG_INFO("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->last_heard, info->user.id, info->user.long_name); fromRadioScratch.which_payload_variant = FromRadio_node_info_tag; fromRadioScratch.node_info = *info; // Stay in current state until done sending nodeinfos } else { - LOG_DEBUG("Done sending nodeinfos\n"); + LOG_INFO("Done sending nodeinfos\n"); state = STATE_SEND_CHANNELS; // Go ahead and send that ID right now return getFromRadio(buf); @@ -164,7 +164,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) } case STATE_SEND_CHANNELS: - LOG_DEBUG("getFromRadio=STATE_SEND_CHANNELS\n"); + LOG_INFO("getFromRadio=STATE_SEND_CHANNELS\n"); fromRadioScratch.which_payload_variant = FromRadio_channel_tag; fromRadioScratch.channel = channels.getByIndex(config_state); config_state++; @@ -176,7 +176,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_CONFIG: - LOG_DEBUG("getFromRadio=STATE_SEND_CONFIG\n"); + LOG_INFO("getFromRadio=STATE_SEND_CONFIG\n"); fromRadioScratch.which_payload_variant = FromRadio_config_tag; switch (config_state) { case Config_device_tag: @@ -222,7 +222,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_MODULECONFIG: - LOG_DEBUG("getFromRadio=STATE_SEND_MODULECONFIG\n"); + LOG_INFO("getFromRadio=STATE_SEND_MODULECONFIG\n"); fromRadioScratch.which_payload_variant = FromRadio_moduleConfig_tag; switch (config_state) { case ModuleConfig_mqtt_tag: @@ -272,7 +272,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_COMPLETE_ID: - LOG_DEBUG("getFromRadio=STATE_SEND_COMPLETE_ID\n"); + LOG_INFO("getFromRadio=STATE_SEND_COMPLETE_ID\n"); fromRadioScratch.which_payload_variant = FromRadio_config_complete_id_tag; fromRadioScratch.config_complete_id = config_nonce; config_nonce = 0; @@ -281,7 +281,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_PACKETS: // Do we have a message from the mesh? - LOG_DEBUG("getFromRadio=STATE_SEND_PACKETS\n"); + LOG_INFO("getFromRadio=STATE_SEND_PACKETS\n"); if (packetForPhone) { printPacket("phone downloaded packet", packetForPhone); @@ -311,7 +311,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) void PhoneAPI::handleDisconnect() { - LOG_DEBUG("PhoneAPI disconnect\n"); + LOG_INFO("PhoneAPI disconnect\n"); } void PhoneAPI::releasePhonePacket() @@ -373,7 +373,7 @@ int PhoneAPI::onNotify(uint32_t newValue) // from idle) if (state == STATE_SEND_PACKETS) { - LOG_DEBUG("Telling client we have new packets %u\n", newValue); + LOG_INFO("Telling client we have new packets %u\n", newValue); onNowHasData(newValue); } else LOG_DEBUG("(Client not yet interested in packets)\n"); diff --git a/src/mesh/ProtobufModule.h b/src/mesh/ProtobufModule.h index bac38b786..61fc95b7a 100644 --- a/src/mesh/ProtobufModule.h +++ b/src/mesh/ProtobufModule.h @@ -70,7 +70,7 @@ template class ProtobufModule : protected SinglePortModule // it would be better to update even if the message was destined to others. auto &p = mp.decoded; - LOG_DEBUG("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, + LOG_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, p.payload.size); T scratch; @@ -80,7 +80,7 @@ template class ProtobufModule : protected SinglePortModule if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { decoded = &scratch; } else { - LOG_DEBUG("Error decoding protobuf module!\n"); + LOG_ERROR("Error decoding protobuf module!\n"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } diff --git a/src/mesh/RF95Interface.cpp b/src/mesh/RF95Interface.cpp index e679775c3..4502d0810 100644 --- a/src/mesh/RF95Interface.cpp +++ b/src/mesh/RF95Interface.cpp @@ -68,11 +68,11 @@ bool RF95Interface::init() setTransmitEnable(false); int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, currentLimit, preambleLength); - LOG_DEBUG("RF95 init result %d\n", res); + LOG_INFO("RF95 init result %d\n", res); - LOG_DEBUG("Frequency set to %f\n", getFreq()); - LOG_DEBUG("Bandwidth set to %f\n", bw); - LOG_DEBUG("Power output set to %d\n", power); + LOG_INFO("Frequency set to %f\n", getFreq()); + LOG_INFO("Bandwidth set to %f\n", bw); + LOG_INFO("Power output set to %d\n", power); // current limit was removed from module' ctor // override default value (60 mA) diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index f3971ddb0..7c0f238a0 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -117,7 +117,7 @@ void initRegion() for (; r->code != Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) ; myRegion = r; - LOG_DEBUG("Wanted region %d, using %s\n", config.lora.region, r->name); + LOG_INFO("Wanted region %d, using %s\n", config.lora.region, r->name); } /** @@ -284,7 +284,7 @@ bool RadioInterface::reconfigure() bool RadioInterface::init() { - LOG_DEBUG("Starting meshradio init...\n"); + LOG_INFO("Starting meshradio init...\n"); configChangedObserver.observe(&service.configChanged); preflightSleepObserver.observe(&preflightSleep); @@ -449,13 +449,13 @@ void RadioInterface::applyModemConfig() saveChannelNum(channel_num); saveFreq(freq + config.lora.frequency_offset); - LOG_DEBUG("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); - LOG_DEBUG("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); - LOG_DEBUG("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); - LOG_DEBUG("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw); - LOG_DEBUG("Radio channel_num: %d\n", channel_num); - LOG_DEBUG("Radio frequency: %f\n", getFreq()); - LOG_DEBUG("Slot time: %u msec\n", slotTimeMsec); + LOG_INFO("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); + LOG_INFO("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); + LOG_INFO("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); + LOG_INFO("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw); + LOG_INFO("Radio channel_num: %d\n", channel_num); + LOG_INFO("Radio frequency: %f\n", getFreq()); + LOG_INFO("Slot time: %u msec\n", slotTimeMsec); } /** @@ -470,11 +470,11 @@ void RadioInterface::limitPower() maxPower = myRegion->powerLimit; if ((power > maxPower) && !devicestate.owner.is_licensed) { - LOG_DEBUG("Lowering transmit power because of regulatory limits\n"); + LOG_INFO("Lowering transmit power because of regulatory limits\n"); power = maxPower; } - LOG_DEBUG("Set radio: final power level=%d\n", power); + LOG_INFO("Set radio: final power level=%d\n", power); } diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 127a246c0..53eaeca60 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -82,17 +82,17 @@ bool RadioLibInterface::canSendImmediately() if (busyTx || busyRx) { if (busyTx) - LOG_DEBUG("Can not send yet, busyTx\n"); + LOG_WARN("Can not send yet, busyTx\n"); // If we've been trying to send the same packet more than one minute and we haven't gotten a // TX IRQ from the radio, the radio is probably broken. if (busyTx && (millis() - lastTxStart > 60000)) { - LOG_DEBUG("Hardware Failure! busyTx for more than 60s\n"); + LOG_ERROR("Hardware Failure! busyTx for more than 60s\n"); RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED); // reboot in 5 seconds when this condition occurs. rebootAtMsec = lastTxStart + 65000; } if (busyRx) - LOG_DEBUG("Can not send yet, busyRx\n"); + LOG_WARN("Can not send yet, busyRx\n"); return false; } else return true; @@ -111,13 +111,13 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) { if (disabled || !config.lora.tx_enabled) { - LOG_DEBUG("send - !config.lora.tx_enabled\n"); + LOG_WARN("send - !config.lora.tx_enabled\n"); packetPool.release(p); return ERRNO_DISABLED; } } else { - LOG_DEBUG("send - lora tx disable because RegionCode_Unset\n"); + LOG_WARN("send - lora tx disable because RegionCode_Unset\n"); packetPool.release(p); return ERRNO_DISABLED; } @@ -127,7 +127,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) #else if (disabled || !config.lora.tx_enabled) { - LOG_DEBUG("send - !config.lora.tx_enabled\n"); + LOG_WARN("send - !config.lora.tx_enabled\n"); packetPool.release(p); return ERRNO_DISABLED; } @@ -319,7 +319,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) int state = iface->readData(radiobuf, length); if (state != RADIOLIB_ERR_NONE) { - LOG_DEBUG("ignoring received packet due to error=%d\n", state); + LOG_ERROR("ignoring received packet due to error=%d\n", state); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); @@ -331,7 +331,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // check for short packets if (payloadLen < 0) { - LOG_DEBUG("ignoring received packet too short\n"); + LOG_WARN("ignoring received packet too short\n"); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); } else { @@ -374,7 +374,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) { printPacket("Starting low level send", txp); if (disabled || !config.lora.tx_enabled) { - LOG_DEBUG("startSend is dropping tx packet because we are disabled\n"); + LOG_WARN("startSend is dropping tx packet because we are disabled\n"); packetPool.release(txp); } else { setStandby(); // Cancel any already in process receives @@ -385,7 +385,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) int res = iface->startTransmit(radiobuf, numbytes); if (res != RADIOLIB_ERR_NONE) { - LOG_DEBUG("startTransmit failed, error=%d\n", res); + LOG_ERROR("startTransmit failed, error=%d\n", res); RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG); // This send failed, but make sure to 'complete' it properly diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 826a3f089..a94e8c295 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -136,7 +136,7 @@ void Router::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelI void Router::abortSendAndNak(Routing_Error err, MeshPacket *p) { - LOG_DEBUG("Error=%d, returning NAK and dropping packet.\n", err); + LOG_ERROR("Error=%d, returning NAK and dropping packet.\n", err); sendAckNak(Routing_Error_NO_INTERFACE, getFrom(p), p->id, p->channel); packetPool.release(p); } @@ -239,7 +239,7 @@ ErrorCode Router::send(MeshPacket *p) shouldActuallyEncrypt = false; } - LOG_DEBUG("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); + LOG_INFO("Should encrypt MQTT?: %d\n", shouldActuallyEncrypt); // the packet is currently in a decrypted state. send it now if they want decrypted packets if (mqtt && !shouldActuallyEncrypt) @@ -307,9 +307,9 @@ bool perhapsDecode(MeshPacket *p) // Take those raw bytes and convert them back into a well structured protobuf we can understand memset(&p->decoded, 0, sizeof(p->decoded)); if (!pb_decode_from_bytes(bytes, rawSize, &Data_msg, &p->decoded)) { - LOG_DEBUG("Invalid protobufs in received mesh packet (bad psk?)!\n"); + LOG_ERROR("Invalid protobufs in received mesh packet (bad psk?)!\n"); } else if (p->decoded.portnum == PortNum_UNKNOWN_APP) { - LOG_DEBUG("Invalid portnum (bad psk?)!\n"); + LOG_ERROR("Invalid portnum (bad psk?)!\n"); } else { // parsing was successful p->which_payload_variant = MeshPacket_decoded_tag; // change type to decoded @@ -348,7 +348,7 @@ bool perhapsDecode(MeshPacket *p) } } - LOG_DEBUG("No suitable channel found for decoding, hash was 0x%x!\n", p->channel); + LOG_WARN("No suitable channel found for decoding, hash was 0x%x!\n", p->channel); return false; } diff --git a/src/mesh/SX126xInterface.cpp b/src/mesh/SX126xInterface.cpp index 1caf8c9d8..15b808852 100644 --- a/src/mesh/SX126xInterface.cpp +++ b/src/mesh/SX126xInterface.cpp @@ -12,7 +12,7 @@ SX126xInterface::SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, SPIClass &spi) : RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module) { - LOG_DEBUG("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_WARN("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); } /// Initialise the Driver transport hardware and software. @@ -55,11 +55,11 @@ bool SX126xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage, useRegulatorLDO); // \todo Display actual typename of the adapter, not just `SX126x` - LOG_DEBUG("SX126x init result %d\n", res); + LOG_INFO("SX126x init result %d\n", res); - LOG_DEBUG("Frequency set to %f\n", getFreq()); - LOG_DEBUG("Bandwidth set to %f\n", bw); - LOG_DEBUG("Power output set to %d\n", power); + LOG_INFO("Frequency set to %f\n", getFreq()); + LOG_INFO("Bandwidth set to %f\n", bw); + LOG_INFO("Power output set to %d\n", power); // current limit was removed from module' ctor // override default value (60 mA) diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index b96801794..cc6d299c8 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -49,7 +49,7 @@ bool SX128xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength); // \todo Display actual typename of the adapter, not just `SX128x` - LOG_DEBUG("SX128x init result %d\n", res); + LOG_INFO("SX128x init result %d\n", res); if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (res == RADIOLIB_ERR_INVALID_FREQUENCY)) { LOG_WARN("Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting.\n"); @@ -61,13 +61,13 @@ bool SX128xInterface::init() #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else - LOG_DEBUG("FIXME implement reboot for this platform. Skipping for now.\n"); + LOG_ERROR("FIXME implement reboot for this platform. Skipping for now.\n"); #endif } - LOG_DEBUG("Frequency set to %f\n", getFreq()); - LOG_DEBUG("Bandwidth set to %f\n", bw); - LOG_DEBUG("Power output set to %d\n", power); + LOG_INFO("Frequency set to %f\n", getFreq()); + LOG_INFO("Bandwidth set to %f\n", bw); + LOG_INFO("Power output set to %d\n", power); if (res == RADIOLIB_ERR_NONE) res = lora.setCRC(2); @@ -145,7 +145,7 @@ void SX128xInterface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) - LOG_DEBUG("SX128x standby failed with error %d\n", err); + LOG_ERROR("SX128x standby failed with error %d\n", err); assert(err == RADIOLIB_ERR_NONE); diff --git a/src/mesh/eth/ethClient.cpp b/src/mesh/eth/ethClient.cpp index 57decacdc..588913781 100644 --- a/src/mesh/eth/ethClient.cpp +++ b/src/mesh/eth/ethClient.cpp @@ -29,10 +29,10 @@ static int32_t reconnectETH() Ethernet.maintain(); if (!ethStartupComplete) { // Start web server - LOG_DEBUG("... Starting network services\n"); + LOG_INFO("... Starting network services\n"); #ifndef DISABLE_NTP - LOG_DEBUG("Starting NTP time client\n"); + LOG_INFO("Starting NTP time client\n"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif @@ -51,7 +51,7 @@ static int32_t reconnectETH() #ifndef DISABLE_NTP if (isEthernetAvailable() && (ntp_renew < millis())) { - LOG_DEBUG("Updating NTP time from %s\n", config.network.ntp_server); + LOG_INFO("Updating NTP time from %s\n", config.network.ntp_server); if (timeClient.update()) { LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); @@ -64,7 +64,7 @@ static int32_t reconnectETH() ntp_renew = millis() + 43200 * 1000; // success, refresh every 12 hours } else { - LOG_DEBUG("NTP Update failed\n"); + LOG_ERROR("NTP Update failed\n"); ntp_renew = millis() + 300 * 1000; // failure, retry every 5 minutes } } @@ -96,32 +96,32 @@ bool initEthernet() getMacAddr(mac); // FIXME use the BLE MAC for now... if (config.network.eth_mode == Config_NetworkConfig_EthMode_DHCP) { - LOG_DEBUG("starting Ethernet DHCP\n"); + LOG_INFO("starting Ethernet DHCP\n"); status = Ethernet.begin(mac); } else if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC) { - LOG_DEBUG("starting Ethernet Static\n"); + LOG_INFO("starting Ethernet Static\n"); Ethernet.begin(mac, config.network.ipv4_config.ip, config.network.ipv4_config.dns, config.network.ipv4_config.subnet); } else { - LOG_DEBUG("Ethernet Disabled\n"); + LOG_INFO("Ethernet Disabled\n"); return false; } if (status == 0) { if (Ethernet.hardwareStatus() == EthernetNoHardware) { - LOG_DEBUG("Ethernet shield was not found.\n"); + LOG_ERROR("Ethernet shield was not found.\n"); return false; } else if (Ethernet.linkStatus() == LinkOFF) { - LOG_DEBUG("Ethernet cable is not connected.\n"); + LOG_ERROR("Ethernet cable is not connected.\n"); return false; } else{ - LOG_DEBUG("Unknown Ethernet error.\n"); + LOG_ERROR("Unknown Ethernet error.\n"); return false; } } else { - LOG_DEBUG("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); - LOG_DEBUG("Subnet Mask %u.%u.%u.%u\n",Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); - LOG_DEBUG("Gateway IP %u.%u.%u.%u\n",Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); - LOG_DEBUG("DNS Server IP %u.%u.%u.%u\n",Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); + LOG_INFO("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); + LOG_INFO("Subnet Mask %u.%u.%u.%u\n",Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); + LOG_INFO("Gateway IP %u.%u.%u.%u\n",Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); + LOG_INFO("DNS Server IP %u.%u.%u.%u\n",Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); } ethEvent = new Periodic("ethConnect", reconnectETH); @@ -129,7 +129,7 @@ bool initEthernet() return true; } else { - LOG_DEBUG("Not using Ethernet\n"); + LOG_INFO("Not using Ethernet\n"); return false; } } diff --git a/src/mesh/eth/ethServerAPI.cpp b/src/mesh/eth/ethServerAPI.cpp index 4159d285a..d91b798a0 100644 --- a/src/mesh/eth/ethServerAPI.cpp +++ b/src/mesh/eth/ethServerAPI.cpp @@ -9,14 +9,14 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new ethServerPort(port); - LOG_DEBUG("API server listening on TCP port %d\n", port); + LOG_INFO("API server listening on TCP port %d\n", port); apiPort->init(); } } ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), concurrency::OSThread("ethServerAPI"), client(_client) { - LOG_DEBUG("Incoming ethernet connection\n"); + LOG_INFO("Incoming ethernet connection\n"); } ethServerAPI::~ethServerAPI() @@ -44,7 +44,7 @@ int32_t ethServerAPI::runOnce() if (client.connected()) { return StreamAPI::runOncePart(); } else { - LOG_DEBUG("Client dropped connection, suspending API service\n"); + LOG_INFO("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run return 0; } @@ -71,7 +71,7 @@ int32_t ethServerPort::runOnce() if (client) { // Close any previous connection (see FIXME in header file) if (openAPI) { - LOG_DEBUG("Force closing previous TCP connection\n"); + LOG_WARN("Force closing previous TCP connection\n"); delete openAPI; } diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 22d97a2b6..7551a0828 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -335,7 +335,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) if (params->getQueryParameter("delete", paramValDelete)) { std::string pathDelete = "/" + paramValDelete; if (FSCom.remove(pathDelete.c_str())) { - Serial.println(pathDelete.c_str()); + LOG_INFO("%s\n", pathDelete.c_str()); JSONObject jsonObjOuter; jsonObjOuter["status"] = new JSONValue("ok"); JSONValue *value = new JSONValue(jsonObjOuter); @@ -343,7 +343,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) delete value; return; } else { - Serial.println(pathDelete.c_str()); + LOG_INFO("%s\n", pathDelete.c_str()); JSONObject jsonObjOuter; jsonObjOuter["status"] = new JSONValue("Error"); JSONValue *value = new JSONValue(jsonObjOuter); @@ -379,13 +379,13 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) if (FSCom.exists(filename.c_str())) { file = FSCom.open(filename.c_str()); if (!file.available()) { - LOG_DEBUG("File not available - %s\n", filename.c_str()); + LOG_WARN("File not available - %s\n", filename.c_str()); } } else if (FSCom.exists(filenameGzip.c_str())) { file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Encoding", "gzip"); if (!file.available()) { - LOG_DEBUG("File not available - %s\n", filenameGzip.c_str()); + LOG_WARN("File not available - %s\n", filenameGzip.c_str()); } } else { has_set_content_type = true; @@ -393,7 +393,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Type", "text/html"); if (!file.available()) { - LOG_DEBUG("File not available - %s\n", filenameGzip.c_str()); + LOG_WARN("File not available - %s\n", filenameGzip.c_str()); res->println("Web server is running.

The content you are looking for can't be found. Please see: FAQ.

admin"); @@ -437,7 +437,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) return; } else { - LOG_DEBUG("ERROR: This should not have happened...\n"); + LOG_ERROR("This should not have happened...\n"); res->println("ERROR: This should not have happened..."); } } @@ -472,7 +472,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) LOG_DEBUG("Form Upload - multipart/form-data\n"); parser = new HTTPMultipartBodyParser(req); } else { - Serial.printf("Unknown POST Content-Type: %s\n", contentType.c_str()); + LOG_DEBUG("Unknown POST Content-Type: %s\n", contentType.c_str()); return; } @@ -671,7 +671,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res) */ void handleHotspot(HTTPRequest *req, HTTPResponse *res) { - LOG_DEBUG("Hotspot Request\n"); + LOG_INFO("Hotspot Request\n"); /* If we don't do a redirect, be sure to return a "Success" message @@ -697,7 +697,7 @@ void handleDeleteFsContent(HTTPRequest *req, HTTPResponse *res) res->println("

Meshtastic

\n"); res->println("Deleting Content in /static/*"); - LOG_DEBUG("Deleting files from /static/* : \n"); + LOG_INFO("Deleting files from /static/* : \n"); htmlDeleteDir("/static"); diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index 10f8067f6..9b22016df 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -74,13 +74,13 @@ static void taskCreateCert(void *parameter) prefs.remove("cert"); #endif - LOG_DEBUG("Checking if we have a previously saved SSL Certificate.\n"); + LOG_INFO("Checking if we have a previously saved SSL Certificate.\n"); size_t pkLen = prefs.getBytesLength("PK"); size_t certLen = prefs.getBytesLength("cert"); if (pkLen && certLen) { - LOG_DEBUG("Existing SSL Certificate found!\n"); + LOG_INFO("Existing SSL Certificate found!\n"); uint8_t *pkBuffer = new uint8_t[pkLen]; prefs.getBytes("PK", pkBuffer, pkLen); @@ -95,7 +95,7 @@ static void taskCreateCert(void *parameter) } else { - LOG_DEBUG("Creating the certificate. This may take a while. Please wait...\n"); + LOG_INFO("Creating the certificate. This may take a while. Please wait...\n"); yield(); cert = new SSLCert(); yield(); @@ -104,10 +104,10 @@ static void taskCreateCert(void *parameter) yield(); if (createCertResult != 0) { - LOG_DEBUG("Creating the certificate failed\n"); + LOG_ERROR("Creating the certificate failed\n"); } else { - LOG_DEBUG("Creating the certificate was successful\n"); + LOG_INFO("Creating the certificate was successful\n"); LOG_DEBUG("Created Private Key: %d Bytes\n", cert->getPKLength()); @@ -159,7 +159,7 @@ void createSSLCert() runLoop = true; } } - LOG_DEBUG("SSL Cert Ready!\n"); + LOG_INFO("SSL Cert Ready!\n"); } } @@ -191,15 +191,15 @@ void initWebServer() registerHandlers(insecureServer, secureServer); if (secureServer) { - LOG_DEBUG("Starting Secure Web Server...\n"); + LOG_INFO("Starting Secure Web Server...\n"); secureServer->start(); } - LOG_DEBUG("Starting Insecure Web Server...\n"); + LOG_INFO("Starting Insecure Web Server...\n"); insecureServer->start(); if (insecureServer->isRunning()) { - LOG_DEBUG("Web Servers Ready! :-) \n"); + LOG_INFO("Web Servers Ready! :-) \n"); isWebServerReady = true; } else { - LOG_DEBUG("Web Servers Failed! ;-( \n"); + LOG_ERROR("Web Servers Failed! ;-( \n"); } } diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 13e127756..cba09dd7c 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -56,7 +56,7 @@ static int32_t reconnectWiFi() // Make sure we clear old connection credentials WiFi.disconnect(false, true); - LOG_DEBUG("Reconnecting to WiFi access point %s\n",wifiName); + LOG_INFO("Reconnecting to WiFi access point %s\n",wifiName); WiFi.mode(WIFI_MODE_STA); WiFi.begin(wifiName, wifiPsw); @@ -101,12 +101,12 @@ bool isWifiAvailable() // Disable WiFi void deinitWifi() { - LOG_DEBUG("WiFi deinit\n"); + LOG_INFO("WiFi deinit\n"); if (isWifiAvailable()) { WiFi.disconnect(true); WiFi.mode(WIFI_MODE_NULL); - LOG_DEBUG("WiFi Turned Off\n"); + LOG_INFO("WiFi Turned Off\n"); // WiFi.printDiag(Serial); } } @@ -115,20 +115,20 @@ static void onNetworkConnected() { if (!APStartupComplete) { // Start web server - LOG_DEBUG("Starting network services\n"); + LOG_INFO("Starting network services\n"); // start mdns if (!MDNS.begin("Meshtastic")) { - LOG_DEBUG("Error setting up MDNS responder!\n"); + LOG_ERROR("Error setting up MDNS responder!\n"); } else { - LOG_DEBUG("mDNS responder started\n"); - LOG_DEBUG("mDNS Host: Meshtastic.local\n"); + LOG_INFO("mDNS responder started\n"); + LOG_INFO("mDNS Host: Meshtastic.local\n"); MDNS.addService("http", "tcp", 80); MDNS.addService("https", "tcp", 443); } #ifndef DISABLE_NTP - LOG_DEBUG("Starting NTP time client\n"); + LOG_INFO("Starting NTP time client\n"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif @@ -182,8 +182,7 @@ bool initWifi() WiFi.onEvent( [](WiFiEvent_t event, WiFiEventInfo_t info) { - Serial.print("WiFi lost connection. Reason: "); - Serial.println(info.wifi_sta_disconnected.reason); + LOG_WARN("WiFi lost connection. Reason: %s", info.wifi_sta_disconnected.reason); /* If we are disconnected from the AP for some reason, @@ -201,7 +200,7 @@ bool initWifi() } return true; } else { - LOG_DEBUG("Not using WIFI\n"); + LOG_INFO("Not using WIFI\n"); return false; } } @@ -213,133 +212,131 @@ static void WiFiEvent(WiFiEvent_t event) switch (event) { case ARDUINO_EVENT_WIFI_READY: - LOG_DEBUG("WiFi interface ready\n"); + LOG_INFO("WiFi interface ready\n"); break; case ARDUINO_EVENT_WIFI_SCAN_DONE: - LOG_DEBUG("Completed scan for access points\n"); + LOG_INFO("Completed scan for access points\n"); break; case ARDUINO_EVENT_WIFI_STA_START: - LOG_DEBUG("WiFi station started\n"); + LOG_INFO("WiFi station started\n"); break; case ARDUINO_EVENT_WIFI_STA_STOP: - LOG_DEBUG("WiFi station stopped\n"); + LOG_INFO("WiFi station stopped\n"); break; case ARDUINO_EVENT_WIFI_STA_CONNECTED: - LOG_DEBUG("Connected to access point\n"); + LOG_INFO("Connected to access point\n"); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - LOG_DEBUG("Disconnected from WiFi access point\n"); + LOG_INFO("Disconnected from WiFi access point\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: - LOG_DEBUG("Authentication mode of access point has changed\n"); + LOG_INFO("Authentication mode of access point has changed\n"); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: - LOG_DEBUG("Obtained IP address: "); - Serial.println(WiFi.localIP()); + LOG_INFO("Obtained IP address: ", WiFi.localIPv6()); onNetworkConnected(); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP6: - LOG_DEBUG("Obtained IP6 address: "); - Serial.println(WiFi.localIPv6()); + LOG_INFO("Obtained IP6 address: %s", WiFi.localIPv6()); break; case ARDUINO_EVENT_WIFI_STA_LOST_IP: - LOG_DEBUG("Lost IP address and IP address is reset to 0\n"); + LOG_INFO("Lost IP address and IP address is reset to 0\n"); WiFi.disconnect(false, true); needReconnect = true; wifiReconnect->setIntervalFromNow(1000); break; case ARDUINO_EVENT_WPS_ER_SUCCESS: - LOG_DEBUG("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_FAILED: - LOG_DEBUG("WiFi Protected Setup (WPS): failed in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): failed in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_TIMEOUT: - LOG_DEBUG("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_PIN: - LOG_DEBUG("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); break; case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP: - LOG_DEBUG("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); break; case ARDUINO_EVENT_WIFI_AP_START: - LOG_DEBUG("WiFi access point started\n"); + LOG_INFO("WiFi access point started\n"); break; case ARDUINO_EVENT_WIFI_AP_STOP: - LOG_DEBUG("WiFi access point stopped\n"); + LOG_INFO("WiFi access point stopped\n"); break; case ARDUINO_EVENT_WIFI_AP_STACONNECTED: - LOG_DEBUG("Client connected\n"); + LOG_INFO("Client connected\n"); break; case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: - LOG_DEBUG("Client disconnected\n"); + LOG_INFO("Client disconnected\n"); break; case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: - LOG_DEBUG("Assigned IP address to client\n"); + LOG_INFO("Assigned IP address to client\n"); break; case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: - LOG_DEBUG("Received probe request\n"); + LOG_INFO("Received probe request\n"); break; case ARDUINO_EVENT_WIFI_AP_GOT_IP6: - LOG_DEBUG("IPv6 is preferred\n"); + LOG_INFO("IPv6 is preferred\n"); break; case ARDUINO_EVENT_WIFI_FTM_REPORT: - LOG_DEBUG("Fast Transition Management report\n"); + LOG_INFO("Fast Transition Management report\n"); break; case ARDUINO_EVENT_ETH_START: - LOG_DEBUG("Ethernet started\n"); + LOG_INFO("Ethernet started\n"); break; case ARDUINO_EVENT_ETH_STOP: - LOG_DEBUG("Ethernet stopped\n"); + LOG_INFO("Ethernet stopped\n"); break; case ARDUINO_EVENT_ETH_CONNECTED: - LOG_DEBUG("Ethernet connected\n"); + LOG_INFO("Ethernet connected\n"); break; case ARDUINO_EVENT_ETH_DISCONNECTED: - LOG_DEBUG("Ethernet disconnected\n"); + LOG_INFO("Ethernet disconnected\n"); break; case ARDUINO_EVENT_ETH_GOT_IP: - LOG_DEBUG("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); + LOG_INFO("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); break; case ARDUINO_EVENT_ETH_GOT_IP6: - LOG_DEBUG("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); + LOG_INFO("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); break; case ARDUINO_EVENT_SC_SCAN_DONE: - LOG_DEBUG("SmartConfig: Scan done\n"); + LOG_INFO("SmartConfig: Scan done\n"); break; case ARDUINO_EVENT_SC_FOUND_CHANNEL: - LOG_DEBUG("SmartConfig: Found channel\n"); + LOG_INFO("SmartConfig: Found channel\n"); break; case ARDUINO_EVENT_SC_GOT_SSID_PSWD: - LOG_DEBUG("SmartConfig: Got SSID and password\n"); + LOG_INFO("SmartConfig: Got SSID and password\n"); break; case ARDUINO_EVENT_SC_SEND_ACK_DONE: - LOG_DEBUG("SmartConfig: Send ACK done\n"); + LOG_INFO("SmartConfig: Send ACK done\n"); break; case ARDUINO_EVENT_PROV_INIT: - LOG_DEBUG("Provisioning: Init\n"); + LOG_INFO("Provisioning: Init\n"); break; case ARDUINO_EVENT_PROV_DEINIT: - LOG_DEBUG("Provisioning: Stopped\n"); + LOG_INFO("Provisioning: Stopped\n"); break; case ARDUINO_EVENT_PROV_START: - LOG_DEBUG("Provisioning: Started\n"); + LOG_INFO("Provisioning: Started\n"); break; case ARDUINO_EVENT_PROV_END: - LOG_DEBUG("Provisioning: End\n"); + LOG_INFO("Provisioning: End\n"); break; case ARDUINO_EVENT_PROV_CRED_RECV: - LOG_DEBUG("Provisioning: Credentials received\n"); + LOG_INFO("Provisioning: Credentials received\n"); break; case ARDUINO_EVENT_PROV_CRED_FAIL: - LOG_DEBUG("Provisioning: Credentials failed\n"); + LOG_INFO("Provisioning: Credentials failed\n"); break; case ARDUINO_EVENT_PROV_CRED_SUCCESS: - LOG_DEBUG("Provisioning: Credentials success\n"); + LOG_INFO("Provisioning: Credentials success\n"); break; default: break; diff --git a/src/mesh/mesh-pb-constants.cpp b/src/mesh/mesh-pb-constants.cpp index cbf4c76d3..d8a981054 100644 --- a/src/mesh/mesh-pb-constants.cpp +++ b/src/mesh/mesh-pb-constants.cpp @@ -12,7 +12,7 @@ size_t pb_encode_to_bytes(uint8_t *destbuf, size_t destbufsize, const pb_msgdesc { pb_ostream_t stream = pb_ostream_from_buffer(destbuf, destbufsize); if (!pb_encode(&stream, fields, src_struct)) { - LOG_DEBUG("Panic: can't encode protobuf reason='%s'\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Panic: can't encode protobuf reason='%s'\n", PB_GET_ERROR(&stream)); assert(0); // If this asser fails it probably means you made a field too large for the max limits specified in mesh.options } else { return stream.bytes_written; @@ -24,7 +24,7 @@ bool pb_decode_from_bytes(const uint8_t *srcbuf, size_t srcbufsize, const pb_msg { pb_istream_t stream = pb_istream_from_buffer(srcbuf, srcbufsize); if (!pb_decode(&stream, fields, dest_struct)) { - LOG_DEBUG("Error: can't decode protobuf reason='%s', pb_msgdesc 0x%p\n", PB_GET_ERROR(&stream), fields); + LOG_ERROR("Can't decode protobuf reason='%s', pb_msgdesc 0x%p\n", PB_GET_ERROR(&stream), fields); return false; } else { return true; diff --git a/src/mesh/wifi/WiFiServerAPI.cpp b/src/mesh/wifi/WiFiServerAPI.cpp index 98e38f926..136dfadb7 100644 --- a/src/mesh/wifi/WiFiServerAPI.cpp +++ b/src/mesh/wifi/WiFiServerAPI.cpp @@ -9,14 +9,14 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new WiFiServerPort(port); - LOG_DEBUG("API server listening on TCP port %d\n", port); + LOG_INFO("API server listening on TCP port %d\n", port); apiPort->init(); } } WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), concurrency::OSThread("WiFiServerAPI"), client(_client) { - LOG_DEBUG("Incoming wifi connection\n"); + LOG_INFO("Incoming wifi connection\n"); } WiFiServerAPI::~WiFiServerAPI() @@ -44,7 +44,7 @@ int32_t WiFiServerAPI::runOnce() if (client.connected()) { return StreamAPI::runOncePart(); } else { - LOG_DEBUG("Client dropped connection, suspending API service\n"); + LOG_INFO("Client dropped connection, suspending API service\n"); enabled = false; // we no longer need to run return 0; } @@ -71,7 +71,7 @@ int32_t WiFiServerPort::runOnce() if (client) { // Close any previous connection (see FIXME in header file) if (openAPI) { - LOG_DEBUG("Force closing previous TCP connection\n"); + LOG_INFO("Force closing previous TCP connection\n"); delete openAPI; } diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 30bff79b6..b6ea8826a 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -50,23 +50,23 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) * Getters */ case AdminMessage_get_owner_request_tag: - LOG_DEBUG("Client is getting owner\n"); + LOG_INFO("Client is getting owner\n"); handleGetOwner(mp); break; case AdminMessage_get_config_request_tag: - LOG_DEBUG("Client is getting config\n"); + LOG_INFO("Client is getting config\n"); handleGetConfig(mp, r->get_config_request); break; case AdminMessage_get_module_config_request_tag: - LOG_DEBUG("Client is getting module config\n"); + LOG_INFO("Client is getting module config\n"); handleGetModuleConfig(mp, r->get_module_config_request); break; case AdminMessage_get_channel_request_tag: { uint32_t i = r->get_channel_request - 1; - LOG_DEBUG("Client is getting channel %u\n", i); + LOG_INFO("Client is getting channel %u\n", i); if (i >= MAX_NUM_CHANNELS) myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); else @@ -78,22 +78,22 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) * Setters */ case AdminMessage_set_owner_tag: - LOG_DEBUG("Client is setting owner\n"); + LOG_INFO("Client is setting owner\n"); handleSetOwner(r->set_owner); break; case AdminMessage_set_config_tag: - LOG_DEBUG("Client is setting the config\n"); + LOG_INFO("Client is setting the config\n"); handleSetConfig(r->set_config); break; case AdminMessage_set_module_config_tag: - LOG_DEBUG("Client is setting the module config\n"); + LOG_INFO("Client is setting the module config\n"); handleSetModuleConfig(r->set_module_config); break; case AdminMessage_set_channel_tag: - LOG_DEBUG("Client is setting channel %d\n", r->set_channel.index); + LOG_INFO("Client is setting channel %d\n", r->set_channel.index); if (r->set_channel.index < 0 || r->set_channel.index >= (int)MAX_NUM_CHANNELS) myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); else @@ -111,15 +111,15 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) int32_t s = r->reboot_ota_seconds; #ifdef ARCH_ESP32 if (BleOta::getOtaAppVersion().isEmpty()) { - LOG_DEBUG("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); + LOG_INFO("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); screen->startRebootScreen(); }else{ screen->startFirmwareUpdateScreen(); BleOta::switchToOtaApp(); - LOG_DEBUG("Rebooting to OTA in %d seconds\n", s); + LOG_INFO("Rebooting to OTA in %d seconds\n", s); } #else - LOG_DEBUG("Not on ESP32, scheduling regular reboot in %d seconds\n", s); + LOG_INFO("Not on ESP32, scheduling regular reboot in %d seconds\n", s); screen->startRebootScreen(); #endif rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); @@ -127,40 +127,40 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) } case AdminMessage_shutdown_seconds_tag: { int32_t s = r->shutdown_seconds; - LOG_DEBUG("Shutdown in %d seconds\n", s); + LOG_INFO("Shutdown in %d seconds\n", s); shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } case AdminMessage_get_device_metadata_request_tag: { - LOG_DEBUG("Client is getting device metadata\n"); + LOG_INFO("Client is getting device metadata\n"); handleGetDeviceMetadata(mp); break; } case AdminMessage_factory_reset_tag: { - LOG_DEBUG("Initiating factory reset\n"); + LOG_INFO("Initiating factory reset\n"); nodeDB.factoryReset(); reboot(DEFAULT_REBOOT_SECONDS); break; } case AdminMessage_nodedb_reset_tag: { - LOG_DEBUG("Initiating node-db reset\n"); + LOG_INFO("Initiating node-db reset\n"); nodeDB.resetNodes(); reboot(DEFAULT_REBOOT_SECONDS); break; } case AdminMessage_begin_edit_settings_tag: { - LOG_DEBUG("Beginning transaction for editing settings\n"); + LOG_INFO("Beginning transaction for editing settings\n"); hasOpenEditTransaction = true; break; } case AdminMessage_commit_edit_settings_tag: { - LOG_DEBUG("Committing transaction for edited settings\n"); + LOG_INFO("Committing transaction for edited settings\n"); hasOpenEditTransaction = false; saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); break; } #ifdef ARCH_PORTDUINO case AdminMessage_exit_simulator_tag: - LOG_DEBUG("Exiting simulator\n"); + LOG_INFO("Exiting simulator\n"); _exit(0); break; #endif @@ -175,7 +175,7 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) LOG_DEBUG("We did not responded to a request that wanted a respond. req.variant=%d\n", r->which_payload_variant); } else if (handleResult != AdminMessageHandleResult::HANDLED) { // Probably a message sent by us or sent to our local node. FIXME, we should avoid scanning these messages - LOG_DEBUG("Ignoring nonrelevant admin %d\n", r->which_payload_variant); + LOG_INFO("Ignoring nonrelevant admin %d\n", r->which_payload_variant); } break; } @@ -229,7 +229,7 @@ void AdminModule::handleSetConfig(const Config &c) switch (c.which_payload_variant) { case Config_device_tag: - LOG_DEBUG("Setting config: Device\n"); + LOG_INFO("Setting config: Device\n"); config.has_device = true; config.device = c.payload_variant.device; // If we're setting router role for the first time, install its intervals @@ -240,29 +240,29 @@ void AdminModule::handleSetConfig(const Config &c) } break; case Config_position_tag: - LOG_DEBUG("Setting config: Position\n"); + LOG_INFO("Setting config: Position\n"); config.has_position = true; config.position = c.payload_variant.position; // Save nodedb as well in case we got a fixed position packet saveChanges(SEGMENT_DEVICESTATE, false); break; case Config_power_tag: - LOG_DEBUG("Setting config: Power\n"); + LOG_INFO("Setting config: Power\n"); config.has_power = true; config.power = c.payload_variant.power; break; case Config_network_tag: - LOG_DEBUG("Setting config: WiFi\n"); + LOG_INFO("Setting config: WiFi\n"); config.has_network = true; config.network = c.payload_variant.network; break; case Config_display_tag: - LOG_DEBUG("Setting config: Display\n"); + LOG_INFO("Setting config: Display\n"); config.has_display = true; config.display = c.payload_variant.display; break; case Config_lora_tag: - LOG_DEBUG("Setting config: LoRa\n"); + LOG_INFO("Setting config: LoRa\n"); config.has_lora = true; config.lora = c.payload_variant.lora; if (isRegionUnset && @@ -271,7 +271,7 @@ void AdminModule::handleSetConfig(const Config &c) } break; case Config_bluetooth_tag: - LOG_DEBUG("Setting config: Bluetooth\n"); + LOG_INFO("Setting config: Bluetooth\n"); config.has_bluetooth = true; config.bluetooth = c.payload_variant.bluetooth; break; @@ -284,47 +284,47 @@ void AdminModule::handleSetModuleConfig(const ModuleConfig &c) { switch (c.which_payload_variant) { case ModuleConfig_mqtt_tag: - LOG_DEBUG("Setting module config: MQTT\n"); + LOG_INFO("Setting module config: MQTT\n"); moduleConfig.has_mqtt = true; moduleConfig.mqtt = c.payload_variant.mqtt; break; case ModuleConfig_serial_tag: - LOG_DEBUG("Setting module config: Serial\n"); + LOG_INFO("Setting module config: Serial\n"); moduleConfig.has_serial = true; moduleConfig.serial = c.payload_variant.serial; break; case ModuleConfig_external_notification_tag: - LOG_DEBUG("Setting module config: External Notification\n"); + LOG_INFO("Setting module config: External Notification\n"); moduleConfig.has_external_notification = true; moduleConfig.external_notification = c.payload_variant.external_notification; break; case ModuleConfig_store_forward_tag: - LOG_DEBUG("Setting module config: Store & Forward\n"); + LOG_INFO("Setting module config: Store & Forward\n"); moduleConfig.has_store_forward = true; moduleConfig.store_forward = c.payload_variant.store_forward; break; case ModuleConfig_range_test_tag: - LOG_DEBUG("Setting module config: Range Test\n"); + LOG_INFO("Setting module config: Range Test\n"); moduleConfig.has_range_test = true; moduleConfig.range_test = c.payload_variant.range_test; break; case ModuleConfig_telemetry_tag: - LOG_DEBUG("Setting module config: Telemetry\n"); + LOG_INFO("Setting module config: Telemetry\n"); moduleConfig.has_telemetry = true; moduleConfig.telemetry = c.payload_variant.telemetry; break; case ModuleConfig_canned_message_tag: - LOG_DEBUG("Setting module config: Canned Message\n"); + LOG_INFO("Setting module config: Canned Message\n"); moduleConfig.has_canned_message = true; moduleConfig.canned_message = c.payload_variant.canned_message; break; case ModuleConfig_audio_tag: - LOG_DEBUG("Setting module config: Audio\n"); + LOG_INFO("Setting module config: Audio\n"); moduleConfig.has_audio = true; moduleConfig.audio = c.payload_variant.audio; break; case ModuleConfig_remote_hardware_tag: - LOG_DEBUG("Setting module config: Remote Hardware\n"); + LOG_INFO("Setting module config: Remote Hardware\n"); moduleConfig.has_remote_hardware = true; moduleConfig.remote_hardware = c.payload_variant.remote_hardware; break; @@ -363,38 +363,38 @@ void AdminModule::handleGetConfig(const MeshPacket &req, const uint32_t configTy if (req.decoded.want_response) { switch (configType) { case AdminMessage_ConfigType_DEVICE_CONFIG: - LOG_DEBUG("Getting config: Device\n"); + LOG_INFO("Getting config: Device\n"); res.get_config_response.which_payload_variant = Config_device_tag; res.get_config_response.payload_variant.device = config.device; break; case AdminMessage_ConfigType_POSITION_CONFIG: - LOG_DEBUG("Getting config: Position\n"); + LOG_INFO("Getting config: Position\n"); res.get_config_response.which_payload_variant = Config_position_tag; res.get_config_response.payload_variant.position = config.position; break; case AdminMessage_ConfigType_POWER_CONFIG: - LOG_DEBUG("Getting config: Power\n"); + LOG_INFO("Getting config: Power\n"); res.get_config_response.which_payload_variant = Config_power_tag; res.get_config_response.payload_variant.power = config.power; break; case AdminMessage_ConfigType_NETWORK_CONFIG: - LOG_DEBUG("Getting config: Network\n"); + LOG_INFO("Getting config: Network\n"); res.get_config_response.which_payload_variant = Config_network_tag; res.get_config_response.payload_variant.network = config.network; writeSecret(res.get_config_response.payload_variant.network.wifi_psk, config.network.wifi_psk); break; case AdminMessage_ConfigType_DISPLAY_CONFIG: - LOG_DEBUG("Getting config: Display\n"); + LOG_INFO("Getting config: Display\n"); res.get_config_response.which_payload_variant = Config_display_tag; res.get_config_response.payload_variant.display = config.display; break; case AdminMessage_ConfigType_LORA_CONFIG: - LOG_DEBUG("Getting config: LoRa\n"); + LOG_INFO("Getting config: LoRa\n"); res.get_config_response.which_payload_variant = Config_lora_tag; res.get_config_response.payload_variant.lora = config.lora; break; case AdminMessage_ConfigType_BLUETOOTH_CONFIG: - LOG_DEBUG("Getting config: Bluetooth\n"); + LOG_INFO("Getting config: Bluetooth\n"); res.get_config_response.which_payload_variant = Config_bluetooth_tag; res.get_config_response.payload_variant.bluetooth = config.bluetooth; break; @@ -418,48 +418,48 @@ void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t co if (req.decoded.want_response) { switch (configType) { case AdminMessage_ModuleConfigType_MQTT_CONFIG: - LOG_DEBUG("Getting module config: MQTT\n"); + LOG_INFO("Getting module config: MQTT\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_mqtt_tag; res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt; break; case AdminMessage_ModuleConfigType_SERIAL_CONFIG: - LOG_DEBUG("Getting module config: Serial\n"); + LOG_INFO("Getting module config: Serial\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_serial_tag; res.get_module_config_response.payload_variant.serial = moduleConfig.serial; break; case AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: - LOG_DEBUG("Getting module config: External Notification\n"); + LOG_INFO("Getting module config: External Notification\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_external_notification_tag; res.get_module_config_response.payload_variant.external_notification = moduleConfig.external_notification; break; case AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: - LOG_DEBUG("Getting module config: Store & Forward\n"); + LOG_INFO("Getting module config: Store & Forward\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_store_forward_tag; res.get_module_config_response.payload_variant.store_forward = moduleConfig.store_forward; break; case AdminMessage_ModuleConfigType_RANGETEST_CONFIG: - LOG_DEBUG("Getting module config: Range Test\n"); + LOG_INFO("Getting module config: Range Test\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_range_test_tag; res.get_module_config_response.payload_variant.range_test = moduleConfig.range_test; break; case AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: - LOG_DEBUG("Getting module config: Telemetry\n"); + LOG_INFO("Getting module config: Telemetry\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_telemetry_tag; res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry; break; case AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: - LOG_DEBUG("Getting module config: Canned Message\n"); + LOG_INFO("Getting module config: Canned Message\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_canned_message_tag; res.get_module_config_response.payload_variant.canned_message = moduleConfig.canned_message; break; case AdminMessage_ModuleConfigType_AUDIO_CONFIG: - LOG_DEBUG("Getting module config: Audio\n"); + LOG_INFO("Getting module config: Audio\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_audio_tag; res.get_module_config_response.payload_variant.audio = moduleConfig.audio; break; case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: - LOG_DEBUG("Getting module config: Remote Hardware\n"); + LOG_INFO("Getting module config: Remote Hardware\n"); res.get_module_config_response.which_payload_variant = ModuleConfig_remote_hardware_tag; res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware; break; @@ -506,7 +506,7 @@ void AdminModule::handleGetChannel(const MeshPacket &req, uint32_t channelIndex) void AdminModule::reboot(int32_t seconds) { - LOG_DEBUG("Rebooting in %d seconds\n", seconds); + LOG_INFO("Rebooting in %d seconds\n", seconds); screen->startRebootScreen(); rebootAtMsec = (seconds < 0) ? 0 : (millis() + seconds * 1000); } @@ -514,10 +514,10 @@ void AdminModule::reboot(int32_t seconds) void AdminModule::saveChanges(int saveWhat, bool shouldReboot) { if (!hasOpenEditTransaction) { - LOG_DEBUG("Saving changes to disk\n"); + LOG_INFO("Saving changes to disk\n"); service.reloadConfig(saveWhat); // Calls saveToDisk among other things } else { - LOG_DEBUG("Delaying save of changes to disk until the open transaction is committed\n"); + LOG_INFO("Delaying save of changes to disk until the open transaction is committed\n"); } if (shouldReboot) { diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index f1a9e099f..f1ae94e6c 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -49,10 +49,10 @@ CannedMessageModule::CannedMessageModule() if (moduleConfig.canned_message.enabled) { this->loadProtoForModule(); if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) { - LOG_DEBUG("CannedMessageModule: No messages are configured. Module is disabled\n"); + LOG_INFO("CannedMessageModule: No messages are configured. Module is disabled\n"); this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; } else { - LOG_DEBUG("CannedMessageModule is enabled\n"); + LOG_INFO("CannedMessageModule is enabled\n"); this->inputObserver.observe(inputBroker); } } @@ -198,7 +198,7 @@ void CannedMessageModule::sendText(NodeNum dest, const char *message, bool wantR p->decoded.payload.size++; } - LOG_DEBUG("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); + LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); service.sendToMesh(p); } diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index cabed32e3..f1f1fb2c1 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -48,15 +48,15 @@ int32_t ExternalNotificationModule::runOnce() if (nagCycleCutoff < millis()) { #endif nagCycleCutoff = UINT32_MAX; - LOG_DEBUG("Turning off external notification: "); + LOG_INFO("Turning off external notification: "); for (int i = 0; i < 2; i++) { if (getExternal(i)) { setExternalOff(i); externalTurnedOn[i] = 0; - LOG_DEBUG("%d ", i); + LOG_INFO("%d ", i); } } - LOG_DEBUG("\n"); + LOG_INFO("\n"); return INT32_MAX; // save cycles till we're needed again } @@ -175,26 +175,26 @@ ExternalNotificationModule::ExternalNotificationModule() strncpy(rtttlConfig.ringtone, "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#", sizeof(rtttlConfig.ringtone)); } - LOG_DEBUG("Initializing External Notification Module\n"); + LOG_INFO("Initializing External Notification Module\n"); output = moduleConfig.external_notification.output ? moduleConfig.external_notification.output : EXT_NOTIFICATION_MODULE_OUTPUT; // Set the direction of a pin - LOG_DEBUG("Using Pin %i in digital mode\n", output); + LOG_INFO("Using Pin %i in digital mode\n", output); pinMode(output, OUTPUT); setExternalOff(0); externalTurnedOn[0] = 0; if(moduleConfig.external_notification.output_vibra) { - LOG_DEBUG("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); + LOG_INFO("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); setExternalOff(1); externalTurnedOn[1] = 0; } if(moduleConfig.external_notification.output_buzzer) { if (!moduleConfig.external_notification.use_pwm) { - LOG_DEBUG("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); + LOG_INFO("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT); setExternalOff(2); externalTurnedOn[2] = 0; @@ -203,11 +203,11 @@ ExternalNotificationModule::ExternalNotificationModule() ? config.device.buzzer_gpio : PIN_BUZZER; // in PWM Mode we force the buzzer pin if it is set - LOG_DEBUG("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); + LOG_INFO("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); } } } else { - LOG_DEBUG("External Notification Module Disabled\n"); + LOG_INFO("External Notification Module Disabled\n"); enabled = false; } } @@ -229,7 +229,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell) { if (containsBell) { - LOG_DEBUG("externalNotificationModule - Notification Bell\n"); + LOG_INFO("externalNotificationModule - Notification Bell\n"); setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -241,7 +241,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell_vibra) { if (containsBell) { - LOG_DEBUG("externalNotificationModule - Notification Bell (Vibra)\n"); + LOG_INFO("externalNotificationModule - Notification Bell (Vibra)\n"); setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -253,7 +253,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (moduleConfig.external_notification.alert_bell_buzzer) { if (containsBell) { - LOG_DEBUG("externalNotificationModule - Notification Bell (Buzzer)\n"); + LOG_INFO("externalNotificationModule - Notification Bell (Buzzer)\n"); if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { @@ -270,7 +270,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } if (moduleConfig.external_notification.alert_message) { - LOG_DEBUG("externalNotificationModule - Notification Module\n"); + LOG_INFO("externalNotificationModule - Notification Module\n"); setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -281,7 +281,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) if (!moduleConfig.external_notification.use_pwm) { if (moduleConfig.external_notification.alert_message_vibra) { - LOG_DEBUG("externalNotificationModule - Notification Module (Vibra)\n"); + LOG_INFO("externalNotificationModule - Notification Module (Vibra)\n"); setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; @@ -291,7 +291,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } if (moduleConfig.external_notification.alert_message_buzzer) { - LOG_DEBUG("externalNotificationModule - Notification Module (Buzzer)\n"); + LOG_INFO("externalNotificationModule - Notification Module (Buzzer)\n"); if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); } else { @@ -310,7 +310,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) } } else { - LOG_DEBUG("External Notification Module Disabled\n"); + LOG_INFO("External Notification Module Disabled\n"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want @@ -331,13 +331,13 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule switch (request->which_payload_variant) { case AdminMessage_get_ringtone_request_tag: - LOG_DEBUG("Client is getting ringtone\n"); + LOG_INFO("Client is getting ringtone\n"); this->handleGetRingtone(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; case AdminMessage_set_ringtone_message_tag: - LOG_DEBUG("Client is setting ringtone\n"); + LOG_INFO("Client is setting ringtone\n"); this->handleSetRingtone(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; break; @@ -351,7 +351,7 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response) { - LOG_DEBUG("*** handleGetRingtone\n"); + LOG_INFO("*** handleGetRingtone\n"); assert(req.decoded.want_response); response->which_payload_variant = AdminMessage_get_ringtone_response_tag; @@ -366,7 +366,7 @@ void ExternalNotificationModule::handleSetRingtone(const char *from_msg) if (*from_msg) { changed |= strcmp(rtttlConfig.ringtone, from_msg); strcpy(rtttlConfig.ringtone, from_msg); - LOG_DEBUG("*** from_msg.text:%s\n", from_msg); + LOG_INFO("*** from_msg.text:%s\n", from_msg); } if (changed) { diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index b4e054717..d8047c5f0 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -46,7 +46,7 @@ MeshPacket *NodeInfoModule::allocReply() { User &u = owner; - LOG_DEBUG("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); + LOG_INFO("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); return allocDataProtobuf(u); } @@ -65,7 +65,7 @@ int32_t NodeInfoModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - LOG_DEBUG("Sending our nodeinfo to mesh (wantReplies=%d)\n", requestReplies); + LOG_INFO("Sending our nodeinfo to mesh (wantReplies=%d)\n", requestReplies); sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies) return default_broadcast_interval_secs * 1000; diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 2df3b029b..6680eaba5 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -32,7 +32,7 @@ bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr } // Log packet size and list of fields - LOG_DEBUG("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size, + LOG_INFO("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size, p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "", p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "", p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "", @@ -109,12 +109,12 @@ MeshPacket *PositionModule::allocReply() // nodes shouldn't trust it anyways) Note: we allow a device with a local GPS to include the time, so that gpsless // devices can get time. if (getRTCQuality() < RTCQualityDevice) { - LOG_DEBUG("Stripping time %u from position send\n", p.time); + LOG_INFO("Stripping time %u from position send\n", p.time); p.time = 0; } else - LOG_DEBUG("Providing time to mesh %u\n", p.time); + LOG_INFO("Providing time to mesh %u\n", p.time); - LOG_DEBUG("Position reply: time=%i, latI=%i, lonI=-%i\n", p.time, p.latitude_i, p.longitude_i); + LOG_INFO("Position reply: time=%i, latI=%i, lonI=-%i\n", p.time, p.latitude_i, p.longitude_i); return allocDataProtobuf(p); } @@ -155,11 +155,11 @@ int32_t PositionModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - LOG_DEBUG("Sending pos@%x:6 to mesh (wantReplies=%d)\n", node->position.timestamp, requestReplies); + LOG_INFO("Sending pos@%x:6 to mesh (wantReplies=%d)\n", node->position.timestamp, requestReplies); sendOurPosition(NODENUM_BROADCAST, requestReplies); } } else { - LOG_DEBUG("Channel utilization is >40 percent. Skipping this opportunity to send.\n"); + LOG_WARN("Channel utilization is >40 percent. Skipping this opportunity to send.\n"); } } else if (config.position.position_broadcast_smart_enabled) { @@ -194,7 +194,7 @@ int32_t PositionModule::runOnce() bool requestReplies = currentGeneration != radioGeneration; currentGeneration = radioGeneration; - LOG_DEBUG("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp, + LOG_INFO("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp, requestReplies, distance, distanceTravelThreshold, timeTravel); sendOurPosition(NODENUM_BROADCAST, requestReplies); @@ -209,7 +209,7 @@ int32_t PositionModule::runOnce() } } } else { - LOG_DEBUG("Channel utilization is >25 percent. Skipping this opportunity to send.\n"); + LOG_WARN("Channel utilization is >25 percent. Skipping this opportunity to send.\n"); } } diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 9958fbe39..70d90063e 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -55,7 +55,7 @@ RemoteHardwareModule::RemoteHardwareModule() bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr) { auto p = *pptr; - LOG_DEBUG("Received RemoteHardware typ=%d\n", p.type); + LOG_INFO("Received RemoteHardware typ=%d\n", p.type); switch (p.type) { case HardwareMessage_Type_WRITE_GPIOS: @@ -95,7 +95,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar lastWatchMsec = 0; // Force a new publish soon previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) enabled = true; // Let our thread run at least once - LOG_DEBUG("Now watching GPIOs 0x%llx\n", watchGpios); + LOG_INFO("Now watching GPIOs 0x%llx\n", watchGpios); break; } @@ -104,7 +104,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar break; // Ignore - we might see our own replies default: - LOG_DEBUG("Hardware operation %d not yet implemented! FIXME\n", p.type); + LOG_ERROR("Hardware operation %d not yet implemented! FIXME\n", p.type); break; } @@ -121,7 +121,7 @@ int32_t RemoteHardwareModule::runOnce() if (curVal != previousWatch) { previousWatch = curVal; - LOG_DEBUG("Broadcasting GPIOS 0x%llx changed!\n", curVal); + LOG_INFO("Broadcasting GPIOS 0x%llx changed!\n", curVal); // Something changed! Tell the world with a broadcast message HardwareMessage r = HardwareMessage_init_default; diff --git a/src/modules/ReplyModule.cpp b/src/modules/ReplyModule.cpp index cd0dbec3a..bf4e691fb 100644 --- a/src/modules/ReplyModule.cpp +++ b/src/modules/ReplyModule.cpp @@ -11,7 +11,7 @@ MeshPacket *ReplyModule::allocReply() auto req = *currentRequest; auto &p = req.decoded; // The incoming message is in p.payload - LOG_DEBUG("Received message from=0x%0x, id=%d, msg=%.*s\n", req.from, req.id, p.payload.size, p.payload.bytes); + LOG_INFO("Received message from=0x%0x, id=%d, msg=%.*s\n", req.from, req.id, p.payload.size, p.payload.bytes); screen->print("Sending reply\n"); diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index f3708a704..704c123cd 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -109,7 +109,7 @@ int32_t SerialModule::runOnce() if (firstTime) { // Interface with the serial peripheral from in here. - LOG_DEBUG("Initializing serial peripheral interface\n"); + LOG_INFO("Initializing serial peripheral interface\n"); uint32_t baud = 0; @@ -213,14 +213,14 @@ int32_t SerialModule::runOnce() serialModuleRadio->sendPayload(); - LOG_DEBUG("Received: %s\n", serialStringChar); + LOG_INFO("Received: %s\n", serialStringChar); } } } return (10); } else { - LOG_DEBUG("Serial Module Disabled\n"); + LOG_INFO("Serial Module Disabled\n"); return INT32_MAX; } @@ -305,7 +305,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } } else { - LOG_DEBUG("Serial Module Disabled\n"); + LOG_INFO("Serial Module Disabled\n"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want } diff --git a/src/modules/Telemetry/DeviceTelemetry.cpp b/src/modules/Telemetry/DeviceTelemetry.cpp index 301aa1797..109d8b5b1 100644 --- a/src/modules/Telemetry/DeviceTelemetry.cpp +++ b/src/modules/Telemetry/DeviceTelemetry.cpp @@ -34,7 +34,7 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemet if (t->which_variant == Telemetry_device_metrics_tag) { const char *sender = getSenderShortName(mp); - LOG_DEBUG("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", + LOG_INFO("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", sender, t->variant.device_metrics.air_util_tx, t->variant.device_metrics.channel_utilization, @@ -60,7 +60,7 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) t.variant.device_metrics.channel_utilization = myNodeInfo.channel_utilization; t.variant.device_metrics.voltage = powerStatus->getBatteryVoltageMv() / 1000.0; - LOG_DEBUG("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", + LOG_INFO("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", t.variant.device_metrics.air_util_tx, t.variant.device_metrics.channel_utilization, t.variant.device_metrics.battery_level, @@ -74,10 +74,10 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); nodeDB.updateTelemetry(nodeDB.getNodeNum(), t, RX_SRC_LOCAL); if (phoneOnly) { - LOG_DEBUG("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone\n"); service.sendToPhone(p); } else { - LOG_DEBUG("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh\n"); service.sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index fa90dc7cf..3aeef50b2 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -75,7 +75,7 @@ int32_t EnvironmentTelemetryModule::runOnce() firstTime = 0; if (moduleConfig.telemetry.environment_measurement_enabled) { - LOG_DEBUG("Environment Telemetry: Initializing\n"); + LOG_INFO("Environment Telemetry: Initializing\n"); // it's possible to have this module enabled, only for displaying values on the screen. // therefore, we should only enable the sensor loop if measurement is also enabled if (bmp280Sensor.hasSensor()) @@ -162,7 +162,7 @@ void EnvironmentTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiSt if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Telemetry_msg, &lastMeasurement)) { display->setFont(FONT_SMALL); display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error"); - LOG_DEBUG("Unable to decode last packet"); + LOG_ERROR("Unable to decode last packet"); return; } @@ -187,7 +187,7 @@ bool EnvironmentTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Te if (t->which_variant == Telemetry_environment_metrics_tag) { const char *sender = getSenderShortName(mp); - LOG_DEBUG("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", + LOG_INFO("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", sender, t->variant.environment_metrics.barometric_pressure, t->variant.environment_metrics.current, @@ -234,7 +234,7 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) if (ina260Sensor.hasSensor()) ina260Sensor.getMetrics(&m); - LOG_DEBUG("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", + LOG_INFO("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n", m.variant.environment_metrics.barometric_pressure, m.variant.environment_metrics.current, m.variant.environment_metrics.gas_resistance, @@ -251,10 +251,10 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { - LOG_DEBUG("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone\n"); service.sendToPhone(p); } else { - LOG_DEBUG("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh\n"); service.sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/Sensor/BME280Sensor.cpp b/src/modules/Telemetry/Sensor/BME280Sensor.cpp index e33c1e014..26f48f89d 100644 --- a/src/modules/Telemetry/Sensor/BME280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME280Sensor.cpp @@ -11,7 +11,7 @@ BME280Sensor::BME280Sensor() : } int32_t BME280Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/BME680Sensor.cpp b/src/modules/Telemetry/Sensor/BME680Sensor.cpp index f07de0d8d..44690fbaa 100644 --- a/src/modules/Telemetry/Sensor/BME680Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME680Sensor.cpp @@ -10,7 +10,7 @@ BME680Sensor::BME680Sensor() : } int32_t BME680Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp index 29a73e282..eddc30649 100644 --- a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp @@ -11,7 +11,7 @@ BMP280Sensor::BMP280Sensor() : } int32_t BMP280Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/INA219Sensor.cpp b/src/modules/Telemetry/Sensor/INA219Sensor.cpp index 9ae886f15..4a732e73d 100644 --- a/src/modules/Telemetry/Sensor/INA219Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA219Sensor.cpp @@ -10,7 +10,7 @@ INA219Sensor::INA219Sensor() : } int32_t INA219Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/INA260Sensor.cpp b/src/modules/Telemetry/Sensor/INA260Sensor.cpp index e648cd824..5b3064e7d 100644 --- a/src/modules/Telemetry/Sensor/INA260Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA260Sensor.cpp @@ -10,7 +10,7 @@ INA260Sensor::INA260Sensor() : } int32_t INA260Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp index 295fccdfc..1f75a9aa1 100644 --- a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp +++ b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp @@ -11,7 +11,7 @@ LPS22HBSensor::LPS22HBSensor() : } int32_t LPS22HBSensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp index 3f0cafdfe..4dd3be635 100644 --- a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp @@ -10,7 +10,7 @@ MCP9808Sensor::MCP9808Sensor() : } int32_t MCP9808Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp index 4d367823d..528d5a030 100644 --- a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp @@ -10,7 +10,7 @@ SHT31Sensor::SHT31Sensor() : } int32_t SHT31Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp index b19d12692..3a20d37a1 100644 --- a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp @@ -10,7 +10,7 @@ SHTC3Sensor::SHTC3Sensor() : } int32_t SHTC3Sensor::runOnce() { - LOG_DEBUG("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s\n", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/TelemetrySensor.h b/src/modules/Telemetry/Sensor/TelemetrySensor.h index 642c82b3a..87f2d68ba 100644 --- a/src/modules/Telemetry/Sensor/TelemetrySensor.h +++ b/src/modules/Telemetry/Sensor/TelemetrySensor.h @@ -21,10 +21,10 @@ class TelemetrySensor int32_t initI2CSensor() { if (!status) { - LOG_DEBUG("Could not connect to detected %s sensor.\n Removing from nodeTelemetrySensorsMap.\n", sensorName); + LOG_WARN("Could not connect to detected %s sensor.\n Removing from nodeTelemetrySensorsMap.\n", sensorName); nodeTelemetrySensorsMap[sensorType] = 0; } else { - LOG_DEBUG("Opened %s sensor on default i2c bus\n", sensorName); + LOG_INFO("Opened %s sensor on default i2c bus\n", sensorName); setup(); } return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; diff --git a/src/modules/TextMessageModule.cpp b/src/modules/TextMessageModule.cpp index 7e7115b8d..c5dcca95a 100644 --- a/src/modules/TextMessageModule.cpp +++ b/src/modules/TextMessageModule.cpp @@ -8,7 +8,7 @@ TextMessageModule *textMessageModule; ProcessMessage TextMessageModule::handleReceived(const MeshPacket &mp) { auto &p = mp.decoded; - LOG_DEBUG("Received text msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); + LOG_INFO("Received text msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); // We only store/display messages destined for us. // Keep a copy of the most recent text message. diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index 4558c5957..ba35a2f40 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -50,12 +50,12 @@ void TraceRouteModule::appendMyID(RouteDiscovery* updated) void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest) { - LOG_DEBUG("Route traced:\n"); - LOG_DEBUG("0x%x --> ", origin); + LOG_INFO("Route traced:\n"); + LOG_INFO("0x%x --> ", origin); for (uint8_t i=0; iroute_count; i++) { - LOG_DEBUG("0x%x --> ", r->route[i]); + LOG_INFO("0x%x --> ", r->route[i]); } - if (dest != NODENUM_BROADCAST) LOG_DEBUG("0x%x\n", dest); else LOG_DEBUG("...\n"); + if (dest != NODENUM_BROADCAST) LOG_INFO("0x%x\n", dest); else LOG_INFO("...\n"); } diff --git a/src/modules/WaypointModule.cpp b/src/modules/WaypointModule.cpp index 9ab9a5879..6be2ff51a 100644 --- a/src/modules/WaypointModule.cpp +++ b/src/modules/WaypointModule.cpp @@ -8,7 +8,7 @@ WaypointModule *waypointModule; ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp) { auto &p = mp.decoded; - LOG_DEBUG("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); + LOG_INFO("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); notifyObservers(&mp); diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 8a9dbcf7f..27d4b6ba4 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -71,7 +71,7 @@ void run_codec2(void* parameter) // 4 bytes of header in each frame hex c0 de c2 plus the bitrate memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); - LOG_DEBUG("Starting codec2 task\n"); + LOG_INFO("Starting codec2 task\n"); while (true) { uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); @@ -86,7 +86,7 @@ void run_codec2(void* parameter) if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) { - LOG_DEBUG("Sending %d codec2 bytes\n", audioModule->encode_frame_size); + LOG_INFO("Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); } @@ -127,7 +127,7 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), // moduleConfig.audio.ptt_pin = 39; if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - LOG_DEBUG("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + LOG_INFO("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; @@ -136,10 +136,10 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), encode_frame_num = (Constants_DATA_PAYLOAD_LEN - sizeof(tx_header)) / encode_codec_size; encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes adc_buffer_size = codec2_samples_per_frame(codec2); - LOG_DEBUG(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); + LOG_INFO(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { - LOG_DEBUG("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); + LOG_INFO("Codec2 disabled (AudioModule %d, Region %s, permitted %d)\n", moduleConfig.audio.codec2_enabled, myRegion->name, myRegion->audioPermitted); } } @@ -173,7 +173,7 @@ int32_t AudioModule::runOnce() esp_err_t res; if (firstTime) { // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC - LOG_DEBUG("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); + LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), .sample_rate = 8000, @@ -189,7 +189,7 @@ int32_t AudioModule::runOnce() }; res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); if(res != ESP_OK) - LOG_DEBUG("Failed to install I2S driver: %d\n", res); + LOG_ERROR("Failed to install I2S driver: %d\n", res); const i2s_pin_config_t pin_config = { .bck_io_num = moduleConfig.audio.i2s_sck, @@ -199,16 +199,16 @@ int32_t AudioModule::runOnce() }; res = i2s_set_pin(I2S_PORT, &pin_config); if(res != ESP_OK) - LOG_DEBUG("Failed to set I2S pin config: %d\n", res); + LOG_ERROR("Failed to set I2S pin config: %d\n", res); res = i2s_start(I2S_PORT); if(res != ESP_OK) - LOG_DEBUG("Failed to start I2S: %d\n", res); + LOG_ERROR("Failed to start I2S: %d\n", res); radio_state = RadioState::rx; // Configure PTT input - LOG_DEBUG("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + LOG_INFO("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; @@ -217,17 +217,17 @@ int32_t AudioModule::runOnce() // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { - LOG_DEBUG("PTT pressed, switching to TX\n"); + LOG_INFO("PTT pressed, switching to TX\n"); radio_state = RadioState::tx; e.frameChanged = true; this->notifyObservers(&e); } } else { if (radio_state == RadioState::tx) { - LOG_DEBUG("PTT released, switching to RX\n"); + LOG_INFO("PTT released, switching to RX\n"); if (tx_encode_frame_index > sizeof(tx_header)) { // Send the incomplete frame - LOG_DEBUG("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); + LOG_INFO("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); sendPayload(); } tx_encode_frame_index = sizeof(tx_header); @@ -258,7 +258,7 @@ int32_t AudioModule::runOnce() } return 100; } else { - LOG_DEBUG("Audio Module Disabled\n"); + LOG_INFO("Audio Module Disabled\n"); return INT32_MAX; } diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index e8e9f62dd..4cc27833b 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -53,10 +53,10 @@ int32_t RangeTestModule::runOnce() firstTime = 0; if (moduleConfig.range_test.sender) { - LOG_DEBUG("Initializing Range Test Module -- Sender\n"); + LOG_INFO("Initializing Range Test Module -- Sender\n"); return (5000); // Sending first message 5 seconds after initilization. } else { - LOG_DEBUG("Initializing Range Test Module -- Receiver\n"); + LOG_INFO("Initializing Range Test Module -- Receiver\n"); return (INT32_MAX); // This thread does not need to run as a receiver } @@ -65,19 +65,19 @@ int32_t RangeTestModule::runOnce() if (moduleConfig.range_test.sender) { // If sender - LOG_DEBUG("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); + LOG_INFO("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); - LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - LOG_DEBUG("fixed_position() %d\n", config.position.fixed_position); + LOG_INFO("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); + LOG_INFO("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); + LOG_INFO("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); + LOG_INFO("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); + LOG_INFO("fixed_position() %d\n", config.position.fixed_position); // Only send packets if the channel is less than 25% utilized. if (airTime->channelUtilizationPercent() < 25) { rangeTestModuleRadio->sendPayload(); } else { - LOG_DEBUG("rangeTest - Channel utilization is >25 percent. Skipping this opportunity to send.\n"); + LOG_WARN("RangeTest - Channel utilization is >25 percent. Skipping this opportunity to send.\n"); } return (senderHeartbeat); @@ -88,9 +88,8 @@ int32_t RangeTestModule::runOnce() } - } else { - LOG_DEBUG("Range Test Module - Disabled\n"); + LOG_INFO("Range Test Module - Disabled\n"); } #endif @@ -136,7 +135,7 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) /* auto &p = mp.decoded; LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", - nodeDB.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); + LOG_INFO.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); */ if (getFrom(&mp) != nodeDB.getNodeNum()) { @@ -174,7 +173,7 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) } } else { - LOG_DEBUG("Range Test Module Disabled\n"); + LOG_INFO("Range Test Module Disabled\n"); } #endif @@ -229,16 +228,16 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) File fileToWrite = FSCom.open("/static/rangetest.csv", FILE_WRITE); if (!fileToWrite) { - LOG_DEBUG("There was an error opening the file for writing\n"); + LOG_ERROR("There was an error opening the file for writing\n"); return 0; } // Print the CSV header if (fileToWrite.println( "time,from,sender name,sender lat,sender long,rx lat,rx long,rx elevation,rx snr,distance,hop limit,payload")) { - LOG_DEBUG("File was written\n"); + LOG_INFO("File was written\n"); } else { - LOG_DEBUG("File write failed\n"); + LOG_ERROR("File write failed\n"); } fileToWrite.close(); @@ -248,7 +247,7 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) File fileToAppend = FSCom.open("/static/rangetest.csv", FILE_APPEND); if (!fileToAppend) { - LOG_DEBUG("There was an error opening the file for appending\n"); + LOG_ERROR("There was an error opening the file for appending\n"); return 0; } diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 524aa0670..5378d2c4d 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -28,20 +28,20 @@ int32_t StoreForwardModule::runOnce() StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_PING; storeForwardModule->sendMessage(this->busyTo, sf); - LOG_DEBUG("*** S&F - Done. (ROUTER_PING)\n"); + LOG_INFO("*** S&F - Done. (ROUTER_PING)\n"); this->packetHistoryTXQueue_index = 0; this->busy = false; } else { this->packetHistoryTXQueue_index++; } } else { - LOG_DEBUG("*** Channel utilization is too high. Retrying later.\n"); + LOG_WARN("*** Channel utilization is too high. Retrying later.\n"); } LOG_DEBUG("*** SF bitrate = %f bytes / sec\n", myNodeInfo.bitrate); } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && (airTime->channelUtilizationPercent() < polite_channel_util_percent)) { lastHeartbeat = millis(); - LOG_DEBUG("*** Sending heartbeat\n"); + LOG_INFO("*** Sending heartbeat\n"); StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; sf.which_variant = StoreAndForward_heartbeat_tag; @@ -87,11 +87,11 @@ void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) uint32_t queueSize = storeForwardModule->historyQueueCreate(msAgo, to); if (queueSize) { - LOG_DEBUG ("*** S&F - Sending %u message(s)\n", queueSize); + LOG_INFO("*** S&F - Sending %u message(s)\n", queueSize); this->busy = true; // runOnce() will pickup the next steps once busy = true. this->busyTo = to; } else { - LOG_DEBUG ("*** S&F - No history to send\n"); + LOG_INFO("*** S&F - No history to send\n"); } StoreAndForward sf = StoreAndForward_init_zero; sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; @@ -164,7 +164,7 @@ MeshPacket *StoreForwardModule::allocReply() void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) { - LOG_DEBUG("*** Sending S&F Payload\n"); + LOG_INFO("*** Sending S&F Payload\n"); MeshPacket *p = allocReply(); p->to = dest; @@ -241,7 +241,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { storeForwardModule->historyAdd(mp); - LOG_DEBUG("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); + LOG_INFO("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { auto &p = mp.decoded; @@ -251,7 +251,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &StoreAndForward_msg, &scratch)) { decoded = &scratch; } else { - LOG_DEBUG("Error decoding protobuf module!\n"); + LOG_ERROR("Error decoding protobuf module!\n"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } @@ -281,7 +281,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo if(is_server) { // stop sending stuff, the client wants to abort or has another error if ((this->busy) && (this->busyTo == getFrom(&mp))) { - LOG_DEBUG("*** Client in ERROR or ABORT requested\n"); + LOG_ERROR("*** Client in ERROR or ABORT requested\n"); this->packetHistoryTXQueue_index = 0; this->busy = false; } @@ -291,11 +291,11 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_HISTORY: if(is_server) { requests_history++; - LOG_DEBUG("*** Client Request to send HISTORY\n"); + LOG_INFO("*** Client Request to send HISTORY\n"); // Send the last 60 minutes of messages. if (this->busy) { storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); - LOG_DEBUG("*** S&F - Busy. Try again shortly.\n"); + LOG_INFO("*** S&F - Busy. Try again shortly.\n"); } else { if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)){ storeForwardModule->historySend(p->variant.history.window * 60000, getFrom(&mp)); // window is in minutes @@ -308,7 +308,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_PING: if(is_server) { - LOG_DEBUG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); + LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); // respond with a ROUTER PONG storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_PONG); } @@ -316,7 +316,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_PONG: if(is_server) { - LOG_DEBUG("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); + LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); // The Client is alive, update NodeDB nodeDB.updateFrom(mp); } @@ -324,10 +324,10 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo case StoreAndForward_RequestResponse_CLIENT_STATS: if(is_server) { - LOG_DEBUG("*** Client Request to send STATS\n"); + LOG_INFO("*** Client Request to send STATS\n"); if (this->busy) { storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); - LOG_DEBUG("*** S&F - Busy. Try again shortly.\n"); + LOG_INFO("*** S&F - Busy. Try again shortly.\n"); } else { storeForwardModule->statsSend(getFrom(&mp)); } @@ -352,7 +352,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo heartbeatInterval = p->variant.heartbeat.period; } lastHeartbeat = millis(); - LOG_DEBUG("*** StoreAndForward Heartbeat received\n"); + LOG_INFO("*** StoreAndForward Heartbeat received\n"); } break; @@ -386,7 +386,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo // These fields only have informational purpose on a client. Fill them to consume later. if (p->which_variant == StoreAndForward_history_tag) { this->historyReturnWindow = p->variant.history.window / 60000; - LOG_DEBUG("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); + LOG_INFO("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); } } break; @@ -418,7 +418,7 @@ StoreForwardModule::StoreForwardModule() // Router if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { - LOG_DEBUG("*** Initializing Store & Forward Module in Router mode\n"); + LOG_INFO("*** Initializing Store & Forward Module in Router mode\n"); if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { @@ -444,19 +444,19 @@ StoreForwardModule::StoreForwardModule() this->populatePSRAM(); is_server = true; } else { - LOG_DEBUG("*** Device has less than 1M of PSRAM free.\n"); - LOG_DEBUG("*** Store & Forward Module - disabling server.\n"); + LOG_INFO("*** Device has less than 1M of PSRAM free.\n"); + LOG_INFO("*** Store & Forward Module - disabling server.\n"); } } else { - LOG_DEBUG("*** Device doesn't have PSRAM.\n"); - LOG_DEBUG("*** Store & Forward Module - disabling server.\n"); + LOG_INFO("*** Device doesn't have PSRAM.\n"); + LOG_INFO("*** Store & Forward Module - disabling server.\n"); } // Client } if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { is_client = true; - LOG_DEBUG("*** Initializing Store & Forward Module in Client mode\n"); + LOG_INFO("*** Initializing Store & Forward Module in Client mode\n"); } } #endif diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 33122d091..b5550d3ff 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -42,7 +42,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) payloadStr[length] = 0; // null terminated string JSONValue *json_value = JSON::Parse(payloadStr); if (json_value != NULL) { - LOG_DEBUG("JSON Received on MQTT, parsing..\n"); + LOG_INFO("JSON Received on MQTT, parsing..\n"); // check if it is a valid envelope JSONObject json; json = json_value->AsObject(); @@ -50,7 +50,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) // this is a valid envelope if (json["payload"]->IsString() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) { std::string jsonPayloadStr = json["payload"]->AsString(); - LOG_DEBUG("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); + LOG_INFO("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); // construct protobuf data packet using TEXT_MESSAGE, send it to the mesh MeshPacket *p = router->allocForSending(); @@ -61,7 +61,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) MeshPacket *packet = packetPool.allocCopy(*p); service.sendToMesh(packet, RX_SRC_LOCAL); } else { - LOG_DEBUG("Received MQTT json payload too long, dropping\n"); + LOG_WARN("Received MQTT json payload too long, dropping\n"); } } else { LOG_DEBUG("JSON Ignoring downlink message we originally sent.\n"); @@ -87,23 +87,23 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) LOG_DEBUG("JSON Ignoring downlink message we originally sent.\n"); } } else{ - LOG_DEBUG("JSON Received payload on MQTT but not a valid envelope\n"); + LOG_ERROR("JSON Received payload on MQTT but not a valid envelope\n"); } } else { // no json, this is an invalid payload - LOG_DEBUG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); } delete json_value; } else { if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) { - LOG_DEBUG("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); return; }else { if (strcmp(e.gateway_id, owner.id) == 0) - LOG_DEBUG("Ignoring downlink message we originally sent.\n"); + LOG_INFO("Ignoring downlink message we originally sent.\n"); else { if (e.packet) { - LOG_DEBUG("Received MQTT topic %s, len=%u\n", topic, length); + LOG_INFO("Received MQTT topic %s, len=%u\n", topic, length); MeshPacket *p = packetPool.allocCopy(*e.packet); // ignore messages sent by us or if we don't have the channel key @@ -166,22 +166,22 @@ void MQTT::reconnect() } pubSub.setServer(serverAddr, serverPort); - LOG_DEBUG("Connecting to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, serverPort, mqttUsername, mqttPassword); + LOG_INFO("Connecting to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, serverPort, mqttUsername, mqttPassword); auto myStatus = (statusTopic + owner.id); bool connected = pubSub.connect(owner.id, mqttUsername, mqttPassword, myStatus.c_str(), 1, true, "offline"); if (connected) { - LOG_DEBUG("MQTT connected\n"); + LOG_INFO("MQTT connected\n"); enabled = true; // Start running background process again runASAP = true; reconnectCount = 0; /// FIXME, include more information in the status text bool ok = pubSub.publish(myStatus.c_str(), "online", true); - LOG_DEBUG("published %d\n", ok); + LOG_INFO("published %d\n", ok); sendSubscriptions(); } else { - LOG_DEBUG("Failed to contact MQTT server (%d/10)...\n",reconnectCount); + LOG_ERROR("Failed to contact MQTT server (%d/10)...\n",reconnectCount); #if HAS_WIFI && !defined(ARCH_PORTDUINO) if (reconnectCount > 9) { needReconnect = true; @@ -200,11 +200,11 @@ void MQTT::sendSubscriptions() auto &ch = channels.getByIndex(i); if (ch.settings.downlink_enabled) { String topic = cryptTopic + channels.getGlobalId(i) + "/#"; - LOG_DEBUG("Subscribing to %s\n", topic.c_str()); + LOG_INFO("Subscribing to %s\n", topic.c_str()); pubSub.subscribe(topic.c_str(), 1); // FIXME, is QOS 1 right? if (moduleConfig.mqtt.json_enabled == true) { String topicDecoded = jsonTopic + channels.getGlobalId(i) + "/#"; - LOG_DEBUG("Subscribing to %s\n", topicDecoded.c_str()); + LOG_INFO("Subscribing to %s\n", topicDecoded.c_str()); pubSub.subscribe(topicDecoded.c_str(), 1); // FIXME, is QOS 1 right? } } @@ -254,7 +254,7 @@ int32_t MQTT::runOnce() size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); String topic = cryptTopic + env->channel_id + "/" + owner.id; - LOG_DEBUG("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); + LOG_INFO("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); pubSub.publish(topic.c_str(), bytes, numBytes, false); @@ -264,7 +264,7 @@ int32_t MQTT::runOnce() auto jsonString = this->downstreamPacketToJson(env->packet); if (jsonString.length() != 0) { String topicJson = jsonTopic + env->channel_id + "/" + owner.id; - LOG_DEBUG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + LOG_INFO("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); } } @@ -279,7 +279,7 @@ int32_t MQTT::runOnce() } else { // we are connected to server, check often for new requests on the TCP port if (!wantConnection) { - LOG_DEBUG("MQTT link not needed, dropping\n"); + LOG_INFO("MQTT link not needed, dropping\n"); pubSub.disconnect(); } @@ -317,14 +317,14 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp); if (jsonString.length() != 0) { String topicJson = jsonTopic + channelId + "/" + owner.id; - LOG_DEBUG("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); + LOG_INFO("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), jsonString.c_str()); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false); } } } else { - LOG_DEBUG("MQTT not connected, queueing packet\n"); + LOG_INFO("MQTT not connected, queueing packet\n"); if (mqttQueue.numFree() == 0) { - LOG_DEBUG("NOTE: MQTT queue is full, discarding oldest\n"); + LOG_WARN("NOTE: MQTT queue is full, discarding oldest\n"); ServiceEnvelope *d = mqttQueue.dequeuePtr(0); if (d) mqttPool.release(d); @@ -357,13 +357,13 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) // check if this is a JSON payload JSONValue *json_value = JSON::Parse(payloadStr); if (json_value != NULL) { - LOG_DEBUG("text message payload is of type json\n"); + LOG_INFO("text message payload is of type json\n"); // if it is, then we can just use the json object jsonObj["payload"] = json_value; } else { // if it isn't, then we need to create a json object // with the string as the value - LOG_DEBUG("text message payload is of type plaintext\n"); + LOG_INFO("text message payload is of type plaintext\n"); msgPayload["text"] = new JSONValue(payloadStr); jsonObj["payload"] = new JSONValue(msgPayload); } @@ -392,7 +392,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) } jsonObj["payload"] = new JSONValue(msgPayload); } else - LOG_DEBUG("Error decoding protobuf for telemetry message!\n"); + LOG_ERROR("Error decoding protobuf for telemetry message!\n"); }; break; } @@ -410,7 +410,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) msgPayload["hardware"] = new JSONValue(decoded->hw_model); jsonObj["payload"] = new JSONValue(msgPayload); } else - LOG_DEBUG("Error decoding protobuf for nodeinfo message!\n"); + LOG_ERROR("Error decoding protobuf for nodeinfo message!\n"); }; break; } @@ -429,7 +429,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) if((int)decoded->altitude){msgPayload["altitude"] = new JSONValue((int)decoded->altitude);} jsonObj["payload"] = new JSONValue(msgPayload); } else { - LOG_DEBUG("Error decoding protobuf for position message!\n"); + LOG_ERROR("Error decoding protobuf for position message!\n"); } }; break; @@ -452,7 +452,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) msgPayload["longitude_i"] = new JSONValue((int)decoded->longitude_i); jsonObj["payload"] = new JSONValue(msgPayload); } else { - LOG_DEBUG("Error decoding protobuf for position message!\n"); + LOG_ERROR("Error decoding protobuf for position message!\n"); } }; break; @@ -474,7 +474,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) JSONValue *value = new JSONValue(jsonObj); std::string jsonStr = value->Stringify(); - LOG_DEBUG("serialized json message: %s\n", jsonStr.c_str()); + LOG_INFO("serialized json message: %s\n", jsonStr.c_str()); delete value; return jsonStr; diff --git a/src/nimble/NimbleBluetooth.cpp b/src/nimble/NimbleBluetooth.cpp index ae33e4702..78bf135fe 100644 --- a/src/nimble/NimbleBluetooth.cpp +++ b/src/nimble/NimbleBluetooth.cpp @@ -22,7 +22,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - LOG_DEBUG("BLE notify fromNum\n"); + LOG_INFO("BLE notify fromNum\n"); uint8_t val[4]; put_le32(val, fromRadioNum); @@ -46,7 +46,7 @@ static BluetoothPhoneAPI *bluetoothPhoneAPI; class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks { virtual void onWrite(NimBLECharacteristic *pCharacteristic) { - LOG_DEBUG("To Radio onwrite\n"); + LOG_INFO("To Radio onwrite\n"); auto val = pCharacteristic->getValue(); bluetoothPhoneAPI->handleToRadio(val.data(), val.length()); @@ -56,7 +56,7 @@ class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks { virtual void onRead(NimBLECharacteristic *pCharacteristic) { - LOG_DEBUG("From Radio onread\n"); + LOG_INFO("From Radio onread\n"); uint8_t fromRadioBytes[FromRadio_size]; size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes); @@ -72,11 +72,11 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks uint32_t passkey = config.bluetooth.fixed_pin; if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_RANDOM_PIN) { - LOG_DEBUG("Using random passkey\n"); + LOG_INFO("Using random passkey\n"); // This is the passkey to be entered on peer - we pick a number >100,000 to ensure 6 digits passkey = random(100000, 999999); } - LOG_DEBUG("*** Enter passkey %d on the peer side ***\n", passkey); + LOG_INFO("*** Enter passkey %d on the peer side ***\n", passkey); powerFSM.trigger(EVENT_BLUETOOTH_PAIR); screen->startBluetoothPinScreen(passkey); @@ -87,7 +87,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) { - LOG_DEBUG("BLE authentication complete\n"); + LOG_INFO("BLE authentication complete\n"); if (passkeyShowing) { passkeyShowing = false; @@ -98,7 +98,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onDisconnect(NimBLEServer* pServer, ble_gap_conn_desc *desc) { - LOG_DEBUG("BLE disconnect\n"); + LOG_INFO("BLE disconnect\n"); } }; @@ -108,7 +108,7 @@ static NimbleBluetoothFromRadioCallback *fromRadioCallbacks; void NimbleBluetooth::shutdown() { // Shutdown bluetooth for minimum power draw - LOG_DEBUG("Disable bluetooth\n"); + LOG_INFO("Disable bluetooth\n"); //Bluefruit.Advertising.stop(); NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); pAdvertising->reset(); @@ -125,7 +125,7 @@ void NimbleBluetooth::setup() // Uncomment for testing // NimbleBluetooth::clearBonds(); - LOG_DEBUG("Initialise the NimBLE bluetooth module\n"); + LOG_INFO("Initialise the NimBLE bluetooth module\n"); NimBLEDevice::init(getDeviceName()); NimBLEDevice::setPower(ESP_PWR_LVL_P9); @@ -186,7 +186,7 @@ void updateBatteryLevel(uint8_t level) void NimbleBluetooth::clearBonds() { - LOG_DEBUG("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!\n"); NimBLEDevice::deleteAllBonds(); } diff --git a/src/platform/esp32/SimpleAllocator.cpp b/src/platform/esp32/SimpleAllocator.cpp index 4855e8edf..9e2a0c7d2 100644 --- a/src/platform/esp32/SimpleAllocator.cpp +++ b/src/platform/esp32/SimpleAllocator.cpp @@ -9,7 +9,7 @@ void *SimpleAllocator::alloc(size_t size) assert(nextFree + size <= sizeof(bytes)); void *res = &bytes[nextFree]; nextFree += size; - Serial.printf("Total simple allocs %u\n", nextFree); + LOG_DEBUG("Total simple allocs %u\n", nextFree); return res; } @@ -52,7 +52,7 @@ void *operator new(size_t sz) throw(std::bad_alloc) void operator delete(void *ptr) throw() { if (activeAllocator) - Serial.println("Warning: leaking an active allocator object"); // We don't properly handle this yet + LOG_DEBUG("Warning: leaking an active allocator object\n"); // We don't properly handle this yet else free(ptr); } diff --git a/src/platform/nrf52/NRF52Bluetooth.cpp b/src/platform/nrf52/NRF52Bluetooth.cpp index 950d6b7a4..7bbc1a7bb 100644 --- a/src/platform/nrf52/NRF52Bluetooth.cpp +++ b/src/platform/nrf52/NRF52Bluetooth.cpp @@ -33,7 +33,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - LOG_DEBUG("BLE notify fromNum\n"); + LOG_INFO("BLE notify fromNum\n"); fromNum.notify32(fromRadioNum); } @@ -55,7 +55,7 @@ void onConnect(uint16_t conn_handle) char central_name[32] = {0}; connection->getPeerName(central_name, sizeof(central_name)); - LOG_DEBUG("BLE Connected to %s\n", central_name); + LOG_INFO("BLE Connected to %s\n", central_name); } /** @@ -66,21 +66,21 @@ void onConnect(uint16_t conn_handle) void onDisconnect(uint16_t conn_handle, uint8_t reason) { // FIXME - we currently assume only one active connection - LOG_DEBUG("BLE Disconnected, reason = 0x%x\n", reason); + LOG_INFO("BLE Disconnected, reason = 0x%x\n", reason); } void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value) { // Display the raw request packet - LOG_DEBUG("CCCD Updated: %u\n", cccd_value); + LOG_INFO("CCCD Updated: %u\n", cccd_value); // Check the characteristic this CCCD update is associated with in case // this handler is used for multiple CCCD records. if (chr->uuid == fromNum.uuid) { if (chr->notifyEnabled(conn_hdl)) { - LOG_DEBUG("fromNum 'Notify' enabled\n"); + LOG_INFO("fromNum 'Notify' enabled\n"); } else { - LOG_DEBUG("fromNum 'Notify' disabled\n"); + LOG_INFO("fromNum 'Notify' disabled\n"); } } } @@ -135,14 +135,14 @@ void onFromRadioAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_e // or make empty if the queue is empty fromRadio.write(fromRadioBytes, numBytes); } else { - // LOG_DEBUG("Ignoring successor read\n"); + // LOG_INFO("Ignoring successor read\n"); } authorizeRead(conn_hdl); } void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, uint16_t len) { - LOG_DEBUG("toRadioWriteCb data %p, len %u\n", data, len); + LOG_INFO("toRadioWriteCb data %p, len %u\n", data, len); bluetoothPhoneAPI->handleToRadio(data, len); } @@ -152,7 +152,7 @@ void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, ui */ void onFromNumAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_evt_read_t *request) { - LOG_DEBUG("fromNumAuthorizeCb\n"); + LOG_INFO("fromNumAuthorizeCb\n"); authorizeRead(conn_hdl); } @@ -204,14 +204,14 @@ static uint32_t configuredPasskey; void NRF52Bluetooth::shutdown() { // Shutdown bluetooth for minimum power draw - LOG_DEBUG("Disable NRF52 bluetooth\n"); + LOG_INFO("Disable NRF52 bluetooth\n"); Bluefruit.Advertising.stop(); } void NRF52Bluetooth::setup() { // Initialise the Bluefruit module - LOG_DEBUG("Initialize the Bluefruit nRF52 module\n"); + LOG_INFO("Initialize the Bluefruit nRF52 module\n"); Bluefruit.autoConnLed(false); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.begin(); @@ -225,7 +225,7 @@ void NRF52Bluetooth::setup() configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ? config.bluetooth.fixed_pin : random(100000, 999999); auto pinString = std::to_string(configuredPasskey); - LOG_DEBUG("Bluetooth pin set to '%i'\n", configuredPasskey); + LOG_INFO("Bluetooth pin set to '%i'\n", configuredPasskey); Bluefruit.Security.setPIN(pinString.c_str()); Bluefruit.Security.setIOCaps(true, false, false); Bluefruit.Security.setPairPasskeyCallback(NRF52Bluetooth::onPairingPasskey); @@ -248,30 +248,30 @@ void NRF52Bluetooth::setup() bledfu.begin(); // Install the DFU helper // Configure and Start the Device Information Service - LOG_DEBUG("Configuring the Device Information Service\n"); + LOG_INFO("Configuring the Device Information Service\n"); bledis.setModel(optstr(HW_VERSION)); bledis.setFirmwareRev(optstr(APP_VERSION)); bledis.begin(); // Start the BLE Battery Service and set it to 100% - LOG_DEBUG("Configuring the Battery Service\n"); + LOG_INFO("Configuring the Battery Service\n"); blebas.begin(); blebas.write(0); // Unknown battery level for now // Setup the Heart Rate Monitor service using // BLEService and BLECharacteristic classes - LOG_DEBUG("Configuring the Mesh bluetooth service\n"); + LOG_INFO("Configuring the Mesh bluetooth service\n"); setupMeshService(); // Supposedly debugging works with soft device if you disable advertising if (isSoftDeviceAllowed) { // Setup the advertising packet(s) - LOG_DEBUG("Setting up the advertising payload(s)\n"); + LOG_INFO("Setting up the advertising payload(s)\n"); startAdv(); - LOG_DEBUG("Advertising\n"); + LOG_INFO("Advertising\n"); } } @@ -283,7 +283,7 @@ void updateBatteryLevel(uint8_t level) void NRF52Bluetooth::clearBonds() { - LOG_DEBUG("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!\n"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); @@ -293,12 +293,12 @@ void NRF52Bluetooth::clearBonds() void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle) { - LOG_DEBUG("BLE connection secured\n"); + LOG_INFO("BLE connection secured\n"); } bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passkey[6], bool match_request) { - LOG_DEBUG("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3); + LOG_INFO("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3); screen->startBluetoothPinScreen(configuredPasskey); if (match_request) @@ -309,16 +309,16 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke if (!Bluefruit.connected(conn_handle)) break; } } - LOG_DEBUG("BLE passkey pairing: match_request=%i\n", match_request); + LOG_INFO("BLE passkey pairing: match_request=%i\n", match_request); return true; } void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_status) { if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS) - LOG_DEBUG("BLE pairing success\n"); + LOG_INFO("BLE pairing success\n"); else - LOG_DEBUG("BLE pairing failed\n"); + LOG_INFO("BLE pairing failed\n"); screen->stopBluetoothPinScreen(); } diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp index c53c548b5..9a942a606 100644 --- a/src/platform/nrf52/main-nrf52.cpp +++ b/src/platform/nrf52/main-nrf52.cpp @@ -32,7 +32,7 @@ bool loopCanSleep() { // handle standard gcc assert failures void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *failedexpr) { - LOG_DEBUG("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr); + LOG_ERROR("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr); // debugger_break(); FIXME doesn't work, possibly not for segger // Reboot cpu NVIC_SystemReset(); @@ -73,7 +73,7 @@ void setBluetoothEnable(bool on) if (on) { if (!nrf52Bluetooth) { if (!useSoftDevice) - LOG_DEBUG("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); + LOG_INFO("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); else { nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth->setup(); @@ -142,7 +142,7 @@ void nrf52Setup() #ifdef BQ25703A_ADDR auto *bq = new BQ25713(); if (!bq->setup()) - LOG_DEBUG("ERROR! Charge controller init failed\n"); + LOG_ERROR("ERROR! Charge controller init failed\n"); #endif // Init random seed @@ -178,8 +178,7 @@ void cpuDeepSleep(uint64_t msecToWake) auto ok = sd_power_system_off(); if (ok != NRF_SUCCESS) { - LOG_DEBUG("FIXME: Ignoring soft device (EasyDMA pending?) and forcing " - "system-off!\n"); + LOG_ERROR("FIXME: Ignoring soft device (EasyDMA pending?) and forcing system-off!\n"); NRF_POWER->SYSTEMOFF = 1; } diff --git a/src/platform/portduino/SimRadio.cpp b/src/platform/portduino/SimRadio.cpp index 016b91045..87800de22 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -108,9 +108,9 @@ bool SimRadio::canSendImmediately() if (busyTx || busyRx) { if (busyTx) - LOG_DEBUG("Can not send yet, busyTx\n"); + LOG_WARN("Can not send yet, busyTx\n"); if (busyRx) - LOG_DEBUG("Can not send yet, busyRx\n"); + LOG_WARN("Can not send yet, busyRx\n"); return false; } else return true; @@ -199,7 +199,7 @@ void SimRadio::startSend(MeshPacket * txp) memcpy(&c.data.bytes, p->decoded.payload.bytes, p->decoded.payload.size); c.data.size = p->decoded.payload.size; } else { - LOG_DEBUG("Payload size is larger than compressed message allows! Sending empty payload.\n"); + LOG_WARN("Payload size is larger than compressed message allows! Sending empty payload.\n"); } p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Compressed_msg, &c); p->decoded.portnum = PortNum_SIMULATOR_APP; diff --git a/src/shutdown.h b/src/shutdown.h index 23f5d7252..7a57d789a 100644 --- a/src/shutdown.h +++ b/src/shutdown.h @@ -7,14 +7,14 @@ void powerCommandsCheck() { if (rebootAtMsec && millis() > rebootAtMsec) { - LOG_DEBUG("Rebooting\n"); + LOG_INFO("Rebooting\n"); #if defined(ARCH_ESP32) ESP.restart(); #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else rebootAtMsec = -1; - LOG_DEBUG("FIXME implement reboot for this platform. Skipping for now.\n"); + LOG_WARN("FIXME implement reboot for this platform. Skipping for now.\n"); #endif } @@ -35,7 +35,7 @@ void powerCommandsCheck() #endif if (shutdownAtMsec && millis() > shutdownAtMsec) { - LOG_DEBUG("Shutting down from admin command\n"); + LOG_INFO("Shutting down from admin command\n"); #ifdef HAS_PMU if (pmu_found == true) { playShutdownMelody(); @@ -45,7 +45,7 @@ void powerCommandsCheck() playShutdownMelody(); power->shutdown(); #else - LOG_DEBUG("FIXME implement shutdown for this platform"); + LOG_WARN("FIXME implement shutdown for this platform"); #endif } } diff --git a/src/sleep.cpp b/src/sleep.cpp index ee38da699..c85eec3ff 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -90,7 +90,7 @@ void setLed(bool ledOn) void setGPSPower(bool on) { - LOG_DEBUG("Setting GPS power=%d\n", on); + LOG_INFO("Setting GPS power=%d\n", on); #ifdef HAS_PMU if (pmu_found && PMU){ @@ -136,7 +136,7 @@ void initDeepSleep() if (wakeCause == ESP_SLEEP_WAKEUP_TIMER) reason = "timeout"; - LOG_DEBUG("booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason); + LOG_INFO("Booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason); #endif } @@ -174,13 +174,13 @@ void doGPSpowersave(bool on) #ifdef HAS_PMU if (on) { - LOG_DEBUG("Turning GPS back on\n"); + LOG_INFO("Turning GPS back on\n"); gps->forceWake(1); setGPSPower(1); } else { - LOG_DEBUG("Turning off GPS chip\n"); + LOG_INFO("Turning off GPS chip\n"); notifyGPSSleep.notifyObservers(NULL); setGPSPower(0); } @@ -188,12 +188,12 @@ void doGPSpowersave(bool on) #ifdef PIN_GPS_WAKE if (on) { - LOG_DEBUG("Waking GPS"); + LOG_INFO("Waking GPS"); gps->forceWake(1); } else { - LOG_DEBUG("GPS entering sleep"); + LOG_INFO("GPS entering sleep"); notifyGPSSleep.notifyObservers(NULL); } #endif @@ -201,7 +201,7 @@ void doGPSpowersave(bool on) void doDeepSleep(uint64_t msecToWake) { - LOG_DEBUG("Entering deep sleep for %lu seconds\n", msecToWake / 1000); + LOG_INFO("Entering deep sleep for %lu seconds\n", msecToWake / 1000); // not using wifi yet, but once we are this is needed to shutoff the radio hw // esp_wifi_stop(); @@ -310,7 +310,7 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more r esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause(); #ifdef BUTTON_PIN if (cause == ESP_SLEEP_WAKEUP_GPIO) - LOG_DEBUG("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN)); + LOG_INFO("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN)); #endif return cause; From ef1fb877ba806f118a53869ac05f8b4d5b47501a Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Fri, 30 Dec 2022 10:47:31 -0600 Subject: [PATCH 108/119] Prefix log levels --- src/DebugConfiguration.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/DebugConfiguration.h b/src/DebugConfiguration.h index cae83cb18..389a35d81 100644 --- a/src/DebugConfiguration.h +++ b/src/DebugConfiguration.h @@ -13,11 +13,11 @@ #define SERIAL_BAUD 115200 // Serial debug baud rate #endif -#define LOG_LEVEL_DEBUG "DEBUG" -#define LOG_LEVEL_INFO "INFO " -#define LOG_LEVEL_WARN "WARN " -#define LOG_LEVEL_ERROR "ERROR" -#define LOG_LEVEL_TRACE "TRACE" +#define MESHTASTIC_LOG_LEVEL_DEBUG "DEBUG" +#define MESHTASTIC_LOG_LEVEL_INFO "INFO " +#define MESHTASTIC_LOG_LEVEL_WARN "WARN " +#define MESHTASTIC_LOG_LEVEL_ERROR "ERROR" +#define MESHTASTIC_LOG_LEVEL_TRACE "TRACE" #include "SerialConsole.h" @@ -30,11 +30,11 @@ #define LOG_ERROR(...) SEGGER_RTT_printf(0, __VA_ARGS__) #else #ifdef DEBUG_PORT -#define LOG_DEBUG(...) DEBUG_PORT.log(LOG_LEVEL_DEBUG, __VA_ARGS__) -#define LOG_INFO(...) DEBUG_PORT.log(LOG_LEVEL_INFO, __VA_ARGS__) -#define LOG_WARN(...) DEBUG_PORT.log(LOG_LEVEL_WARN, __VA_ARGS__) -#define LOG_ERROR(...) DEBUG_PORT.log(LOG_LEVEL_ERROR, __VA_ARGS__) -#define LOG_TRACE(...) DEBUG_PORT.log(LOG_TRACE, __VA_ARGS__) +#define LOG_DEBUG(...) DEBUG_PORT.log(MESHTASTIC_LOG_LEVEL_DEBUG, __VA_ARGS__) +#define LOG_INFO(...) DEBUG_PORT.log(MESHTASTIC_LOG_LEVEL_INFO, __VA_ARGS__) +#define LOG_WARN(...) DEBUG_PORT.log(MESHTASTIC_LOG_LEVEL_WARN, __VA_ARGS__) +#define LOG_ERROR(...) DEBUG_PORT.log(MESHTASTIC_LOG_LEVEL_ERROR, __VA_ARGS__) +#define LOG_TRACE(...) DEBUG_PORT.log(MESHTASTIC_LOG_TRACE, __VA_ARGS__) #else #define LOG_DEBUG(...) #define LOG_INFO(...) From 3d3aba584efb991edbd62bfe5e435a35e281d02f Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Fri, 30 Dec 2022 10:56:57 -0600 Subject: [PATCH 109/119] Include --- src/platform/esp32/SimpleAllocator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/platform/esp32/SimpleAllocator.cpp b/src/platform/esp32/SimpleAllocator.cpp index 9e2a0c7d2..0fb6677d2 100644 --- a/src/platform/esp32/SimpleAllocator.cpp +++ b/src/platform/esp32/SimpleAllocator.cpp @@ -1,6 +1,6 @@ -#include "SimpleAllocator.h" #include "assert.h" - +#include "configuration.h" +#include "SimpleAllocator.h" SimpleAllocator::SimpleAllocator() { reset(); } From 19436b7d547b0c2f6c48fc050ae836010f59d52d Mon Sep 17 00:00:00 2001 From: Joshua Pirihi Date: Sat, 31 Dec 2022 06:40:02 +1300 Subject: [PATCH 110/119] Increase MQTT buffer size --- src/mqtt/MQTT.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index df2d9b093..6637c324a 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -165,6 +165,7 @@ void MQTT::reconnect() serverAddr = server.c_str(); } pubSub.setServer(serverAddr, serverPort); + pubSub.setBufferSize(512); DEBUG_MSG("Connecting to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, serverPort, mqttUsername, mqttPassword); auto myStatus = (statusTopic + owner.id); From 092a753a6f938342fed358a8eb165f376ef94659 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Fri, 30 Dec 2022 20:27:35 +0100 Subject: [PATCH 111/119] yea, well --- src/concurrency/OSThread.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 4bf4baa8c..2e5ee0ba8 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -82,9 +82,9 @@ void OSThread::run() #ifdef DEBUG_HEAP auto newHeap = ESP.getFreeHeap(); if (newHeap < heap) - DEBUG_MSG("------ Thread %s leaked heap %d -> %d (%d) ------\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + LOG_DEBUG("------ Thread %s leaked heap %d -> %d (%d) ------\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); if (heap < newHeap) - DEBUG_MSG("++++++ Thread %s freed heap %d -> %d (%d) ++++++\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + LOG_DEBUG("++++++ Thread %s freed heap %d -> %d (%d) ++++++\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); #endif runned(); From b55fe549e3cb27e4753f7f062bd9621ec45e17f4 Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Sat, 31 Dec 2022 20:10:44 -0600 Subject: [PATCH 112/119] Update CI badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5bae2f345..533fb8af2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Meshtastic Firmware ![GitHub release downloads](https://img.shields.io/github/downloads/meshtastic/firmware/total) -[![CI](https://img.shields.io/github/workflow/status/meshtastic/firmware/CI?label=actions&logo=github&color=yellow)](https://github.com/meshtastic/firmware/actions/workflows/main_matrix.yml) +![GitHub Workflow Status (with branch)](https://img.shields.io/github/actions/workflow/status/meshtastic/firmware/main_matrix.yml?branch=master&label=CI) [![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/firmware)](https://cla-assistant.io/meshtastic/firmware) [![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) [![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) From 2d62cbe345ee7be3937b54fbd32b901c27644bf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 1 Jan 2023 21:08:07 +0100 Subject: [PATCH 113/119] I am dumb. --- src/modules/Modules.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index 96a6c0582..cd873a466 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -75,7 +75,7 @@ void setupModules() new RangeTestModule(); #elif defined(ARCH_NRF52) - new ExternalNotificationModule(); + externalNotificationModule = new ExternalNotificationModule(); #endif // NOTE! This module must be added LAST because it likes to check for replies from other modules and avoid sending extra acks From 63c8ca9ca58194537cd6eaaa3342fc35cfbc8e02 Mon Sep 17 00:00:00 2001 From: Sacha Weatherstone Date: Mon, 2 Jan 2023 16:44:05 +1100 Subject: [PATCH 114/119] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 533fb8af2..d9698fa57 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Meshtastic Firmware ![GitHub release downloads](https://img.shields.io/github/downloads/meshtastic/firmware/total) -![GitHub Workflow Status (with branch)](https://img.shields.io/github/actions/workflow/status/meshtastic/firmware/main_matrix.yml?branch=master&label=CI) +[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/firmware/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/firmware/actions/workflows/ci.yml) [![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/firmware)](https://cla-assistant.io/meshtastic/firmware) [![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) [![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) From 1077846e8deba788a528d7932dc88d2db2013de3 Mon Sep 17 00:00:00 2001 From: Sacha Weatherstone Date: Mon, 2 Jan 2023 16:44:38 +1100 Subject: [PATCH 115/119] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d9698fa57..d450b88d3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Meshtastic Firmware ![GitHub release downloads](https://img.shields.io/github/downloads/meshtastic/firmware/total) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/firmware/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/firmware/actions/workflows/ci.yml) +[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/firmware/main_matrix.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/firmware/actions/workflows/ci.yml) [![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/firmware)](https://cla-assistant.io/meshtastic/firmware) [![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) [![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) From bca70d10d02619c816aa64f66b96f118a072904b Mon Sep 17 00:00:00 2001 From: thebentern Date: Tue, 3 Jan 2023 12:20:39 +0000 Subject: [PATCH 116/119] [create-pull-request] automated change --- protobufs | 2 +- src/mesh/generated/config.pb.h | 26 +++++++++++++------------- src/mesh/generated/telemetry.pb.h | 8 ++++---- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/protobufs b/protobufs index e406029f6..6048ecd2f 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit e406029f68d8a554f43fd1f250baca6b3c1a9a33 +Subproject commit 6048ecd2f8433005bb73ab4505386a7bbdb78c86 diff --git a/src/mesh/generated/config.pb.h b/src/mesh/generated/config.pb.h index a5f7694cb..38e53d0c8 100644 --- a/src/mesh/generated/config.pb.h +++ b/src/mesh/generated/config.pb.h @@ -60,12 +60,12 @@ typedef enum _Config_PositionConfig_PositionFlags { Config_PositionConfig_PositionFlags_SPEED = 512 } Config_PositionConfig_PositionFlags; -typedef enum _Config_NetworkConfig_EthMode { +typedef enum _Config_NetworkConfig_AddressMode { /* obtain ip address via DHCP */ - Config_NetworkConfig_EthMode_DHCP = 0, + Config_NetworkConfig_AddressMode_DHCP = 0, /* use static ip address */ - Config_NetworkConfig_EthMode_STATIC = 1 -} Config_NetworkConfig_EthMode; + Config_NetworkConfig_AddressMode_STATIC = 1 +} Config_NetworkConfig_AddressMode; /* How the GPS coordinates are displayed on the OLED screen. */ typedef enum _Config_DisplayConfig_GpsCoordinateFormat { @@ -292,7 +292,7 @@ typedef struct _Config_NetworkConfig { /* Enable Ethernet */ bool eth_enabled; /* acquire an address via DHCP or assign static */ - Config_NetworkConfig_EthMode eth_mode; + Config_NetworkConfig_AddressMode address_mode; /* struct to keep static address */ bool has_ipv4_config; Config_NetworkConfig_IpV4Config ipv4_config; @@ -416,9 +416,9 @@ extern "C" { #define _Config_PositionConfig_PositionFlags_MAX Config_PositionConfig_PositionFlags_SPEED #define _Config_PositionConfig_PositionFlags_ARRAYSIZE ((Config_PositionConfig_PositionFlags)(Config_PositionConfig_PositionFlags_SPEED+1)) -#define _Config_NetworkConfig_EthMode_MIN Config_NetworkConfig_EthMode_DHCP -#define _Config_NetworkConfig_EthMode_MAX Config_NetworkConfig_EthMode_STATIC -#define _Config_NetworkConfig_EthMode_ARRAYSIZE ((Config_NetworkConfig_EthMode)(Config_NetworkConfig_EthMode_STATIC+1)) +#define _Config_NetworkConfig_AddressMode_MIN Config_NetworkConfig_AddressMode_DHCP +#define _Config_NetworkConfig_AddressMode_MAX Config_NetworkConfig_AddressMode_STATIC +#define _Config_NetworkConfig_AddressMode_ARRAYSIZE ((Config_NetworkConfig_AddressMode)(Config_NetworkConfig_AddressMode_STATIC+1)) #define _Config_DisplayConfig_GpsCoordinateFormat_MIN Config_DisplayConfig_GpsCoordinateFormat_DEC #define _Config_DisplayConfig_GpsCoordinateFormat_MAX Config_DisplayConfig_GpsCoordinateFormat_OSGR @@ -453,7 +453,7 @@ extern "C" { -#define Config_NetworkConfig_eth_mode_ENUMTYPE Config_NetworkConfig_EthMode +#define Config_NetworkConfig_address_mode_ENUMTYPE Config_NetworkConfig_AddressMode #define Config_DisplayConfig_gps_format_ENUMTYPE Config_DisplayConfig_GpsCoordinateFormat @@ -472,7 +472,7 @@ extern "C" { #define Config_DeviceConfig_init_default {_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0} #define Config_PositionConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} #define Config_PowerConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0} -#define Config_NetworkConfig_init_default {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_default} +#define Config_NetworkConfig_init_default {0, "", "", "", 0, _Config_NetworkConfig_AddressMode_MIN, false, Config_NetworkConfig_IpV4Config_init_default} #define Config_NetworkConfig_IpV4Config_init_default {0, 0, 0, 0} #define Config_DisplayConfig_init_default {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} #define Config_LoRaConfig_init_default {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} @@ -481,7 +481,7 @@ extern "C" { #define Config_DeviceConfig_init_zero {_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0} #define Config_PositionConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} #define Config_PowerConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0} -#define Config_NetworkConfig_init_zero {0, "", "", "", 0, _Config_NetworkConfig_EthMode_MIN, false, Config_NetworkConfig_IpV4Config_init_zero} +#define Config_NetworkConfig_init_zero {0, "", "", "", 0, _Config_NetworkConfig_AddressMode_MIN, false, Config_NetworkConfig_IpV4Config_init_zero} #define Config_NetworkConfig_IpV4Config_init_zero {0, 0, 0, 0} #define Config_DisplayConfig_init_zero {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} #define Config_LoRaConfig_init_zero {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} @@ -519,7 +519,7 @@ extern "C" { #define Config_NetworkConfig_wifi_psk_tag 4 #define Config_NetworkConfig_ntp_server_tag 5 #define Config_NetworkConfig_eth_enabled_tag 6 -#define Config_NetworkConfig_eth_mode_tag 7 +#define Config_NetworkConfig_address_mode_tag 7 #define Config_NetworkConfig_ipv4_config_tag 8 #define Config_DisplayConfig_screen_on_secs_tag 1 #define Config_DisplayConfig_gps_format_tag 2 @@ -613,7 +613,7 @@ X(a, STATIC, SINGULAR, STRING, wifi_ssid, 3) \ X(a, STATIC, SINGULAR, STRING, wifi_psk, 4) \ X(a, STATIC, SINGULAR, STRING, ntp_server, 5) \ X(a, STATIC, SINGULAR, BOOL, eth_enabled, 6) \ -X(a, STATIC, SINGULAR, UENUM, eth_mode, 7) \ +X(a, STATIC, SINGULAR, UENUM, address_mode, 7) \ X(a, STATIC, OPTIONAL, MESSAGE, ipv4_config, 8) #define Config_NetworkConfig_CALLBACK NULL #define Config_NetworkConfig_DEFAULT NULL diff --git a/src/mesh/generated/telemetry.pb.h b/src/mesh/generated/telemetry.pb.h index 1b294dc1a..e5c71a2b7 100644 --- a/src/mesh/generated/telemetry.pb.h +++ b/src/mesh/generated/telemetry.pb.h @@ -71,10 +71,10 @@ typedef struct _EnvironmentMetrics { /* Types of Measurements the telemetry module is equipped to handle */ typedef struct _Telemetry { - /* This is usually not sent over the mesh (to save space), but it is sent - from the phone so that the local device can set its RTC If it is sent over - the mesh (because there are devices on the mesh without GPS), it will only - be sent by devices which has a hardware GPS clock (IE Mobile Phone). + /* This is usually not sent over the mesh (to save space), but it is sent + from the phone so that the local device can set its RTC If it is sent over + the mesh (because there are devices on the mesh without GPS), it will only + be sent by devices which has a hardware GPS clock (IE Mobile Phone). seconds since 1970 */ uint32_t time; pb_size_t which_variant; From 021fc8235c80af5cb84c8fc4a010df0a7cac859e Mon Sep 17 00:00:00 2001 From: Ben Meadors Date: Tue, 3 Jan 2023 06:24:47 -0600 Subject: [PATCH 117/119] Renamed eth_mode to address_mode --- src/mesh/eth/ethClient.cpp | 4 ++-- src/mesh/http/WiFiAPClient.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mesh/eth/ethClient.cpp b/src/mesh/eth/ethClient.cpp index 588913781..29f55ebee 100644 --- a/src/mesh/eth/ethClient.cpp +++ b/src/mesh/eth/ethClient.cpp @@ -95,10 +95,10 @@ bool initEthernet() getMacAddr(mac); // FIXME use the BLE MAC for now... - if (config.network.eth_mode == Config_NetworkConfig_EthMode_DHCP) { + if (config.network.address_mode == Config_NetworkConfig_AddressMode_DHCP) { LOG_INFO("starting Ethernet DHCP\n"); status = Ethernet.begin(mac); - } else if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC) { + } else if (config.network.address_mode == Config_NetworkConfig_AddressMode_STATIC) { LOG_INFO("starting Ethernet Static\n"); Ethernet.begin(mac, config.network.ipv4_config.ip, config.network.ipv4_config.dns, config.network.ipv4_config.subnet); } else { diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index cba09dd7c..ec34f9927 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -169,7 +169,7 @@ bool initWifi() WiFi.onEvent(WiFiEvent); WiFi.setAutoReconnect(false); WiFi.setSleep(false); - if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC && config.network.ipv4_config.ip != 0) { + if (config.network.address_mode == Config_NetworkConfig_AddressMode_STATIC && config.network.ipv4_config.ip != 0) { WiFi.config(config.network.ipv4_config.ip, config.network.ipv4_config.gateway, config.network.ipv4_config.subnet, From 52903f83e3e0eacf8cfc379e81ef91043baa2e04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 3 Jan 2023 19:19:11 +0100 Subject: [PATCH 118/119] remove Merge duplication --- src/detect/i2cScan.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/detect/i2cScan.h b/src/detect/i2cScan.h index 482a24a57..77d1fff17 100644 --- a/src/detect/i2cScan.h +++ b/src/detect/i2cScan.h @@ -195,10 +195,6 @@ void scanI2Cdevice() LOG_INFO("SHT31 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; } - if (addr == SHT31_ADDR) { - DEBUG_MSG("SHT31 sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; - } if (addr == SHTC3_ADDR) { LOG_INFO("SHTC3 sensor found\n"); nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; From 64895cc7eb891fd938d4a4ce91b15d704071fcfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Tue, 3 Jan 2023 19:21:11 +0100 Subject: [PATCH 119/119] remove Merge duplication --- src/graphics/Screen.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index cfa30a21b..53ca75a51 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -545,23 +545,6 @@ static void drawGPSpowerstat(OLEDDisplay *display, int16_t x, int16_t y, const G #endif } -//Draw status when gps is disabled by PMU -static void drawGPSpowerstat(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps) -{ -#ifdef HAS_PMU - String displayLine = "GPS disabled"; - int16_t xPos = display->getStringWidth(displayLine); - - if (!config.position.gps_enabled){ - display->drawString(x + xPos, y, displayLine); -#ifdef GPS_POWER_TOGGLE - display->drawString(x + xPos, y - 2 + FONT_HEIGHT_SMALL, " by button"); -#endif - //display->drawString(x + xPos, y + 2, displayLine); - } -#endif -} - static void drawGPSAltitude(OLEDDisplay *display, int16_t x, int16_t y, const GPSStatus *gps) { String displayLine = "";