Merge pull request #2081 from meshtastic/log-levels

Created more structured enterprisey logging with levels
This commit is contained in:
Ben Meadors
2022-12-30 11:30:23 -06:00
committed by GitHub
92 changed files with 1069 additions and 1062 deletions

View File

@@ -98,8 +98,8 @@ class ButtonThread : public concurrency::OSThread
userButtonTouch.tick(); userButtonTouch.tick();
canSleep &= userButtonTouch.isIdle(); canSleep &= userButtonTouch.isIdle();
#endif #endif
// if (!canSleep) DEBUG_MSG("Supressing sleep!\n"); // if (!canSleep) LOG_DEBUG("Supressing sleep!\n");
// else DEBUG_MSG("sleep ok\n"); // else LOG_DEBUG("sleep ok\n");
return 5; return 5;
} }
@@ -108,12 +108,12 @@ class ButtonThread : public concurrency::OSThread
static void touchPressed() static void touchPressed()
{ {
screen->forceDisplay(); screen->forceDisplay();
DEBUG_MSG("touch press!\n"); LOG_DEBUG("touch press!\n");
} }
static void userButtonPressed() static void userButtonPressed()
{ {
// DEBUG_MSG("press!\n"); // LOG_DEBUG("press!\n");
#ifdef BUTTON_PIN #ifdef BUTTON_PIN
if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) ||
!moduleConfig.canned_message.enabled) { !moduleConfig.canned_message.enabled) {
@@ -123,7 +123,7 @@ class ButtonThread : public concurrency::OSThread
} }
static void userButtonPressedLong() static void userButtonPressedLong()
{ {
// DEBUG_MSG("Long press!\n"); // LOG_DEBUG("Long press!\n");
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
screen->adjustBrightness(); screen->adjustBrightness();
#endif #endif
@@ -139,7 +139,7 @@ class ButtonThread : public concurrency::OSThread
// may wake the board immediatedly. // may wake the board immediatedly.
if ((!shutdown_on_long_stop) && (millis() > 30 * 1000)) { if ((!shutdown_on_long_stop) && (millis() > 30 * 1000)) {
screen->startShutdownScreen(); screen->startShutdownScreen();
DEBUG_MSG("Shutdown from long press"); LOG_INFO("Shutdown from long press");
playBeep(); playBeep();
#ifdef PIN_LED1 #ifdef PIN_LED1
ledOff(PIN_LED1); ledOff(PIN_LED1);
@@ -154,7 +154,7 @@ class ButtonThread : public concurrency::OSThread
} }
#endif #endif
} else { } 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 defined(GPS_POWER_TOGGLE)
if(config.position.gps_enabled) 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 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); config.position.gps_enabled = !(config.position.gps_enabled);
doGPSpowersave(config.position.gps_enabled); doGPSpowersave(config.position.gps_enabled);
@@ -187,7 +187,7 @@ class ButtonThread : public concurrency::OSThread
static void userButtonPressedLongStart() static void userButtonPressedLongStart()
{ {
if (millis() > 30 * 1000) { if (millis() > 30 * 1000) {
DEBUG_MSG("Long press start!\n"); LOG_DEBUG("Long press start!\n");
longPressTime = millis(); longPressTime = millis();
} }
} }
@@ -195,7 +195,7 @@ class ButtonThread : public concurrency::OSThread
static void userButtonPressedLongStop() static void userButtonPressedLongStop()
{ {
if (millis() > 30 * 1000) { if (millis() > 30 * 1000) {
DEBUG_MSG("Long press stop!\n"); LOG_DEBUG("Long press stop!\n");
longPressTime = 0; longPressTime = 0;
if (shutdown_on_long_stop) { if (shutdown_on_long_stop) {
playShutdownMelody(); playShutdownMelody();

View File

@@ -13,17 +13,33 @@
#define SERIAL_BAUD 115200 // Serial debug baud rate #define SERIAL_BAUD 115200 // Serial debug baud rate
#endif #endif
#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" #include "SerialConsole.h"
#define DEBUG_PORT (*console) // Serial debug port #define DEBUG_PORT (*console) // Serial debug port
#ifdef USE_SEGGER #ifdef USE_SEGGER
#define DEBUG_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 #else
#ifdef DEBUG_PORT #ifdef DEBUG_PORT
#define DEBUG_MSG(...) DEBUG_PORT.logDebug(__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 #else
#define DEBUG_MSG(...) #define LOG_DEBUG(...)
#define LOG_INFO(...)
#define LOG_WARN(...)
#define LOG_ERROR(...)
#endif #endif
#endif #endif

View File

@@ -21,13 +21,13 @@ bool copyFile(const char* from, const char* to)
File f1 = FSCom.open(from, FILE_O_READ); File f1 = FSCom.open(from, FILE_O_READ);
if (!f1){ if (!f1){
DEBUG_MSG("Failed to open source file %s\n", from); LOG_ERROR("Failed to open source file %s\n", from);
return false; return false;
} }
File f2 = FSCom.open(to, FILE_O_WRITE); File f2 = FSCom.open(to, FILE_O_WRITE);
if (!f2) { if (!f2) {
DEBUG_MSG("Failed to open destination file %s\n", to); LOG_ERROR("Failed to open destination file %s\n", to);
return false; return false;
} }
@@ -79,7 +79,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false)
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
listDir(file.path(), levels -1, del); listDir(file.path(), levels -1, del);
if(del) { if(del) {
DEBUG_MSG("Removing %s\n", file.path()); LOG_DEBUG("Removing %s\n", file.path());
strcpy(buffer, file.path()); strcpy(buffer, file.path());
file.close(); file.close();
FSCom.rmdir(buffer); 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)) #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO))
listDir(file.name(), levels -1, del); listDir(file.name(), levels -1, del);
if(del) { if(del) {
DEBUG_MSG("Removing %s\n", file.name()); LOG_DEBUG("Removing %s\n", file.name());
strcpy(buffer, file.name()); strcpy(buffer, file.name());
file.close(); file.close();
FSCom.rmdir(buffer); FSCom.rmdir(buffer);
@@ -104,26 +104,26 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false)
} else { } else {
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
if(del) { if(del) {
DEBUG_MSG("Deleting %s\n", file.path()); LOG_DEBUG("Deleting %s\n", file.path());
strcpy(buffer, file.path()); strcpy(buffer, file.path());
file.close(); file.close();
FSCom.remove(buffer); FSCom.remove(buffer);
} else { } else {
DEBUG_MSG(" %s (%i Bytes)\n", file.path(), file.size()); LOG_DEBUG(" %s (%i Bytes)\n", file.path(), file.size());
file.close(); file.close();
} }
#elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO))
if(del) { if(del) {
DEBUG_MSG("Deleting %s\n", file.name()); LOG_DEBUG("Deleting %s\n", file.name());
strcpy(buffer, file.name()); strcpy(buffer, file.name());
file.close(); file.close();
FSCom.remove(buffer); FSCom.remove(buffer);
} else { } else {
DEBUG_MSG(" %s (%i Bytes)\n", file.name(), file.size()); LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size());
file.close(); file.close();
} }
#else #else
DEBUG_MSG(" %s (%i Bytes)\n", file.name(), file.size()); LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size());
file.close(); file.close();
#endif #endif
} }
@@ -131,7 +131,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false)
} }
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
if(del) { if(del) {
DEBUG_MSG("Removing %s\n", root.path()); LOG_DEBUG("Removing %s\n", root.path());
strcpy(buffer, root.path()); strcpy(buffer, root.path());
root.close(); root.close();
FSCom.rmdir(buffer); 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)) #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO))
if(del) { if(del) {
DEBUG_MSG("Removing %s\n", root.name()); LOG_DEBUG("Removing %s\n", root.name());
strcpy(buffer, root.name()); strcpy(buffer, root.name());
root.close(); root.close();
FSCom.rmdir(buffer); FSCom.rmdir(buffer);
@@ -170,13 +170,13 @@ void fsInit()
#ifdef FSCom #ifdef FSCom
if (!FSBegin()) if (!FSBegin())
{ {
DEBUG_MSG("ERROR filesystem mount Failed. Formatting...\n"); LOG_ERROR("Filesystem mount Failed. Formatting...\n");
assert(0); // FIXME - report failure to phone assert(0); // FIXME - report failure to phone
} }
#ifdef ARCH_ESP32 #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 #else
DEBUG_MSG("Filesystem files:\n"); LOG_DEBUG("Filesystem files:\n");
#endif #endif
listDir("/", 10); listDir("/", 10);
#endif #endif
@@ -189,29 +189,29 @@ void setupSDCard()
SDHandler.begin(SPI_SCK, SPI_MISO, SPI_MOSI); SDHandler.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
if (!SD.begin(SDCARD_CS, SDHandler)) { if (!SD.begin(SDCARD_CS, SDHandler)) {
DEBUG_MSG("No SD_MMC card detected\n"); LOG_DEBUG("No SD_MMC card detected\n");
return ; return ;
} }
uint8_t cardType = SD.cardType(); uint8_t cardType = SD.cardType();
if (cardType == CARD_NONE) { if (cardType == CARD_NONE) {
DEBUG_MSG("No SD_MMC card attached\n"); LOG_DEBUG("No SD_MMC card attached\n");
return ; return ;
} }
DEBUG_MSG("SD_MMC Card Type: "); LOG_DEBUG("SD_MMC Card Type: ");
if (cardType == CARD_MMC) { if (cardType == CARD_MMC) {
DEBUG_MSG("MMC\n"); LOG_DEBUG("MMC\n");
} else if (cardType == CARD_SD) { } else if (cardType == CARD_SD) {
DEBUG_MSG("SDSC\n"); LOG_DEBUG("SDSC\n");
} else if (cardType == CARD_SDHC) { } else if (cardType == CARD_SDHC) {
DEBUG_MSG("SDHC\n"); LOG_DEBUG("SDHC\n");
} else { } else {
DEBUG_MSG("UNKNOWN\n"); LOG_DEBUG("UNKNOWN\n");
} }
uint64_t cardSize = SD.cardSize() / (1024 * 1024); uint64_t cardSize = SD.cardSize() / (1024 * 1024);
DEBUG_MSG("SD Card Size: %lluMB\n", cardSize); LOG_DEBUG("SD Card Size: %lluMB\n", cardSize);
DEBUG_MSG("Total space: %llu MB\n", SD.totalBytes() / (1024 * 1024)); LOG_DEBUG("Total space: %llu MB\n", SD.totalBytes() / (1024 * 1024));
DEBUG_MSG("Used space: %llu MB\n", SD.usedBytes() / (1024 * 1024)); LOG_DEBUG("Used space: %llu MB\n", SD.usedBytes() / (1024 * 1024));
#endif #endif
} }

View File

@@ -53,7 +53,7 @@ class GPSStatus : public Status
{ {
if (config.position.fixed_position) { if (config.position.fixed_position) {
#ifdef GPS_EXTRAVERBOSE #ifdef GPS_EXTRAVERBOSE
DEBUG_MSG("WARNING: Using fixed latitude\n"); LOG_WARN("Using fixed latitude\n");
#endif #endif
NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum());
return node->position.latitude_i; return node->position.latitude_i;
@@ -66,7 +66,7 @@ class GPSStatus : public Status
{ {
if (config.position.fixed_position) { if (config.position.fixed_position) {
#ifdef GPS_EXTRAVERBOSE #ifdef GPS_EXTRAVERBOSE
DEBUG_MSG("WARNING: Using fixed longitude\n"); LOG_WARN("Using fixed longitude\n");
#endif #endif
NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum());
return node->position.longitude_i; return node->position.longitude_i;
@@ -79,7 +79,7 @@ class GPSStatus : public Status
{ {
if (config.position.fixed_position) { if (config.position.fixed_position) {
#ifdef GPS_EXTRAVERBOSE #ifdef GPS_EXTRAVERBOSE
DEBUG_MSG("WARNING: Using fixed altitude\n"); LOG_WARN("Using fixed altitude\n");
#endif #endif
NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum());
return node->position.altitude; return node->position.altitude;
@@ -97,7 +97,7 @@ class GPSStatus : public Status
bool matches(const GPSStatus *newStatus) const bool matches(const GPSStatus *newStatus) const
{ {
#ifdef GPS_EXTRAVERBOSE #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 #endif
return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || newStatus->isPowerSaving !=isPowerSaving || 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.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)) { if (isDirty && p.timestamp && (newStatus->p.timestamp == p.timestamp)) {
// We can NEVER be in two locations at the same time! (also PR #886) // 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_ERROR("BUG: Positional timestamp unchanged from prev solution\n");
} }
initialized = true; initialized = true;
@@ -126,11 +126,11 @@ class GPSStatus : public Status
if (isDirty) { if (isDirty) {
if (hasLock) { if (hasLock) {
// In debug logs, identify position by @timestamp:stage (stage 3 = notify) // 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.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); p.ground_speed * 1e-2, p.sats_in_view);
} else } else
DEBUG_MSG("No GPS lock\n"); LOG_DEBUG("No GPS lock\n");
onNewStatus.notifyObservers(this); onNewStatus.notifyObservers(this);
} }
return 0; return 0;

View File

@@ -70,7 +70,7 @@ namespace meshtastic {
numTotal = newStatus->getNumTotal(); numTotal = newStatus->getNumTotal();
} }
if(isDirty || newStatus->forceUpdate) { 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); onNewStatus.notifyObservers(this);
} }
return 0; return 0;

View File

@@ -129,7 +129,7 @@ class AnalogBatteryLevel : public HasBatteryLevel
#else #else
scaled = VBAT_RAW_TO_SCALED(raw); // defined in variant.h scaled = VBAT_RAW_TO_SCALED(raw); // defined in variant.h
#endif #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; last_read_value = scaled;
return scaled; return scaled;
} else { } else {
@@ -190,7 +190,7 @@ Power::Power() : OSThread("Power")
bool Power::analogInit() bool Power::analogInit()
{ {
#ifdef BATTERY_PIN #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 // disable any internal pullups
pinMode(BATTERY_PIN, INPUT); pinMode(BATTERY_PIN, INPUT);
@@ -242,7 +242,7 @@ void Power::shutdown()
#endif #endif
#ifdef HAS_PMU #ifdef HAS_PMU
DEBUG_MSG("Shutting down\n"); LOG_INFO("Shutting down\n");
if(PMU) { if(PMU) {
PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF); PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF);
PMU->shutdown(); PMU->shutdown();
@@ -283,12 +283,12 @@ void Power::readPowerStatus()
const PowerStatus powerStatus2 = const PowerStatus powerStatus2 =
PowerStatus(hasBattery ? OptTrue : OptFalse, batteryLevel->isVbusIn() ? OptTrue : OptFalse, PowerStatus(hasBattery ? OptTrue : OptFalse, batteryLevel->isVbusIn() ? OptTrue : OptFalse,
batteryLevel->isCharging() ? OptTrue : OptFalse, batteryVoltageMv, batteryChargePercent); 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()); powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent());
newStatus.notifyObservers(&powerStatus2); newStatus.notifyObservers(&powerStatus2);
#ifdef DEBUG_HEAP #ifdef DEBUG_HEAP
if (lastheap != ESP.getFreeHeap()){ 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(); lastheap = ESP.getFreeHeap();
} }
#endif #endif
@@ -299,11 +299,11 @@ void Power::readPowerStatus()
if (powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) { if (powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) {
if (batteryLevel->getBattVoltage() < MIN_BAT_MILLIVOLTS) { if (batteryLevel->getBattVoltage() < MIN_BAT_MILLIVOLTS) {
low_voltage_counter++; 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) { if (low_voltage_counter > 10) {
// We can't trigger deep sleep on NRF52, it's freezing the board // We can't trigger deep sleep on NRF52, it's freezing the board
//powerFSM.trigger(EVENT_LOW_BATTERY); //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 { } else {
low_voltage_counter = 0; low_voltage_counter = 0;
@@ -333,12 +333,12 @@ int32_t Power::runOnce()
PMU->getIrqStatus(); PMU->getIrqStatus();
if(PMU->isVbusRemoveIrq()){ if(PMU->isVbusRemoveIrq()){
DEBUG_MSG("USB unplugged\n"); LOG_INFO("USB unplugged\n");
powerFSM.trigger(EVENT_POWER_DISCONNECTED); powerFSM.trigger(EVENT_POWER_DISCONNECTED);
} }
if (PMU->isVbusInsertIrq()) { if (PMU->isVbusInsertIrq()) {
DEBUG_MSG("USB plugged In\n"); LOG_INFO("USB plugged In\n");
powerFSM.trigger(EVENT_POWER_CONNECTED); powerFSM.trigger(EVENT_POWER_CONNECTED);
} }
@@ -346,20 +346,20 @@ int32_t Power::runOnce()
Other things we could check if we cared... Other things we could check if we cared...
if (PMU->isBatChagerStartIrq()) { if (PMU->isBatChagerStartIrq()) {
DEBUG_MSG("Battery start charging\n"); LOG_DEBUG("Battery start charging\n");
} }
if (PMU->isBatChagerDoneIrq()) { if (PMU->isBatChagerDoneIrq()) {
DEBUG_MSG("Battery fully charged\n"); LOG_DEBUG("Battery fully charged\n");
} }
if (PMU->isBatInsertIrq()) { if (PMU->isBatInsertIrq()) {
DEBUG_MSG("Battery inserted\n"); LOG_DEBUG("Battery inserted\n");
} }
if (PMU->isBatRemoveIrq()) { if (PMU->isBatRemoveIrq()) {
DEBUG_MSG("Battery removed\n"); LOG_DEBUG("Battery removed\n");
} }
*/ */
if (PMU->isPekeyLongPressIrq()) { if (PMU->isPekeyLongPressIrq()) {
DEBUG_MSG("PEK long button press\n"); LOG_DEBUG("PEK long button press\n");
screen->setOn(false); screen->setOn(false);
} }
@@ -401,22 +401,22 @@ bool Power::axpChipInit()
if (!PMU) { if (!PMU) {
PMU = new XPowersAXP2101(*w); PMU = new XPowersAXP2101(*w);
if (!PMU->init()) { if (!PMU->init()) {
DEBUG_MSG("Warning: Failed to find AXP2101 power management\n"); LOG_WARN("Failed to find AXP2101 power management\n");
delete PMU; delete PMU;
PMU = NULL; PMU = NULL;
} else { } else {
DEBUG_MSG("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); LOG_INFO("AXP2101 PMU init succeeded, using AXP2101 PMU\n");
} }
} }
if (!PMU) { if (!PMU) {
PMU = new XPowersAXP192(*w); PMU = new XPowersAXP192(*w);
if (!PMU->init()) { if (!PMU->init()) {
DEBUG_MSG("Warning: Failed to find AXP192 power management\n"); LOG_WARN("Failed to find AXP192 power management\n");
delete PMU; delete PMU;
PMU = NULL; PMU = NULL;
} else { } else {
DEBUG_MSG("AXP192 PMU init succeeded, using AXP192 PMU\n"); LOG_INFO("AXP192 PMU init succeeded, using AXP192 PMU\n");
} }
} }
@@ -538,44 +538,44 @@ bool Power::axpChipInit()
PMU->enableVbusVoltageMeasure(); PMU->enableVbusVoltageMeasure();
PMU->enableBattVoltageMeasure(); PMU->enableBattVoltageMeasure();
DEBUG_MSG("=======================================================================\n"); LOG_DEBUG("=======================================================================\n");
if (PMU->isChannelAvailable(XPOWERS_DCDC1)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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)) { 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 // We can safely ignore this approach for most (or all) boards because MCU turned off
// earlier than battery discharged to 2.6V. // earlier than battery discharged to 2.6V.

View File

@@ -32,7 +32,7 @@ static bool isPowered()
static void sdsEnter() static void sdsEnter()
{ {
DEBUG_MSG("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 // FIXME - make sure GPS and LORA radio are off first - because we want close to zero current draw
doDeepSleep(getConfiguredOrDefaultMs(config.power.sds_secs)); doDeepSleep(getConfiguredOrDefaultMs(config.power.sds_secs));
} }
@@ -41,7 +41,7 @@ extern Power *power;
static void shutdownEnter() static void shutdownEnter()
{ {
DEBUG_MSG("Enter state: SHUTDOWN\n"); LOG_INFO("Enter state: SHUTDOWN\n");
power->shutdown(); power->shutdown();
} }
@@ -51,16 +51,16 @@ static uint32_t secsSlept;
static void lsEnter() static void lsEnter()
{ {
DEBUG_MSG("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); screen->setOn(false);
secsSlept = 0; // How long have we been sleeping this time secsSlept = 0; // How long have we been sleeping this time
// DEBUG_MSG("lsEnter end\n"); // LOG_INFO("lsEnter end\n");
} }
static void lsIdle() static void lsIdle()
{ {
// DEBUG_MSG("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); // LOG_INFO("lsIdle begin ls_secs=%u\n", getPref_ls_secs());
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
@@ -82,7 +82,7 @@ static void lsIdle()
wakeCause2 = doLightSleep(1); // leave led on for 1ms wakeCause2 = doLightSleep(1); // leave led on for 1ms
secsSlept += sleepTime; secsSlept += sleepTime;
// DEBUG_MSG("sleeping, flash led!\n"); // LOG_INFO("sleeping, flash led!\n");
break; break;
case ESP_SLEEP_WAKEUP_UART: case ESP_SLEEP_WAKEUP_UART:
@@ -93,7 +93,7 @@ static void lsIdle()
default: default:
// We woke for some other reason (button press, device interrupt) // We woke for some other reason (button press, device interrupt)
// uint64_t status = esp_sleep_get_ext1_wakeup_status(); // uint64_t status = esp_sleep_get_ext1_wakeup_status();
DEBUG_MSG("wakeCause2 %d\n", wakeCause2); LOG_INFO("wakeCause2 %d\n", wakeCause2);
#ifdef BUTTON_PIN #ifdef BUTTON_PIN
bool pressed = !digitalRead(BUTTON_PIN); bool pressed = !digitalRead(BUTTON_PIN);
@@ -117,7 +117,7 @@ static void lsIdle()
} else { } else {
// Time to stop sleeping! // Time to stop sleeping!
setLed(false); setLed(false);
DEBUG_MSG("reached ls_secs, servicing loop()\n"); LOG_INFO("Reached ls_secs, servicing loop()\n");
powerFSM.trigger(EVENT_WAKE_TIMER); powerFSM.trigger(EVENT_WAKE_TIMER);
} }
#endif #endif
@@ -125,7 +125,7 @@ static void lsIdle()
static void lsExit() static void lsExit()
{ {
DEBUG_MSG("Exit state: LS\n"); LOG_INFO("Exit state: LS\n");
// setGPSPower(true); // restore GPS power // setGPSPower(true); // restore GPS power
if (gps) if (gps)
gps->forceWake(true); gps->forceWake(true);
@@ -133,7 +133,7 @@ static void lsExit()
static void nbEnter() static void nbEnter()
{ {
DEBUG_MSG("Enter state: NB\n"); LOG_INFO("Enter state: NB\n");
screen->setOn(false); screen->setOn(false);
setBluetoothEnable(false); setBluetoothEnable(false);
@@ -148,7 +148,7 @@ static void darkEnter()
static void serialEnter() static void serialEnter()
{ {
DEBUG_MSG("Enter state: SERIAL\n"); LOG_INFO("Enter state: SERIAL\n");
setBluetoothEnable(false); setBluetoothEnable(false);
screen->setOn(true); screen->setOn(true);
screen->print("Serial connected\n"); screen->print("Serial connected\n");
@@ -161,10 +161,10 @@ static void serialExit()
static void powerEnter() static void powerEnter()
{ {
DEBUG_MSG("Enter state: POWER\n"); LOG_INFO("Enter state: POWER\n");
if (!isPowered()) { if (!isPowered()) {
// If we got here, we are in the wrong state - we should be in powered, let that state ahndle things // 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_INFO("Loss of power in Powered\n");
powerFSM.trigger(EVENT_POWER_DISCONNECTED); powerFSM.trigger(EVENT_POWER_DISCONNECTED);
} else { } else {
screen->setOn(true); screen->setOn(true);
@@ -177,7 +177,7 @@ static void powerIdle()
{ {
if (!isPowered()) { if (!isPowered()) {
// If we got here, we are in the wrong state // If we got here, we are in the wrong state
DEBUG_MSG("Loss of power in Powered\n"); LOG_INFO("Loss of power in Powered\n");
powerFSM.trigger(EVENT_POWER_DISCONNECTED); powerFSM.trigger(EVENT_POWER_DISCONNECTED);
} }
} }
@@ -191,7 +191,7 @@ static void powerExit()
static void onEnter() static void onEnter()
{ {
DEBUG_MSG("Enter state: ON\n"); LOG_INFO("Enter state: ON\n");
screen->setOn(true); screen->setOn(true);
setBluetoothEnable(true); setBluetoothEnable(true);
@@ -221,7 +221,7 @@ static void screenPress()
static void bootEnter() static void bootEnter()
{ {
DEBUG_MSG("Enter state: BOOT\n"); LOG_INFO("Enter state: BOOT\n");
} }
State stateSHUTDOWN(shutdownEnter, NULL, NULL, "SHUTDOWN"); 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 isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER ? 1 : 0);
bool hasPower = isPowered(); bool hasPower = isPowered();
DEBUG_MSG("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"); powerFSM.add_timed_transition(&stateBOOT, hasPower ? &statePOWER : &stateON, 3 * 1000, NULL, "boot timeout");
// wake timer expired or a packet arrived // wake timer expired or a packet arrived

View File

@@ -82,7 +82,7 @@ class PowerStatus : public Status
isCharging = newStatus->isCharging; isCharging = newStatus->isCharging;
} }
if (isDirty) { if (isDirty) {
// DEBUG_MSG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent); // LOG_DEBUG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent);
onNewStatus.notifyObservers(this); onNewStatus.notifyObservers(this);
} }
return 0; return 0;

View File

@@ -58,7 +58,7 @@ size_t RedirectablePrint::vprintf(const char *format, va_list arg)
return len; return len;
} }
size_t RedirectablePrint::logDebug(const char *format, ...) size_t RedirectablePrint::log(const char *logLevel, const char *format, ...)
{ {
size_t r = 0; 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 min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % 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 } else
r += printf("??:??:?? %u ", millis() / 1000); r += printf("%s | ??:??:?? %u ", logLevel, millis() / 1000);
auto thread = concurrency::OSThread::currentThread; auto thread = concurrency::OSThread::currentThread;
if (thread) { if (thread) {
@@ -99,7 +99,6 @@ size_t RedirectablePrint::logDebug(const char *format, ...)
print("] "); print("] ");
} }
} }
r += vprintf(format, arg); r += vprintf(format, arg);
va_end(arg); va_end(arg);

View File

@@ -33,11 +33,8 @@ class RedirectablePrint : public Print
* If the provide format string ends with a newline we assume it is the final print of a single * 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 * 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. * 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))); size_t log(const char *logLevel, const char *format, ...) __attribute__ ((format (printf, 3, 4)));
/** like printf but va_list based */ /** like printf but va_list based */
size_t vprintf(const char *format, va_list arg); size_t vprintf(const char *format, va_list arg);

View File

@@ -10,18 +10,18 @@ void AirTime::logAirtime(reportTypes reportType, uint32_t airtime_ms)
{ {
if (reportType == TX_LOG) { 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; this->airtimes.periodTX[0] = this->airtimes.periodTX[0] + airtime_ms;
myNodeInfo.air_period_tx[0] = myNodeInfo.air_period_tx[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; this->utilizationTX[this->getPeriodUtilHour()] = this->utilizationTX[this->getPeriodUtilHour()] + airtime_ms;
} else if (reportType == RX_LOG) { } 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; this->airtimes.periodRX[0] = this->airtimes.periodRX[0] + airtime_ms;
myNodeInfo.air_period_rx[0] = myNodeInfo.air_period_rx[0] + airtime_ms; myNodeInfo.air_period_rx[0] = myNodeInfo.air_period_rx[0] + airtime_ms;
} else if (reportType == RX_ALL_LOG) { } 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; 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()) { 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) { for (int i = PERIODS_TO_LOG - 2; i >= 0; --i) {
this->airtimes.periodTX[i + 1] = this->airtimes.periodTX[i]; this->airtimes.periodTX[i + 1] = this->airtimes.periodTX[i];
@@ -101,7 +101,7 @@ float AirTime::channelUtilizationPercent()
uint32_t sum = 0; uint32_t sum = 0;
for (uint32_t i = 0; i < CHANNEL_UTILIZATION_PERIODS; i++) { for (uint32_t i = 0; i < CHANNEL_UTILIZATION_PERIODS; i++) {
sum += this->channelUtilization[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; return (float(sum) / float(CHANNEL_UTILIZATION_PERIODS * 10 * 1000)) * 100;
@@ -189,13 +189,13 @@ int32_t AirTime::runOnce()
myNodeInfo.air_util_tx = airTime->utilizationTXPercent(); 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++) { for (uint32_t i = 0; i < MINUTES_IN_HOUR; i++) {
DEBUG_MSG( LOG_DEBUG(
"%d,", this->utilizationTX[i] "%d,", this->utilizationTX[i]
); );
} }
DEBUG_MSG("\n"); LOG_DEBUG("\n");
*/ */
return (1000 * 1); return (1000 * 1);
} }

View File

@@ -13,12 +13,12 @@ InterruptableDelay::~InterruptableDelay() {}
*/ */
bool InterruptableDelay::delay(uint32_t msec) 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) // sem take will return false if we timed out (i.e. were not interrupted)
bool r = semaphore.take(msec); bool r = semaphore.take(msec);
// DEBUG_MSG("interrupt=%d\n", r); // LOG_DEBUG("interrupt=%d\n", r);
return !r; return !r;
} }

View File

@@ -33,11 +33,11 @@ IRAM_ATTR bool NotifiedWorkerThread::notifyCommon(uint32_t v, bool overwrite)
notification = v; notification = v;
if (debugNotification) if (debugNotification)
DEBUG_MSG("setting notification %d\n", v); LOG_DEBUG("setting notification %d\n", v);
return true; return true;
} else { } else {
if (debugNotification) if (debugNotification)
DEBUG_MSG("dropping notification %d\n", v); LOG_DEBUG("dropping notification %d\n", v);
return false; 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 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 setIntervalFromNow(delay); // a new version of setInterval relative to the current time
if (debugNotification) if (debugNotification)
DEBUG_MSG("delaying notification %u\n", delay); LOG_DEBUG("delaying notification %u\n", delay);
} }
return didIt; return didIt;

View File

@@ -61,13 +61,13 @@ bool OSThread::shouldRun(unsigned long time)
bool r = Thread::shouldRun(time); bool r = Thread::shouldRun(time);
if (showRun && r) 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) 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) if (showDisabled && !enabled)
DEBUG_MSG("Thread %s: disabled\n", ThreadName.c_str()); LOG_DEBUG("Thread %s: disabled\n", ThreadName.c_str());
return r; return r;
} }

View File

@@ -3,13 +3,13 @@
uint32_t axpDebugRead() uint32_t axpDebugRead()
{ {
axp.debugCharging(); axp.debugCharging();
DEBUG_MSG("vbus current %f\n", axp.getVbusCurrent()); LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent());
DEBUG_MSG("charge current %f\n", axp.getBattChargeCurrent()); LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent());
DEBUG_MSG("bat voltage %f\n", axp.getBattVoltage()); LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage());
DEBUG_MSG("batt pct %d\n", axp.getBattPercentage()); LOG_DEBUG("batt pct %d\n", axp.getBattPercentage());
DEBUG_MSG("is battery connected %d\n", axp.isBatteryConnect()); LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect());
DEBUG_MSG("is USB connected %d\n", axp.isVBUSPlug()); LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug());
DEBUG_MSG("is charging %d\n", axp.isChargeing()); LOG_DEBUG("is charging %d\n", axp.isChargeing());
return 30 * 1000; return 30 * 1000;
} }

View File

@@ -52,9 +52,9 @@ void scanEInkDevice(void)
d_writeCommand(0x20); d_writeCommand(0x20);
eink_found = (d_waitWhileBusy(150) > 0) ? true : false; eink_found = (d_waitWhileBusy(150) > 0) ? true : false;
if(eink_found) if(eink_found)
DEBUG_MSG("EInk display found\n"); LOG_DEBUG("EInk display found\n");
else else
DEBUG_MSG("EInk display not found\n"); LOG_DEBUG("EInk display not found\n");
SPI1.end(); SPI1.end();
} }
#endif #endif

View File

@@ -15,30 +15,30 @@ void printATECCInfo()
#if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL)
atecc.readConfigZone(false); atecc.readConfigZone(false);
DEBUG_MSG("ATECC608B Serial Number: "); LOG_DEBUG("ATECC608B Serial Number: ");
for (int i = 0 ; i < 9 ; i++) { 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++) { 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"); LOG_DEBUG("ATECC608B Config %s",atecc.configLockStatus ? "Locked" : "Unlocked");
DEBUG_MSG(", Data %s",atecc.dataOTPLockStatus ? "Locked" : "Unlocked"); LOG_DEBUG(", Data %s",atecc.dataOTPLockStatus ? "Locked" : "Unlocked");
DEBUG_MSG(", Slot 0 %s\n",atecc.slot0LockStatus ? "Locked" : "Unlocked"); LOG_DEBUG(", Slot 0 %s\n",atecc.slot0LockStatus ? "Locked" : "Unlocked");
if (atecc.configLockStatus && atecc.dataOTPLockStatus && atecc.slot0LockStatus) { if (atecc.configLockStatus && atecc.dataOTPLockStatus && atecc.slot0LockStatus) {
if (atecc.generatePublicKey() == false) { if (atecc.generatePublicKey() == false) {
DEBUG_MSG("ATECC608B Error generating public key\n"); LOG_DEBUG("ATECC608B Error generating public key\n");
} else { } else {
DEBUG_MSG("ATECC608B Public Key: "); LOG_DEBUG("ATECC608B Public Key: ");
for (int i = 0 ; i < 64 ; i++) { 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 #endif
@@ -51,7 +51,7 @@ uint16_t getRegisterValue(uint8_t address, uint8_t reg, uint8_t length) {
Wire.endTransmission(); Wire.endTransmission();
delay(20); delay(20);
Wire.requestFrom(address, length); Wire.requestFrom(address, length);
DEBUG_MSG("Wire.available() = %d\n", Wire.available()); LOG_DEBUG("Wire.available() = %d\n", Wire.available());
if (Wire.available() == 2) { if (Wire.available() == 2) {
// Read MSB, then LSB // Read MSB, then LSB
value = (uint16_t)Wire.read() << 8; value = (uint16_t)Wire.read() << 8;
@@ -86,7 +86,7 @@ uint8_t oled_probe(byte addr)
} }
c++; c++;
} while ((r != r_prev) && (c < 4)); } 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; return o_probe;
} }
@@ -99,7 +99,7 @@ void scanI2Cdevice()
Wire.beginTransmission(addr); Wire.beginTransmission(addr);
err = Wire.endTransmission(); err = Wire.endTransmission();
if (err == 0) { 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++; nDevices++;
@@ -107,20 +107,20 @@ void scanI2Cdevice()
screen_found = addr; screen_found = addr;
screen_model = oled_probe(addr); screen_model = oled_probe(addr);
if (screen_model == 1) { if (screen_model == 1) {
DEBUG_MSG("ssd1306 display found\n"); LOG_INFO("ssd1306 display found\n");
} else if (screen_model == 2) { } else if (screen_model == 2) {
DEBUG_MSG("sh1106 display found\n"); LOG_INFO("sh1106 display found\n");
} else { } else {
DEBUG_MSG("unknown display found\n"); LOG_INFO("unknown display found\n");
} }
} }
#if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL)
if (addr == ATECC608B_ADDR) { if (addr == ATECC608B_ADDR) {
keystore_found = addr; keystore_found = addr;
if (atecc.begin(keystore_found) == true) { if (atecc.begin(keystore_found) == true) {
DEBUG_MSG("ATECC608B initialized\n"); LOG_INFO("ATECC608B initialized\n");
} else { } else {
DEBUG_MSG("ATECC608B initialization failed\n"); LOG_WARN("ATECC608B initialization failed\n");
} }
printATECCInfo(); printATECCInfo();
} }
@@ -128,7 +128,7 @@ void scanI2Cdevice()
#ifdef RV3028_RTC #ifdef RV3028_RTC
if (addr == RV3028_RTC){ if (addr == RV3028_RTC){
rtc_found = addr; rtc_found = addr;
DEBUG_MSG("RV3028 RTC found\n"); LOG_INFO("RV3028 RTC found\n");
Melopero_RV3028 rtc; Melopero_RV3028 rtc;
rtc.initI2C(); rtc.initI2C();
rtc.writeToRegister(0x35,0x07); // no Clkout rtc.writeToRegister(0x35,0x07); // no Clkout
@@ -138,7 +138,7 @@ void scanI2Cdevice()
#ifdef PCF8563_RTC #ifdef PCF8563_RTC
if (addr == PCF8563_RTC){ if (addr == PCF8563_RTC){
rtc_found = addr; rtc_found = addr;
DEBUG_MSG("PCF8563 RTC found\n"); LOG_INFO("PCF8563 RTC found\n");
} }
#endif #endif
if (addr == CARDKB_ADDR) { if (addr == CARDKB_ADDR) {
@@ -146,86 +146,86 @@ void scanI2Cdevice()
// Do we have the RAK14006 instead? // Do we have the RAK14006 instead?
registerValue = getRegisterValue(addr, 0x04, 1); registerValue = getRegisterValue(addr, 0x04, 1);
if (registerValue == 0x02) { // KEYPAD_VERSION if (registerValue == 0x02) { // KEYPAD_VERSION
DEBUG_MSG("RAK14004 found\n"); LOG_INFO("RAK14004 found\n");
kb_model = 0x02; kb_model = 0x02;
} else { } else {
DEBUG_MSG("m5 cardKB found\n"); LOG_INFO("m5 cardKB found\n");
kb_model = 0x00; kb_model = 0x00;
} }
} }
if (addr == ST7567_ADDRESS) { if (addr == ST7567_ADDRESS) {
screen_found = addr; screen_found = addr;
DEBUG_MSG("st7567 display found\n"); LOG_INFO("st7567 display found\n");
} }
#ifdef HAS_PMU #ifdef HAS_PMU
if (addr == XPOWERS_AXP192_AXP2101_ADDRESS) { if (addr == XPOWERS_AXP192_AXP2101_ADDRESS) {
pmu_found = true; pmu_found = true;
DEBUG_MSG("axp192/axp2101 PMU found\n"); LOG_INFO("axp192/axp2101 PMU found\n");
} }
#endif #endif
if (addr == BME_ADDR || addr == BME_ADDR_ALTERNATE) { if (addr == BME_ADDR || addr == BME_ADDR_ALTERNATE) {
registerValue = getRegisterValue(addr, 0xD0, 1); // GET_ID registerValue = getRegisterValue(addr, 0xD0, 1); // GET_ID
if (registerValue == 0x61) { if (registerValue == 0x61) {
DEBUG_MSG("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; nodeTelemetrySensorsMap[TelemetrySensorType_BME680] = addr;
} else if (registerValue == 0x60) { } else if (registerValue == 0x60) {
DEBUG_MSG("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; nodeTelemetrySensorsMap[TelemetrySensorType_BME280] = addr;
} else { } else {
DEBUG_MSG("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; nodeTelemetrySensorsMap[TelemetrySensorType_BMP280] = addr;
} }
} }
if (addr == INA_ADDR || addr == INA_ADDR_ALTERNATE) { if (addr == INA_ADDR || addr == INA_ADDR_ALTERNATE) {
registerValue = getRegisterValue(addr, 0xFE, 2); 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) { if (registerValue == 0x5449) {
DEBUG_MSG("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; nodeTelemetrySensorsMap[TelemetrySensorType_INA260] = addr;
} else { // Assume INA219 if INA260 ID is not found } else { // Assume INA219 if INA260 ID is not found
DEBUG_MSG("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; nodeTelemetrySensorsMap[TelemetrySensorType_INA219] = addr;
} }
} }
if (addr == MCP9808_ADDR) { if (addr == MCP9808_ADDR) {
nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr;
DEBUG_MSG("MCP9808 sensor found\n"); LOG_INFO("MCP9808 sensor found\n");
} }
if (addr == SHT31_ADDR) { if (addr == SHT31_ADDR) {
DEBUG_MSG("SHT31 sensor found\n"); LOG_INFO("SHT31 sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr;
} }
if (addr == SHTC3_ADDR) { if (addr == SHTC3_ADDR) {
DEBUG_MSG("SHTC3 sensor found\n"); LOG_INFO("SHTC3 sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr;
} }
if (addr == LPS22HB_ADDR || addr == LPS22HB_ADDR_ALT) { if (addr == LPS22HB_ADDR || addr == LPS22HB_ADDR_ALT) {
DEBUG_MSG("LPS22HB sensor found\n"); LOG_INFO("LPS22HB sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_LPS22] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_LPS22] = addr;
} }
// High rate sensors, will be processed internally // High rate sensors, will be processed internally
if (addr == QMC6310_ADDR) { if (addr == QMC6310_ADDR) {
DEBUG_MSG("QMC6310 Highrate 3-Axis magnetic sensor found\n"); LOG_INFO("QMC6310 Highrate 3-Axis magnetic sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_QMC6310] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_QMC6310] = addr;
} }
if (addr == QMI8658_ADDR) { if (addr == QMI8658_ADDR) {
DEBUG_MSG("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); LOG_INFO("QMI8658 Highrate 6-Axis inertial measurement sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_QMI8658] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_QMI8658] = addr;
} }
if (addr == QMC5883L_ADDR) { if (addr == QMC5883L_ADDR) {
DEBUG_MSG("QMC5883L Highrate 3-Axis magnetic sensor found\n"); LOG_INFO("QMC5883L Highrate 3-Axis magnetic sensor found\n");
nodeTelemetrySensorsMap[TelemetrySensorType_QMC5883L] = addr; nodeTelemetrySensorsMap[TelemetrySensorType_QMC5883L] = addr;
} }
} else if (err == 4) { } else if (err == 4) {
DEBUG_MSG("Unknow error at address 0x%x\n", addr); LOG_ERROR("Unknow error at address 0x%x\n", addr);
} }
} }
if (nDevices == 0) if (nDevices == 0)
DEBUG_MSG("No I2C devices found\n"); LOG_INFO("No I2C devices found\n");
else else
DEBUG_MSG("%i I2C devices found\n",nDevices); LOG_INFO("%i I2C devices found\n",nDevices);
} }
#else #else
void scanI2Cdevice() {} void scanI2Cdevice() {}

View File

@@ -203,7 +203,7 @@ if (!config.position.tx_gpio)
0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0xAF}; 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0xAF};
_serial_gps->write(_message_nmea, sizeof(_message_nmea)); _serial_gps->write(_message_nmea, sizeof(_message_nmea));
if (!getACK(0x06, 0x00)) { if (!getACK(0x06, 0x00)) {
DEBUG_MSG("WARNING: Unable to enable NMEA Mode.\n"); LOG_WARN("Unable to enable NMEA Mode.\n");
return true; 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}; 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)); _serial_gps->write(_message_GGL, sizeof(_message_GGL));
if (!getACK(0x06, 0x01)) { if (!getACK(0x06, 0x01)) {
DEBUG_MSG("WARNING: Unable to disable NMEA GGL.\n"); LOG_WARN("Unable to disable NMEA GGL.\n");
return true; 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}; 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)); _serial_gps->write(_message_GSA, sizeof(_message_GSA));
if (!getACK(0x06, 0x01)) { if (!getACK(0x06, 0x01)) {
DEBUG_MSG("WARNING: Unable to disable NMEA GSA.\n"); LOG_WARN("Unable to disable NMEA GSA.\n");
return true; 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}; 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)); _serial_gps->write(_message_GSV, sizeof(_message_GSV));
if (!getACK(0x06, 0x01)) { if (!getACK(0x06, 0x01)) {
DEBUG_MSG("WARNING: Unable to disable NMEA GSV.\n"); LOG_WARN("Unable to disable NMEA GSV.\n");
return true; 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}; 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)); _serial_gps->write(_message_VTG, sizeof(_message_VTG));
if (!getACK(0x06, 0x01)) { if (!getACK(0x06, 0x01)) {
DEBUG_MSG("WARNING: Unable to disable NMEA VTG.\n"); LOG_WARN("Unable to disable NMEA VTG.\n");
return true; 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}; 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)); _serial_gps->write(_message_RMC, sizeof(_message_RMC));
if (!getACK(0x06, 0x01)) { if (!getACK(0x06, 0x01)) {
DEBUG_MSG("WARNING: Unable to enable NMEA RMC.\n"); LOG_WARN("Unable to enable NMEA RMC.\n");
return true; 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}; 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)); _serial_gps->write(_message_GGA, sizeof(_message_GGA));
if (!getACK(0x06, 0x01)) { 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) void GPS::setAwake(bool on)
{ {
if (!wakeAllowed && on) { if (!wakeAllowed && on) {
DEBUG_MSG("Inhibiting because !wakeAllowed\n"); LOG_WARN("Inhibiting because !wakeAllowed\n");
on = false; on = false;
} }
if (isAwake != on) { if (isAwake != on) {
DEBUG_MSG("WANT GPS=%d\n", on); LOG_DEBUG("WANT GPS=%d\n", on);
if (on) { if (on) {
lastWakeStartMsec = millis(); lastWakeStartMsec = millis();
wake(); wake();
@@ -412,7 +412,7 @@ void GPS::publishUpdate()
shouldPublish = false; shouldPublish = false;
// In debug logs, identify position by @timestamp:stage (stage 2 = publish) // 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 // Notify any status instances that are observing us
const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasValidLocation, isConnected(), isPowerSaving(), p); 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)){ if((config.position.gps_enabled == 1) && (gnssModel == GNSS_MODEL_UBLOX)){
// reset the GPS on next bootup // reset the GPS on next bootup
if(devicestate.did_gps_reset && (millis() > 60000) && !hasFlow()) { 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; devicestate.did_gps_reset = false;
nodeDB.saveDeviceStateToDisk(); nodeDB.saveDeviceStateToDisk();
} }
@@ -447,7 +447,7 @@ int32_t GPS::runOnce()
// While we are awake // While we are awake
if (isAwake) { if (isAwake) {
// DEBUG_MSG("looking for location\n"); // LOG_DEBUG("looking for location\n");
if ((now - lastWhileActiveMsec) > 5000) { if ((now - lastWhileActiveMsec) > 5000) {
lastWhileActiveMsec = now; lastWhileActiveMsec = now;
whileActive(); whileActive();
@@ -462,7 +462,7 @@ int32_t GPS::runOnce()
bool gotLoc = lookForLocation(); bool gotLoc = lookForLocation();
if (gotLoc && !hasValidLocation) { // declare that we have location ASAP if (gotLoc && !hasValidLocation) { // declare that we have location ASAP
DEBUG_MSG("hasValidLocation RISING EDGE\n"); LOG_DEBUG("hasValidLocation RISING EDGE\n");
hasValidLocation = true; hasValidLocation = true;
shouldPublish = true; shouldPublish = true;
} }
@@ -473,13 +473,13 @@ int32_t GPS::runOnce()
bool tooLong = wakeTime != UINT32_MAX && (now - lastWakeStartMsec) > wakeTime; bool tooLong = wakeTime != UINT32_MAX && (now - lastWakeStartMsec) > wakeTime;
// Once we get a location we no longer desperately want an update // 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 ((gotLoc && gotTime) || tooLong) {
if (tooLong) { if (tooLong) {
// we didn't get a location during this ack window, therefore declare loss of lock // we didn't get a location during this ack window, therefore declare loss of lock
if (hasValidLocation) { 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; p = Position_init_default;
hasValidLocation = false; hasValidLocation = false;
@@ -501,7 +501,7 @@ int32_t GPS::runOnce()
void GPS::forceWake(bool on) void GPS::forceWake(bool on)
{ {
if (on) { if (on) {
DEBUG_MSG("Allowing GPS lock\n"); LOG_DEBUG("Allowing GPS lock\n");
// lastSleepStartMsec = 0; // Force an update ASAP // lastSleepStartMsec = 0; // Force an update ASAP
wakeAllowed = true; wakeAllowed = true;
} else { } 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 /// 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) int GPS::prepareSleep(void *unused)
{ {
DEBUG_MSG("GPS prepare sleep!\n"); LOG_INFO("GPS prepare sleep!\n");
forceWake(false); forceWake(false);
return 0; 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 /// 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) int GPS::prepareDeepSleep(void *unused)
{ {
DEBUG_MSG("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) // For deep sleep we also want abandon any lock attempts (because we want minimum power)
getSleepTime(); getSleepTime();
@@ -568,7 +568,7 @@ GnssModel_t GPS::probe()
if(index != -1){ if(index != -1){
ver = ver.substring(index); ver = ver.substring(index);
if (ver.startsWith("$GPTXT,01,01,02")) { if (ver.startsWith("$GPTXT,01,01,02")) {
DEBUG_MSG("L76K GNSS init succeeded, using L76K GNSS Module\n"); LOG_INFO("L76K GNSS init succeeded, using L76K GNSS Module\n");
return GNSS_MODEL_MTK; return GNSS_MODEL_MTK;
} }
} }
@@ -580,7 +580,7 @@ GnssModel_t GPS::probe()
_serial_gps->write(cfg_rate, sizeof(cfg_rate)); _serial_gps->write(cfg_rate, sizeof(cfg_rate));
// Check that the returned response class and message ID are correct // Check that the returned response class and message ID are correct
if (!getAck(buffer, 256, 0x06, 0x08)) { 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; return GNSS_MODEL_UNKONW;
} }
@@ -611,12 +611,12 @@ GnssModel_t GPS::probe()
break; break;
} }
DEBUG_MSG("Module Info : \n"); LOG_DEBUG("Module Info : \n");
DEBUG_MSG("Soft version: %s\n",info.swVersion); LOG_DEBUG("Soft version: %s\n",info.swVersion);
DEBUG_MSG("Hard version: %s\n",info.hwVersion); LOG_DEBUG("Hard version: %s\n",info.hwVersion);
DEBUG_MSG("Extensions:%d\n",info.extensionNo); LOG_DEBUG("Extensions:%d\n",info.extensionNo);
for (int i = 0; i < info.extensionNo; i++) { 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)); memset(buffer,0,sizeof(buffer));
@@ -625,15 +625,15 @@ GnssModel_t GPS::probe()
for (int i = 0; i < info.extensionNo; ++i) { for (int i = 0; i < info.extensionNo; ++i) {
if (!strncmp(info.extension[i], "OD=", 3)) { if (!strncmp(info.extension[i], "OD=", 3)) {
strcpy((char *)buffer, &(info.extension[i][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)) { if (strlen((char*)buffer)) {
DEBUG_MSG("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{ }else{
DEBUG_MSG("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); LOG_INFO("UBlox GNSS init succeeded, using UBlox GNSS Module\n");
} }
return GNSS_MODEL_UBLOX; return GNSS_MODEL_UBLOX;
@@ -652,9 +652,9 @@ GPS *createGps()
#else #else
if (config.position.gps_enabled) { if (config.position.gps_enabled) {
#ifdef GPS_ALTITUDE_HAE #ifdef GPS_ALTITUDE_HAE
DEBUG_MSG("Using HAE altitude model\n"); LOG_DEBUG("Using HAE altitude model\n");
#else #else
DEBUG_MSG("Using MSL altitude model\n"); LOG_DEBUG("Using MSL altitude model\n");
#endif #endif
if (GPS::_serial_gps) { 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 // Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just

View File

@@ -53,9 +53,9 @@ bool NMEAGPS::setupGPS()
// see NMEAGPS.h // see NMEAGPS.h
gsafixtype.begin(reader, NMEA_MSG_GXGSA, 2); gsafixtype.begin(reader, NMEA_MSG_GXGSA, 2);
gsapdop.begin(reader, NMEA_MSG_GXGSA, 15); 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 #else
DEBUG_MSG("GxGSA NOT available\n"); LOG_DEBUG("GxGSA NOT available\n");
#endif #endif
return true; 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_year = d.year() - 1900;
t.tm_isdst = false; t.tm_isdst = false;
if (t.tm_mon > -1){ 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); perhapsSetRTC(RTCQualityGPS, t);
return true; return true;
} else } else
@@ -109,7 +109,7 @@ bool NMEAGPS::lookForLocation()
#ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS
fixType = atoi(gsafixtype.value()); // will set to zero if no data 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 #endif
// check if GPS has an acceptable lock // check if GPS has an acceptable lock
@@ -117,7 +117,7 @@ bool NMEAGPS::lookForLocation()
return false; return false;
#ifdef GPS_EXTRAVERBOSE #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(), reader.location.age(),
#ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS
gsafixtype.age(), gsafixtype.age(),
@@ -137,7 +137,7 @@ bool NMEAGPS::lookForLocation()
(reader.time.age() < GPS_SOL_EXPIRY_MS) && (reader.time.age() < GPS_SOL_EXPIRY_MS) &&
(reader.date.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_WARN("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age());
return false; return false;
} }
@@ -151,13 +151,13 @@ bool NMEAGPS::lookForLocation()
// Bail out EARLY to avoid overwriting previous good data (like #857) // Bail out EARLY to avoid overwriting previous good data (like #857)
if (toDegInt(loc.lat) > 900000000) { if (toDegInt(loc.lat) > 900000000) {
#ifdef GPS_EXTRAVERBOSE #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 #endif
return false; return false;
} }
if (toDegInt(loc.lng) > 1800000000) { if (toDegInt(loc.lng) > 1800000000) {
#ifdef GPS_EXTRAVERBOSE #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 #endif
return false; return false;
} }
@@ -168,7 +168,7 @@ bool NMEAGPS::lookForLocation()
#ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS
p.HDOP = reader.hdop.value(); p.HDOP = reader.hdop.value();
p.PDOP = TinyGPSPlus::parseDecimal(gsapdop.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 #else
// FIXME! naive PDOP emulation (assumes VDOP==HDOP) // FIXME! naive PDOP emulation (assumes VDOP==HDOP)
// correct formula is PDOP = SQRT(HDOP^2 + VDOP^2) // correct formula is PDOP = SQRT(HDOP^2 + VDOP^2)
@@ -212,7 +212,7 @@ bool NMEAGPS::lookForLocation()
if (reader.course.value() < 36000) { // sanity check 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 p.ground_track = reader.course.value() * 1e3; // Scale the heading (in degrees * 10^-2) to match the expected degrees * 10^-5
} else { } else {
DEBUG_MSG("BOGUS course.value() REJECTED: %d\n", LOG_WARN("BOGUS course.value() REJECTED: %d\n",
reader.course.value()); reader.course.value());
} }
} }
@@ -251,7 +251,7 @@ bool NMEAGPS::whileIdle()
// First consume any chars that have piled up at the receiver // First consume any chars that have piled up at the receiver
while (_serial_gps->available() > 0) { while (_serial_gps->available() > 0) {
int c = _serial_gps->read(); int c = _serial_gps->read();
// DEBUG_MSG("%c", c); // LOG_DEBUG("%c", c);
isValid |= reader.encode(c); isValid |= reader.encode(c);
} }

View File

@@ -33,7 +33,7 @@ void readFromRTC()
t.tm_sec = rtc.getSecond(); t.tm_sec = rtc.getSecond();
tv.tv_sec = mktime(&t); tv.tv_sec = mktime(&t);
tv.tv_usec = 0; 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; timeStartMsec = now;
zeroOffsetSecs = tv.tv_sec; zeroOffsetSecs = tv.tv_sec;
if (currentQuality == RTCQualityNone) { if (currentQuality == RTCQualityNone) {
@@ -59,7 +59,7 @@ void readFromRTC()
t.tm_sec = tc.second; t.tm_sec = tc.second;
tv.tv_sec = mktime(&t); tv.tv_sec = mktime(&t);
tv.tv_usec = 0; 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; timeStartMsec = now;
zeroOffsetSecs = tv.tv_sec; zeroOffsetSecs = tv.tv_sec;
if (currentQuality == RTCQualityNone) { if (currentQuality == RTCQualityNone) {
@@ -69,7 +69,7 @@ void readFromRTC()
#else #else
if (!gettimeofday(&tv, NULL)) { if (!gettimeofday(&tv, NULL)) {
uint32_t now = millis(); 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; timeStartMsec = now;
zeroOffsetSecs = tv.tv_sec; zeroOffsetSecs = tv.tv_sec;
} }
@@ -86,11 +86,11 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv)
if (q > currentQuality) { if (q > currentQuality) {
currentQuality = q; currentQuality = q;
shouldSet = true; 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)) { } 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 // Every 12 hrs we will slam in a new GPS time, to correct for local RTC clock drift
shouldSet = true; 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 else
shouldSet = false; shouldSet = false;
@@ -109,7 +109,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv)
rtc.initI2C(); rtc.initI2C();
tm *t = localtime(&tv->tv_sec); 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); 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) #elif defined(PCF8563_RTC)
if(rtc_found == PCF8563_RTC) { if(rtc_found == PCF8563_RTC) {
@@ -121,7 +121,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv)
#endif #endif
tm *t = localtime(&tv->tv_sec); 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); 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) #elif defined(ARCH_ESP32)
settimeofday(tv, NULL); settimeofday(tv, NULL);
@@ -149,9 +149,9 @@ bool perhapsSetRTC(RTCQuality q, struct tm &t)
tv.tv_sec = res; tv.tv_sec = res;
tv.tv_usec = 0; // time.centisecond() * (10 / 1000); 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) { 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; return false;
} else { } else {
return perhapsSetRTC(q, &tv); return perhapsSetRTC(q, &tv);

View File

@@ -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) #if defined(TTGO_T_ECHO)
// ePaper.Reset(); // wake the screen from sleep // 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) // Put screen to sleep to save power (possibly not necessary because we already did poweroff inside of display)
adafruitDisplay->hibernate(); adafruitDisplay->hibernate();
DEBUG_MSG("done\n"); LOG_DEBUG("done\n");
return true; return true;
} else { } else {
// DEBUG_MSG("Skipping eink display\n"); // LOG_DEBUG("Skipping eink display\n");
return false; return false;
} }
} }
@@ -162,7 +162,7 @@ void EInkDisplay::setDetected(uint8_t detected)
// Connect to the display // Connect to the display
bool EInkDisplay::connect() bool EInkDisplay::connect()
{ {
DEBUG_MSG("Doing EInk init\n"); LOG_INFO("Doing EInk init\n");
#ifdef PIN_EINK_PWR_ON #ifdef PIN_EINK_PWR_ON
digitalWrite(PIN_EINK_PWR_ON, HIGH); // If we need to assert a pin to power external peripherals digitalWrite(PIN_EINK_PWR_ON, HIGH); // If we need to assert a pin to power external peripherals

View File

@@ -276,9 +276,9 @@ static void drawModuleFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int
} else { } else {
// otherwise, just display the module frame that's aligned with the current frame // otherwise, just display the module frame that's aligned with the current frame
module_frame = state->currentFrame; 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); MeshModule &pi = *moduleFrames.at(module_frame);
pi.drawFrame(display, state, x, y); pi.drawFrame(display, state, x, y);
} }
@@ -368,7 +368,7 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state
MeshPacket &mp = devicestate.rx_text_message; MeshPacket &mp = devicestate.rx_text_message;
NodeInfo *node = nodeDB.getNode(getFrom(&mp)); 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); // mp.decoded.variant.data.decoded.bytes);
// Demo for drawStringMaxWidth: // Demo for drawStringMaxWidth:
@@ -882,7 +882,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_
if (!hasNodeHeading) { if (!hasNodeHeading) {
// direction to node is unknown so display question mark // direction to node is unknown so display question mark
// Debug info for gps lock errors // 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->drawString(compassX - FONT_HEIGHT_SMALL / 4, compassY - FONT_HEIGHT_SMALL / 2, "?");
} }
display->drawCircle(compassX, compassY, getCompassDiam(display) / 2); display->drawCircle(compassX, compassY, getCompassDiam(display) / 2);
@@ -936,14 +936,14 @@ void Screen::handleSetOn(bool on)
if (on != screenOn) { if (on != screenOn) {
if (on) { if (on) {
DEBUG_MSG("Turning on screen\n"); LOG_INFO("Turning on screen\n");
dispdev.displayOn(); dispdev.displayOn();
dispdev.displayOn(); dispdev.displayOn();
enabled = true; enabled = true;
setInterval(0); // Draw ASAP setInterval(0); // Draw ASAP
runASAP = true; runASAP = true;
} else { } else {
DEBUG_MSG("Turning off screen\n"); LOG_INFO("Turning off screen\n");
dispdev.displayOff(); dispdev.displayOff();
enabled = false; enabled = false;
} }
@@ -1056,7 +1056,7 @@ int32_t Screen::runOnce()
// serialSinceMsec adjusts for additional serial wait time during nRF52 bootup // serialSinceMsec adjusts for additional serial wait time during nRF52 bootup
static bool showingBootScreen = true; static bool showingBootScreen = true;
if (showingBootScreen && (millis() > (logo_timeout + serialSinceMsec))) { if (showingBootScreen && (millis() > (logo_timeout + serialSinceMsec))) {
DEBUG_MSG("Done with boot screen...\n"); LOG_INFO("Done with boot screen...\n");
stopBootScreen(); stopBootScreen();
showingBootScreen = false; showingBootScreen = false;
} }
@@ -1065,7 +1065,7 @@ int32_t Screen::runOnce()
if (strlen(oemStore.oem_text) > 0) { if (strlen(oemStore.oem_text) > 0) {
static bool showingOEMBootScreen = true; static bool showingOEMBootScreen = true;
if (showingOEMBootScreen && (millis() > ((logo_timeout / 2) + serialSinceMsec))) { if (showingOEMBootScreen && (millis() > ((logo_timeout / 2) + serialSinceMsec))) {
DEBUG_MSG("Switch to OEM screen...\n"); LOG_INFO("Switch to OEM screen...\n");
// Change frames. // Change frames.
static FrameCallback bootOEMFrames[] = {drawOEMBootScreen}; static FrameCallback bootOEMFrames[] = {drawOEMBootScreen};
static const int bootOEMFrameCount = sizeof(bootOEMFrames) / sizeof(bootOEMFrames[0]); static const int bootOEMFrameCount = sizeof(bootOEMFrames) / sizeof(bootOEMFrames[0]);
@@ -1127,7 +1127,7 @@ int32_t Screen::runOnce()
handleRebootScreen(); handleRebootScreen();
break; break;
default: default:
DEBUG_MSG("BUG: invalid cmd\n"); LOG_ERROR("Invalid screen cmd\n");
} }
} }
@@ -1158,12 +1158,12 @@ int32_t Screen::runOnce()
// standard screen loop handling here // standard screen loop handling here
if (config.display.auto_screen_carousel_secs > 0 && if (config.display.auto_screen_carousel_secs > 0 &&
(millis() - lastScreenTransition) > (config.display.auto_screen_carousel_secs * 1000)) { (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(); 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 // 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 // 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 // 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() void Screen::setSSLFrames()
{ {
if (address_found) { if (address_found) {
// DEBUG_MSG("showing SSL frames\n"); // LOG_DEBUG("showing SSL frames\n");
static FrameCallback sslFrames[] = {drawSSLScreen}; static FrameCallback sslFrames[] = {drawSSLScreen};
ui.setFrames(sslFrames, 1); ui.setFrames(sslFrames, 1);
ui.update(); ui.update();
@@ -1206,7 +1206,7 @@ void Screen::setSSLFrames()
void Screen::setWelcomeFrames() void Screen::setWelcomeFrames()
{ {
if (address_found) { if (address_found) {
// DEBUG_MSG("showing Welcome frames\n"); // LOG_DEBUG("showing Welcome frames\n");
ui.disableAllIndicators(); ui.disableAllIndicators();
static FrameCallback welcomeFrames[] = {drawWelcomeScreen}; static FrameCallback welcomeFrames[] = {drawWelcomeScreen};
@@ -1218,13 +1218,13 @@ void Screen::setWelcomeFrames()
// restore our regular frame list // restore our regular frame list
void Screen::setFrames() void Screen::setFrames()
{ {
DEBUG_MSG("showing standard frames\n"); LOG_DEBUG("showing standard frames\n");
showingNormalScreen = true; showingNormalScreen = true;
moduleFrames = MeshModule::GetMeshModulesWithUIFrames(); 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(); 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) // We don't show the node info our our node (if we have it yet - we should)
size_t numnodes = nodeStatus->getNumTotal(); size_t numnodes = nodeStatus->getNumTotal();
@@ -1243,7 +1243,7 @@ void Screen::setFrames()
normalFrames[numframes++] = drawModuleFrame; 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 we have a critical fault, show it first
if (myNodeInfo.error_code) if (myNodeInfo.error_code)
@@ -1276,7 +1276,7 @@ void Screen::setFrames()
} }
#endif #endif
DEBUG_MSG("Finished building frames. numframes: %d\n", numframes); LOG_DEBUG("Finished building frames. numframes: %d\n", numframes);
ui.setFrames(normalFrames, numframes); ui.setFrames(normalFrames, numframes);
ui.enableAllIndicators(); ui.enableAllIndicators();
@@ -1289,7 +1289,7 @@ void Screen::setFrames()
void Screen::handleStartBluetoothPinScreen(uint32_t pin) void Screen::handleStartBluetoothPinScreen(uint32_t pin)
{ {
DEBUG_MSG("showing bluetooth screen\n"); LOG_DEBUG("showing bluetooth screen\n");
showingNormalScreen = false; showingNormalScreen = false;
static FrameCallback btFrames[] = {drawFrameBluetooth}; static FrameCallback btFrames[] = {drawFrameBluetooth};
@@ -1303,7 +1303,7 @@ void Screen::handleStartBluetoothPinScreen(uint32_t pin)
void Screen::handleShutdownScreen() void Screen::handleShutdownScreen()
{ {
DEBUG_MSG("showing shutdown screen\n"); LOG_DEBUG("showing shutdown screen\n");
showingNormalScreen = false; showingNormalScreen = false;
static FrameCallback shutdownFrames[] = {drawFrameShutdown}; static FrameCallback shutdownFrames[] = {drawFrameShutdown};
@@ -1315,7 +1315,7 @@ void Screen::handleShutdownScreen()
void Screen::handleRebootScreen() void Screen::handleRebootScreen()
{ {
DEBUG_MSG("showing reboot screen\n"); LOG_DEBUG("showing reboot screen\n");
showingNormalScreen = false; showingNormalScreen = false;
static FrameCallback rebootFrames[] = {drawFrameReboot}; static FrameCallback rebootFrames[] = {drawFrameReboot};
@@ -1327,7 +1327,7 @@ void Screen::handleRebootScreen()
void Screen::handleStartFirmwareUpdateScreen() void Screen::handleStartFirmwareUpdateScreen()
{ {
DEBUG_MSG("showing firmware screen\n"); LOG_DEBUG("showing firmware screen\n");
showingNormalScreen = false; showingNormalScreen = false;
static FrameCallback btFrames[] = {drawFrameFirmware}; 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 // the string passed into us probably has a newline, but that would confuse the logging system
// so strip it // so strip it
DEBUG_MSG("Screen: %.*s\n", strlen(text) - 1, text); LOG_DEBUG("Screen: %.*s\n", strlen(text) - 1, text);
if (!useDisplay || !showingNormalScreen) if (!useDisplay || !showingNormalScreen)
return; return;
@@ -1778,7 +1778,7 @@ void Screen::adjustBrightness()
int Screen::handleStatusUpdate(const meshtastic::Status *arg) 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()) { switch (arg->getStatusType()) {
case STATUS_TYPE_NODE: case STATUS_TYPE_NODE:
if (showingNormalScreen && nodeStatus->getLastNumTotal() != nodeStatus->getNumTotal()) { if (showingNormalScreen && nodeStatus->getLastNumTotal() != nodeStatus->getNumTotal()) {

View File

@@ -59,7 +59,7 @@ void TFTDisplay::setDetected(uint8_t detected)
bool TFTDisplay::connect() bool TFTDisplay::connect()
{ {
concurrency::LockGuard g(spiLock); concurrency::LockGuard g(spiLock);
DEBUG_MSG("Doing TFT init\n"); LOG_INFO("Doing TFT init\n");
#ifdef TFT_BL #ifdef TFT_BL
digitalWrite(TFT_BL, HIGH); digitalWrite(TFT_BL, HIGH);

View File

@@ -28,7 +28,7 @@ void RotaryEncoderInterruptBase::init(
this->rotaryLevelA = digitalRead(this->_pinA); this->rotaryLevelA = digitalRead(this->_pinA);
this->rotaryLevelB = digitalRead(this->_pinB); this->rotaryLevelB = digitalRead(this->_pinB);
DEBUG_MSG("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() int32_t RotaryEncoderInterruptBase::runOnce()
@@ -38,13 +38,13 @@ int32_t RotaryEncoderInterruptBase::runOnce()
e.source = this->_originName; e.source = this->_originName;
if (this->action == ROTARY_ACTION_PRESSED) { if (this->action == ROTARY_ACTION_PRESSED) {
DEBUG_MSG("Rotary event Press\n"); LOG_DEBUG("Rotary event Press\n");
e.inputEvent = this->_eventPressed; e.inputEvent = this->_eventPressed;
} else if (this->action == ROTARY_ACTION_CW) { } else if (this->action == ROTARY_ACTION_CW) {
DEBUG_MSG("Rotary event CW\n"); LOG_DEBUG("Rotary event CW\n");
e.inputEvent = this->_eventCw; e.inputEvent = this->_eventCw;
} else if (this->action == ROTARY_ACTION_CCW) { } else if (this->action == ROTARY_ACTION_CCW) {
DEBUG_MSG("Rotary event CCW\n"); LOG_DEBUG("Rotary event CCW\n");
e.inputEvent = this->_eventCcw; e.inputEvent = this->_eventCcw;
} }
@@ -104,7 +104,7 @@ RotaryEncoderInterruptBaseStateType RotaryEncoderInterruptBase::intHandler(bool
newState = ROTARY_EVENT_OCCURRED; newState = ROTARY_EVENT_OCCURRED;
if ((this->action != ROTARY_ACTION_PRESSED) && (this->action != action)) { if ((this->action != ROTARY_ACTION_PRESSED) && (this->action != action)) {
this->action = action; this->action = action;
DEBUG_MSG("Rotary action\n"); LOG_DEBUG("Rotary action\n");
} }
} }
} else if (!actualPinRaising && (otherPinLevel == HIGH)) { } else if (!actualPinRaising && (otherPinLevel == HIGH)) {

View File

@@ -26,7 +26,7 @@ void UpDownInterruptBase::init(
attachInterrupt(this->_pinDown, onIntDown, RISING); attachInterrupt(this->_pinDown, onIntDown, RISING);
attachInterrupt(this->_pinUp, onIntUp, 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); this->_pinDown, this->_pinUp, pinPress);
} }
@@ -34,7 +34,7 @@ void UpDownInterruptBase::intPressHandler()
{ {
InputEvent e; InputEvent e;
e.source = this->_originName; e.source = this->_originName;
DEBUG_MSG("GPIO event Press\n"); LOG_DEBUG("GPIO event Press\n");
e.inputEvent = this->_eventPressed; e.inputEvent = this->_eventPressed;
this->notifyObservers(&e); this->notifyObservers(&e);
} }
@@ -43,7 +43,7 @@ void UpDownInterruptBase::intDownHandler()
{ {
InputEvent e; InputEvent e;
e.source = this->_originName; e.source = this->_originName;
DEBUG_MSG("GPIO event Down\n"); LOG_DEBUG("GPIO event Down\n");
e.inputEvent = this->_eventDown; e.inputEvent = this->_eventDown;
this->notifyObservers(&e); this->notifyObservers(&e);
} }
@@ -52,7 +52,7 @@ void UpDownInterruptBase::intUpHandler()
{ {
InputEvent e; InputEvent e;
e.source = this->_originName; e.source = this->_originName;
DEBUG_MSG("GPIO event Up\n"); LOG_DEBUG("GPIO event Up\n");
e.inputEvent = this->_eventUp; e.inputEvent = this->_eventUp;
this->notifyObservers(&e); this->notifyObservers(&e);
} }

View File

@@ -56,7 +56,7 @@ int32_t KbI2cBase::runOnce()
} }
} }
if (PrintDataBuf != 0) { if (PrintDataBuf != 0) {
DEBUG_MSG("RAK14004 key 0x%x pressed\n", PrintDataBuf); LOG_DEBUG("RAK14004 key 0x%x pressed\n", PrintDataBuf);
InputEvent e; InputEvent e;
e.inputEvent = MATRIXKEY; e.inputEvent = MATRIXKEY;
e.source = this->_originName; e.source = this->_originName;

View File

@@ -174,7 +174,7 @@ void setup()
serialSinceMsec = millis(); 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(); initDeepSleep();
@@ -256,7 +256,7 @@ void setup()
Wire1.beginTransmission(PCF8563_RTC); Wire1.beginTransmission(PCF8563_RTC);
if (Wire1.endTransmission() == 0){ if (Wire1.endTransmission() == 0){
rtc_found = PCF8563_RTC; rtc_found = PCF8563_RTC;
DEBUG_MSG("PCF8563 RTC found\n"); LOG_INFO("PCF8563 RTC found\n");
} }
#endif #endif
@@ -282,7 +282,7 @@ void setup()
#endif #endif
// Hello // 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 #ifdef ARCH_ESP32
// Don't init display if we don't have one or we are waking headless due to a timer event // 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) if (gps)
gpsStatus->observe(&gps->newStatus); gpsStatus->observe(&gps->newStatus);
else else
DEBUG_MSG("Warning: No GPS found - running without GPS\n"); LOG_WARN("No GPS found - running without GPS\n");
nodeStatus->observe(&nodeDB.newStatus); nodeStatus->observe(&nodeDB.newStatus);
@@ -355,7 +355,7 @@ void setup()
// ONCE we will factory reset the GPS for bug #327 // ONCE we will factory reset the GPS for bug #327
if (gps && !devicestate.did_gps_reset) { 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 if (gps->factoryReset()) { // If we don't succeed try again next time
devicestate.did_gps_reset = true; devicestate.did_gps_reset = true;
nodeDB.saveToDisk(SEGMENT_DEVICESTATE); nodeDB.saveToDisk(SEGMENT_DEVICESTATE);
@@ -374,11 +374,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new RF95Interface(RF95_NSS, RF95_IRQ, RF95_RESET, SPI); rIf = new RF95Interface(RF95_NSS, RF95_IRQ, RF95_RESET, SPI);
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find RF95 radio\n"); LOG_WARN("Failed to find RF95 radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("RF95 Radio init succeeded, using RF95 radio\n"); LOG_INFO("RF95 Radio init succeeded, using RF95 radio\n");
} }
} }
#endif #endif
@@ -387,11 +387,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new SX1280Interface(SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY, SPI); rIf = new SX1280Interface(SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY, SPI);
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find SX1280 radio\n"); LOG_WARN("Failed to find SX1280 radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("SX1280 Radio init succeeded, using SX1280 radio\n"); LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio\n");
} }
} }
#endif #endif
@@ -400,11 +400,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new SX1262Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); rIf = new SX1262Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI);
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find SX1262 radio\n"); LOG_WARN("Failed to find SX1262 radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("SX1262 Radio init succeeded, using SX1262 radio\n"); LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio\n");
} }
} }
#endif #endif
@@ -413,11 +413,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new SX1268Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); rIf = new SX1268Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI);
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find SX1268 radio\n"); LOG_WARN("Failed to find SX1268 radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("SX1268 Radio init succeeded, using SX1268 radio\n"); LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio\n");
} }
} }
#endif #endif
@@ -426,11 +426,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new LLCC68Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI); rIf = new LLCC68Interface(SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY, SPI);
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find LLCC68 radio\n"); LOG_WARN("Failed to find LLCC68 radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("LLCC68 Radio init succeeded, using LLCC68 radio\n"); LOG_INFO("LLCC68 Radio init succeeded, using LLCC68 radio\n");
} }
} }
#endif #endif
@@ -439,11 +439,11 @@ void setup()
if (!rIf) { if (!rIf) {
rIf = new SimRadio; rIf = new SimRadio;
if (!rIf->init()) { if (!rIf->init()) {
DEBUG_MSG("Warning: Failed to find simulated radio\n"); LOG_WARN("Failed to find simulated radio\n");
delete rIf; delete rIf;
rIf = NULL; rIf = NULL;
} else { } else {
DEBUG_MSG("Using SIMULATED radio!\n"); LOG_INFO("Using SIMULATED radio!\n");
} }
} }
#endif #endif
@@ -451,11 +451,11 @@ void setup()
// check if the radio chip matches the selected region // check if the radio chip matches the selected region
if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLora())){ 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; config.lora.region = Config_LoRaConfig_RegionCode_UNSET;
nodeDB.saveToDisk(SEGMENT_CONFIG); nodeDB.saveToDisk(SEGMENT_CONFIG);
if(!rIf->reconfigure()) { if(!rIf->reconfigure()) {
DEBUG_MSG("Reconfigure failed, rebooting\n"); LOG_WARN("Reconfigure failed, rebooting\n");
screen->startRebootScreen(); screen->startRebootScreen();
rebootAtMsec = millis() + 5000; 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 // Calculate and save the bit rate to myNodeInfo
// TODO: This needs to be added what ever method changes the channel from the phone. // 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; 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 // 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(); long delayMsec = mainController.runOrDelay();
/* if (mainController.nextThread && delayMsec) /* 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())); */ mainController.nextThread->tillRun(millis())); */
// We want to sleep as long as possible here - because it saves power // We want to sleep as long as possible here - because it saves power
if (!runASAP && loopCanSleep()) { if (!runASAP && loopCanSleep()) {
// if(delayMsec > 100) DEBUG_MSG("sleeping %ld\n", delayMsec); // if(delayMsec > 100) LOG_DEBUG("sleeping %ld\n", delayMsec);
mainDelay.delay(delayMsec); mainDelay.delay(delayMsec);
} }
// if (didWake) DEBUG_MSG("wake!\n"); // if (didWake) LOG_DEBUG("wake!\n");
} }

View File

@@ -255,10 +255,10 @@ static int mem_test(uint32_t *_start, size_t len, bool doRead = true, bool doWri
int rcode = 0; int rcode = 0;
incr = 1; incr = 1;
//DEBUG_MSG("memtest read=%d, write=%d\n", doRead, doWrite); //LOG_DEBUG("memtest read=%d, write=%d\n", doRead, doWrite);
if (doWrite) { if (doWrite) {
//DEBUG_MSG("writing\n"); //LOG_DEBUG("writing\n");
for (addr = start, val = pattern; addr < end; addr++) { for (addr = start, val = pattern; addr < end; addr++) {
*addr = val; *addr = val;
val += incr; val += incr;
@@ -266,11 +266,11 @@ static int mem_test(uint32_t *_start, size_t len, bool doRead = true, bool doWri
} }
if (doRead) { if (doRead) {
//DEBUG_MSG("reading\n"); //LOG_DEBUG("reading\n");
for (addr = start, val = pattern; addr < end; addr++) { for (addr = start, val = pattern; addr < end; addr++) {
readback = *addr; readback = *addr;
if (readback != val) { if (readback != val) {
DEBUG_MSG("Mem error @ 0x%08X: " LOG_ERROR("Mem error @ 0x%08X: "
"found 0x%08lX, expected 0x%08lX\n", "found 0x%08lX, expected 0x%08lX\n",
addr, readback, val); addr, readback, val);
rcode++; rcode++;

View File

@@ -106,30 +106,30 @@ CryptoKey Channels::getKey(ChannelIndex chIndex)
k.length = channelSettings.psk.size; k.length = channelSettings.psk.size;
if (k.length == 0) { if (k.length == 0) {
if (ch.role == Channel_Role_SECONDARY) { 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); k = getKey(primaryIndex);
} else } else
DEBUG_MSG("Warning: User disabled encryption\n"); LOG_WARN("User disabled encryption\n");
} else if (k.length == 1) { } else if (k.length == 1) {
// Convert the short single byte variants of psk into variant that can be used more generally // Convert the short single byte variants of psk into variant that can be used more generally
uint8_t pskIndex = k.bytes[0]; 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) if (pskIndex == 0)
k.length = 0; // Turn off encryption k.length = 0; // Turn off encryption
else if (oemStore.oem_aes_key.size > 1) { else if (oemStore.oem_aes_key.size > 1) {
// Use the OEM key // 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); memcpy(k.bytes, oemStore.oem_aes_key.bytes , oemStore.oem_aes_key.size);
k.length = oemStore.oem_aes_key.size; k.length = oemStore.oem_aes_key.size;
// Bump up the last byte of PSK as needed // Bump up the last byte of PSK as needed
uint8_t *last = k.bytes + oemStore.oem_aes_key.size - 1; uint8_t *last = k.bytes + oemStore.oem_aes_key.size - 1;
*last = *last + pskIndex - 1; // index of 1 means no change vs defaultPSK *last = *last + pskIndex - 1; // index of 1 means no change vs defaultPSK
if (k.length < 16) { 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; k.length = 16;
} else if (k.length < 32 && 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; k.length = 32;
} }
} else { } else {
@@ -142,12 +142,12 @@ CryptoKey Channels::getKey(ChannelIndex chIndex)
} else if (k.length < 16) { } 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 // 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 // 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; k.length = 16;
} else if (k.length < 32 && 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 // 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 // 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; k.length = 32;
} }
} }
@@ -308,11 +308,11 @@ const char *Channels::getPrimaryName()
bool Channels::decryptForHash(ChannelIndex chIndex, ChannelHash channelHash) bool Channels::decryptForHash(ChannelIndex chIndex, ChannelHash channelHash)
{ {
if (chIndex > getNumChannels() || getHash(chIndex) != 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); // channelHash);
return false; return false;
} else { } 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); setCrypto(chIndex);
return true; return true;
} }

View File

@@ -3,7 +3,7 @@
void CryptoEngine::setKey(const CryptoKey &k) 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; 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) 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) 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");
} }
/** /**

View File

@@ -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 bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK
if (isAck && p->to != getNodeNum()) { if (isAck && p->to != getNodeNum()) {
// do not flood direct message that is ACKed // 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 Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM
} }
if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) { if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) {
@@ -47,17 +47,17 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c)
traceRouteModule->updateRoute(tosend); 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 // 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 // We are careful not to call our hooked version of send() - because we don't want to check this again
Router::send(tosend); Router::send(tosend);
} else { } else {
DEBUG_MSG("Not rebroadcasting. Role = Role_ClientMute\n"); LOG_DEBUG("Not rebroadcasting. Role = Role_ClientMute\n");
} }
} else { } else {
DEBUG_MSG("Ignoring a simple (0 id) broadcast\n"); LOG_DEBUG("Ignoring a simple (0 id) broadcast\n");
} }
} }

View File

@@ -52,7 +52,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr
p->to = to; p->to = to;
p->decoded.request_id = idFrom; p->decoded.request_id = idFrom;
p->channel = chIndex; 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_ERROR("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id);
return p; return p;
} }
@@ -68,7 +68,7 @@ MeshPacket *MeshModule::allocErrorResponse(Routing_Error err, const MeshPacket *
void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) void MeshModule::callPlugins(const MeshPacket &mp, RxSource src)
{ {
// DEBUG_MSG("In call modules\n"); // LOG_DEBUG("In call modules\n");
bool moduleFound = false; bool moduleFound = false;
// We now allow **encrypted** packets to pass through the modules // 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 assert(!pi.myReply); // If it is !null it means we have a bug, because it should have been sent the previous time
if (wantsPacket) { if (wantsPacket) {
DEBUG_MSG("Module '%s' wantsPacket=%d\n", pi.name, wantsPacket); LOG_DEBUG("Module '%s' wantsPacket=%d\n", pi.name, wantsPacket);
moduleFound = true; moduleFound = true;
@@ -134,20 +134,20 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src)
// any other node. // any other node.
if (mp.decoded.want_response && toUs && (getFrom(&mp) != ourNodeNum || mp.to == ourNodeNum) && !currentReply) { if (mp.decoded.want_response && toUs && (getFrom(&mp) != ourNodeNum || mp.to == ourNodeNum) && !currentReply) {
pi.sendResponse(mp); pi.sendResponse(mp);
DEBUG_MSG("Module '%s' sent a response\n", pi.name); LOG_INFO("Module '%s' sent a response\n", pi.name);
} else { } 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 the requester didn't ask for a response we might need to discard unused replies to prevent memory leaks
if (pi.myReply) { if (pi.myReply) {
DEBUG_MSG("Discarding an unneeded response\n"); LOG_DEBUG("Discarding an unneeded response\n");
packetPool.release(pi.myReply); packetPool.release(pi.myReply);
pi.myReply = NULL; pi.myReply = NULL;
} }
if (handled == ProcessMessage::STOP) { 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; 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 // 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 // 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) // 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 // 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) 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, mp.decoded.portnum,
(src == RX_SRC_LOCAL) ? "LOCAL":"REMOTE"); (src == RX_SRC_LOCAL) ? "LOCAL":"REMOTE");
} }
@@ -199,7 +199,7 @@ void MeshModule::sendResponse(const MeshPacket &req)
currentReply = r; currentReply = r;
} else { } else {
// Ignore - this is now expected behavior for routing module (because it ignores some replies) // 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 *> MeshModule::GetMeshModulesWithUIFrames()
for (auto i = modules->begin(); i != modules->end(); ++i) { for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i; auto &pi = **i;
if (pi.wantUIFrame()) { if (pi.wantUIFrame()) {
DEBUG_MSG("Module wants a UI Frame\n"); LOG_DEBUG("Module wants a UI Frame\n");
modulesWithUIFrames.push_back(&pi); modulesWithUIFrames.push_back(&pi);
} }
} }
@@ -244,7 +244,7 @@ void MeshModule::observeUIEvents(
Observable<const UIFrameEvent *> *observable = Observable<const UIFrameEvent *> *observable =
pi.getUIFrameObservable(); pi.getUIFrameObservable();
if (observable != NULL) { if (observable != NULL) {
DEBUG_MSG("Module wants a UI Frame\n"); LOG_DEBUG("Module wants a UI Frame\n");
observer->observe(observable); observer->observe(observable);
} }
} }
@@ -261,7 +261,7 @@ AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const MeshP
if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE)
{ {
// In case we have a response it always has priority. // 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, pi.name,
response->which_payload_variant); response->which_payload_variant);
handled = h; handled = h;

View File

@@ -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 /// The owner User record just got updated, update our node DB and broadcast the info into the mesh
void MeshService::reloadOwner(bool shouldSave) void MeshService::reloadOwner(bool shouldSave)
{ {
// DEBUG_MSG("reloadOwner()\n"); // LOG_DEBUG("reloadOwner()\n");
// update our local data directly // update our local data directly
nodeDB.updateUser(nodeDB.getNodeNum(), owner); nodeDB.updateUser(nodeDB.getNodeNum(), owner);
assert(nodeInfoModule); assert(nodeInfoModule);
@@ -140,7 +140,7 @@ void MeshService::handleToRadio(MeshPacket &p)
// Switch the port from PortNum_SIMULATOR_APP back to the original PortNum // Switch the port from PortNum_SIMULATOR_APP back to the original PortNum
p.decoded.portnum = decoded->portnum; p.decoded.portnum = decoded->portnum;
} else } else
DEBUG_MSG("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 // Let SimRadio receive as if it did via its LoRa chip
SimRadio::instance->startReceive(&p); SimRadio::instance->startReceive(&p);
@@ -148,7 +148,7 @@ void MeshService::handleToRadio(MeshPacket &p)
} }
#endif #endif
if (p.from != 0) { // We don't let phones assign nodenums to their sent messages 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; p.from = 0;
} else { } else {
// p.from = nodeDB.getNodeNum(); // 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 (node->has_position && (node->position.latitude_i != 0 || node->position.longitude_i != 0)) {
if (positionModule) { if (positionModule) {
DEBUG_MSG("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); positionModule->sendOurPosition(dest, wantReplies);
} }
} else { } else {
if (nodeInfoModule) { if (nodeInfoModule) {
DEBUG_MSG("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); nodeInfoModule->sendOurNodeInfo(dest, wantReplies);
} }
} }
@@ -212,7 +212,7 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies)
void MeshService::sendToPhone(MeshPacket *p) void MeshService::sendToPhone(MeshPacket *p)
{ {
if (toPhoneQueue.numFree() == 0) { if (toPhoneQueue.numFree() == 0) {
DEBUG_MSG("NOTE: tophone queue is full, discarding oldest\n"); LOG_WARN("ToPhone queue is full, discarding oldest\n");
MeshPacket *d = toPhoneQueue.dequeuePtr(0); MeshPacket *d = toPhoneQueue.dequeuePtr(0);
if (d) if (d)
releaseToPool(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 GPS has lost lock, if we are fixed position we should just keep using
// the old position // the old position
#ifdef GPS_EXTRAVERBOSE #ifdef GPS_EXTRAVERBOSE
DEBUG_MSG("onGPSchanged() - lost validLocation\n"); LOG_DEBUG("onGPSchanged() - lost validLocation\n");
#endif #endif
if (config.position.fixed_position) { if (config.position.fixed_position) {
DEBUG_MSG("WARNING: Using fixed position\n"); LOG_WARN("Using fixed position\n");
pos = node->position; pos = node->position;
} }
} }
@@ -276,7 +276,7 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus)
pos.time = getValidTime(RTCQualityGPS); pos.time = getValidTime(RTCQualityGPS);
// In debug logs, identify position by @timestamp:stage (stage 4 = nodeDB) // 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); pos.longitude_i, pos.altitude);
// Update our current position in the local DB // Update our current position in the local DB

View File

@@ -86,7 +86,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset)
} }
if (channelFile.channels_count != MAX_NUM_CHANNELS) { if (channelFile.channels_count != MAX_NUM_CHANNELS) {
DEBUG_MSG("Setting default channel and radio preferences!\n"); LOG_INFO("Setting default channel and radio preferences!\n");
channels.initDefaults(); channels.initDefaults();
} }
@@ -96,7 +96,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset)
// temp hack for quicker testing // temp hack for quicker testing
// devicestate.no_save = true; // devicestate.no_save = true;
if (devicestate.no_save) { 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 // Sleep quite frequently to stress test the BLE comms, broadcast position every 6 mins
config.display.screen_on_secs = 10; config.display.screen_on_secs = 10;
@@ -114,7 +114,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset)
initRegion(); initRegion();
if (didFactoryReset) { if (didFactoryReset) {
DEBUG_MSG("Rebooting due to factory reset"); LOG_INFO("Rebooting due to factory reset");
screen->startRebootScreen(); screen->startRebootScreen();
rebootAtMsec = millis() + (5 * 1000); rebootAtMsec = millis() + (5 * 1000);
} }
@@ -124,7 +124,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset)
bool NodeDB::factoryReset() bool NodeDB::factoryReset()
{ {
DEBUG_MSG("Performing factory reset!\n"); LOG_INFO("Performing factory reset!\n");
// first, remove the "/prefs" (this removes most prefs) // first, remove the "/prefs" (this removes most prefs)
rmDir("/prefs"); rmDir("/prefs");
// second, install default state (this will deal with the duplicate mac address issue) // second, install default state (this will deal with the duplicate mac address issue)
@@ -140,7 +140,7 @@ bool NodeDB::factoryReset()
#endif #endif
#ifdef ARCH_NRF52 #ifdef ARCH_NRF52
Bluefruit.begin(); Bluefruit.begin();
DEBUG_MSG("Clearing bluetooth bonds!\n"); LOG_INFO("Clearing bluetooth bonds!\n");
bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_PERIPH);
bond_print_list(BLE_GAP_ROLE_CENTRAL); bond_print_list(BLE_GAP_ROLE_CENTRAL);
Bluefruit.Periph.clearBonds(); Bluefruit.Periph.clearBonds();
@@ -151,7 +151,7 @@ bool NodeDB::factoryReset()
void NodeDB::installDefaultConfig() void NodeDB::installDefaultConfig()
{ {
DEBUG_MSG("Installing default LocalConfig\n"); LOG_INFO("Installing default LocalConfig\n");
memset(&config, 0, sizeof(LocalConfig)); memset(&config, 0, sizeof(LocalConfig));
config.version = DEVICESTATE_CUR_VER; config.version = DEVICESTATE_CUR_VER;
config.has_device = true; config.has_device = true;
@@ -203,7 +203,7 @@ void NodeDB::initConfigIntervals()
void NodeDB::installDefaultModuleConfig() void NodeDB::installDefaultModuleConfig()
{ {
DEBUG_MSG("Installing default ModuleConfig\n"); LOG_INFO("Installing default ModuleConfig\n");
memset(&moduleConfig, 0, sizeof(ModuleConfig)); memset(&moduleConfig, 0, sizeof(ModuleConfig));
moduleConfig.version = DEVICESTATE_CUR_VER; moduleConfig.version = DEVICESTATE_CUR_VER;
@@ -230,7 +230,7 @@ void NodeDB::initModuleConfigIntervals()
void NodeDB::installDefaultChannels() void NodeDB::installDefaultChannels()
{ {
DEBUG_MSG("Installing default ChannelFile\n"); LOG_INFO("Installing default ChannelFile\n");
memset(&channelFile, 0, sizeof(ChannelFile)); memset(&channelFile, 0, sizeof(ChannelFile));
channelFile.version = DEVICESTATE_CUR_VER; channelFile.version = DEVICESTATE_CUR_VER;
} }
@@ -244,7 +244,7 @@ void NodeDB::resetNodes()
void NodeDB::installDefaultDeviceState() void NodeDB::installDefaultDeviceState()
{ {
DEBUG_MSG("Installing default DeviceState\n"); LOG_INFO("Installing default DeviceState\n");
memset(&devicestate, 0, sizeof(DeviceState)); memset(&devicestate, 0, sizeof(DeviceState));
*numNodes = 0; *numNodes = 0;
@@ -275,7 +275,7 @@ void NodeDB::installDefaultDeviceState()
void NodeDB::init() void NodeDB::init()
{ {
DEBUG_MSG("Initializing NodeDB\n"); LOG_INFO("Initializing NodeDB\n");
loadFromDisk(); loadFromDisk();
uint32_t devicestateCRC = crc32Buffer(&devicestate, sizeof(devicestate)); uint32_t devicestateCRC = crc32Buffer(&devicestate, sizeof(devicestate));
@@ -311,7 +311,7 @@ void NodeDB::init()
preferences.begin("meshtastic", false); preferences.begin("meshtastic", false);
myNodeInfo.reboot_count = preferences.getUInt("rebootCounter", 0); myNodeInfo.reboot_count = preferences.getUInt("rebootCounter", 0);
preferences.end(); 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 ESP32 has a wifi radio. This will need to be modified at some point so
* the test isn't so simplistic. * the test isn't so simplistic.
@@ -320,7 +320,7 @@ void NodeDB::init()
#endif #endif
resetRadioConfig(); // If bogus settings got saved, then fix them 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))) if (devicestateCRC != crc32Buffer(&devicestate, sizeof(devicestate)))
saveWhat |= SEGMENT_DEVICESTATE; saveWhat |= SEGMENT_DEVICESTATE;
@@ -352,7 +352,7 @@ void NodeDB::pickNewNodeNum()
NodeInfo *found; NodeInfo *found;
while ((found = getNode(r)) && memcmp(found->user.macaddr, owner.macaddr, sizeof(owner.macaddr))) { 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 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; 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); auto f = FSCom.open(filename, FILE_O_READ);
if (f) { if (f) {
DEBUG_MSG("Loading %s\n", filename); LOG_INFO("Loading %s\n", filename);
pb_istream_t stream = {&readcb, &f, protoSize}; 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); memset(dest_struct, 0, objSize);
if (!pb_decode(&stream, fields, dest_struct)) { if (!pb_decode(&stream, fields, dest_struct)) {
DEBUG_MSG("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 { } else {
okay = true; okay = true;
} }
f.close(); f.close();
} else { } else {
DEBUG_MSG("No %s preferences found\n", filename); LOG_INFO("No %s preferences found\n", filename);
} }
#else #else
DEBUG_MSG("ERROR: Filesystem not implemented\n"); LOG_ERROR("ERROR: Filesystem not implemented\n");
#endif #endif
return okay; return okay;
} }
@@ -405,10 +405,10 @@ void NodeDB::loadFromDisk()
installDefaultDeviceState(); // Our in RAM copy might now be corrupt installDefaultDeviceState(); // Our in RAM copy might now be corrupt
} else { } else {
if (devicestate.version < DEVICESTATE_MIN_VER) { if (devicestate.version < DEVICESTATE_MIN_VER) {
DEBUG_MSG("Warn: devicestate %d is old, discarding\n", devicestate.version); LOG_WARN("Devicestate %d is old, discarding\n", devicestate.version);
factoryReset(); factoryReset();
} else { } else {
DEBUG_MSG("Loaded saved devicestate version %d\n", devicestate.version); LOG_INFO("Loaded saved devicestate version %d\n", devicestate.version);
} }
} }
@@ -416,10 +416,10 @@ void NodeDB::loadFromDisk()
installDefaultConfig(); // Our in RAM copy might now be corrupt installDefaultConfig(); // Our in RAM copy might now be corrupt
} else { } else {
if (config.version < DEVICESTATE_MIN_VER) { if (config.version < DEVICESTATE_MIN_VER) {
DEBUG_MSG("Warn: config %d is old, discarding\n", config.version); LOG_WARN("config %d is old, discarding\n", config.version);
installDefaultConfig(); installDefaultConfig();
} else { } else {
DEBUG_MSG("Loaded saved config version %d\n", config.version); LOG_INFO("Loaded saved config version %d\n", config.version);
} }
} }
@@ -427,10 +427,10 @@ void NodeDB::loadFromDisk()
installDefaultModuleConfig(); // Our in RAM copy might now be corrupt installDefaultModuleConfig(); // Our in RAM copy might now be corrupt
} else { } else {
if (moduleConfig.version < DEVICESTATE_MIN_VER) { if (moduleConfig.version < DEVICESTATE_MIN_VER) {
DEBUG_MSG("Warn: moduleConfig %d is old, discarding\n", moduleConfig.version); LOG_WARN("moduleConfig %d is old, discarding\n", moduleConfig.version);
installDefaultModuleConfig(); installDefaultModuleConfig();
} else { } else {
DEBUG_MSG("Loaded saved moduleConfig version %d\n", moduleConfig.version); LOG_INFO("Loaded saved moduleConfig version %d\n", moduleConfig.version);
} }
} }
@@ -438,15 +438,15 @@ void NodeDB::loadFromDisk()
installDefaultChannels(); // Our in RAM copy might now be corrupt installDefaultChannels(); // Our in RAM copy might now be corrupt
} else { } else {
if (channelFile.version < DEVICESTATE_MIN_VER) { if (channelFile.version < DEVICESTATE_MIN_VER) {
DEBUG_MSG("Warn: channelFile %d is old, discarding\n", channelFile.version); LOG_WARN("channelFile %d is old, discarding\n", channelFile.version);
installDefaultChannels(); installDefaultChannels();
} else { } else {
DEBUG_MSG("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)) if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), &OEMStore_msg, &oemStore))
DEBUG_MSG("Loaded OEMStore\n"); LOG_INFO("Loaded OEMStore\n");
} }
/** Save a protobuf from a file, return true for success */ /** 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"; filenameTmp += ".tmp";
auto f = FSCom.open(filenameTmp.c_str(), FILE_O_WRITE); auto f = FSCom.open(filenameTmp.c_str(), FILE_O_WRITE);
if (f) { if (f) {
DEBUG_MSG("Saving %s\n", filename); LOG_INFO("Saving %s\n", filename);
pb_ostream_t stream = {&writecb, &f, protoSize}; pb_ostream_t stream = {&writecb, &f, protoSize};
if (!pb_encode(&stream, fields, dest_struct)) { if (!pb_encode(&stream, fields, dest_struct)) {
DEBUG_MSG("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 { } else {
okay = true; okay = true;
} }
@@ -471,11 +471,11 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_
// brief window of risk here ;-) // brief window of risk here ;-)
if (FSCom.exists(filename) && !FSCom.remove(filename)) 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)) if (!renameFile(filenameTmp.c_str(), filename))
DEBUG_MSG("Error: can't rename new pref file\n"); LOG_ERROR("Error: can't rename new pref file\n");
} else { } else {
DEBUG_MSG("Can't write prefs\n"); LOG_ERROR("Can't write prefs\n");
#ifdef ARCH_NRF52 #ifdef ARCH_NRF52
static uint8_t failedCounter = 0; static uint8_t failedCounter = 0;
failedCounter++; failedCounter++;
@@ -487,7 +487,7 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_
#endif #endif
} }
#else #else
DEBUG_MSG("ERROR: Filesystem not implemented\n"); LOG_ERROR("ERROR: Filesystem not implemented\n");
#endif #endif
return okay; return okay;
} }
@@ -548,7 +548,7 @@ void NodeDB::saveToDisk(int saveWhat)
saveChannelsToDisk(); saveChannelsToDisk();
} }
} else { } 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) { if (src == RX_SRC_LOCAL) {
// Local packet, fully authoritative // 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_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); p.longitude_i, p.altitude);
info->position = p; info->position = p;
} else if ((p.time > 0) && !p.latitude_i && !p.longitude_i && !p.timestamp && !p.location_source) { } 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 // FIXME SPECIAL TIME SETTING PACKET FROM EUD TO RADIO
// (stop-gap fix for issue #900) // (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; info->position.time = p.time;
} else { } else {
@@ -615,7 +615,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src)
// recorded based on the packet rxTime // recorded based on the packet rxTime
// //
// FIXME perhaps handle RX_SRC_USER separately? // 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_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 // First, back up fields that we want to protect from overwrite
uint32_t tmp_time = info->position.time; 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) { if (src == RX_SRC_LOCAL) {
// Local packet, fully authoritative // Local packet, fully authoritative
DEBUG_MSG("updateTelemetry LOCAL\n"); LOG_DEBUG("updateTelemetry LOCAL\n");
} else { } 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->device_metrics = t.variant.device_metrics;
info->has_device_metrics = true; info->has_device_metrics = true;
@@ -664,13 +664,13 @@ void NodeDB::updateUser(uint32_t nodeId, const User &p)
return; 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, bool changed = memcmp(&info->user, &p,
sizeof(info->user)); // Both of these blocks start as filled with zero so I think this is okay sizeof(info->user)); // Both of these blocks start as filled with zero so I think this is okay
info->user = p; 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; info->has_user = true;
if (changed) { if (changed) {
@@ -689,7 +689,7 @@ void NodeDB::updateUser(uint32_t nodeId, const User &p)
void NodeDB::updateFrom(const MeshPacket &mp) void NodeDB::updateFrom(const MeshPacket &mp)
{ {
if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.from) { 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)); NodeInfo *info = getOrCreateNode(getFrom(&mp));
if (!info) { if (!info) {
@@ -756,9 +756,9 @@ void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *f
String lcd = String("Critical error ") + code + "!\n"; String lcd = String("Critical error ") + code + "!\n";
screen->print(lcd.c_str()); screen->print(lcd.c_str());
if (filename) if (filename)
DEBUG_MSG("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 else
DEBUG_MSG("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 // Record error to DB
myNodeInfo.error_code = code; 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 // Currently portuino is mostly used for simulation. Make sue the user notices something really bad happend
#ifdef ARCH_PORTDUINO #ifdef ARCH_PORTDUINO
DEBUG_MSG("A critical failure occurred, portduino is exiting..."); LOG_ERROR("A critical failure occurred, portduino is exiting...");
exit(2); exit(2);
#endif #endif
} }

View File

@@ -14,7 +14,7 @@ PacketHistory::PacketHistory()
bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate)
{ {
if (p->id == 0) { 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 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) { 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) { if (withUpdate) {
@@ -61,7 +61,7 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate)
void PacketHistory::clearExpiredRecentPackets() { void PacketHistory::clearExpiredRecentPackets() {
uint32_t now = millis(); 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(); ) { for (auto it = recentPackets.begin(); it != recentPackets.end(); ) {
if ((now - it->rxTimeMsec) >= FLOOD_EXPIRE_TIME) { 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());
} }

View File

@@ -37,7 +37,7 @@ void PhoneAPI::handleStartConfig()
// even if we were already connected - restart our state machine // even if we were already connected - restart our state machine
state = STATE_SEND_MY_INFO; state = STATE_SEND_MY_INFO;
DEBUG_MSG("Starting API client config\n"); LOG_INFO("Starting API client config\n");
nodeInfoForPhone = NULL; // Don't keep returning old nodeinfos 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 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 // this will break once we have multiple instances of PhoneAPI running independently
@@ -60,7 +60,7 @@ void PhoneAPI::checkConnectionTimeout()
if (isConnected()) { if (isConnected()) {
bool newContact = checkIsConnected(); bool newContact = checkIsConnected();
if (!newContact) { if (!newContact) {
DEBUG_MSG("Lost phone connection\n"); LOG_INFO("Lost phone connection\n");
close(); close();
} }
} }
@@ -83,20 +83,20 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength)
return handleToRadioPacket(toRadioScratch.packet); return handleToRadioPacket(toRadioScratch.packet);
case ToRadio_want_config_id_tag: case ToRadio_want_config_id_tag:
config_nonce = toRadioScratch.want_config_id; config_nonce = toRadioScratch.want_config_id;
DEBUG_MSG("Client wants config, nonce=%u\n", config_nonce); LOG_INFO("Client wants config, nonce=%u\n", config_nonce);
handleStartConfig(); handleStartConfig();
break; break;
case ToRadio_disconnect_tag: case ToRadio_disconnect_tag:
DEBUG_MSG("Disconnecting from phone\n"); LOG_INFO("Disconnecting from phone\n");
close(); close();
break; break;
default: default:
// Ignore nop messages // Ignore nop messages
// DEBUG_MSG("Error: unexpected ToRadio variant\n"); // LOG_DEBUG("Error: unexpected ToRadio variant\n");
break; break;
} }
} else { } else {
DEBUG_MSG("Error: ignoring malformed toradio\n"); LOG_ERROR("Error: ignoring malformed toradio\n");
} }
return false; return false;
@@ -119,7 +119,7 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength)
size_t PhoneAPI::getFromRadio(uint8_t *buf) size_t PhoneAPI::getFromRadio(uint8_t *buf)
{ {
if (!available()) { if (!available()) {
// DEBUG_MSG("getFromRadio=not available\n"); // LOG_DEBUG("getFromRadio=not available\n");
return 0; return 0;
} }
// In case we send a FromRadio packet // In case we send a FromRadio packet
@@ -128,11 +128,11 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
// Advance states as needed // Advance states as needed
switch (state) { switch (state) {
case STATE_SEND_NOTHING: case STATE_SEND_NOTHING:
DEBUG_MSG("getFromRadio=STATE_SEND_NOTHING\n"); LOG_INFO("getFromRadio=STATE_SEND_NOTHING\n");
break; break;
case STATE_SEND_MY_INFO: case STATE_SEND_MY_INFO:
DEBUG_MSG("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 // 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. // app not to send locations on our behalf.
myNodeInfo.has_gps = gps && gps->isConnected(); // Update with latest GPS connect info myNodeInfo.has_gps = gps && gps->isConnected(); // Update with latest GPS connect info
@@ -144,18 +144,18 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
break; break;
case STATE_SEND_NODEINFO: { case STATE_SEND_NODEINFO: {
DEBUG_MSG("getFromRadio=STATE_SEND_NODEINFO\n"); LOG_INFO("getFromRadio=STATE_SEND_NODEINFO\n");
const NodeInfo *info = nodeInfoForPhone; const NodeInfo *info = nodeInfoForPhone;
nodeInfoForPhone = NULL; // We just consumed a nodeinfo, will need a new one next time nodeInfoForPhone = NULL; // We just consumed a nodeinfo, will need a new one next time
if (info) { 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_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); info->user.long_name);
fromRadioScratch.which_payload_variant = FromRadio_node_info_tag; fromRadioScratch.which_payload_variant = FromRadio_node_info_tag;
fromRadioScratch.node_info = *info; fromRadioScratch.node_info = *info;
// Stay in current state until done sending nodeinfos // Stay in current state until done sending nodeinfos
} else { } else {
DEBUG_MSG("Done sending nodeinfos\n"); LOG_INFO("Done sending nodeinfos\n");
state = STATE_SEND_CHANNELS; state = STATE_SEND_CHANNELS;
// Go ahead and send that ID right now // Go ahead and send that ID right now
return getFromRadio(buf); return getFromRadio(buf);
@@ -164,7 +164,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
} }
case STATE_SEND_CHANNELS: case STATE_SEND_CHANNELS:
DEBUG_MSG("getFromRadio=STATE_SEND_CHANNELS\n"); LOG_INFO("getFromRadio=STATE_SEND_CHANNELS\n");
fromRadioScratch.which_payload_variant = FromRadio_channel_tag; fromRadioScratch.which_payload_variant = FromRadio_channel_tag;
fromRadioScratch.channel = channels.getByIndex(config_state); fromRadioScratch.channel = channels.getByIndex(config_state);
config_state++; config_state++;
@@ -176,7 +176,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
break; break;
case STATE_SEND_CONFIG: case STATE_SEND_CONFIG:
DEBUG_MSG("getFromRadio=STATE_SEND_CONFIG\n"); LOG_INFO("getFromRadio=STATE_SEND_CONFIG\n");
fromRadioScratch.which_payload_variant = FromRadio_config_tag; fromRadioScratch.which_payload_variant = FromRadio_config_tag;
switch (config_state) { switch (config_state) {
case Config_device_tag: case Config_device_tag:
@@ -222,7 +222,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
break; break;
case STATE_SEND_MODULECONFIG: case STATE_SEND_MODULECONFIG:
DEBUG_MSG("getFromRadio=STATE_SEND_MODULECONFIG\n"); LOG_INFO("getFromRadio=STATE_SEND_MODULECONFIG\n");
fromRadioScratch.which_payload_variant = FromRadio_moduleConfig_tag; fromRadioScratch.which_payload_variant = FromRadio_moduleConfig_tag;
switch (config_state) { switch (config_state) {
case ModuleConfig_mqtt_tag: case ModuleConfig_mqtt_tag:
@@ -272,7 +272,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
break; break;
case STATE_SEND_COMPLETE_ID: case STATE_SEND_COMPLETE_ID:
DEBUG_MSG("getFromRadio=STATE_SEND_COMPLETE_ID\n"); LOG_INFO("getFromRadio=STATE_SEND_COMPLETE_ID\n");
fromRadioScratch.which_payload_variant = FromRadio_config_complete_id_tag; fromRadioScratch.which_payload_variant = FromRadio_config_complete_id_tag;
fromRadioScratch.config_complete_id = config_nonce; fromRadioScratch.config_complete_id = config_nonce;
config_nonce = 0; config_nonce = 0;
@@ -281,7 +281,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
case STATE_SEND_PACKETS: case STATE_SEND_PACKETS:
// Do we have a message from the mesh? // Do we have a message from the mesh?
DEBUG_MSG("getFromRadio=STATE_SEND_PACKETS\n"); LOG_INFO("getFromRadio=STATE_SEND_PACKETS\n");
if (packetForPhone) { if (packetForPhone) {
printPacket("phone downloaded packet", packetForPhone); printPacket("phone downloaded packet", packetForPhone);
@@ -301,17 +301,17 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
// Encapsulate as a FromRadio packet // Encapsulate as a FromRadio packet
size_t numbytes = pb_encode_to_bytes(buf, FromRadio_size, &FromRadio_msg, &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); LOG_DEBUG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes);
return numbytes; return numbytes;
} }
DEBUG_MSG("no FromRadio packet available\n"); LOG_DEBUG("no FromRadio packet available\n");
return 0; return 0;
} }
void PhoneAPI::handleDisconnect() void PhoneAPI::handleDisconnect()
{ {
DEBUG_MSG("PhoneAPI disconnect\n"); LOG_INFO("PhoneAPI disconnect\n");
} }
void PhoneAPI::releasePhonePacket() void PhoneAPI::releasePhonePacket()
@@ -345,7 +345,7 @@ bool PhoneAPI::available()
if (!packetForPhone) if (!packetForPhone)
packetForPhone = service.getForPhone(); packetForPhone = service.getForPhone();
bool hasPacket = !!packetForPhone; bool hasPacket = !!packetForPhone;
// DEBUG_MSG("available hasPacket=%d\n", hasPacket); // LOG_DEBUG("available hasPacket=%d\n", hasPacket);
return hasPacket; return hasPacket;
} }
default: default:
@@ -373,10 +373,10 @@ int PhoneAPI::onNotify(uint32_t newValue)
// from idle) // from idle)
if (state == STATE_SEND_PACKETS) { if (state == STATE_SEND_PACKETS) {
DEBUG_MSG("Telling client we have new packets %u\n", newValue); LOG_INFO("Telling client we have new packets %u\n", newValue);
onNowHasData(newValue); onNowHasData(newValue);
} else } else
DEBUG_MSG("(Client not yet interested in packets)\n"); LOG_DEBUG("(Client not yet interested in packets)\n");
return 0; return 0;
} }

View File

@@ -44,7 +44,7 @@ template <class T> class ProtobufModule : protected SinglePortModule
p->decoded.payload.size = p->decoded.payload.size =
pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), fields, &payload); 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; return p;
} }
@@ -70,7 +70,7 @@ template <class T> class ProtobufModule : protected SinglePortModule
// it would be better to update even if the message was destined to others. // it would be better to update even if the message was destined to others.
auto &p = mp.decoded; 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_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum,
p.payload.size); p.payload.size);
T scratch; T scratch;
@@ -80,7 +80,7 @@ template <class T> class ProtobufModule : protected SinglePortModule
if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) {
decoded = &scratch; decoded = &scratch;
} else { } else {
DEBUG_MSG("Error decoding protobuf module!\n"); LOG_ERROR("Error decoding protobuf module!\n");
// if we can't decode it, nobody can process it! // if we can't decode it, nobody can process it!
return ProcessMessage::STOP; return ProcessMessage::STOP;
} }

View File

@@ -68,17 +68,17 @@ bool RF95Interface::init()
setTransmitEnable(false); setTransmitEnable(false);
int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, currentLimit, preambleLength); int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, currentLimit, preambleLength);
DEBUG_MSG("RF95 init result %d\n", res); LOG_INFO("RF95 init result %d\n", res);
DEBUG_MSG("Frequency set to %f\n", getFreq()); LOG_INFO("Frequency set to %f\n", getFreq());
DEBUG_MSG("Bandwidth set to %f\n", bw); LOG_INFO("Bandwidth set to %f\n", bw);
DEBUG_MSG("Power output set to %d\n", power); LOG_INFO("Power output set to %d\n", power);
// current limit was removed from module' ctor // current limit was removed from module' ctor
// override default value (60 mA) // override default value (60 mA)
res = lora->setCurrentLimit(currentLimit); res = lora->setCurrentLimit(currentLimit);
DEBUG_MSG("Current limit set to %f\n", currentLimit); LOG_DEBUG("Current limit set to %f\n", currentLimit);
DEBUG_MSG("Current limit set result %d\n", res); LOG_DEBUG("Current limit set result %d\n", res);
if (res == RADIOLIB_ERR_NONE) if (res == RADIOLIB_ERR_NONE)
res = lora->setCRC(RADIOLIB_SX126X_LORA_CRC_ON); res = lora->setCRC(RADIOLIB_SX126X_LORA_CRC_ON);
@@ -190,12 +190,12 @@ bool RF95Interface::isChannelActive()
result = lora->scanChannel(); result = lora->scanChannel();
if (result == RADIOLIB_PREAMBLE_DETECTED) { if (result == RADIOLIB_PREAMBLE_DETECTED) {
// DEBUG_MSG("Channel is busy!\n"); // LOG_DEBUG("Channel is busy!\n");
return true; return true;
} }
assert(result != RADIOLIB_ERR_WRONG_MODEM); assert(result != RADIOLIB_ERR_WRONG_MODEM);
// DEBUG_MSG("Channel is free!\n"); // LOG_DEBUG("Channel is free!\n");
return false; return false;
} }

View File

@@ -117,7 +117,7 @@ void initRegion()
for (; r->code != Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) for (; r->code != Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++)
; ;
myRegion = r; myRegion = r;
DEBUG_MSG("Wanted region %d, using %s\n", config.lora.region, r->name); LOG_INFO("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; 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); pl, msecs);
return 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); size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded);
uint32_t packetAirtime = getPacketTime(numbytes + sizeof(PacketHeader)); uint32_t packetAirtime = getPacketTime(numbytes + sizeof(PacketHeader));
// Make sure enough time has elapsed for this packet to be sent and an ACK is received. // 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(); float channelUtil = airTime->channelUtilizationPercent();
uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); 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 // 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. */ current channel utilization. */
float channelUtil = airTime->channelUtilizationPercent(); float channelUtil = airTime->channelUtilizationPercent();
uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); 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; return random(0, pow(2, CWsize)) * slotTimeMsec;
} }
@@ -210,14 +210,14 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr)
// low SNR = small CW size (Short Delay) // low SNR = small CW size (Short Delay)
uint32_t delay = 0; uint32_t delay = 0;
uint8_t CWsize = map(snr, SNR_MIN, SNR_MAX, CWmin, CWmax); 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 || if (config.device.role == Config_DeviceConfig_Role_ROUTER ||
config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT) { config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT) {
delay = random(0, 2*CWsize) * slotTimeMsec; 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 { } else {
delay = random(0, pow(2, CWsize)) * slotTimeMsec; 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; return delay;
@@ -225,47 +225,47 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr)
void printPacket(const char *prefix, const MeshPacket *p) 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); p->want_ack, p->hop_limit, p->channel);
if (p->which_payload_variant == MeshPacket_decoded_tag) { if (p->which_payload_variant == MeshPacket_decoded_tag) {
auto &s = p->decoded; auto &s = p->decoded;
DEBUG_MSG(" Portnum=%d", s.portnum); LOG_DEBUG(" Portnum=%d", s.portnum);
if (s.want_response) if (s.want_response)
DEBUG_MSG(" WANTRESP"); LOG_DEBUG(" WANTRESP");
if (s.source != 0) if (s.source != 0)
DEBUG_MSG(" source=%08x", s.source); LOG_DEBUG(" source=%08x", s.source);
if (s.dest != 0) if (s.dest != 0)
DEBUG_MSG(" dest=%08x", s.dest); LOG_DEBUG(" dest=%08x", s.dest);
if (s.request_id) 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 /* now inside Data and therefore kinda opaque
if (s.which_ackVariant == SubPacket_success_id_tag) 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) 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 { } else {
DEBUG_MSG(" encrypted"); LOG_DEBUG(" encrypted");
} }
if (p->rx_time != 0) { 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) { 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) { if (p->rx_rssi != 0) {
DEBUG_MSG(" rxRSSI=%g", p->rx_rssi); LOG_DEBUG(" rxRSSI=%g", p->rx_rssi);
} }
if (p->priority != 0) if (p->priority != 0)
DEBUG_MSG(" priority=%d", p->priority); LOG_DEBUG(" priority=%d", p->priority);
DEBUG_MSG(")\n"); LOG_DEBUG(")\n");
} }
RadioInterface::RadioInterface() RadioInterface::RadioInterface()
@@ -273,7 +273,7 @@ RadioInterface::RadioInterface()
assert(sizeof(PacketHeader) == 16); // make sure the compiler did what we expected assert(sizeof(PacketHeader) == 16); // make sure the compiler did what we expected
// Can't print strings this early - serial not setup yet // 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() bool RadioInterface::reconfigure()
@@ -284,7 +284,7 @@ bool RadioInterface::reconfigure()
bool RadioInterface::init() bool RadioInterface::init()
{ {
DEBUG_MSG("Starting meshradio init...\n"); LOG_INFO("Starting meshradio init...\n");
configChangedObserver.observe(&service.configChanged); configChangedObserver.observe(&service.configChanged);
preflightSleepObserver.observe(&preflightSleep); preflightSleepObserver.observe(&preflightSleep);
@@ -449,13 +449,13 @@ void RadioInterface::applyModemConfig()
saveChannelNum(channel_num); saveChannelNum(channel_num);
saveFreq(freq + config.lora.frequency_offset); saveFreq(freq + config.lora.frequency_offset);
DEBUG_MSG("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); LOG_INFO("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); LOG_INFO("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); LOG_INFO("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); LOG_INFO("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw);
DEBUG_MSG("Radio channel_num: %d\n", channel_num); LOG_INFO("Radio channel_num: %d\n", channel_num);
DEBUG_MSG("Radio frequency: %f\n", getFreq()); LOG_INFO("Radio frequency: %f\n", getFreq());
DEBUG_MSG("Slot time: %u msec\n", slotTimeMsec); LOG_INFO("Slot time: %u msec\n", slotTimeMsec);
} }
/** /**
@@ -470,11 +470,11 @@ void RadioInterface::limitPower()
maxPower = myRegion->powerLimit; maxPower = myRegion->powerLimit;
if ((power > maxPower) && !devicestate.owner.is_licensed) { if ((power > maxPower) && !devicestate.owner.is_licensed) {
DEBUG_MSG("Lowering transmit power because of regulatory limits\n"); LOG_INFO("Lowering transmit power because of regulatory limits\n");
power = maxPower; power = maxPower;
} }
DEBUG_MSG("Set radio: final power level=%d\n", power); LOG_INFO("Set radio: final power level=%d\n", power);
} }
@@ -491,7 +491,7 @@ size_t RadioInterface::beginSending(MeshPacket *p)
{ {
assert(!sendingPacket); 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 assert(p->which_payload_variant == MeshPacket_encrypted_tag); // It should have already been encoded by now
lastTxStart = millis(); lastTxStart = millis();

View File

@@ -82,17 +82,17 @@ bool RadioLibInterface::canSendImmediately()
if (busyTx || busyRx) { if (busyTx || busyRx) {
if (busyTx) if (busyTx)
DEBUG_MSG("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 // 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. // TX IRQ from the radio, the radio is probably broken.
if (busyTx && (millis() - lastTxStart > 60000)) { if (busyTx && (millis() - lastTxStart > 60000)) {
DEBUG_MSG("Hardware Failure! busyTx for more than 60s\n"); LOG_ERROR("Hardware Failure! busyTx for more than 60s\n");
RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED); RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED);
// reboot in 5 seconds when this condition occurs. // reboot in 5 seconds when this condition occurs.
rebootAtMsec = lastTxStart + 65000; rebootAtMsec = lastTxStart + 65000;
} }
if (busyRx) if (busyRx)
DEBUG_MSG("Can not send yet, busyRx\n"); LOG_WARN("Can not send yet, busyRx\n");
return false; return false;
} else } else
return true; return true;
@@ -111,13 +111,13 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) { if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) {
if (disabled || !config.lora.tx_enabled) { if (disabled || !config.lora.tx_enabled) {
DEBUG_MSG("send - !config.lora.tx_enabled\n"); LOG_WARN("send - !config.lora.tx_enabled\n");
packetPool.release(p); packetPool.release(p);
return ERRNO_DISABLED; return ERRNO_DISABLED;
} }
} else { } else {
DEBUG_MSG("send - lora tx disable because RegionCode_Unset\n"); LOG_WARN("send - lora tx disable because RegionCode_Unset\n");
packetPool.release(p); packetPool.release(p);
return ERRNO_DISABLED; return ERRNO_DISABLED;
} }
@@ -127,7 +127,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
#else #else
if (disabled || !config.lora.tx_enabled) { if (disabled || !config.lora.tx_enabled) {
DEBUG_MSG("send - !config.lora.tx_enabled\n"); LOG_WARN("send - !config.lora.tx_enabled\n");
packetPool.release(p); packetPool.release(p);
return ERRNO_DISABLED; return ERRNO_DISABLED;
} }
@@ -138,7 +138,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
#ifndef LORA_DISABLE_SENDING #ifndef LORA_DISABLE_SENDING
printPacket("enqueuing for send", p); 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; 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 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, // set (random) transmit delay to let others reconfigure their radio,
// to avoid collisions and implement timing-based flooding // 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(); setTransmitDelay();
return res; return res;
@@ -162,7 +162,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
{ {
bool res = txQueue.empty(); bool res = txQueue.empty();
if (!res) // only print debug messages if we are vetoing sleep 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; return res;
} }
@@ -175,7 +175,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
packetPool.release(p); // free the packet we just removed packetPool.release(p); // free the packet we just removed
bool result = (p != NULL); 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; return result;
} }
@@ -192,27 +192,27 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
case ISR_TX: case ISR_TX:
handleTransmitInterrupt(); handleTransmitInterrupt();
startReceive(); startReceive();
// DEBUG_MSG("tx complete - starting timer\n"); // LOG_DEBUG("tx complete - starting timer\n");
startTransmitTimer(); startTransmitTimer();
break; break;
case ISR_RX: case ISR_RX:
handleReceiveInterrupt(); handleReceiveInterrupt();
startReceive(); startReceive();
// DEBUG_MSG("rx complete - starting timer\n"); // LOG_DEBUG("rx complete - starting timer\n");
startTransmitTimer(); startTransmitTimer();
break; break;
case TRANSMIT_DELAY_COMPLETED: 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 // 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? // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode?
if (!txQueue.empty()) { if (!txQueue.empty()) {
if (!canSendImmediately()) { 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 setTransmitDelay(); // currently Rx/Tx-ing: reset random delay
} else { } else {
if (isChannelActive()) { // check if there is currently a LoRa packet on the channel 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 setTransmitDelay(); // reset random delay
} else { } else {
// Send any outgoing packets we have ready // Send any outgoing packets we have ready
@@ -226,7 +226,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
} }
} }
} else { } else {
// DEBUG_MSG("done with txqueue\n"); // LOG_DEBUG("done with txqueue\n");
} }
break; break;
default: default:
@@ -249,7 +249,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
startTransmitTimer(true); startTransmitTimer(true);
} else { } else {
// If there is a SNR, start a timer scaled based on that SNR. // 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); 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 we have work to do and the timer wasn't already scheduled, schedule it now
if (!txQueue.empty()) { if (!txQueue.empty()) {
uint32_t delay = !withDelay ? 1 : getTxDelayMsec(); 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 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 we have work to do and the timer wasn't already scheduled, schedule it now
if (!txQueue.empty()) { if (!txQueue.empty()) {
uint32_t delay = getTxDelayMsecWeighted(snr); 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 notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable
} }
} }
void RadioLibInterface::handleTransmitInterrupt() 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 // This can be null if we forced the device to enter standby mode. In that case
// ignore the transmit interrupt // ignore the transmit interrupt
if (sendingPacket) if (sendingPacket)
@@ -296,7 +296,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
// We are done sending that packet, release it // We are done sending that packet, release it
packetPool.release(p); 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? // 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) { 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; return;
} }
@@ -319,7 +319,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
int state = iface->readData(radiobuf, length); int state = iface->readData(radiobuf, length);
if (state != RADIOLIB_ERR_NONE) { if (state != RADIOLIB_ERR_NONE) {
DEBUG_MSG("ignoring received packet due to error=%d\n", state); LOG_ERROR("ignoring received packet due to error=%d\n", state);
rxBad++; rxBad++;
airTime->logAirtime(RX_ALL_LOG, xmitMsec); airTime->logAirtime(RX_ALL_LOG, xmitMsec);
@@ -331,7 +331,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
// check for short packets // check for short packets
if (payloadLen < 0) { if (payloadLen < 0) {
DEBUG_MSG("ignoring received packet too short\n"); LOG_WARN("ignoring received packet too short\n");
rxBad++; rxBad++;
airTime->logAirtime(RX_ALL_LOG, xmitMsec); airTime->logAirtime(RX_ALL_LOG, xmitMsec);
} else { } else {
@@ -374,7 +374,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
{ {
printPacket("Starting low level send", txp); printPacket("Starting low level send", txp);
if (disabled || !config.lora.tx_enabled) { if (disabled || !config.lora.tx_enabled) {
DEBUG_MSG("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); packetPool.release(txp);
} else { } else {
setStandby(); // Cancel any already in process receives setStandby(); // Cancel any already in process receives
@@ -385,7 +385,7 @@ ErrorCode RadioLibInterface::send(MeshPacket *p)
int res = iface->startTransmit(radiobuf, numbytes); int res = iface->startTransmit(radiobuf, numbytes);
if (res != RADIOLIB_ERR_NONE) { if (res != RADIOLIB_ERR_NONE) {
DEBUG_MSG("startTransmit failed, error=%d\n", res); LOG_ERROR("startTransmit failed, error=%d\n", res);
RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG); RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG);
// This send failed, but make sure to 'complete' it properly // This send failed, but make sure to 'complete' it properly

View File

@@ -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 // current limit was removed from module' ctor
// override default value (60 mA) // override default value (60 mA)
state = setCurrentLimit(currentLimit); state = setCurrentLimit(currentLimit);
DEBUG_MSG("Current limit set to %f\n", currentLimit); LOG_DEBUG("Current limit set to %f\n", currentLimit);
DEBUG_MSG("Current limit set result %d\n", state); LOG_DEBUG("Current limit set result %d\n", state);
// configure settings not accessible by API // configure settings not accessible by API
state = config(); state = config();

View File

@@ -42,14 +42,14 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p)
auto key = GlobalPacketId(getFrom(p), p->id); auto key = GlobalPacketId(getFrom(p), p->id);
auto old = findPendingPacket(key); auto old = findPendingPacket(key);
if (old) { 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 // 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 // marked as wantAck
sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel);
stopRetransmission(key); stopRetransmission(key);
} else { } 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. */ * 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()) { 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 // 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); MeshPacket *tosend = packetPool.allocCopy(*p);
tosend->hop_limit--; // bump down the hop count tosend->hop_limit--; // bump down the hop count
Router::send(tosend); 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->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 (p->want_ack) {
if (MeshModule::currentReply) 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 else
if (p->which_payload_variant == MeshPacket_decoded_tag) if (p->which_payload_variant == MeshPacket_decoded_tag)
sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); 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 // We intentionally don't check wasSeenRecently, because it is harmless to delete non existent retransmission records
if (ackId || nakId) { if (ackId || nakId) {
if (ackId) { 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); stopRetransmission(p->to, ackId);
} else { } 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); stopRetransmission(p->to, nakId);
} }
} }
@@ -190,14 +190,14 @@ int32_t ReliableRouter::doRetransmissions()
// FIXME, handle 51 day rolloever here!!! // FIXME, handle 51 day rolloever here!!!
if (p.nextTxMsec <= now) { if (p.nextTxMsec <= now) {
if (p.numRetransmissions == 0) { 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); p.packet->id);
sendAckNak(Routing_Error_MAX_RETRANSMIT, getFrom(p.packet), p.packet->id, p.packet->channel); 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 // Note: we don't stop retransmission here, instead the Nak packet gets processed in sniffReceived
stopRetransmission(it->first); stopRetransmission(it->first);
stillValid = false; // just deleted it stillValid = false; // just deleted it
} else { } 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); 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 // 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); assert(iface);
auto d = iface->getRetransmissionMsec(pending->packet); auto d = iface->getRetransmissionMsec(pending->packet);
pending->nextTxMsec = millis() + d; 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); printPacket("", pending->packet);
setReceivedMessage(); // Run ASAP, so we can figure out our correct sleep time setReceivedMessage(); // Run ASAP, so we can figure out our correct sleep time
} }

View File

@@ -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 // 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)); /* LOG_DEBUG("Size of NodeInfo %d\n", sizeof(NodeInfo));
DEBUG_MSG("Size of SubPacket %d\n", sizeof(SubPacket)); LOG_DEBUG("Size of SubPacket %d\n", sizeof(SubPacket));
DEBUG_MSG("Size of MeshPacket %d\n", sizeof(MeshPacket)); */ LOG_DEBUG("Size of MeshPacket %d\n", sizeof(MeshPacket)); */
fromRadioQueue.setReader(this); fromRadioQueue.setReader(this);
} }
@@ -67,7 +67,7 @@ int32_t Router::runOnce()
perhapsHandleReceived(mp); 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 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) // 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 // Note: we mask the high order bit to ensure that we never pass a 'negative' number to random
i = random(numPacketId & 0x7fffffff); 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++; i++;
@@ -136,14 +136,14 @@ void Router::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelI
void Router::abortSendAndNak(Routing_Error err, MeshPacket *p) void Router::abortSendAndNak(Routing_Error err, MeshPacket *p)
{ {
DEBUG_MSG("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); sendAckNak(Routing_Error_NO_INTERFACE, getFrom(p), p->id, p->channel);
packetPool.release(p); packetPool.release(p);
} }
void Router::setReceivedMessage() 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 setInterval(0); // Run ASAP, so we can figure out our correct sleep time
runASAP = true; 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) 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++) for (size_t i = 0; i < numbytes; i++)
DEBUG_MSG("%02x ", p[i]); LOG_DEBUG("%02x ", p[i]);
DEBUG_MSG("\n"); LOG_DEBUG("\n");
} }
/** /**
@@ -193,7 +193,7 @@ ErrorCode Router::send(MeshPacket *p)
float hourlyTxPercent = airTime->utilizationTXPercent(); float hourlyTxPercent = airTime->utilizationTXPercent();
if (hourlyTxPercent > myRegion->dutyCycle) { if (hourlyTxPercent > myRegion->dutyCycle) {
uint8_t silentMinutes = airTime->getSilentMinutes(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; Routing_Error err = Routing_Error_DUTY_CYCLE_LIMIT;
abortSendAndNak(err, p); abortSendAndNak(err, p);
return err; return err;
@@ -239,7 +239,7 @@ ErrorCode Router::send(MeshPacket *p)
shouldActuallyEncrypt = false; shouldActuallyEncrypt = false;
} }
DEBUG_MSG("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 // the packet is currently in a decrypted state. send it now if they want decrypted packets
if (mqtt && !shouldActuallyEncrypt) if (mqtt && !shouldActuallyEncrypt)
@@ -276,14 +276,14 @@ bool Router::cancelSending(NodeNum from, PacketId id)
*/ */
void Router::sniffReceived(const MeshPacket *p, const Routing *c) 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 // FIXME, update nodedb here for any packet that passes through us
} }
bool perhapsDecode(MeshPacket *p) 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) if (p->which_payload_variant == MeshPacket_decoded_tag)
return true; // If packet was already decoded just return 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 // Take those raw bytes and convert them back into a well structured protobuf we can understand
memset(&p->decoded, 0, sizeof(p->decoded)); memset(&p->decoded, 0, sizeof(p->decoded));
if (!pb_decode_from_bytes(bytes, rawSize, &Data_msg, &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_ERROR("Invalid protobufs in received mesh packet (bad psk?)!\n");
} else if (p->decoded.portnum == PortNum_UNKNOWN_APP) { } else if (p->decoded.portnum == PortNum_UNKNOWN_APP) {
DEBUG_MSG("Invalid portnum (bad psk?)!\n"); LOG_ERROR("Invalid portnum (bad psk?)!\n");
} else { } else {
// parsing was successful // parsing was successful
p->which_payload_variant = MeshPacket_decoded_tag; // change type to decoded 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) { 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) { } 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); 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); 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_WARN("No suitable channel found for decoding, hash was 0x%x!\n", p->channel);
return false; return false;
} }
@@ -374,20 +374,20 @@ Routing_Error perhapsEncode(MeshPacket *p)
int compressed_len; int compressed_len;
compressed_len = unishox2_compress_simple(original_payload, p->decoded.payload.size, compressed_out); compressed_len = unishox2_compress_simple(original_payload, p->decoded.payload.size, compressed_out);
DEBUG_MSG("Original length - %d \n", p->decoded.payload.size); LOG_DEBUG("Original length - %d \n", p->decoded.payload.size);
DEBUG_MSG("Compressed length - %d \n", compressed_len); LOG_DEBUG("Compressed length - %d \n", compressed_len);
DEBUG_MSG("Original message - %s \n", p->decoded.payload.bytes); 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 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) { 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? // Set the uncompressed payload varient anyway. Shouldn't hurt?
// p->decoded.which_payloadVariant = Data_payload_tag; // p->decoded.which_payloadVariant = Data_payload_tag;
// Otherwise we use the compressor // Otherwise we use the compressor
} else { } else {
DEBUG_MSG("Using compressed message.\n"); LOG_DEBUG("Using compressed message.\n");
// Copy the compressed data into the meshpacket // Copy the compressed data into the meshpacket
p->decoded.payload.size = compressed_len; 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); bool ignore = is_in_repeated(config.lora.ignore_incoming, p->from);
if (ignore) 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)) { 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 // Note: we avoid calling shouldFilterReceived if we are supposed to ignore certain nodes - because some overrides might

View File

@@ -12,7 +12,7 @@ SX126xInterface<T>::SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq,
SPIClass &spi) SPIClass &spi)
: RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module) : 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_WARN("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy);
} }
/// Initialise the Driver transport hardware and software. /// Initialise the Driver transport hardware and software.
@@ -55,17 +55,17 @@ bool SX126xInterface<T>::init()
int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage, useRegulatorLDO); int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage, useRegulatorLDO);
// \todo Display actual typename of the adapter, not just `SX126x` // \todo Display actual typename of the adapter, not just `SX126x`
DEBUG_MSG("SX126x init result %d\n", res); LOG_INFO("SX126x init result %d\n", res);
DEBUG_MSG("Frequency set to %f\n", getFreq()); LOG_INFO("Frequency set to %f\n", getFreq());
DEBUG_MSG("Bandwidth set to %f\n", bw); LOG_INFO("Bandwidth set to %f\n", bw);
DEBUG_MSG("Power output set to %d\n", power); LOG_INFO("Power output set to %d\n", power);
// current limit was removed from module' ctor // current limit was removed from module' ctor
// override default value (60 mA) // override default value (60 mA)
res = lora.setCurrentLimit(currentLimit); res = lora.setCurrentLimit(currentLimit);
DEBUG_MSG("Current limit set to %f\n", currentLimit); LOG_DEBUG("Current limit set to %f\n", currentLimit);
DEBUG_MSG("Current limit set result %d\n", res); LOG_DEBUG("Current limit set result %d\n", res);
#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) #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 // 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<T>::setStandby()
int err = lora.standby(); int err = lora.standby();
if (err != RADIOLIB_ERR_NONE) 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); assert(err == RADIOLIB_ERR_NONE);
@@ -192,7 +192,7 @@ void SX126xInterface<T>::setStandby()
template<typename T> template<typename T>
void SX126xInterface<T>::addReceiveMetadata(MeshPacket *mp) void SX126xInterface<T>::addReceiveMetadata(MeshPacket *mp)
{ {
// DEBUG_MSG("PacketStatus %x\n", lora.getPacketStatus()); // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus());
mp->rx_snr = lora.getSNR(); mp->rx_snr = lora.getSNR();
mp->rx_rssi = lround(lora.getRSSI()); mp->rx_rssi = lround(lora.getRSSI());
} }
@@ -275,7 +275,7 @@ bool SX126xInterface<T>::isActivelyReceiving()
// this is not correct - often always true - need to add an extra conditional // this is not correct - often always true - need to add an extra conditional
// size_t bytesPending = lora.getPacketLength(); // size_t bytesPending = lora.getPacketLength();
// if (hasPreamble) DEBUG_MSG("rx hasPreamble\n"); // if (hasPreamble) LOG_DEBUG("rx hasPreamble\n");
return hasPreamble; return hasPreamble;
} }
@@ -284,7 +284,7 @@ bool SX126xInterface<T>::sleep()
{ {
// Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // 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` // \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 setStandby(); // Stop any pending operations
// turn off TCXO if it was powered // turn off TCXO if it was powered

View File

@@ -49,10 +49,10 @@ bool SX128xInterface<T>::init()
int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength); int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength);
// \todo Display actual typename of the adapter, not just `SX128x` // \todo Display actual typename of the adapter, not just `SX128x`
DEBUG_MSG("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)) { 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; config.lora.region = Config_LoRaConfig_RegionCode_LORA_24;
nodeDB.saveToDisk(SEGMENT_CONFIG); nodeDB.saveToDisk(SEGMENT_CONFIG);
delay(2000); delay(2000);
@@ -61,13 +61,13 @@ bool SX128xInterface<T>::init()
#elif defined(ARCH_NRF52) #elif defined(ARCH_NRF52)
NVIC_SystemReset(); NVIC_SystemReset();
#else #else
DEBUG_MSG("FIXME implement reboot for this platform. Skipping for now.\n"); LOG_ERROR("FIXME implement reboot for this platform. Skipping for now.\n");
#endif #endif
} }
DEBUG_MSG("Frequency set to %f\n", getFreq()); LOG_INFO("Frequency set to %f\n", getFreq());
DEBUG_MSG("Bandwidth set to %f\n", bw); LOG_INFO("Bandwidth set to %f\n", bw);
DEBUG_MSG("Power output set to %d\n", power); LOG_INFO("Power output set to %d\n", power);
if (res == RADIOLIB_ERR_NONE) if (res == RADIOLIB_ERR_NONE)
res = lora.setCRC(2); res = lora.setCRC(2);
@@ -145,7 +145,7 @@ void SX128xInterface<T>::setStandby()
int err = lora.standby(); int err = lora.standby();
if (err != RADIOLIB_ERR_NONE) if (err != RADIOLIB_ERR_NONE)
DEBUG_MSG("SX128x standby failed with error %d\n", err); LOG_ERROR("SX128x standby failed with error %d\n", err);
assert(err == RADIOLIB_ERR_NONE); assert(err == RADIOLIB_ERR_NONE);
@@ -167,7 +167,7 @@ void SX128xInterface<T>::setStandby()
template<typename T> template<typename T>
void SX128xInterface<T>::addReceiveMetadata(MeshPacket *mp) void SX128xInterface<T>::addReceiveMetadata(MeshPacket *mp)
{ {
// DEBUG_MSG("PacketStatus %x\n", lora.getPacketStatus()); // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus());
mp->rx_snr = lora.getSNR(); mp->rx_snr = lora.getSNR();
mp->rx_rssi = lround(lora.getRSSI()); mp->rx_rssi = lround(lora.getRSSI());
} }
@@ -248,7 +248,7 @@ bool SX128xInterface<T>::sleep()
{ {
// Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // 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` // \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 setStandby(); // Stop any pending operations
// turn off TCXO if it was powered // turn off TCXO if it was powered

View File

@@ -95,7 +95,7 @@ void StreamAPI::writeStream()
void StreamAPI::emitTxBuffer(size_t len) void StreamAPI::emitTxBuffer(size_t len)
{ {
if (len != 0) { if (len != 0) {
// DEBUG_MSG("emit tx %d\n", len); // LOG_DEBUG("emit tx %d\n", len);
txBuf[0] = START1; txBuf[0] = START1;
txBuf[1] = START2; txBuf[1] = START2;
txBuf[2] = (len >> 8) & 0xff; txBuf[2] = (len >> 8) & 0xff;
@@ -114,7 +114,7 @@ void StreamAPI::emitRebooted()
fromRadioScratch.which_payload_variant = FromRadio_rebooted_tag; fromRadioScratch.which_payload_variant = FromRadio_rebooted_tag;
fromRadioScratch.rebooted = true; 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)); emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, &FromRadio_msg, &fromRadioScratch));
} }

View File

@@ -29,10 +29,10 @@ static int32_t reconnectETH()
Ethernet.maintain(); Ethernet.maintain();
if (!ethStartupComplete) { if (!ethStartupComplete) {
// Start web server // Start web server
DEBUG_MSG("... Starting network services\n"); LOG_INFO("... Starting network services\n");
#ifndef DISABLE_NTP #ifndef DISABLE_NTP
DEBUG_MSG("Starting NTP time client\n"); LOG_INFO("Starting NTP time client\n");
timeClient.begin(); timeClient.begin();
timeClient.setUpdateInterval(60 * 60); // Update once an hour timeClient.setUpdateInterval(60 * 60); // Update once an hour
#endif #endif
@@ -51,9 +51,9 @@ static int32_t reconnectETH()
#ifndef DISABLE_NTP #ifndef DISABLE_NTP
if (isEthernetAvailable() && (ntp_renew < millis())) { if (isEthernetAvailable() && (ntp_renew < millis())) {
DEBUG_MSG("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()) { 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; struct timeval tv;
tv.tv_sec = timeClient.getEpochTime(); tv.tv_sec = timeClient.getEpochTime();
@@ -64,7 +64,7 @@ static int32_t reconnectETH()
ntp_renew = millis() + 43200 * 1000; // success, refresh every 12 hours ntp_renew = millis() + 43200 * 1000; // success, refresh every 12 hours
} else { } else {
DEBUG_MSG("NTP Update failed\n"); LOG_ERROR("NTP Update failed\n");
ntp_renew = millis() + 300 * 1000; // failure, retry every 5 minutes 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... getMacAddr(mac); // FIXME use the BLE MAC for now...
if (config.network.eth_mode == Config_NetworkConfig_EthMode_DHCP) { if (config.network.eth_mode == Config_NetworkConfig_EthMode_DHCP) {
DEBUG_MSG("starting Ethernet DHCP\n"); LOG_INFO("starting Ethernet DHCP\n");
status = Ethernet.begin(mac); status = Ethernet.begin(mac);
} else if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC) { } else if (config.network.eth_mode == Config_NetworkConfig_EthMode_STATIC) {
DEBUG_MSG("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); Ethernet.begin(mac, config.network.ipv4_config.ip, config.network.ipv4_config.dns, config.network.ipv4_config.subnet);
} else { } else {
DEBUG_MSG("Ethernet Disabled\n"); LOG_INFO("Ethernet Disabled\n");
return false; return false;
} }
if (status == 0) { if (status == 0) {
if (Ethernet.hardwareStatus() == EthernetNoHardware) { if (Ethernet.hardwareStatus() == EthernetNoHardware) {
DEBUG_MSG("Ethernet shield was not found.\n"); LOG_ERROR("Ethernet shield was not found.\n");
return false; return false;
} else if (Ethernet.linkStatus() == LinkOFF) { } else if (Ethernet.linkStatus() == LinkOFF) {
DEBUG_MSG("Ethernet cable is not connected.\n"); LOG_ERROR("Ethernet cable is not connected.\n");
return false; return false;
} else{ } else{
DEBUG_MSG("Unknown Ethernet error.\n"); LOG_ERROR("Unknown Ethernet error.\n");
return false; return false;
} }
} else { } else {
DEBUG_MSG("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); LOG_INFO("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]); LOG_INFO("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]); LOG_INFO("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_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); ethEvent = new Periodic("ethConnect", reconnectETH);
@@ -129,7 +129,7 @@ bool initEthernet()
return true; return true;
} else { } else {
DEBUG_MSG("Not using Ethernet\n"); LOG_INFO("Not using Ethernet\n");
return false; return false;
} }
} }

View File

@@ -9,14 +9,14 @@ void initApiServer(int port)
// Start API server on port 4403 // Start API server on port 4403
if (!apiPort) { if (!apiPort) {
apiPort = new ethServerPort(port); apiPort = new ethServerPort(port);
DEBUG_MSG("API server listening on TCP port %d\n", port); LOG_INFO("API server listening on TCP port %d\n", port);
apiPort->init(); apiPort->init();
} }
} }
ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), concurrency::OSThread("ethServerAPI"), client(_client) ethServerAPI::ethServerAPI(EthernetClient &_client) : StreamAPI(&client), concurrency::OSThread("ethServerAPI"), client(_client)
{ {
DEBUG_MSG("Incoming ethernet connection\n"); LOG_INFO("Incoming ethernet connection\n");
} }
ethServerAPI::~ethServerAPI() ethServerAPI::~ethServerAPI()
@@ -44,7 +44,7 @@ int32_t ethServerAPI::runOnce()
if (client.connected()) { if (client.connected()) {
return StreamAPI::runOncePart(); return StreamAPI::runOncePart();
} else { } else {
DEBUG_MSG("Client dropped connection, suspending API service\n"); LOG_INFO("Client dropped connection, suspending API service\n");
enabled = false; // we no longer need to run enabled = false; // we no longer need to run
return 0; return 0;
} }
@@ -71,7 +71,7 @@ int32_t ethServerPort::runOnce()
if (client) { if (client) {
// Close any previous connection (see FIXME in header file) // Close any previous connection (see FIXME in header file)
if (openAPI) { if (openAPI) {
DEBUG_MSG("Force closing previous TCP connection\n"); LOG_WARN("Force closing previous TCP connection\n");
delete openAPI; delete openAPI;
} }

View File

@@ -140,7 +140,7 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer)
void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res)
{ {
DEBUG_MSG("webAPI handleAPIv1FromRadio\n"); LOG_DEBUG("webAPI handleAPIv1FromRadio\n");
/* /*
For documentation, see: For documentation, see:
@@ -185,12 +185,12 @@ void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res)
res->write(txBuf, len); 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) void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res)
{ {
DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); LOG_DEBUG("webAPI handleAPIv1ToRadio\n");
/* /*
For documentation, see: For documentation, see:
@@ -213,11 +213,11 @@ void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res)
byte buffer[MAX_TO_FROM_RADIO_SIZE]; byte buffer[MAX_TO_FROM_RADIO_SIZE];
size_t s = req->readBytes(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); webAPI.handleToRadio(buffer, s);
res->write(buffer, s); res->write(buffer, s);
DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); LOG_DEBUG("webAPI handleAPIv1ToRadio\n");
} }
void htmlDeleteDir(const char *dirname) void htmlDeleteDir(const char *dirname)
@@ -238,7 +238,7 @@ void htmlDeleteDir(const char *dirname)
} else { } else {
String fileName = String(file.name()); String fileName = String(file.name());
file.close(); file.close();
DEBUG_MSG(" %s\n", fileName.c_str()); LOG_DEBUG(" %s\n", fileName.c_str());
FSCom.remove(fileName); FSCom.remove(fileName);
} }
file = root.openNextFile(); file = root.openNextFile();
@@ -335,7 +335,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res)
if (params->getQueryParameter("delete", paramValDelete)) { if (params->getQueryParameter("delete", paramValDelete)) {
std::string pathDelete = "/" + paramValDelete; std::string pathDelete = "/" + paramValDelete;
if (FSCom.remove(pathDelete.c_str())) { if (FSCom.remove(pathDelete.c_str())) {
Serial.println(pathDelete.c_str()); LOG_INFO("%s\n", pathDelete.c_str());
JSONObject jsonObjOuter; JSONObject jsonObjOuter;
jsonObjOuter["status"] = new JSONValue("ok"); jsonObjOuter["status"] = new JSONValue("ok");
JSONValue *value = new JSONValue(jsonObjOuter); JSONValue *value = new JSONValue(jsonObjOuter);
@@ -343,7 +343,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res)
delete value; delete value;
return; return;
} else { } else {
Serial.println(pathDelete.c_str()); LOG_INFO("%s\n", pathDelete.c_str());
JSONObject jsonObjOuter; JSONObject jsonObjOuter;
jsonObjOuter["status"] = new JSONValue("Error"); jsonObjOuter["status"] = new JSONValue("Error");
JSONValue *value = new JSONValue(jsonObjOuter); JSONValue *value = new JSONValue(jsonObjOuter);
@@ -379,13 +379,13 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res)
if (FSCom.exists(filename.c_str())) { if (FSCom.exists(filename.c_str())) {
file = FSCom.open(filename.c_str()); file = FSCom.open(filename.c_str());
if (!file.available()) { if (!file.available()) {
DEBUG_MSG("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())) { } else if (FSCom.exists(filenameGzip.c_str())) {
file = FSCom.open(filenameGzip.c_str()); file = FSCom.open(filenameGzip.c_str());
res->setHeader("Content-Encoding", "gzip"); res->setHeader("Content-Encoding", "gzip");
if (!file.available()) { if (!file.available()) {
DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); LOG_WARN("File not available - %s\n", filenameGzip.c_str());
} }
} else { } else {
has_set_content_type = true; has_set_content_type = true;
@@ -393,7 +393,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res)
file = FSCom.open(filenameGzip.c_str()); file = FSCom.open(filenameGzip.c_str());
res->setHeader("Content-Type", "text/html"); res->setHeader("Content-Type", "text/html");
if (!file.available()) { if (!file.available()) {
DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); LOG_WARN("File not available - %s\n", filenameGzip.c_str());
res->println("Web server is running.<br><br>The content you are looking for can't be found. Please see: <a " res->println("Web server is running.<br><br>The content you are looking for can't be found. Please see: <a "
"href=https://meshtastic.org/docs/getting-started/faq#wifi--web-browser>FAQ</a>.<br><br><a " "href=https://meshtastic.org/docs/getting-started/faq#wifi--web-browser>FAQ</a>.<br><br><a "
"href=/admin>admin</a>"); "href=/admin>admin</a>");
@@ -437,7 +437,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res)
return; return;
} else { } else {
DEBUG_MSG("ERROR: This should not have happened...\n"); LOG_ERROR("This should not have happened...\n");
res->println("ERROR: This should not have happened..."); res->println("ERROR: This should not have happened...");
} }
} }
@@ -445,7 +445,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res)
void handleFormUpload(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"); res->setHeader("Connection", "close");
// First, we need to check the encoding of the form that we have received. // 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. // Then we select the body parser based on the encoding.
// Actually we do this only for documentary purposes, we know the form is going // Actually we do this only for documentary purposes, we know the form is going
// to be multipart/form-data. // 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; HTTPBodyParser *parser;
std::string contentType = req->getHeader("Content-Type"); std::string contentType = req->getHeader("Content-Type");
@@ -469,10 +469,10 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
// Now, we can decide based on the content type: // Now, we can decide based on the content type:
if (contentType == "multipart/form-data") { 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); parser = new HTTPMultipartBodyParser(req);
} else { } else {
Serial.printf("Unknown POST Content-Type: %s\n", contentType.c_str()); LOG_DEBUG("Unknown POST Content-Type: %s\n", contentType.c_str());
return; return;
} }
@@ -499,19 +499,19 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
std::string filename = parser->getFieldFilename(); std::string filename = parser->getFieldFilename();
std::string mimeType = parser->getFieldMimeType(); std::string mimeType = parser->getFieldMimeType();
// We log all three values, so that you can observe the upload on the serial monitor: // 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()); mimeType.c_str());
// Double check that it is what we expect // Double check that it is what we expect
if (name != "file") { if (name != "file") {
DEBUG_MSG("Skipping unexpected field\n"); LOG_DEBUG("Skipping unexpected field\n");
res->println("<p>No file found.</p>"); res->println("<p>No file found.</p>");
return; return;
} }
// Double check that it is what we expect // Double check that it is what we expect
if (filename == "") { if (filename == "") {
DEBUG_MSG("Skipping unexpected field\n"); LOG_DEBUG("Skipping unexpected field\n");
res->println("<p>No file found.</p>"); res->println("<p>No file found.</p>");
return; return;
} }
@@ -532,7 +532,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
byte buf[512]; byte buf[512];
size_t readLength = parser->read(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. // Abort the transfer if there is less than 50k space left on the filesystem.
if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) {
@@ -548,7 +548,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
// if (readLength) { // if (readLength) {
file.write(buf, readLength); file.write(buf, readLength);
fileLength += readLength; fileLength += readLength;
DEBUG_MSG("File Length %i\n", fileLength); LOG_DEBUG("File Length %i\n", fileLength);
//} //}
} }
// enableLoopWDT(); // enableLoopWDT();
@@ -671,7 +671,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res)
*/ */
void handleHotspot(HTTPRequest *req, HTTPResponse *res) void handleHotspot(HTTPRequest *req, HTTPResponse *res)
{ {
DEBUG_MSG("Hotspot Request\n"); LOG_INFO("Hotspot Request\n");
/* /*
If we don't do a redirect, be sure to return a "Success" message 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("<h1>Meshtastic</h1>\n"); res->println("<h1>Meshtastic</h1>\n");
res->println("Deleting Content in /static/*"); res->println("Deleting Content in /static/*");
DEBUG_MSG("Deleting files from /static/* : \n"); LOG_INFO("Deleting files from /static/* : \n");
htmlDeleteDir("/static"); htmlDeleteDir("/static");
@@ -771,7 +771,7 @@ void handleRestart(HTTPRequest *req, HTTPResponse *res)
res->println("<h1>Meshtastic</h1>\n"); res->println("<h1>Meshtastic</h1>\n");
res->println("Restarting"); res->println("Restarting");
DEBUG_MSG("***** Restarted on HTTP(s) Request *****\n"); LOG_DEBUG("***** Restarted on HTTP(s) Request *****\n");
webServerThread->requestRestart = (millis() / 1000) + 5; webServerThread->requestRestart = (millis() / 1000) + 5;
} }

View File

@@ -68,19 +68,19 @@ static void taskCreateCert(void *parameter)
#if 0 #if 0
// Delete the saved certs (used in debugging) // 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.clear();
prefs.remove("PK"); prefs.remove("PK");
prefs.remove("cert"); prefs.remove("cert");
#endif #endif
DEBUG_MSG("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 pkLen = prefs.getBytesLength("PK");
size_t certLen = prefs.getBytesLength("cert"); size_t certLen = prefs.getBytesLength("cert");
if (pkLen && certLen) { if (pkLen && certLen) {
DEBUG_MSG("Existing SSL Certificate found!\n"); LOG_INFO("Existing SSL Certificate found!\n");
uint8_t *pkBuffer = new uint8_t[pkLen]; uint8_t *pkBuffer = new uint8_t[pkLen];
prefs.getBytes("PK", pkBuffer, pkLen); prefs.getBytes("PK", pkBuffer, pkLen);
@@ -90,12 +90,12 @@ static void taskCreateCert(void *parameter)
cert = new SSLCert(certBuffer, certLen, pkBuffer, pkLen); cert = new SSLCert(certBuffer, certLen, pkBuffer, pkLen);
DEBUG_MSG("Retrieved Private Key: %d Bytes\n", cert->getPKLength()); LOG_DEBUG("Retrieved Private Key: %d Bytes\n", cert->getPKLength());
DEBUG_MSG("Retrieved Certificate: %d Bytes\n", cert->getCertLength()); LOG_DEBUG("Retrieved Certificate: %d Bytes\n", cert->getCertLength());
} else { } else {
DEBUG_MSG("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(); yield();
cert = new SSLCert(); cert = new SSLCert();
yield(); yield();
@@ -104,14 +104,14 @@ static void taskCreateCert(void *parameter)
yield(); yield();
if (createCertResult != 0) { if (createCertResult != 0) {
DEBUG_MSG("Creating the certificate failed\n"); LOG_ERROR("Creating the certificate failed\n");
} else { } else {
DEBUG_MSG("Creating the certificate was successful\n"); LOG_INFO("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("PK", (uint8_t *)cert->getPKData(), cert->getPKLength());
prefs.putBytes("cert", (uint8_t *)cert->getCertData(), cert->getCertLength()); prefs.putBytes("cert", (uint8_t *)cert->getCertData(), cert->getCertLength());
@@ -140,11 +140,11 @@ void createSSLCert()
16, /* Priority of the task. */ 16, /* Priority of the task. */
NULL); /* Task handle. */ 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) { while (!isCertReady) {
if ((millis() / 500) % 2) { if ((millis() / 500) % 2) {
if (runLoop) { if (runLoop) {
DEBUG_MSG("."); LOG_DEBUG(".");
yield(); yield();
esp_task_wdt_reset(); esp_task_wdt_reset();
@@ -159,7 +159,7 @@ void createSSLCert()
runLoop = true; runLoop = true;
} }
} }
DEBUG_MSG("SSL Cert Ready!\n"); LOG_INFO("SSL Cert Ready!\n");
} }
} }
@@ -169,7 +169,7 @@ WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") {}
int32_t WebServerThread::runOnce() int32_t WebServerThread::runOnce()
{ {
// DEBUG_MSG("WebServerThread::runOnce()\n"); // LOG_DEBUG("WebServerThread::runOnce()\n");
handleWebResponse(); handleWebResponse();
if (requestRestart && (millis() / 1000) > requestRestart) { if (requestRestart && (millis() / 1000) > requestRestart) {
@@ -182,7 +182,7 @@ int32_t WebServerThread::runOnce()
void initWebServer() 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. // We can now use the new certificate to setup our server as usual.
secureServer = new HTTPSServer(cert); secureServer = new HTTPSServer(cert);
@@ -191,15 +191,15 @@ void initWebServer()
registerHandlers(insecureServer, secureServer); registerHandlers(insecureServer, secureServer);
if (secureServer) { if (secureServer) {
DEBUG_MSG("Starting Secure Web Server...\n"); LOG_INFO("Starting Secure Web Server...\n");
secureServer->start(); secureServer->start();
} }
DEBUG_MSG("Starting Insecure Web Server...\n"); LOG_INFO("Starting Insecure Web Server...\n");
insecureServer->start(); insecureServer->start();
if (insecureServer->isRunning()) { if (insecureServer->isRunning()) {
DEBUG_MSG("Web Servers Ready! :-) \n"); LOG_INFO("Web Servers Ready! :-) \n");
isWebServerReady = true; isWebServerReady = true;
} else { } else {
DEBUG_MSG("Web Servers Failed! ;-( \n"); LOG_ERROR("Web Servers Failed! ;-( \n");
} }
} }

View File

@@ -56,7 +56,7 @@ static int32_t reconnectWiFi()
// Make sure we clear old connection credentials // Make sure we clear old connection credentials
WiFi.disconnect(false, true); WiFi.disconnect(false, true);
DEBUG_MSG("Reconnecting to WiFi access point %s\n",wifiName); LOG_INFO("Reconnecting to WiFi access point %s\n",wifiName);
WiFi.mode(WIFI_MODE_STA); WiFi.mode(WIFI_MODE_STA);
WiFi.begin(wifiName, wifiPsw); WiFi.begin(wifiName, wifiPsw);
@@ -64,9 +64,9 @@ static int32_t reconnectWiFi()
#ifndef DISABLE_NTP #ifndef DISABLE_NTP
if (WiFi.isConnected() && (((millis() - lastrun_ntp) > 43200000) || (lastrun_ntp == 0))) { // every 12 hours 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()) { 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; struct timeval tv;
tv.tv_sec = timeClient.getEpochTime(); tv.tv_sec = timeClient.getEpochTime();
@@ -76,7 +76,7 @@ static int32_t reconnectWiFi()
lastrun_ntp = millis(); lastrun_ntp = millis();
} else { } else {
DEBUG_MSG("NTP Update failed\n"); LOG_DEBUG("NTP Update failed\n");
} }
} }
#endif #endif
@@ -101,12 +101,12 @@ bool isWifiAvailable()
// Disable WiFi // Disable WiFi
void deinitWifi() void deinitWifi()
{ {
DEBUG_MSG("WiFi deinit\n"); LOG_INFO("WiFi deinit\n");
if (isWifiAvailable()) { if (isWifiAvailable()) {
WiFi.disconnect(true); WiFi.disconnect(true);
WiFi.mode(WIFI_MODE_NULL); WiFi.mode(WIFI_MODE_NULL);
DEBUG_MSG("WiFi Turned Off\n"); LOG_INFO("WiFi Turned Off\n");
// WiFi.printDiag(Serial); // WiFi.printDiag(Serial);
} }
} }
@@ -115,20 +115,20 @@ static void onNetworkConnected()
{ {
if (!APStartupComplete) { if (!APStartupComplete) {
// Start web server // Start web server
DEBUG_MSG("Starting network services\n"); LOG_INFO("Starting network services\n");
// start mdns // start mdns
if (!MDNS.begin("Meshtastic")) { if (!MDNS.begin("Meshtastic")) {
DEBUG_MSG("Error setting up MDNS responder!\n"); LOG_ERROR("Error setting up MDNS responder!\n");
} else { } else {
DEBUG_MSG("mDNS responder started\n"); LOG_INFO("mDNS responder started\n");
DEBUG_MSG("mDNS Host: Meshtastic.local\n"); LOG_INFO("mDNS Host: Meshtastic.local\n");
MDNS.addService("http", "tcp", 80); MDNS.addService("http", "tcp", 80);
MDNS.addService("https", "tcp", 443); MDNS.addService("https", "tcp", 443);
} }
#ifndef DISABLE_NTP #ifndef DISABLE_NTP
DEBUG_MSG("Starting NTP time client\n"); LOG_INFO("Starting NTP time client\n");
timeClient.begin(); timeClient.begin();
timeClient.setUpdateInterval(60 * 60); // Update once an hour timeClient.setUpdateInterval(60 * 60); // Update once an hour
#endif #endif
@@ -182,8 +182,7 @@ bool initWifi()
WiFi.onEvent( WiFi.onEvent(
[](WiFiEvent_t event, WiFiEventInfo_t info) { [](WiFiEvent_t event, WiFiEventInfo_t info) {
Serial.print("WiFi lost connection. Reason: "); LOG_WARN("WiFi lost connection. Reason: %s", info.wifi_sta_disconnected.reason);
Serial.println(info.wifi_sta_disconnected.reason);
/* /*
If we are disconnected from the AP for some reason, If we are disconnected from the AP for some reason,
@@ -196,12 +195,12 @@ bool initWifi()
}, },
WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); 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); wifiReconnect = new Periodic("WifiConnect", reconnectWiFi);
} }
return true; return true;
} else { } else {
DEBUG_MSG("Not using WIFI\n"); LOG_INFO("Not using WIFI\n");
return false; return false;
} }
} }
@@ -209,137 +208,135 @@ bool initWifi()
// Called by the Espressif SDK to // Called by the Espressif SDK to
static void WiFiEvent(WiFiEvent_t event) static void WiFiEvent(WiFiEvent_t event)
{ {
DEBUG_MSG("WiFi-Event %d: ", event); LOG_DEBUG("WiFi-Event %d: ", event);
switch (event) { switch (event) {
case ARDUINO_EVENT_WIFI_READY: case ARDUINO_EVENT_WIFI_READY:
DEBUG_MSG("WiFi interface ready\n"); LOG_INFO("WiFi interface ready\n");
break; break;
case ARDUINO_EVENT_WIFI_SCAN_DONE: case ARDUINO_EVENT_WIFI_SCAN_DONE:
DEBUG_MSG("Completed scan for access points\n"); LOG_INFO("Completed scan for access points\n");
break; break;
case ARDUINO_EVENT_WIFI_STA_START: case ARDUINO_EVENT_WIFI_STA_START:
DEBUG_MSG("WiFi station started\n"); LOG_INFO("WiFi station started\n");
break; break;
case ARDUINO_EVENT_WIFI_STA_STOP: case ARDUINO_EVENT_WIFI_STA_STOP:
DEBUG_MSG("WiFi station stopped\n"); LOG_INFO("WiFi station stopped\n");
break; break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED: case ARDUINO_EVENT_WIFI_STA_CONNECTED:
DEBUG_MSG("Connected to access point\n"); LOG_INFO("Connected to access point\n");
break; break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
DEBUG_MSG("Disconnected from WiFi access point\n"); LOG_INFO("Disconnected from WiFi access point\n");
WiFi.disconnect(false, true); WiFi.disconnect(false, true);
needReconnect = true; needReconnect = true;
wifiReconnect->setIntervalFromNow(1000); wifiReconnect->setIntervalFromNow(1000);
break; break;
case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
DEBUG_MSG("Authentication mode of access point has changed\n"); LOG_INFO("Authentication mode of access point has changed\n");
break; break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP: case ARDUINO_EVENT_WIFI_STA_GOT_IP:
DEBUG_MSG("Obtained IP address: "); LOG_INFO("Obtained IP address: ", WiFi.localIPv6());
Serial.println(WiFi.localIP());
onNetworkConnected(); onNetworkConnected();
break; break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6: case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
DEBUG_MSG("Obtained IP6 address: "); LOG_INFO("Obtained IP6 address: %s", WiFi.localIPv6());
Serial.println(WiFi.localIPv6());
break; break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP: case ARDUINO_EVENT_WIFI_STA_LOST_IP:
DEBUG_MSG("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); WiFi.disconnect(false, true);
needReconnect = true; needReconnect = true;
wifiReconnect->setIntervalFromNow(1000); wifiReconnect->setIntervalFromNow(1000);
break; break;
case ARDUINO_EVENT_WPS_ER_SUCCESS: case ARDUINO_EVENT_WPS_ER_SUCCESS:
DEBUG_MSG("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); LOG_INFO("WiFi Protected Setup (WPS): succeeded in enrollee mode\n");
break; break;
case ARDUINO_EVENT_WPS_ER_FAILED: case ARDUINO_EVENT_WPS_ER_FAILED:
DEBUG_MSG("WiFi Protected Setup (WPS): failed in enrollee mode\n"); LOG_INFO("WiFi Protected Setup (WPS): failed in enrollee mode\n");
break; break;
case ARDUINO_EVENT_WPS_ER_TIMEOUT: case ARDUINO_EVENT_WPS_ER_TIMEOUT:
DEBUG_MSG("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); LOG_INFO("WiFi Protected Setup (WPS): timeout in enrollee mode\n");
break; break;
case ARDUINO_EVENT_WPS_ER_PIN: case ARDUINO_EVENT_WPS_ER_PIN:
DEBUG_MSG("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); LOG_INFO("WiFi Protected Setup (WPS): pin code in enrollee mode\n");
break; break;
case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP: case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP:
DEBUG_MSG("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; break;
case ARDUINO_EVENT_WIFI_AP_START: case ARDUINO_EVENT_WIFI_AP_START:
DEBUG_MSG("WiFi access point started\n"); LOG_INFO("WiFi access point started\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_STOP: case ARDUINO_EVENT_WIFI_AP_STOP:
DEBUG_MSG("WiFi access point stopped\n"); LOG_INFO("WiFi access point stopped\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_STACONNECTED: case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
DEBUG_MSG("Client connected\n"); LOG_INFO("Client connected\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
DEBUG_MSG("Client disconnected\n"); LOG_INFO("Client disconnected\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
DEBUG_MSG("Assigned IP address to client\n"); LOG_INFO("Assigned IP address to client\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
DEBUG_MSG("Received probe request\n"); LOG_INFO("Received probe request\n");
break; break;
case ARDUINO_EVENT_WIFI_AP_GOT_IP6: case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
DEBUG_MSG("IPv6 is preferred\n"); LOG_INFO("IPv6 is preferred\n");
break; break;
case ARDUINO_EVENT_WIFI_FTM_REPORT: case ARDUINO_EVENT_WIFI_FTM_REPORT:
DEBUG_MSG("Fast Transition Management report\n"); LOG_INFO("Fast Transition Management report\n");
break; break;
case ARDUINO_EVENT_ETH_START: case ARDUINO_EVENT_ETH_START:
DEBUG_MSG("Ethernet started\n"); LOG_INFO("Ethernet started\n");
break; break;
case ARDUINO_EVENT_ETH_STOP: case ARDUINO_EVENT_ETH_STOP:
DEBUG_MSG("Ethernet stopped\n"); LOG_INFO("Ethernet stopped\n");
break; break;
case ARDUINO_EVENT_ETH_CONNECTED: case ARDUINO_EVENT_ETH_CONNECTED:
DEBUG_MSG("Ethernet connected\n"); LOG_INFO("Ethernet connected\n");
break; break;
case ARDUINO_EVENT_ETH_DISCONNECTED: case ARDUINO_EVENT_ETH_DISCONNECTED:
DEBUG_MSG("Ethernet disconnected\n"); LOG_INFO("Ethernet disconnected\n");
break; break;
case ARDUINO_EVENT_ETH_GOT_IP: case ARDUINO_EVENT_ETH_GOT_IP:
DEBUG_MSG("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); LOG_INFO("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n");
break; break;
case ARDUINO_EVENT_ETH_GOT_IP6: case ARDUINO_EVENT_ETH_GOT_IP6:
DEBUG_MSG("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); LOG_INFO("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n");
break; break;
case ARDUINO_EVENT_SC_SCAN_DONE: case ARDUINO_EVENT_SC_SCAN_DONE:
DEBUG_MSG("SmartConfig: Scan done\n"); LOG_INFO("SmartConfig: Scan done\n");
break; break;
case ARDUINO_EVENT_SC_FOUND_CHANNEL: case ARDUINO_EVENT_SC_FOUND_CHANNEL:
DEBUG_MSG("SmartConfig: Found channel\n"); LOG_INFO("SmartConfig: Found channel\n");
break; break;
case ARDUINO_EVENT_SC_GOT_SSID_PSWD: case ARDUINO_EVENT_SC_GOT_SSID_PSWD:
DEBUG_MSG("SmartConfig: Got SSID and password\n"); LOG_INFO("SmartConfig: Got SSID and password\n");
break; break;
case ARDUINO_EVENT_SC_SEND_ACK_DONE: case ARDUINO_EVENT_SC_SEND_ACK_DONE:
DEBUG_MSG("SmartConfig: Send ACK done\n"); LOG_INFO("SmartConfig: Send ACK done\n");
break; break;
case ARDUINO_EVENT_PROV_INIT: case ARDUINO_EVENT_PROV_INIT:
DEBUG_MSG("Provisioning: Init\n"); LOG_INFO("Provisioning: Init\n");
break; break;
case ARDUINO_EVENT_PROV_DEINIT: case ARDUINO_EVENT_PROV_DEINIT:
DEBUG_MSG("Provisioning: Stopped\n"); LOG_INFO("Provisioning: Stopped\n");
break; break;
case ARDUINO_EVENT_PROV_START: case ARDUINO_EVENT_PROV_START:
DEBUG_MSG("Provisioning: Started\n"); LOG_INFO("Provisioning: Started\n");
break; break;
case ARDUINO_EVENT_PROV_END: case ARDUINO_EVENT_PROV_END:
DEBUG_MSG("Provisioning: End\n"); LOG_INFO("Provisioning: End\n");
break; break;
case ARDUINO_EVENT_PROV_CRED_RECV: case ARDUINO_EVENT_PROV_CRED_RECV:
DEBUG_MSG("Provisioning: Credentials received\n"); LOG_INFO("Provisioning: Credentials received\n");
break; break;
case ARDUINO_EVENT_PROV_CRED_FAIL: case ARDUINO_EVENT_PROV_CRED_FAIL:
DEBUG_MSG("Provisioning: Credentials failed\n"); LOG_INFO("Provisioning: Credentials failed\n");
break; break;
case ARDUINO_EVENT_PROV_CRED_SUCCESS: case ARDUINO_EVENT_PROV_CRED_SUCCESS:
DEBUG_MSG("Provisioning: Credentials success\n"); LOG_INFO("Provisioning: Credentials success\n");
break; break;
default: default:
break; break;

View File

@@ -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); pb_ostream_t stream = pb_ostream_from_buffer(destbuf, destbufsize);
if (!pb_encode(&stream, fields, src_struct)) { if (!pb_encode(&stream, fields, src_struct)) {
DEBUG_MSG("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 assert(0); // If this asser fails it probably means you made a field too large for the max limits specified in mesh.options
} else { } else {
return stream.bytes_written; 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); pb_istream_t stream = pb_istream_from_buffer(srcbuf, srcbufsize);
if (!pb_decode(&stream, fields, dest_struct)) { 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_ERROR("Can't decode protobuf reason='%s', pb_msgdesc 0x%p\n", PB_GET_ERROR(&stream), fields);
return false; return false;
} else { } else {
return true; 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) bool writecb(pb_ostream_t *stream, const uint8_t *buf, size_t count)
{ {
File *file = (File *)stream->state; 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; return file->write(buf, count) == count;
} }
#endif #endif

View File

@@ -9,14 +9,14 @@ void initApiServer(int port)
// Start API server on port 4403 // Start API server on port 4403
if (!apiPort) { if (!apiPort) {
apiPort = new WiFiServerPort(port); apiPort = new WiFiServerPort(port);
DEBUG_MSG("API server listening on TCP port %d\n", port); LOG_INFO("API server listening on TCP port %d\n", port);
apiPort->init(); apiPort->init();
} }
} }
WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), concurrency::OSThread("WiFiServerAPI"), client(_client) WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : StreamAPI(&client), concurrency::OSThread("WiFiServerAPI"), client(_client)
{ {
DEBUG_MSG("Incoming wifi connection\n"); LOG_INFO("Incoming wifi connection\n");
} }
WiFiServerAPI::~WiFiServerAPI() WiFiServerAPI::~WiFiServerAPI()
@@ -44,7 +44,7 @@ int32_t WiFiServerAPI::runOnce()
if (client.connected()) { if (client.connected()) {
return StreamAPI::runOncePart(); return StreamAPI::runOncePart();
} else { } else {
DEBUG_MSG("Client dropped connection, suspending API service\n"); LOG_INFO("Client dropped connection, suspending API service\n");
enabled = false; // we no longer need to run enabled = false; // we no longer need to run
return 0; return 0;
} }
@@ -71,7 +71,7 @@ int32_t WiFiServerPort::runOnce()
if (client) { if (client) {
// Close any previous connection (see FIXME in header file) // Close any previous connection (see FIXME in header file)
if (openAPI) { if (openAPI) {
DEBUG_MSG("Force closing previous TCP connection\n"); LOG_INFO("Force closing previous TCP connection\n");
delete openAPI; delete openAPI;
} }

View File

@@ -50,23 +50,23 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r)
* Getters * Getters
*/ */
case AdminMessage_get_owner_request_tag: case AdminMessage_get_owner_request_tag:
DEBUG_MSG("Client is getting owner\n"); LOG_INFO("Client is getting owner\n");
handleGetOwner(mp); handleGetOwner(mp);
break; break;
case AdminMessage_get_config_request_tag: case AdminMessage_get_config_request_tag:
DEBUG_MSG("Client is getting config\n"); LOG_INFO("Client is getting config\n");
handleGetConfig(mp, r->get_config_request); handleGetConfig(mp, r->get_config_request);
break; break;
case AdminMessage_get_module_config_request_tag: case AdminMessage_get_module_config_request_tag:
DEBUG_MSG("Client is getting module config\n"); LOG_INFO("Client is getting module config\n");
handleGetModuleConfig(mp, r->get_module_config_request); handleGetModuleConfig(mp, r->get_module_config_request);
break; break;
case AdminMessage_get_channel_request_tag: { case AdminMessage_get_channel_request_tag: {
uint32_t i = r->get_channel_request - 1; uint32_t i = r->get_channel_request - 1;
DEBUG_MSG("Client is getting channel %u\n", i); LOG_INFO("Client is getting channel %u\n", i);
if (i >= MAX_NUM_CHANNELS) if (i >= MAX_NUM_CHANNELS)
myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp);
else else
@@ -78,22 +78,22 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r)
* Setters * Setters
*/ */
case AdminMessage_set_owner_tag: case AdminMessage_set_owner_tag:
DEBUG_MSG("Client is setting owner\n"); LOG_INFO("Client is setting owner\n");
handleSetOwner(r->set_owner); handleSetOwner(r->set_owner);
break; break;
case AdminMessage_set_config_tag: case AdminMessage_set_config_tag:
DEBUG_MSG("Client is setting the config\n"); LOG_INFO("Client is setting the config\n");
handleSetConfig(r->set_config); handleSetConfig(r->set_config);
break; break;
case AdminMessage_set_module_config_tag: case AdminMessage_set_module_config_tag:
DEBUG_MSG("Client is setting the module config\n"); LOG_INFO("Client is setting the module config\n");
handleSetModuleConfig(r->set_module_config); handleSetModuleConfig(r->set_module_config);
break; break;
case AdminMessage_set_channel_tag: case AdminMessage_set_channel_tag:
DEBUG_MSG("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) if (r->set_channel.index < 0 || r->set_channel.index >= (int)MAX_NUM_CHANNELS)
myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp);
else else
@@ -111,15 +111,15 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r)
int32_t s = r->reboot_ota_seconds; int32_t s = r->reboot_ota_seconds;
#ifdef ARCH_ESP32 #ifdef ARCH_ESP32
if (BleOta::getOtaAppVersion().isEmpty()) { if (BleOta::getOtaAppVersion().isEmpty()) {
DEBUG_MSG("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(); screen->startRebootScreen();
}else{ }else{
screen->startFirmwareUpdateScreen(); screen->startFirmwareUpdateScreen();
BleOta::switchToOtaApp(); BleOta::switchToOtaApp();
DEBUG_MSG("Rebooting to OTA in %d seconds\n", s); LOG_INFO("Rebooting to OTA in %d seconds\n", s);
} }
#else #else
DEBUG_MSG("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(); screen->startRebootScreen();
#endif #endif
rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000);
@@ -127,40 +127,40 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r)
} }
case AdminMessage_shutdown_seconds_tag: { case AdminMessage_shutdown_seconds_tag: {
int32_t s = r->shutdown_seconds; int32_t s = r->shutdown_seconds;
DEBUG_MSG("Shutdown in %d seconds\n", s); LOG_INFO("Shutdown in %d seconds\n", s);
shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000); shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000);
break; break;
} }
case AdminMessage_get_device_metadata_request_tag: { case AdminMessage_get_device_metadata_request_tag: {
DEBUG_MSG("Client is getting device metadata\n"); LOG_INFO("Client is getting device metadata\n");
handleGetDeviceMetadata(mp); handleGetDeviceMetadata(mp);
break; break;
} }
case AdminMessage_factory_reset_tag: { case AdminMessage_factory_reset_tag: {
DEBUG_MSG("Initiating factory reset\n"); LOG_INFO("Initiating factory reset\n");
nodeDB.factoryReset(); nodeDB.factoryReset();
reboot(DEFAULT_REBOOT_SECONDS); reboot(DEFAULT_REBOOT_SECONDS);
break; break;
} case AdminMessage_nodedb_reset_tag: { } case AdminMessage_nodedb_reset_tag: {
DEBUG_MSG("Initiating node-db reset\n"); LOG_INFO("Initiating node-db reset\n");
nodeDB.resetNodes(); nodeDB.resetNodes();
reboot(DEFAULT_REBOOT_SECONDS); reboot(DEFAULT_REBOOT_SECONDS);
break; break;
} }
case AdminMessage_begin_edit_settings_tag: { case AdminMessage_begin_edit_settings_tag: {
DEBUG_MSG("Beginning transaction for editing settings\n"); LOG_INFO("Beginning transaction for editing settings\n");
hasOpenEditTransaction = true; hasOpenEditTransaction = true;
break; break;
} }
case AdminMessage_commit_edit_settings_tag: { case AdminMessage_commit_edit_settings_tag: {
DEBUG_MSG("Committing transaction for edited settings\n"); LOG_INFO("Committing transaction for edited settings\n");
hasOpenEditTransaction = false; hasOpenEditTransaction = false;
saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS);
break; break;
} }
#ifdef ARCH_PORTDUINO #ifdef ARCH_PORTDUINO
case AdminMessage_exit_simulator_tag: case AdminMessage_exit_simulator_tag:
DEBUG_MSG("Exiting simulator\n"); LOG_INFO("Exiting simulator\n");
_exit(0); _exit(0);
break; break;
#endif #endif
@@ -172,10 +172,10 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r)
if (handleResult == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) { if (handleResult == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) {
myReply = allocDataProtobuf(res); myReply = allocDataProtobuf(res);
} else if (mp.decoded.want_response) { } 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) { } else if (handleResult != AdminMessageHandleResult::HANDLED) {
// Probably a message sent by us or sent to our local node. FIXME, we should avoid scanning these messages // 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_INFO("Ignoring nonrelevant admin %d\n", r->which_payload_variant);
} }
break; break;
} }
@@ -229,7 +229,7 @@ void AdminModule::handleSetConfig(const Config &c)
switch (c.which_payload_variant) { switch (c.which_payload_variant) {
case Config_device_tag: case Config_device_tag:
DEBUG_MSG("Setting config: Device\n"); LOG_INFO("Setting config: Device\n");
config.has_device = true; config.has_device = true;
config.device = c.payload_variant.device; config.device = c.payload_variant.device;
// If we're setting router role for the first time, install its intervals // If we're setting router role for the first time, install its intervals
@@ -240,29 +240,29 @@ void AdminModule::handleSetConfig(const Config &c)
} }
break; break;
case Config_position_tag: case Config_position_tag:
DEBUG_MSG("Setting config: Position\n"); LOG_INFO("Setting config: Position\n");
config.has_position = true; config.has_position = true;
config.position = c.payload_variant.position; config.position = c.payload_variant.position;
// Save nodedb as well in case we got a fixed position packet // Save nodedb as well in case we got a fixed position packet
saveChanges(SEGMENT_DEVICESTATE, false); saveChanges(SEGMENT_DEVICESTATE, false);
break; break;
case Config_power_tag: case Config_power_tag:
DEBUG_MSG("Setting config: Power\n"); LOG_INFO("Setting config: Power\n");
config.has_power = true; config.has_power = true;
config.power = c.payload_variant.power; config.power = c.payload_variant.power;
break; break;
case Config_network_tag: case Config_network_tag:
DEBUG_MSG("Setting config: WiFi\n"); LOG_INFO("Setting config: WiFi\n");
config.has_network = true; config.has_network = true;
config.network = c.payload_variant.network; config.network = c.payload_variant.network;
break; break;
case Config_display_tag: case Config_display_tag:
DEBUG_MSG("Setting config: Display\n"); LOG_INFO("Setting config: Display\n");
config.has_display = true; config.has_display = true;
config.display = c.payload_variant.display; config.display = c.payload_variant.display;
break; break;
case Config_lora_tag: case Config_lora_tag:
DEBUG_MSG("Setting config: LoRa\n"); LOG_INFO("Setting config: LoRa\n");
config.has_lora = true; config.has_lora = true;
config.lora = c.payload_variant.lora; config.lora = c.payload_variant.lora;
if (isRegionUnset && if (isRegionUnset &&
@@ -271,7 +271,7 @@ void AdminModule::handleSetConfig(const Config &c)
} }
break; break;
case Config_bluetooth_tag: case Config_bluetooth_tag:
DEBUG_MSG("Setting config: Bluetooth\n"); LOG_INFO("Setting config: Bluetooth\n");
config.has_bluetooth = true; config.has_bluetooth = true;
config.bluetooth = c.payload_variant.bluetooth; config.bluetooth = c.payload_variant.bluetooth;
break; break;
@@ -284,47 +284,47 @@ void AdminModule::handleSetModuleConfig(const ModuleConfig &c)
{ {
switch (c.which_payload_variant) { switch (c.which_payload_variant) {
case ModuleConfig_mqtt_tag: case ModuleConfig_mqtt_tag:
DEBUG_MSG("Setting module config: MQTT\n"); LOG_INFO("Setting module config: MQTT\n");
moduleConfig.has_mqtt = true; moduleConfig.has_mqtt = true;
moduleConfig.mqtt = c.payload_variant.mqtt; moduleConfig.mqtt = c.payload_variant.mqtt;
break; break;
case ModuleConfig_serial_tag: case ModuleConfig_serial_tag:
DEBUG_MSG("Setting module config: Serial\n"); LOG_INFO("Setting module config: Serial\n");
moduleConfig.has_serial = true; moduleConfig.has_serial = true;
moduleConfig.serial = c.payload_variant.serial; moduleConfig.serial = c.payload_variant.serial;
break; break;
case ModuleConfig_external_notification_tag: case ModuleConfig_external_notification_tag:
DEBUG_MSG("Setting module config: External Notification\n"); LOG_INFO("Setting module config: External Notification\n");
moduleConfig.has_external_notification = true; moduleConfig.has_external_notification = true;
moduleConfig.external_notification = c.payload_variant.external_notification; moduleConfig.external_notification = c.payload_variant.external_notification;
break; break;
case ModuleConfig_store_forward_tag: case ModuleConfig_store_forward_tag:
DEBUG_MSG("Setting module config: Store & Forward\n"); LOG_INFO("Setting module config: Store & Forward\n");
moduleConfig.has_store_forward = true; moduleConfig.has_store_forward = true;
moduleConfig.store_forward = c.payload_variant.store_forward; moduleConfig.store_forward = c.payload_variant.store_forward;
break; break;
case ModuleConfig_range_test_tag: case ModuleConfig_range_test_tag:
DEBUG_MSG("Setting module config: Range Test\n"); LOG_INFO("Setting module config: Range Test\n");
moduleConfig.has_range_test = true; moduleConfig.has_range_test = true;
moduleConfig.range_test = c.payload_variant.range_test; moduleConfig.range_test = c.payload_variant.range_test;
break; break;
case ModuleConfig_telemetry_tag: case ModuleConfig_telemetry_tag:
DEBUG_MSG("Setting module config: Telemetry\n"); LOG_INFO("Setting module config: Telemetry\n");
moduleConfig.has_telemetry = true; moduleConfig.has_telemetry = true;
moduleConfig.telemetry = c.payload_variant.telemetry; moduleConfig.telemetry = c.payload_variant.telemetry;
break; break;
case ModuleConfig_canned_message_tag: case ModuleConfig_canned_message_tag:
DEBUG_MSG("Setting module config: Canned Message\n"); LOG_INFO("Setting module config: Canned Message\n");
moduleConfig.has_canned_message = true; moduleConfig.has_canned_message = true;
moduleConfig.canned_message = c.payload_variant.canned_message; moduleConfig.canned_message = c.payload_variant.canned_message;
break; break;
case ModuleConfig_audio_tag: case ModuleConfig_audio_tag:
DEBUG_MSG("Setting module config: Audio\n"); LOG_INFO("Setting module config: Audio\n");
moduleConfig.has_audio = true; moduleConfig.has_audio = true;
moduleConfig.audio = c.payload_variant.audio; moduleConfig.audio = c.payload_variant.audio;
break; break;
case ModuleConfig_remote_hardware_tag: case ModuleConfig_remote_hardware_tag:
DEBUG_MSG("Setting module config: Remote Hardware\n"); LOG_INFO("Setting module config: Remote Hardware\n");
moduleConfig.has_remote_hardware = true; moduleConfig.has_remote_hardware = true;
moduleConfig.remote_hardware = c.payload_variant.remote_hardware; moduleConfig.remote_hardware = c.payload_variant.remote_hardware;
break; break;
@@ -363,38 +363,38 @@ void AdminModule::handleGetConfig(const MeshPacket &req, const uint32_t configTy
if (req.decoded.want_response) { if (req.decoded.want_response) {
switch (configType) { switch (configType) {
case AdminMessage_ConfigType_DEVICE_CONFIG: case AdminMessage_ConfigType_DEVICE_CONFIG:
DEBUG_MSG("Getting config: Device\n"); LOG_INFO("Getting config: Device\n");
res.get_config_response.which_payload_variant = Config_device_tag; res.get_config_response.which_payload_variant = Config_device_tag;
res.get_config_response.payload_variant.device = config.device; res.get_config_response.payload_variant.device = config.device;
break; break;
case AdminMessage_ConfigType_POSITION_CONFIG: case AdminMessage_ConfigType_POSITION_CONFIG:
DEBUG_MSG("Getting config: Position\n"); LOG_INFO("Getting config: Position\n");
res.get_config_response.which_payload_variant = Config_position_tag; res.get_config_response.which_payload_variant = Config_position_tag;
res.get_config_response.payload_variant.position = config.position; res.get_config_response.payload_variant.position = config.position;
break; break;
case AdminMessage_ConfigType_POWER_CONFIG: case AdminMessage_ConfigType_POWER_CONFIG:
DEBUG_MSG("Getting config: Power\n"); LOG_INFO("Getting config: Power\n");
res.get_config_response.which_payload_variant = Config_power_tag; res.get_config_response.which_payload_variant = Config_power_tag;
res.get_config_response.payload_variant.power = config.power; res.get_config_response.payload_variant.power = config.power;
break; break;
case AdminMessage_ConfigType_NETWORK_CONFIG: case AdminMessage_ConfigType_NETWORK_CONFIG:
DEBUG_MSG("Getting config: Network\n"); LOG_INFO("Getting config: Network\n");
res.get_config_response.which_payload_variant = Config_network_tag; res.get_config_response.which_payload_variant = Config_network_tag;
res.get_config_response.payload_variant.network = config.network; res.get_config_response.payload_variant.network = config.network;
writeSecret(res.get_config_response.payload_variant.network.wifi_psk, config.network.wifi_psk); writeSecret(res.get_config_response.payload_variant.network.wifi_psk, config.network.wifi_psk);
break; break;
case AdminMessage_ConfigType_DISPLAY_CONFIG: case AdminMessage_ConfigType_DISPLAY_CONFIG:
DEBUG_MSG("Getting config: Display\n"); LOG_INFO("Getting config: Display\n");
res.get_config_response.which_payload_variant = Config_display_tag; res.get_config_response.which_payload_variant = Config_display_tag;
res.get_config_response.payload_variant.display = config.display; res.get_config_response.payload_variant.display = config.display;
break; break;
case AdminMessage_ConfigType_LORA_CONFIG: case AdminMessage_ConfigType_LORA_CONFIG:
DEBUG_MSG("Getting config: LoRa\n"); LOG_INFO("Getting config: LoRa\n");
res.get_config_response.which_payload_variant = Config_lora_tag; res.get_config_response.which_payload_variant = Config_lora_tag;
res.get_config_response.payload_variant.lora = config.lora; res.get_config_response.payload_variant.lora = config.lora;
break; break;
case AdminMessage_ConfigType_BLUETOOTH_CONFIG: case AdminMessage_ConfigType_BLUETOOTH_CONFIG:
DEBUG_MSG("Getting config: Bluetooth\n"); LOG_INFO("Getting config: Bluetooth\n");
res.get_config_response.which_payload_variant = Config_bluetooth_tag; res.get_config_response.which_payload_variant = Config_bluetooth_tag;
res.get_config_response.payload_variant.bluetooth = config.bluetooth; res.get_config_response.payload_variant.bluetooth = config.bluetooth;
break; break;
@@ -418,48 +418,48 @@ void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t co
if (req.decoded.want_response) { if (req.decoded.want_response) {
switch (configType) { switch (configType) {
case AdminMessage_ModuleConfigType_MQTT_CONFIG: case AdminMessage_ModuleConfigType_MQTT_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_mqtt_tag;
res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt; res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt;
break; break;
case AdminMessage_ModuleConfigType_SERIAL_CONFIG: case AdminMessage_ModuleConfigType_SERIAL_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_serial_tag;
res.get_module_config_response.payload_variant.serial = moduleConfig.serial; res.get_module_config_response.payload_variant.serial = moduleConfig.serial;
break; break;
case AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: case AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_external_notification_tag;
res.get_module_config_response.payload_variant.external_notification = res.get_module_config_response.payload_variant.external_notification =
moduleConfig.external_notification; moduleConfig.external_notification;
break; break;
case AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: case AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_store_forward_tag;
res.get_module_config_response.payload_variant.store_forward = moduleConfig.store_forward; res.get_module_config_response.payload_variant.store_forward = moduleConfig.store_forward;
break; break;
case AdminMessage_ModuleConfigType_RANGETEST_CONFIG: case AdminMessage_ModuleConfigType_RANGETEST_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_range_test_tag;
res.get_module_config_response.payload_variant.range_test = moduleConfig.range_test; res.get_module_config_response.payload_variant.range_test = moduleConfig.range_test;
break; break;
case AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: case AdminMessage_ModuleConfigType_TELEMETRY_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_telemetry_tag;
res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry; res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry;
break; break;
case AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: case AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_canned_message_tag;
res.get_module_config_response.payload_variant.canned_message = moduleConfig.canned_message; res.get_module_config_response.payload_variant.canned_message = moduleConfig.canned_message;
break; break;
case AdminMessage_ModuleConfigType_AUDIO_CONFIG: case AdminMessage_ModuleConfigType_AUDIO_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_audio_tag;
res.get_module_config_response.payload_variant.audio = moduleConfig.audio; res.get_module_config_response.payload_variant.audio = moduleConfig.audio;
break; break;
case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG:
DEBUG_MSG("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.which_payload_variant = ModuleConfig_remote_hardware_tag;
res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware; res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware;
break; break;
@@ -506,7 +506,7 @@ void AdminModule::handleGetChannel(const MeshPacket &req, uint32_t channelIndex)
void AdminModule::reboot(int32_t seconds) void AdminModule::reboot(int32_t seconds)
{ {
DEBUG_MSG("Rebooting in %d seconds\n", seconds); LOG_INFO("Rebooting in %d seconds\n", seconds);
screen->startRebootScreen(); screen->startRebootScreen();
rebootAtMsec = (seconds < 0) ? 0 : (millis() + seconds * 1000); rebootAtMsec = (seconds < 0) ? 0 : (millis() + seconds * 1000);
} }
@@ -514,10 +514,10 @@ void AdminModule::reboot(int32_t seconds)
void AdminModule::saveChanges(int saveWhat, bool shouldReboot) void AdminModule::saveChanges(int saveWhat, bool shouldReboot)
{ {
if (!hasOpenEditTransaction) { if (!hasOpenEditTransaction) {
DEBUG_MSG("Saving changes to disk\n"); LOG_INFO("Saving changes to disk\n");
service.reloadConfig(saveWhat); // Calls saveToDisk among other things service.reloadConfig(saveWhat); // Calls saveToDisk among other things
} else { } else {
DEBUG_MSG("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) if (shouldReboot)
{ {

View File

@@ -49,10 +49,10 @@ CannedMessageModule::CannedMessageModule()
if (moduleConfig.canned_message.enabled) { if (moduleConfig.canned_message.enabled) {
this->loadProtoForModule(); this->loadProtoForModule();
if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) { if ((this->splitConfiguredMessages() <= 0) && (cardkb_found != CARDKB_ADDR)) {
DEBUG_MSG("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; this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED;
} else { } else {
DEBUG_MSG("CannedMessageModule is enabled\n"); LOG_INFO("CannedMessageModule is enabled\n");
this->inputObserver.observe(inputBroker); this->inputObserver.observe(inputBroker);
} }
} }
@@ -81,7 +81,7 @@ int CannedMessageModule::splitConfiguredMessages()
if (this->messageStore[i] == '|') { if (this->messageStore[i] == '|') {
// Message ending found, replace it with string-end character. // Message ending found, replace it with string-end character.
this->messageStore[i] = '\0'; 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 // hit our max messages, bail
if (messageIndex >= CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT) { if (messageIndex >= CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT) {
@@ -96,7 +96,7 @@ int CannedMessageModule::splitConfiguredMessages()
} }
if (strlen(this->messages[messageIndex - 1]) > 0) { if (strlen(this->messages[messageIndex - 1]) > 0) {
// We have a last message. // 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; this->messagesCount = messageIndex;
} else { } else {
this->messagesCount = messageIndex - 1; this->messagesCount = messageIndex - 1;
@@ -119,17 +119,17 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
bool validEvent = false; bool validEvent = false;
if (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_UP)) { if (event->inputEvent == static_cast<char>(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; this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_UP;
validEvent = true; validEvent = true;
} }
if (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_DOWN)) { if (event->inputEvent == static_cast<char>(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; this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_DOWN;
validEvent = true; validEvent = true;
} }
if (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_SELECT)) { if (event->inputEvent == static_cast<char>(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 // 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)) { if ((this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_DISABLED)) {
powerFSM.trigger(EVENT_PRESS); powerFSM.trigger(EVENT_PRESS);
@@ -140,7 +140,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
} }
} }
if (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL)) { if (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL)) {
DEBUG_MSG("Canned message event Cancel\n"); LOG_DEBUG("Canned message event Cancel\n");
// emulate a timeout. Same result // emulate a timeout. Same result
this->lastTouchMillis = 0; this->lastTouchMillis = 0;
validEvent = true; validEvent = true;
@@ -148,7 +148,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
if ((event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_BACK)) || if ((event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_BACK)) ||
(event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_LEFT)) || (event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_LEFT)) ||
(event->inputEvent == static_cast<char>(ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT))) { (event->inputEvent == static_cast<char>(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) { if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) {
// pass the pressed key // pass the pressed key
this->payload = event->kbchar; this->payload = event->kbchar;
@@ -157,7 +157,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
} }
} }
if (event->inputEvent == static_cast<char>(ANYKEY)) { if (event->inputEvent == static_cast<char>(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 // 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)) { 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; this->runState = CANNED_MESSAGE_RUN_STATE_FREETEXT;
@@ -168,7 +168,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
validEvent = true; validEvent = true;
} }
if (event->inputEvent == static_cast<char>(MATRIXKEY)) { if (event->inputEvent == static_cast<char>(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 will send the text immediately on matrix press
this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_SELECT; this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_SELECT;
this->payload = MATRIXKEY; this->payload = MATRIXKEY;
@@ -198,7 +198,7 @@ void CannedMessageModule::sendText(NodeNum dest, const char *message, bool wantR
p->decoded.payload.size++; 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_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); service.sendToMesh(p);
} }
@@ -209,7 +209,7 @@ int32_t CannedMessageModule::runOnce()
(this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE)) { (this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE)) {
return INT32_MAX; return INT32_MAX;
} }
DEBUG_MSG("Check status\n"); LOG_DEBUG("Check status\n");
UIFrameEvent e = {false, true}; UIFrameEvent e = {false, true};
if (this->runState == CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE) { if (this->runState == CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE) {
// TODO: might have some feedback of sendig state // TODO: might have some feedback of sendig state
@@ -222,7 +222,7 @@ int32_t CannedMessageModule::runOnce()
this->notifyObservers(&e); 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)) { } else if (((this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT)) && ((millis() - this->lastTouchMillis) > INACTIVATE_AFTER_MS)) {
// Reset module // Reset module
DEBUG_MSG("Reset due to lack of activity.\n"); LOG_DEBUG("Reset due to lack of activity.\n");
e.frameChanged = true; e.frameChanged = true;
this->currentMessageIndex = -1; this->currentMessageIndex = -1;
this->freetext = ""; // clear freetext this->freetext = ""; // clear freetext
@@ -236,7 +236,7 @@ int32_t CannedMessageModule::runOnce()
sendText(this->dest, this->freetext.c_str(), true); sendText(this->dest, this->freetext.c_str(), true);
this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE;
} else { } else {
DEBUG_MSG("Reset message is empty.\n"); LOG_DEBUG("Reset message is empty.\n");
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
} }
} else { } else {
@@ -249,7 +249,7 @@ int32_t CannedMessageModule::runOnce()
} }
this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE;
} else { } else {
DEBUG_MSG("Reset message is empty.\n"); LOG_DEBUG("Reset message is empty.\n");
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
} }
} }
@@ -262,7 +262,7 @@ int32_t CannedMessageModule::runOnce()
return 2000; return 2000;
} else if ((this->runState != CANNED_MESSAGE_RUN_STATE_FREETEXT) && (this->currentMessageIndex == -1)) { } else if ((this->runState != CANNED_MESSAGE_RUN_STATE_FREETEXT) && (this->currentMessageIndex == -1)) {
this->currentMessageIndex = 0; 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; e.frameChanged = true;
this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE;
} else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_UP) { } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_UP) {
@@ -272,7 +272,7 @@ int32_t CannedMessageModule::runOnce()
this->cursor = 0; this->cursor = 0;
this->destSelect = false; this->destSelect = false;
this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; 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) { } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_DOWN) {
if (this->messagesCount > 0) { if (this->messagesCount > 0) {
@@ -281,7 +281,7 @@ int32_t CannedMessageModule::runOnce()
this->cursor = 0; this->cursor = 0;
this->destSelect = false; this->destSelect = false;
this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; 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) { } else if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) {
e.frameChanged = true; e.frameChanged = true;
@@ -524,13 +524,13 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const
switch (request->which_payload_variant) { switch (request->which_payload_variant) {
case AdminMessage_get_canned_message_module_messages_request_tag: 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); this->handleGetCannedMessageModuleMessages(mp, response);
result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE;
break; break;
case AdminMessage_set_canned_message_module_messages_tag: 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); this->handleSetCannedMessageModuleMessages(request->set_canned_message_module_messages);
result = AdminMessageHandleResult::HANDLED; result = AdminMessageHandleResult::HANDLED;
break; break;
@@ -544,7 +544,7 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const
void CannedMessageModule::handleGetCannedMessageModuleMessages(const MeshPacket &req, AdminMessage *response) void CannedMessageModule::handleGetCannedMessageModuleMessages(const MeshPacket &req, AdminMessage *response)
{ {
DEBUG_MSG("*** handleGetCannedMessageModuleMessages\n"); LOG_DEBUG("*** handleGetCannedMessageModuleMessages\n");
assert(req.decoded.want_response); assert(req.decoded.want_response);
response->which_payload_variant = AdminMessage_get_canned_message_module_messages_response_tag; 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) { if (*from_msg) {
changed |= strcmp(cannedMessageModuleConfig.messages, from_msg); changed |= strcmp(cannedMessageModuleConfig.messages, from_msg);
strcpy(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) { if (changed) {

View File

@@ -48,15 +48,15 @@ int32_t ExternalNotificationModule::runOnce()
if (nagCycleCutoff < millis()) { if (nagCycleCutoff < millis()) {
#endif #endif
nagCycleCutoff = UINT32_MAX; nagCycleCutoff = UINT32_MAX;
DEBUG_MSG("Turning off external notification: "); LOG_INFO("Turning off external notification: ");
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
if (getExternal(i)) { if (getExternal(i)) {
setExternalOff(i); setExternalOff(i);
externalTurnedOn[i] = 0; externalTurnedOn[i] = 0;
DEBUG_MSG("%d ", i); LOG_INFO("%d ", i);
} }
} }
DEBUG_MSG("\n"); LOG_INFO("\n");
return INT32_MAX; // save cycles till we're needed again 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)); 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_INFO("Initializing External Notification Module\n");
output = moduleConfig.external_notification.output output = moduleConfig.external_notification.output
? moduleConfig.external_notification.output ? moduleConfig.external_notification.output
: EXT_NOTIFICATION_MODULE_OUTPUT; : EXT_NOTIFICATION_MODULE_OUTPUT;
// Set the direction of a pin // Set the direction of a pin
DEBUG_MSG("Using Pin %i in digital mode\n", output); LOG_INFO("Using Pin %i in digital mode\n", output);
pinMode(output, OUTPUT); pinMode(output, OUTPUT);
setExternalOff(0); setExternalOff(0);
externalTurnedOn[0] = 0; externalTurnedOn[0] = 0;
if(moduleConfig.external_notification.output_vibra) { if(moduleConfig.external_notification.output_vibra) {
DEBUG_MSG("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); pinMode(moduleConfig.external_notification.output_vibra, OUTPUT);
setExternalOff(1); setExternalOff(1);
externalTurnedOn[1] = 0; externalTurnedOn[1] = 0;
} }
if(moduleConfig.external_notification.output_buzzer) { if(moduleConfig.external_notification.output_buzzer) {
if (!moduleConfig.external_notification.use_pwm) { if (!moduleConfig.external_notification.use_pwm) {
DEBUG_MSG("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); pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT);
setExternalOff(2); setExternalOff(2);
externalTurnedOn[2] = 0; externalTurnedOn[2] = 0;
@@ -203,11 +203,11 @@ ExternalNotificationModule::ExternalNotificationModule()
? config.device.buzzer_gpio ? config.device.buzzer_gpio
: PIN_BUZZER; : PIN_BUZZER;
// in PWM Mode we force the buzzer pin if it is set // 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_INFO("Using Pin %i in PWM mode\n", config.device.buzzer_gpio);
} }
} }
} else { } else {
DEBUG_MSG("External Notification Module Disabled\n"); LOG_INFO("External Notification Module Disabled\n");
enabled = false; enabled = false;
} }
} }
@@ -229,7 +229,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp)
if (moduleConfig.external_notification.alert_bell) { if (moduleConfig.external_notification.alert_bell) {
if (containsBell) { if (containsBell) {
DEBUG_MSG("externalNotificationModule - Notification Bell\n"); LOG_INFO("externalNotificationModule - Notification Bell\n");
setExternalOn(0); setExternalOn(0);
if (moduleConfig.external_notification.nag_timeout) { if (moduleConfig.external_notification.nag_timeout) {
nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; 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 (moduleConfig.external_notification.alert_bell_vibra) {
if (containsBell) { if (containsBell) {
DEBUG_MSG("externalNotificationModule - Notification Bell (Vibra)\n"); LOG_INFO("externalNotificationModule - Notification Bell (Vibra)\n");
setExternalOn(1); setExternalOn(1);
if (moduleConfig.external_notification.nag_timeout) { if (moduleConfig.external_notification.nag_timeout) {
nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; 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 (moduleConfig.external_notification.alert_bell_buzzer) {
if (containsBell) { if (containsBell) {
DEBUG_MSG("externalNotificationModule - Notification Bell (Buzzer)\n"); LOG_INFO("externalNotificationModule - Notification Bell (Buzzer)\n");
if (!moduleConfig.external_notification.use_pwm) { if (!moduleConfig.external_notification.use_pwm) {
setExternalOn(2); setExternalOn(2);
} else { } else {
@@ -270,7 +270,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp)
} }
if (moduleConfig.external_notification.alert_message) { if (moduleConfig.external_notification.alert_message) {
DEBUG_MSG("externalNotificationModule - Notification Module\n"); LOG_INFO("externalNotificationModule - Notification Module\n");
setExternalOn(0); setExternalOn(0);
if (moduleConfig.external_notification.nag_timeout) { if (moduleConfig.external_notification.nag_timeout) {
nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; 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.use_pwm) {
if (moduleConfig.external_notification.alert_message_vibra) { if (moduleConfig.external_notification.alert_message_vibra) {
DEBUG_MSG("externalNotificationModule - Notification Module (Vibra)\n"); LOG_INFO("externalNotificationModule - Notification Module (Vibra)\n");
setExternalOn(1); setExternalOn(1);
if (moduleConfig.external_notification.nag_timeout) { if (moduleConfig.external_notification.nag_timeout) {
nagCycleCutoff = millis() + moduleConfig.external_notification.nag_timeout * 1000; 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) { if (moduleConfig.external_notification.alert_message_buzzer) {
DEBUG_MSG("externalNotificationModule - Notification Module (Buzzer)\n"); LOG_INFO("externalNotificationModule - Notification Module (Buzzer)\n");
if (!moduleConfig.external_notification.use_pwm) { if (!moduleConfig.external_notification.use_pwm) {
setExternalOn(2); setExternalOn(2);
} else { } else {
@@ -310,7 +310,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp)
} }
} else { } else {
DEBUG_MSG("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 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) { switch (request->which_payload_variant) {
case AdminMessage_get_ringtone_request_tag: case AdminMessage_get_ringtone_request_tag:
DEBUG_MSG("Client is getting ringtone\n"); LOG_INFO("Client is getting ringtone\n");
this->handleGetRingtone(mp, response); this->handleGetRingtone(mp, response);
result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE;
break; break;
case AdminMessage_set_ringtone_message_tag: case AdminMessage_set_ringtone_message_tag:
DEBUG_MSG("Client is setting ringtone\n"); LOG_INFO("Client is setting ringtone\n");
this->handleSetRingtone(request->set_canned_message_module_messages); this->handleSetRingtone(request->set_canned_message_module_messages);
result = AdminMessageHandleResult::HANDLED; result = AdminMessageHandleResult::HANDLED;
break; break;
@@ -351,7 +351,7 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule
void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response) void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response)
{ {
DEBUG_MSG("*** handleGetRingtone\n"); LOG_INFO("*** handleGetRingtone\n");
assert(req.decoded.want_response); assert(req.decoded.want_response);
response->which_payload_variant = AdminMessage_get_ringtone_response_tag; response->which_payload_variant = AdminMessage_get_ringtone_response_tag;
@@ -366,7 +366,7 @@ void ExternalNotificationModule::handleSetRingtone(const char *from_msg)
if (*from_msg) { if (*from_msg) {
changed |= strcmp(rtttlConfig.ringtone, from_msg); changed |= strcmp(rtttlConfig.ringtone, from_msg);
strcpy(rtttlConfig.ringtone, from_msg); strcpy(rtttlConfig.ringtone, from_msg);
DEBUG_MSG("*** from_msg.text:%s\n", from_msg); LOG_INFO("*** from_msg.text:%s\n", from_msg);
} }
if (changed) { if (changed) {

View File

@@ -23,7 +23,7 @@ bool NodeInfoModule::handleReceivedProtobuf(const MeshPacket &mp, User *pptr)
screen->print(lcd.c_str()); 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 return false; // Let others look at this message also if they want
} }
@@ -46,7 +46,7 @@ MeshPacket *NodeInfoModule::allocReply()
{ {
User &u = owner; User &u = owner;
DEBUG_MSG("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); return allocDataProtobuf(u);
} }
@@ -65,7 +65,7 @@ int32_t NodeInfoModule::runOnce()
bool requestReplies = currentGeneration != radioGeneration; bool requestReplies = currentGeneration != radioGeneration;
currentGeneration = radioGeneration; currentGeneration = radioGeneration;
DEBUG_MSG("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) sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies)
return default_broadcast_interval_secs * 1000; return default_broadcast_interval_secs * 1000;

View File

@@ -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) // 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) // to set fixed location, EUD-GPS location or just the time (see also issue #900)
if (nodeDB.getNodeNum() == getFrom(&mp)) { if (nodeDB.getNodeNum() == getFrom(&mp)) {
DEBUG_MSG("Incoming update from MYSELF\n"); LOG_DEBUG("Incoming update from MYSELF\n");
// DEBUG_MSG("Ignored an incoming update from MYSELF\n"); // LOG_DEBUG("Ignored an incoming update from MYSELF\n");
// return false; // return false;
} }
// Log packet size and list of fields // 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_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.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.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 " : "", 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 // 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. // devices can get time.
if (getRTCQuality() < RTCQualityDevice) { if (getRTCQuality() < RTCQualityDevice) {
DEBUG_MSG("Stripping time %u from position send\n", p.time); LOG_INFO("Stripping time %u from position send\n", p.time);
p.time = 0; p.time = 0;
} else } else
DEBUG_MSG("Providing time to mesh %u\n", p.time); LOG_INFO("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_INFO("Position reply: time=%i, latI=%i, lonI=-%i\n", p.time, p.latitude_i, p.longitude_i);
return allocDataProtobuf(p); return allocDataProtobuf(p);
} }
@@ -155,11 +155,11 @@ int32_t PositionModule::runOnce()
bool requestReplies = currentGeneration != radioGeneration; bool requestReplies = currentGeneration != radioGeneration;
currentGeneration = radioGeneration; currentGeneration = radioGeneration;
DEBUG_MSG("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); sendOurPosition(NODENUM_BROADCAST, requestReplies);
} }
} else { } else {
DEBUG_MSG("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) { } else if (config.position.position_broadcast_smart_enabled) {
@@ -194,7 +194,7 @@ int32_t PositionModule::runOnce()
bool requestReplies = currentGeneration != radioGeneration; bool requestReplies = currentGeneration != radioGeneration;
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_INFO("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp,
requestReplies, distance, distanceTravelThreshold, timeTravel); requestReplies, distance, distanceTravelThreshold, timeTravel);
sendOurPosition(NODENUM_BROADCAST, requestReplies); sendOurPosition(NODENUM_BROADCAST, requestReplies);
@@ -209,7 +209,7 @@ int32_t PositionModule::runOnce()
} }
} }
} else { } else {
DEBUG_MSG("Channel utilization is >25 percent. Skipping this opportunity to send.\n"); LOG_WARN("Channel utilization is >25 percent. Skipping this opportunity to send.\n");
} }
} }

View File

@@ -55,7 +55,7 @@ RemoteHardwareModule::RemoteHardwareModule()
bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr) bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr)
{ {
auto p = *pptr; auto p = *pptr;
DEBUG_MSG("Received RemoteHardware typ=%d\n", p.type); LOG_INFO("Received RemoteHardware typ=%d\n", p.type);
switch (p.type) { switch (p.type) {
case HardwareMessage_Type_WRITE_GPIOS: case HardwareMessage_Type_WRITE_GPIOS:
@@ -95,7 +95,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar
lastWatchMsec = 0; // Force a new publish soon lastWatchMsec = 0; // Force a new publish soon
previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) 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 enabled = true; // Let our thread run at least once
DEBUG_MSG("Now watching GPIOs 0x%llx\n", watchGpios); LOG_INFO("Now watching GPIOs 0x%llx\n", watchGpios);
break; break;
} }
@@ -104,7 +104,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar
break; // Ignore - we might see our own replies break; // Ignore - we might see our own replies
default: default:
DEBUG_MSG("Hardware operation %d not yet implemented! FIXME\n", p.type); LOG_ERROR("Hardware operation %d not yet implemented! FIXME\n", p.type);
break; break;
} }
@@ -121,7 +121,7 @@ int32_t RemoteHardwareModule::runOnce()
if (curVal != previousWatch) { if (curVal != previousWatch) {
previousWatch = curVal; previousWatch = curVal;
DEBUG_MSG("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 // Something changed! Tell the world with a broadcast message
HardwareMessage r = HardwareMessage_init_default; HardwareMessage r = HardwareMessage_init_default;

View File

@@ -11,7 +11,7 @@ MeshPacket *ReplyModule::allocReply()
auto req = *currentRequest; auto req = *currentRequest;
auto &p = req.decoded; auto &p = req.decoded;
// The incoming message is in p.payload // 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_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"); screen->print("Sending reply\n");

View File

@@ -109,7 +109,7 @@ int32_t SerialModule::runOnce()
if (firstTime) { if (firstTime) {
// Interface with the serial peripheral from in here. // Interface with the serial peripheral from in here.
DEBUG_MSG("Initializing serial peripheral interface\n"); LOG_INFO("Initializing serial peripheral interface\n");
uint32_t baud = 0; uint32_t baud = 0;
@@ -213,14 +213,14 @@ int32_t SerialModule::runOnce()
serialModuleRadio->sendPayload(); serialModuleRadio->sendPayload();
DEBUG_MSG("Received: %s\n", serialStringChar); LOG_INFO("Received: %s\n", serialStringChar);
} }
} }
} }
return (10); return (10);
} else { } else {
DEBUG_MSG("Serial Module Disabled\n"); LOG_INFO("Serial Module Disabled\n");
return INT32_MAX; return INT32_MAX;
} }
@@ -256,7 +256,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp)
} }
auto &p = mp.decoded; 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); // nodeDB.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes);
if (getFrom(&mp) == nodeDB.getNodeNum()) { if (getFrom(&mp) == nodeDB.getNodeNum()) {
@@ -271,7 +271,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp)
// TODO: need to find out why. // TODO: need to find out why.
if (lastRxID != mp.id) { if (lastRxID != mp.id) {
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.println("* * Message came this device");
Serial2.printf("%s", p.payload.bytes); Serial2.printf("%s", p.payload.bytes);
} }
@@ -305,7 +305,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp)
} }
} else { } else {
DEBUG_MSG("Serial Module Disabled\n"); LOG_INFO("Serial Module Disabled\n");
} }
return ProcessMessage::CONTINUE; // Let others look at this message also if they want return ProcessMessage::CONTINUE; // Let others look at this message also if they want
} }

View File

@@ -34,7 +34,7 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemet
if (t->which_variant == Telemetry_device_metrics_tag) { if (t->which_variant == Telemetry_device_metrics_tag) {
const char *sender = getSenderShortName(mp); const char *sender = getSenderShortName(mp);
DEBUG_MSG("(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, sender,
t->variant.device_metrics.air_util_tx, t->variant.device_metrics.air_util_tx,
t->variant.device_metrics.channel_utilization, 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.channel_utilization = myNodeInfo.channel_utilization;
t.variant.device_metrics.voltage = powerStatus->getBatteryVoltageMv() / 1000.0; 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_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.air_util_tx,
t.variant.device_metrics.channel_utilization, t.variant.device_metrics.channel_utilization,
t.variant.device_metrics.battery_level, t.variant.device_metrics.battery_level,
@@ -74,10 +74,10 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly)
lastMeasurementPacket = packetPool.allocCopy(*p); lastMeasurementPacket = packetPool.allocCopy(*p);
nodeDB.updateTelemetry(nodeDB.getNodeNum(), t, RX_SRC_LOCAL); nodeDB.updateTelemetry(nodeDB.getNodeNum(), t, RX_SRC_LOCAL);
if (phoneOnly) { if (phoneOnly) {
DEBUG_MSG("Sending packet to phone\n"); LOG_INFO("Sending packet to phone\n");
service.sendToPhone(p); service.sendToPhone(p);
} else { } else {
DEBUG_MSG("Sending packet to mesh\n"); LOG_INFO("Sending packet to mesh\n");
service.sendToMesh(p, RX_SRC_LOCAL, true); service.sendToMesh(p, RX_SRC_LOCAL, true);
} }
return true; return true;

View File

@@ -75,7 +75,7 @@ int32_t EnvironmentTelemetryModule::runOnce()
firstTime = 0; firstTime = 0;
if (moduleConfig.telemetry.environment_measurement_enabled) { if (moduleConfig.telemetry.environment_measurement_enabled) {
DEBUG_MSG("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. // 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 // therefore, we should only enable the sensor loop if measurement is also enabled
if (bmp280Sensor.hasSensor()) 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)) { if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Telemetry_msg, &lastMeasurement)) {
display->setFont(FONT_SMALL); display->setFont(FONT_SMALL);
display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error"); display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error");
DEBUG_MSG("Unable to decode last packet"); LOG_ERROR("Unable to decode last packet");
return; return;
} }
@@ -187,7 +187,7 @@ bool EnvironmentTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Te
if (t->which_variant == Telemetry_environment_metrics_tag) { if (t->which_variant == Telemetry_environment_metrics_tag) {
const char *sender = getSenderShortName(mp); 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_INFO("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f, voltage=%f\n",
sender, sender,
t->variant.environment_metrics.barometric_pressure, t->variant.environment_metrics.barometric_pressure,
t->variant.environment_metrics.current, t->variant.environment_metrics.current,
@@ -234,7 +234,7 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly)
if (ina260Sensor.hasSensor()) if (ina260Sensor.hasSensor())
ina260Sensor.getMetrics(&m); ina260Sensor.getMetrics(&m);
DEBUG_MSG("(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.barometric_pressure,
m.variant.environment_metrics.current, m.variant.environment_metrics.current,
m.variant.environment_metrics.gas_resistance, m.variant.environment_metrics.gas_resistance,
@@ -251,10 +251,10 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly)
lastMeasurementPacket = packetPool.allocCopy(*p); lastMeasurementPacket = packetPool.allocCopy(*p);
if (phoneOnly) { if (phoneOnly) {
DEBUG_MSG("Sending packet to phone\n"); LOG_INFO("Sending packet to phone\n");
service.sendToPhone(p); service.sendToPhone(p);
} else { } else {
DEBUG_MSG("Sending packet to mesh\n"); LOG_INFO("Sending packet to mesh\n");
service.sendToMesh(p, RX_SRC_LOCAL, true); service.sendToMesh(p, RX_SRC_LOCAL, true);
} }
return true; return true;

View File

@@ -11,7 +11,7 @@ BME280Sensor::BME280Sensor() :
} }
int32_t BME280Sensor::runOnce() { int32_t BME280Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }
@@ -30,7 +30,7 @@ int32_t BME280Sensor::runOnce() {
void BME280Sensor::setup() { } void BME280Sensor::setup() { }
bool BME280Sensor::getMetrics(Telemetry *measurement) { bool BME280Sensor::getMetrics(Telemetry *measurement) {
DEBUG_MSG("BME280Sensor::getMetrics\n"); LOG_DEBUG("BME280Sensor::getMetrics\n");
bme280.takeForcedMeasurement(); bme280.takeForcedMeasurement();
measurement->variant.environment_metrics.temperature = bme280.readTemperature(); measurement->variant.environment_metrics.temperature = bme280.readTemperature();
measurement->variant.environment_metrics.relative_humidity = bme280.readHumidity(); measurement->variant.environment_metrics.relative_humidity = bme280.readHumidity();

View File

@@ -10,7 +10,7 @@ BME680Sensor::BME680Sensor() :
} }
int32_t BME680Sensor::runOnce() { int32_t BME680Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -11,7 +11,7 @@ BMP280Sensor::BMP280Sensor() :
} }
int32_t BMP280Sensor::runOnce() { int32_t BMP280Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }
@@ -29,7 +29,7 @@ int32_t BMP280Sensor::runOnce() {
void BMP280Sensor::setup() { } void BMP280Sensor::setup() { }
bool BMP280Sensor::getMetrics(Telemetry *measurement) { bool BMP280Sensor::getMetrics(Telemetry *measurement) {
DEBUG_MSG("BMP280Sensor::getMetrics\n"); LOG_DEBUG("BMP280Sensor::getMetrics\n");
bmp280.takeForcedMeasurement(); bmp280.takeForcedMeasurement();
measurement->variant.environment_metrics.temperature = bmp280.readTemperature(); measurement->variant.environment_metrics.temperature = bmp280.readTemperature();
measurement->variant.environment_metrics.barometric_pressure = bmp280.readPressure() / 100.0F; measurement->variant.environment_metrics.barometric_pressure = bmp280.readPressure() / 100.0F;

View File

@@ -10,7 +10,7 @@ INA219Sensor::INA219Sensor() :
} }
int32_t INA219Sensor::runOnce() { int32_t INA219Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -10,7 +10,7 @@ INA260Sensor::INA260Sensor() :
} }
int32_t INA260Sensor::runOnce() { int32_t INA260Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -11,7 +11,7 @@ LPS22HBSensor::LPS22HBSensor() :
} }
int32_t LPS22HBSensor::runOnce() { int32_t LPS22HBSensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -10,7 +10,7 @@ MCP9808Sensor::MCP9808Sensor() :
} }
int32_t MCP9808Sensor::runOnce() { int32_t MCP9808Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }
@@ -23,7 +23,7 @@ void MCP9808Sensor::setup() {
} }
bool MCP9808Sensor::getMetrics(Telemetry *measurement) { bool MCP9808Sensor::getMetrics(Telemetry *measurement) {
DEBUG_MSG("MCP9808Sensor::getMetrics\n"); LOG_DEBUG("MCP9808Sensor::getMetrics\n");
measurement->variant.environment_metrics.temperature = mcp9808.readTempC(); measurement->variant.environment_metrics.temperature = mcp9808.readTempC();
return true; return true;
} }

View File

@@ -10,7 +10,7 @@ SHT31Sensor::SHT31Sensor() :
} }
int32_t SHT31Sensor::runOnce() { int32_t SHT31Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -10,7 +10,7 @@ SHTC3Sensor::SHTC3Sensor() :
} }
int32_t SHTC3Sensor::runOnce() { int32_t SHTC3Sensor::runOnce() {
DEBUG_MSG("Init sensor: %s\n", sensorName); LOG_INFO("Init sensor: %s\n", sensorName);
if (!hasSensor()) { if (!hasSensor()) {
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;
} }

View File

@@ -21,10 +21,10 @@ class TelemetrySensor
int32_t initI2CSensor() { int32_t initI2CSensor() {
if (!status) { if (!status) {
DEBUG_MSG("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; nodeTelemetrySensorsMap[sensorType] = 0;
} else { } else {
DEBUG_MSG("Opened %s sensor on default i2c bus\n", sensorName); LOG_INFO("Opened %s sensor on default i2c bus\n", sensorName);
setup(); setup();
} }
return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS;

View File

@@ -8,7 +8,7 @@ TextMessageModule *textMessageModule;
ProcessMessage TextMessageModule::handleReceived(const MeshPacket &mp) ProcessMessage TextMessageModule::handleReceived(const MeshPacket &mp)
{ {
auto &p = mp.decoded; 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_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. // We only store/display messages destined for us.
// Keep a copy of the most recent text message. // Keep a copy of the most recent text message.

View File

@@ -43,19 +43,19 @@ void TraceRouteModule::appendMyID(RouteDiscovery* updated)
updated->route[updated->route_count] = myNodeInfo.my_node_num; updated->route[updated->route_count] = myNodeInfo.my_node_num;
updated->route_count += 1; updated->route_count += 1;
} else { } 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) void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest)
{ {
DEBUG_MSG("Route traced:\n"); LOG_INFO("Route traced:\n");
DEBUG_MSG("0x%x --> ", origin); LOG_INFO("0x%x --> ", origin);
for (uint8_t i=0; i<r->route_count; i++) { for (uint8_t i=0; i<r->route_count; i++) {
DEBUG_MSG("0x%x --> ", r->route[i]); LOG_INFO("0x%x --> ", r->route[i]);
} }
if (dest != NODENUM_BROADCAST) DEBUG_MSG("0x%x\n", dest); else DEBUG_MSG("...\n"); if (dest != NODENUM_BROADCAST) LOG_INFO("0x%x\n", dest); else LOG_INFO("...\n");
} }

View File

@@ -8,7 +8,7 @@ WaypointModule *waypointModule;
ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp) ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp)
{ {
auto &p = mp.decoded; 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_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); notifyObservers(&mp);

View File

@@ -71,7 +71,7 @@ void run_codec2(void* parameter)
// 4 bytes of header in each frame 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)); memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header));
DEBUG_MSG("Starting codec2 task\n"); LOG_INFO("Starting codec2 task\n");
while (true) { while (true) {
uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); 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))) 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_INFO("Sending %d codec2 bytes\n", audioModule->encode_frame_size);
audioModule->sendPayload(); audioModule->sendPayload();
audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); 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; // moduleConfig.audio.ptt_pin = 39;
if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { 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_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); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); memcpy(tx_header.magic,c2_magic,sizeof(c2_magic));
tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; 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_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 encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes
adc_buffer_size = codec2_samples_per_frame(codec2); 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_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); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask);
} else { } else {
DEBUG_MSG("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; esp_err_t res;
if (firstTime) { if (firstTime) {
// Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC // 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_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 = { 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)), .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, .sample_rate = 8000,
@@ -189,7 +189,7 @@ int32_t AudioModule::runOnce()
}; };
res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
if(res != ESP_OK) if(res != ESP_OK)
DEBUG_MSG("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 = { const i2s_pin_config_t pin_config = {
.bck_io_num = moduleConfig.audio.i2s_sck, .bck_io_num = moduleConfig.audio.i2s_sck,
@@ -199,16 +199,16 @@ int32_t AudioModule::runOnce()
}; };
res = i2s_set_pin(I2S_PORT, &pin_config); res = i2s_set_pin(I2S_PORT, &pin_config);
if(res != ESP_OK) if(res != ESP_OK)
DEBUG_MSG("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); res = i2s_start(I2S_PORT);
if(res != ESP_OK) if(res != ESP_OK)
DEBUG_MSG("Failed to start I2S: %d\n", res); LOG_ERROR("Failed to start I2S: %d\n", res);
radio_state = RadioState::rx; radio_state = RadioState::rx;
// Configure PTT input // Configure PTT input
DEBUG_MSG("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); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT);
firstTime = false; firstTime = false;
@@ -217,17 +217,17 @@ int32_t AudioModule::runOnce()
// Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. // 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 (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) {
if (radio_state == RadioState::rx) { if (radio_state == RadioState::rx) {
DEBUG_MSG("PTT pressed, switching to TX\n"); LOG_INFO("PTT pressed, switching to TX\n");
radio_state = RadioState::tx; radio_state = RadioState::tx;
e.frameChanged = true; e.frameChanged = true;
this->notifyObservers(&e); this->notifyObservers(&e);
} }
} else { } else {
if (radio_state == RadioState::tx) { if (radio_state == RadioState::tx) {
DEBUG_MSG("PTT released, switching to RX\n"); LOG_INFO("PTT released, switching to RX\n");
if (tx_encode_frame_index > sizeof(tx_header)) { if (tx_encode_frame_index > sizeof(tx_header)) {
// Send the incomplete frame // Send the incomplete frame
DEBUG_MSG("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); LOG_INFO("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index);
sendPayload(); sendPayload();
} }
tx_encode_frame_index = sizeof(tx_header); tx_encode_frame_index = sizeof(tx_header);
@@ -258,7 +258,7 @@ int32_t AudioModule::runOnce()
} }
return 100; return 100;
} else { } else {
DEBUG_MSG("Audio Module Disabled\n"); LOG_INFO("Audio Module Disabled\n");
return INT32_MAX; return INT32_MAX;
} }

View File

@@ -53,10 +53,10 @@ int32_t RangeTestModule::runOnce()
firstTime = 0; firstTime = 0;
if (moduleConfig.range_test.sender) { if (moduleConfig.range_test.sender) {
DEBUG_MSG("Initializing Range Test Module -- Sender\n"); LOG_INFO("Initializing Range Test Module -- Sender\n");
return (5000); // Sending first message 5 seconds after initilization. return (5000); // Sending first message 5 seconds after initilization.
} else { } else {
DEBUG_MSG("Initializing Range Test Module -- Receiver\n"); LOG_INFO("Initializing Range Test Module -- Receiver\n");
return (INT32_MAX); return (INT32_MAX);
// This thread does not need to run as a receiver // This thread does not need to run as a receiver
} }
@@ -65,19 +65,19 @@ int32_t RangeTestModule::runOnce()
if (moduleConfig.range_test.sender) { if (moduleConfig.range_test.sender) {
// If sender // If sender
DEBUG_MSG("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); LOG_INFO("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat));
DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); LOG_INFO("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude());
DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); LOG_INFO("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude());
DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); LOG_INFO("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock());
DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); LOG_INFO("gpsStatus->getDOP() %d\n", gpsStatus->getDOP());
DEBUG_MSG("fixed_position() %d\n", config.position.fixed_position); LOG_INFO("fixed_position() %d\n", config.position.fixed_position);
// Only send packets if the channel is less than 25% utilized. // Only send packets if the channel is less than 25% utilized.
if (airTime->channelUtilizationPercent() < 25) { if (airTime->channelUtilizationPercent() < 25) {
rangeTestModuleRadio->sendPayload(); rangeTestModuleRadio->sendPayload();
} else { } else {
DEBUG_MSG("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); return (senderHeartbeat);
@@ -88,9 +88,8 @@ int32_t RangeTestModule::runOnce()
} }
} else { } else {
DEBUG_MSG("Range Test Module - Disabled\n"); LOG_INFO("Range Test Module - Disabled\n");
} }
#endif #endif
@@ -135,8 +134,8 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp)
/* /*
auto &p = mp.decoded; 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); LOG_INFO.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes);
*/ */
if (getFrom(&mp) != nodeDB.getNodeNum()) { if (getFrom(&mp) != nodeDB.getNodeNum()) {
@@ -148,33 +147,33 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp)
/* /*
NodeInfo *n = nodeDB.getNode(getFrom(&mp)); NodeInfo *n = nodeDB.getNode(getFrom(&mp));
DEBUG_MSG("-----------------------------------------\n"); LOG_DEBUG("-----------------------------------------\n");
DEBUG_MSG("p.payload.bytes \"%s\"\n", p.payload.bytes); LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes);
DEBUG_MSG("p.payload.size %d\n", p.payload.size); LOG_DEBUG("p.payload.size %d\n", p.payload.size);
DEBUG_MSG("---- Received Packet:\n"); LOG_DEBUG("---- Received Packet:\n");
DEBUG_MSG("mp.from %d\n", mp.from); LOG_DEBUG("mp.from %d\n", mp.from);
DEBUG_MSG("mp.rx_snr %f\n", mp.rx_snr); LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr);
DEBUG_MSG("mp.hop_limit %d\n", mp.hop_limit); LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit);
// DEBUG_MSG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated // LOG_DEBUG("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 // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated
DEBUG_MSG("---- Node Information of Received Packet (mp.from):\n"); LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n");
DEBUG_MSG("n->user.long_name %s\n", n->user.long_name); LOG_DEBUG("n->user.long_name %s\n", n->user.long_name);
DEBUG_MSG("n->user.short_name %s\n", n->user.short_name); LOG_DEBUG("n->user.short_name %s\n", n->user.short_name);
DEBUG_MSG("n->user.macaddr %X\n", n->user.macaddr); LOG_DEBUG("n->user.macaddr %X\n", n->user.macaddr);
DEBUG_MSG("n->has_position %d\n", n->has_position); LOG_DEBUG("n->has_position %d\n", n->has_position);
DEBUG_MSG("n->position.latitude_i %d\n", n->position.latitude_i); LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i);
DEBUG_MSG("n->position.longitude_i %d\n", n->position.longitude_i); LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i);
DEBUG_MSG("---- Current device location information:\n"); LOG_DEBUG("---- Current device location information:\n");
DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude());
DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude());
DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock());
DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP());
DEBUG_MSG("-----------------------------------------\n"); LOG_DEBUG("-----------------------------------------\n");
*/ */
} }
} else { } else {
DEBUG_MSG("Range Test Module Disabled\n"); LOG_INFO("Range Test Module Disabled\n");
} }
#endif #endif
@@ -188,36 +187,36 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp)
NodeInfo *n = nodeDB.getNode(getFrom(&mp)); NodeInfo *n = nodeDB.getNode(getFrom(&mp));
/* /*
DEBUG_MSG("-----------------------------------------\n"); LOG_DEBUG("-----------------------------------------\n");
DEBUG_MSG("p.payload.bytes \"%s\"\n", p.payload.bytes); LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes);
DEBUG_MSG("p.payload.size %d\n", p.payload.size); LOG_DEBUG("p.payload.size %d\n", p.payload.size);
DEBUG_MSG("---- Received Packet:\n"); LOG_DEBUG("---- Received Packet:\n");
DEBUG_MSG("mp.from %d\n", mp.from); LOG_DEBUG("mp.from %d\n", mp.from);
DEBUG_MSG("mp.rx_snr %f\n", mp.rx_snr); LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr);
DEBUG_MSG("mp.hop_limit %d\n", mp.hop_limit); LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit);
// DEBUG_MSG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Depricated // LOG_DEBUG("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 // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Depricated
DEBUG_MSG("---- Node Information of Received Packet (mp.from):\n"); LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n");
DEBUG_MSG("n->user.long_name %s\n", n->user.long_name); LOG_DEBUG("n->user.long_name %s\n", n->user.long_name);
DEBUG_MSG("n->user.short_name %s\n", n->user.short_name); LOG_DEBUG("n->user.short_name %s\n", n->user.short_name);
DEBUG_MSG("n->user.macaddr %X\n", n->user.macaddr); LOG_DEBUG("n->user.macaddr %X\n", n->user.macaddr);
DEBUG_MSG("n->has_position %d\n", n->has_position); LOG_DEBUG("n->has_position %d\n", n->has_position);
DEBUG_MSG("n->position.latitude_i %d\n", n->position.latitude_i); LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i);
DEBUG_MSG("n->position.longitude_i %d\n", n->position.longitude_i); LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i);
DEBUG_MSG("---- Current device location information:\n"); LOG_DEBUG("---- Current device location information:\n");
DEBUG_MSG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude());
DEBUG_MSG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude());
DEBUG_MSG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock());
DEBUG_MSG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP());
DEBUG_MSG("-----------------------------------------\n"); LOG_DEBUG("-----------------------------------------\n");
*/ */
if (!FSBegin()) { 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; return 0;
} }
if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { 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; return 0;
} }
@@ -229,16 +228,16 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp)
File fileToWrite = FSCom.open("/static/rangetest.csv", FILE_WRITE); File fileToWrite = FSCom.open("/static/rangetest.csv", FILE_WRITE);
if (!fileToWrite) { if (!fileToWrite) {
DEBUG_MSG("There was an error opening the file for writing\n"); LOG_ERROR("There was an error opening the file for writing\n");
return 0; return 0;
} }
// Print the CSV header // Print the CSV header
if (fileToWrite.println( if (fileToWrite.println(
"time,from,sender name,sender lat,sender long,rx lat,rx long,rx elevation,rx snr,distance,hop limit,payload")) { "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_INFO("File was written\n");
} else { } else {
DEBUG_MSG("File write failed\n"); LOG_ERROR("File write failed\n");
} }
fileToWrite.close(); fileToWrite.close();
@@ -248,7 +247,7 @@ bool RangeTestModuleRadio::appendFile(const MeshPacket &mp)
File fileToAppend = FSCom.open("/static/rangetest.csv", FILE_APPEND); File fileToAppend = FSCom.open("/static/rangetest.csv", FILE_APPEND);
if (!fileToAppend) { if (!fileToAppend) {
DEBUG_MSG("There was an error opening the file for appending\n"); LOG_ERROR("There was an error opening the file for appending\n");
return 0; return 0;
} }

View File

@@ -28,20 +28,20 @@ int32_t StoreForwardModule::runOnce()
StoreAndForward sf = StoreAndForward_init_zero; StoreAndForward sf = StoreAndForward_init_zero;
sf.rr = StoreAndForward_RequestResponse_ROUTER_PING; sf.rr = StoreAndForward_RequestResponse_ROUTER_PING;
storeForwardModule->sendMessage(this->busyTo, sf); storeForwardModule->sendMessage(this->busyTo, sf);
DEBUG_MSG("*** S&F - Done. (ROUTER_PING)\n"); LOG_INFO("*** S&F - Done. (ROUTER_PING)\n");
this->packetHistoryTXQueue_index = 0; this->packetHistoryTXQueue_index = 0;
this->busy = false; this->busy = false;
} else { } else {
this->packetHistoryTXQueue_index++; this->packetHistoryTXQueue_index++;
} }
} else { } else {
DEBUG_MSG("*** Channel utilization is too high. Retrying later.\n"); LOG_WARN("*** 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)) { } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && (airTime->channelUtilizationPercent() < polite_channel_util_percent)) {
lastHeartbeat = millis(); lastHeartbeat = millis();
DEBUG_MSG("*** Sending heartbeat\n"); LOG_INFO("*** Sending heartbeat\n");
StoreAndForward sf = StoreAndForward_init_zero; StoreAndForward sf = StoreAndForward_init_zero;
sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT;
sf.which_variant = StoreAndForward_heartbeat_tag; sf.which_variant = StoreAndForward_heartbeat_tag;
@@ -65,7 +65,7 @@ void StoreForwardModule::populatePSRAM()
https://learn.upesy.com/en/programmation/psram.html#psram-tab 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 = this->packetHistoryTXQueue =
static_cast<PacketHistoryStruct *>(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct))); static_cast<PacketHistoryStruct *>(ps_calloc(this->historyReturnMax, sizeof(PacketHistoryStruct)));
@@ -78,8 +78,8 @@ void StoreForwardModule::populatePSRAM()
this->packetHistory = static_cast<PacketHistoryStruct *>(ps_calloc(numberOfPackets, sizeof(PacketHistoryStruct))); this->packetHistory = static_cast<PacketHistoryStruct *>(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()); LOG_DEBUG("*** 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("*** numberOfPackets for packetHistory - %u\n", numberOfPackets);
} }
void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) 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); uint32_t queueSize = storeForwardModule->historyQueueCreate(msAgo, to);
if (queueSize) { if (queueSize) {
DEBUG_MSG ("*** 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->busy = true; // runOnce() will pickup the next steps once busy = true.
this->busyTo = to; this->busyTo = to;
} else { } else {
DEBUG_MSG ("*** S&F - No history to send\n"); LOG_INFO("*** S&F - No history to send\n");
} }
StoreAndForward sf = StoreAndForward_init_zero; StoreAndForward sf = StoreAndForward_init_zero;
sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; 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++) { for (int i = 0; i < this->packetHistoryCurrent; i++) {
/* /*
DEBUG_MSG("SF historyQueueCreate\n"); LOG_DEBUG("SF historyQueueCreate\n");
DEBUG_MSG("SF historyQueueCreate - time %d\n", this->packetHistory[i].time); LOG_DEBUG("SF historyQueueCreate - time %d\n", this->packetHistory[i].time);
DEBUG_MSG("SF historyQueueCreate - millis %d\n", millis()); LOG_DEBUG("SF historyQueueCreate - millis %d\n", millis());
DEBUG_MSG("SF historyQueueCreate - math %d\n", (millis() - msAgo)); LOG_DEBUG("SF historyQueueCreate - math %d\n", (millis() - msAgo));
*/ */
if (this->packetHistory[i].time && (this->packetHistory[i].time < (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 Copy the messages that were received by the router in the last msAgo
to the packetHistoryTXQueue structure. to the packetHistoryTXQueue structure.
@@ -133,8 +133,8 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to)
Constants_DATA_PAYLOAD_LEN); Constants_DATA_PAYLOAD_LEN);
this->packetHistoryTXQueue_size++; this->packetHistoryTXQueue_size++;
DEBUG_MSG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time); LOG_DEBUG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time);
DEBUG_MSG("*** PacketHistoryStruct msg=%s\n", this->packetHistory[i].payload); 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) void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index)
{ {
DEBUG_MSG("*** Sending S&F Payload\n"); LOG_INFO("*** Sending S&F Payload\n");
MeshPacket *p = allocReply(); MeshPacket *p = allocReply();
p->to = dest; p->to = dest;
@@ -227,7 +227,7 @@ void StoreForwardModule::statsSend(uint32_t to)
sf.variant.stats.return_max = this->historyReturnMax; sf.variant.stats.return_max = this->historyReturnMax;
sf.variant.stats.return_window = this->historyReturnWindow; 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); storeForwardModule->sendMessage(to, sf);
} }
@@ -241,7 +241,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp)
if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) { if (mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) {
storeForwardModule->historyAdd(mp); storeForwardModule->historyAdd(mp);
DEBUG_MSG("*** 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) { } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) {
auto &p = mp.decoded; 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)) { if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &StoreAndForward_msg, &scratch)) {
decoded = &scratch; decoded = &scratch;
} else { } else {
DEBUG_MSG("Error decoding protobuf module!\n"); LOG_ERROR("Error decoding protobuf module!\n");
// if we can't decode it, nobody can process it! // if we can't decode it, nobody can process it!
return ProcessMessage::STOP; return ProcessMessage::STOP;
} }
@@ -281,7 +281,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo
if(is_server) { if(is_server) {
// stop sending stuff, the client wants to abort or has another error // stop sending stuff, the client wants to abort or has another error
if ((this->busy) && (this->busyTo == getFrom(&mp))) { if ((this->busy) && (this->busyTo == getFrom(&mp))) {
DEBUG_MSG("*** Client in ERROR or ABORT requested\n"); LOG_ERROR("*** Client in ERROR or ABORT requested\n");
this->packetHistoryTXQueue_index = 0; this->packetHistoryTXQueue_index = 0;
this->busy = false; this->busy = false;
} }
@@ -291,11 +291,11 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo
case StoreAndForward_RequestResponse_CLIENT_HISTORY: case StoreAndForward_RequestResponse_CLIENT_HISTORY:
if(is_server) { if(is_server) {
requests_history++; requests_history++;
DEBUG_MSG("*** Client Request to send HISTORY\n"); LOG_INFO("*** Client Request to send HISTORY\n");
// Send the last 60 minutes of messages. // Send the last 60 minutes of messages.
if (this->busy) { if (this->busy) {
storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY);
DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); LOG_INFO("*** S&F - Busy. Try again shortly.\n");
} else { } else {
if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)){ 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 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: case StoreAndForward_RequestResponse_CLIENT_PING:
if(is_server) { if(is_server) {
DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PING\n");
// respond with a ROUTER PONG // respond with a ROUTER PONG
storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_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: case StoreAndForward_RequestResponse_CLIENT_PONG:
if(is_server) { if(is_server) {
DEBUG_MSG("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PONG\n");
// The Client is alive, update NodeDB // The Client is alive, update NodeDB
nodeDB.updateFrom(mp); nodeDB.updateFrom(mp);
} }
@@ -324,10 +324,10 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo
case StoreAndForward_RequestResponse_CLIENT_STATS: case StoreAndForward_RequestResponse_CLIENT_STATS:
if(is_server) { if(is_server) {
DEBUG_MSG("*** Client Request to send STATS\n"); LOG_INFO("*** Client Request to send STATS\n");
if (this->busy) { if (this->busy) {
storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY);
DEBUG_MSG("*** S&F - Busy. Try again shortly.\n"); LOG_INFO("*** S&F - Busy. Try again shortly.\n");
} else { } else {
storeForwardModule->statsSend(getFrom(&mp)); storeForwardModule->statsSend(getFrom(&mp));
} }
@@ -337,7 +337,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo
case StoreAndForward_RequestResponse_ROUTER_ERROR: case StoreAndForward_RequestResponse_ROUTER_ERROR:
case StoreAndForward_RequestResponse_ROUTER_BUSY: case StoreAndForward_RequestResponse_ROUTER_BUSY:
if(is_client) { if(is_client) {
DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n");
// retry in messages_saved * packetTimeMax ms // 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);
} }
@@ -352,13 +352,13 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo
heartbeatInterval = p->variant.heartbeat.period; heartbeatInterval = p->variant.heartbeat.period;
} }
lastHeartbeat = millis(); lastHeartbeat = millis();
DEBUG_MSG("*** StoreAndForward Heartbeat received\n"); LOG_INFO("*** StoreAndForward Heartbeat received\n");
} }
break; break;
case StoreAndForward_RequestResponse_ROUTER_PING: case StoreAndForward_RequestResponse_ROUTER_PING:
if(is_client) { if(is_client) {
DEBUG_MSG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_PING\n");
// respond with a CLIENT PONG // respond with a CLIENT PONG
storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_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: case StoreAndForward_RequestResponse_ROUTER_STATS:
if(is_client) { 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. // These fields only have informational purpose on a client. Fill them to consume later.
if (p->which_variant == StoreAndForward_stats_tag) { if (p->which_variant == StoreAndForward_stats_tag) {
this->packetHistoryMax = p->variant.stats.messages_total; 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. // These fields only have informational purpose on a client. Fill them to consume later.
if (p->which_variant == StoreAndForward_history_tag) { if (p->which_variant == StoreAndForward_history_tag) {
this->historyReturnWindow = p->variant.history.window / 60000; 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_INFO("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow);
} }
} }
break; break;
@@ -418,7 +418,7 @@ StoreForwardModule::StoreForwardModule()
// Router // Router
if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { 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_INFO("*** Initializing Store & Forward Module in Router mode\n");
if (ESP.getPsramSize() > 0) { if (ESP.getPsramSize() > 0) {
if (ESP.getFreePsram() >= 1024 * 1024) { if (ESP.getFreePsram() >= 1024 * 1024) {
@@ -444,19 +444,19 @@ StoreForwardModule::StoreForwardModule()
this->populatePSRAM(); this->populatePSRAM();
is_server = true; is_server = true;
} else { } else {
DEBUG_MSG("*** Device has less than 1M of PSRAM free.\n"); LOG_INFO("*** Device has less than 1M of PSRAM free.\n");
DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); LOG_INFO("*** Store & Forward Module - disabling server.\n");
} }
} else { } else {
DEBUG_MSG("*** Device doesn't have PSRAM.\n"); LOG_INFO("*** Device doesn't have PSRAM.\n");
DEBUG_MSG("*** Store & Forward Module - disabling server.\n"); LOG_INFO("*** Store & Forward Module - disabling server.\n");
} }
// Client // Client
} }
if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) {
is_client = true; is_client = true;
DEBUG_MSG("*** Initializing Store & Forward Module in Client mode\n"); LOG_INFO("*** Initializing Store & Forward Module in Client mode\n");
} }
} }
#endif #endif

View File

@@ -42,7 +42,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length)
payloadStr[length] = 0; // null terminated string payloadStr[length] = 0; // null terminated string
JSONValue *json_value = JSON::Parse(payloadStr); JSONValue *json_value = JSON::Parse(payloadStr);
if (json_value != NULL) { if (json_value != NULL) {
DEBUG_MSG("JSON Received on MQTT, parsing..\n"); LOG_INFO("JSON Received on MQTT, parsing..\n");
// check if it is a valid envelope // check if it is a valid envelope
JSONObject json; JSONObject json;
json = json_value->AsObject(); json = json_value->AsObject();
@@ -50,7 +50,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length)
// this is a valid envelope // this is a valid envelope
if (json["payload"]->IsString() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) { if (json["payload"]->IsString() && json["type"]->IsString() && (json["sender"]->AsString().compare(owner.id) != 0)) {
std::string jsonPayloadStr = json["payload"]->AsString(); std::string jsonPayloadStr = json["payload"]->AsString();
DEBUG_MSG("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 // construct protobuf data packet using TEXT_MESSAGE, send it to the mesh
MeshPacket *p = router->allocForSending(); MeshPacket *p = router->allocForSending();
@@ -61,10 +61,10 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length)
MeshPacket *packet = packetPool.allocCopy(*p); MeshPacket *packet = packetPool.allocCopy(*p);
service.sendToMesh(packet, RX_SRC_LOCAL); service.sendToMesh(packet, RX_SRC_LOCAL);
} else { } else {
DEBUG_MSG("Received MQTT json payload too long, dropping\n"); LOG_WARN("Received MQTT json payload too long, dropping\n");
} }
} else { } 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)) { } 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 //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); service.sendToMesh(p, RX_SRC_LOCAL);
} else { } else {
DEBUG_MSG("JSON Ignoring downlink message we originally sent.\n"); LOG_DEBUG("JSON Ignoring downlink message we originally sent.\n");
} }
} else{ } else{
DEBUG_MSG("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 { } else {
// no json, this is an invalid payload // no json, this is an invalid payload
DEBUG_MSG("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; delete json_value;
} else { } else {
if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) { if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) {
DEBUG_MSG("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; return;
}else { }else {
if (strcmp(e.gateway_id, owner.id) == 0) if (strcmp(e.gateway_id, owner.id) == 0)
DEBUG_MSG("Ignoring downlink message we originally sent.\n"); LOG_INFO("Ignoring downlink message we originally sent.\n");
else { else {
if (e.packet) { if (e.packet) {
DEBUG_MSG("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); MeshPacket *p = packetPool.allocCopy(*e.packet);
// ignore messages sent by us or if we don't have the channel key // 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); pubSub.setServer(serverAddr, serverPort);
DEBUG_MSG("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); auto myStatus = (statusTopic + owner.id);
bool connected = pubSub.connect(owner.id, mqttUsername, mqttPassword, myStatus.c_str(), 1, true, "offline"); bool connected = pubSub.connect(owner.id, mqttUsername, mqttPassword, myStatus.c_str(), 1, true, "offline");
if (connected) { if (connected) {
DEBUG_MSG("MQTT connected\n"); LOG_INFO("MQTT connected\n");
enabled = true; // Start running background process again enabled = true; // Start running background process again
runASAP = true; runASAP = true;
reconnectCount = 0; reconnectCount = 0;
/// FIXME, include more information in the status text /// FIXME, include more information in the status text
bool ok = pubSub.publish(myStatus.c_str(), "online", true); bool ok = pubSub.publish(myStatus.c_str(), "online", true);
DEBUG_MSG("published %d\n", ok); LOG_INFO("published %d\n", ok);
sendSubscriptions(); sendSubscriptions();
} else { } else {
DEBUG_MSG("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 HAS_WIFI && !defined(ARCH_PORTDUINO)
if (reconnectCount > 9) { if (reconnectCount > 9) {
needReconnect = true; needReconnect = true;
@@ -200,11 +200,11 @@ void MQTT::sendSubscriptions()
auto &ch = channels.getByIndex(i); auto &ch = channels.getByIndex(i);
if (ch.settings.downlink_enabled) { if (ch.settings.downlink_enabled) {
String topic = cryptTopic + channels.getGlobalId(i) + "/#"; String topic = cryptTopic + channels.getGlobalId(i) + "/#";
DEBUG_MSG("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? pubSub.subscribe(topic.c_str(), 1); // FIXME, is QOS 1 right?
if (moduleConfig.mqtt.json_enabled == true) { if (moduleConfig.mqtt.json_enabled == true) {
String topicDecoded = jsonTopic + channels.getGlobalId(i) + "/#"; String topicDecoded = jsonTopic + channels.getGlobalId(i) + "/#";
DEBUG_MSG("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? 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); size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env);
String topic = cryptTopic + env->channel_id + "/" + owner.id; String topic = cryptTopic + env->channel_id + "/" + owner.id;
DEBUG_MSG("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); pubSub.publish(topic.c_str(), bytes, numBytes, false);
@@ -264,7 +264,7 @@ int32_t MQTT::runOnce()
auto jsonString = this->downstreamPacketToJson(env->packet); auto jsonString = this->downstreamPacketToJson(env->packet);
if (jsonString.length() != 0) { if (jsonString.length() != 0) {
String topicJson = jsonTopic + env->channel_id + "/" + owner.id; 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_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); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false);
} }
} }
@@ -279,7 +279,7 @@ int32_t MQTT::runOnce()
} else { } else {
// we are connected to server, check often for new requests on the TCP port // we are connected to server, check often for new requests on the TCP port
if (!wantConnection) { if (!wantConnection) {
DEBUG_MSG("MQTT link not needed, dropping\n"); LOG_INFO("MQTT link not needed, dropping\n");
pubSub.disconnect(); 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); size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env);
String topic = cryptTopic + channelId + "/" + owner.id; 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); 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); auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp);
if (jsonString.length() != 0) { if (jsonString.length() != 0) {
String topicJson = jsonTopic + channelId + "/" + owner.id; 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_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); pubSub.publish(topicJson.c_str(), jsonString.c_str(), false);
} }
} }
} else { } else {
DEBUG_MSG("MQTT not connected, queueing packet\n"); LOG_INFO("MQTT not connected, queueing packet\n");
if (mqttQueue.numFree() == 0) { if (mqttQueue.numFree() == 0) {
DEBUG_MSG("NOTE: MQTT queue is full, discarding oldest\n"); LOG_WARN("NOTE: MQTT queue is full, discarding oldest\n");
ServiceEnvelope *d = mqttQueue.dequeuePtr(0); ServiceEnvelope *d = mqttQueue.dequeuePtr(0);
if (d) if (d)
mqttPool.release(d); mqttPool.release(d);
@@ -350,20 +350,20 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
case PortNum_TEXT_MESSAGE_APP: { case PortNum_TEXT_MESSAGE_APP: {
msgType = "text"; msgType = "text";
// convert bytes to string // 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]; char payloadStr[(mp->decoded.payload.size) + 1];
memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size); memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size);
payloadStr[mp->decoded.payload.size] = 0; // null terminated string payloadStr[mp->decoded.payload.size] = 0; // null terminated string
// check if this is a JSON payload // check if this is a JSON payload
JSONValue *json_value = JSON::Parse(payloadStr); JSONValue *json_value = JSON::Parse(payloadStr);
if (json_value != NULL) { if (json_value != NULL) {
DEBUG_MSG("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 // if it is, then we can just use the json object
jsonObj["payload"] = json_value; jsonObj["payload"] = json_value;
} else { } else {
// if it isn't, then we need to create a json object // if it isn't, then we need to create a json object
// with the string as the value // with the string as the value
DEBUG_MSG("text message payload is of type plaintext\n"); LOG_INFO("text message payload is of type plaintext\n");
msgPayload["text"] = new JSONValue(payloadStr); msgPayload["text"] = new JSONValue(payloadStr);
jsonObj["payload"] = new JSONValue(msgPayload); jsonObj["payload"] = new JSONValue(msgPayload);
} }
@@ -392,7 +392,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
} }
jsonObj["payload"] = new JSONValue(msgPayload); jsonObj["payload"] = new JSONValue(msgPayload);
} else } else
DEBUG_MSG("Error decoding protobuf for telemetry message!\n"); LOG_ERROR("Error decoding protobuf for telemetry message!\n");
}; };
break; break;
} }
@@ -410,7 +410,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
msgPayload["hardware"] = new JSONValue(decoded->hw_model); msgPayload["hardware"] = new JSONValue(decoded->hw_model);
jsonObj["payload"] = new JSONValue(msgPayload); jsonObj["payload"] = new JSONValue(msgPayload);
} else } else
DEBUG_MSG("Error decoding protobuf for nodeinfo message!\n"); LOG_ERROR("Error decoding protobuf for nodeinfo message!\n");
}; };
break; break;
} }
@@ -429,7 +429,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
if((int)decoded->altitude){msgPayload["altitude"] = new JSONValue((int)decoded->altitude);} if((int)decoded->altitude){msgPayload["altitude"] = new JSONValue((int)decoded->altitude);}
jsonObj["payload"] = new JSONValue(msgPayload); jsonObj["payload"] = new JSONValue(msgPayload);
} else { } else {
DEBUG_MSG("Error decoding protobuf for position message!\n"); LOG_ERROR("Error decoding protobuf for position message!\n");
} }
}; };
break; break;
@@ -452,7 +452,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
msgPayload["longitude_i"] = new JSONValue((int)decoded->longitude_i); msgPayload["longitude_i"] = new JSONValue((int)decoded->longitude_i);
jsonObj["payload"] = new JSONValue(msgPayload); jsonObj["payload"] = new JSONValue(msgPayload);
} else { } else {
DEBUG_MSG("Error decoding protobuf for position message!\n"); LOG_ERROR("Error decoding protobuf for position message!\n");
} }
}; };
break; break;
@@ -474,7 +474,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp)
JSONValue *value = new JSONValue(jsonObj); JSONValue *value = new JSONValue(jsonObj);
std::string jsonStr = value->Stringify(); std::string jsonStr = value->Stringify();
DEBUG_MSG("serialized json message: %s\n", jsonStr.c_str()); LOG_INFO("serialized json message: %s\n", jsonStr.c_str());
delete value; delete value;
return jsonStr; return jsonStr;

View File

@@ -22,7 +22,7 @@ class BluetoothPhoneAPI : public PhoneAPI
{ {
PhoneAPI::onNowHasData(fromRadioNum); PhoneAPI::onNowHasData(fromRadioNum);
DEBUG_MSG("BLE notify fromNum\n"); LOG_INFO("BLE notify fromNum\n");
uint8_t val[4]; uint8_t val[4];
put_le32(val, fromRadioNum); put_le32(val, fromRadioNum);
@@ -46,7 +46,7 @@ static BluetoothPhoneAPI *bluetoothPhoneAPI;
class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks
{ {
virtual void onWrite(NimBLECharacteristic *pCharacteristic) { virtual void onWrite(NimBLECharacteristic *pCharacteristic) {
DEBUG_MSG("To Radio onwrite\n"); LOG_INFO("To Radio onwrite\n");
auto val = pCharacteristic->getValue(); auto val = pCharacteristic->getValue();
bluetoothPhoneAPI->handleToRadio(val.data(), val.length()); bluetoothPhoneAPI->handleToRadio(val.data(), val.length());
@@ -56,7 +56,7 @@ class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks
class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks
{ {
virtual void onRead(NimBLECharacteristic *pCharacteristic) { virtual void onRead(NimBLECharacteristic *pCharacteristic) {
DEBUG_MSG("From Radio onread\n"); LOG_INFO("From Radio onread\n");
uint8_t fromRadioBytes[FromRadio_size]; uint8_t fromRadioBytes[FromRadio_size];
size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes); size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes);
@@ -72,11 +72,11 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks
uint32_t passkey = config.bluetooth.fixed_pin; uint32_t passkey = config.bluetooth.fixed_pin;
if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_RANDOM_PIN) { if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_RANDOM_PIN) {
DEBUG_MSG("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 // This is the passkey to be entered on peer - we pick a number >100,000 to ensure 6 digits
passkey = random(100000, 999999); passkey = random(100000, 999999);
} }
DEBUG_MSG("*** 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); powerFSM.trigger(EVENT_BLUETOOTH_PAIR);
screen->startBluetoothPinScreen(passkey); screen->startBluetoothPinScreen(passkey);
@@ -87,7 +87,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks
virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) virtual void onAuthenticationComplete(ble_gap_conn_desc *desc)
{ {
DEBUG_MSG("BLE authentication complete\n"); LOG_INFO("BLE authentication complete\n");
if (passkeyShowing) { if (passkeyShowing) {
passkeyShowing = false; passkeyShowing = false;
@@ -98,7 +98,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks
virtual void onDisconnect(NimBLEServer* pServer, ble_gap_conn_desc *desc) virtual void onDisconnect(NimBLEServer* pServer, ble_gap_conn_desc *desc)
{ {
DEBUG_MSG("BLE disconnect\n"); LOG_INFO("BLE disconnect\n");
} }
}; };
@@ -108,7 +108,7 @@ static NimbleBluetoothFromRadioCallback *fromRadioCallbacks;
void NimbleBluetooth::shutdown() void NimbleBluetooth::shutdown()
{ {
// Shutdown bluetooth for minimum power draw // Shutdown bluetooth for minimum power draw
DEBUG_MSG("Disable bluetooth\n"); LOG_INFO("Disable bluetooth\n");
//Bluefruit.Advertising.stop(); //Bluefruit.Advertising.stop();
NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising();
pAdvertising->reset(); pAdvertising->reset();
@@ -125,7 +125,7 @@ void NimbleBluetooth::setup()
// Uncomment for testing // Uncomment for testing
// NimbleBluetooth::clearBonds(); // NimbleBluetooth::clearBonds();
DEBUG_MSG("Initialise the NimBLE bluetooth module\n"); LOG_INFO("Initialise the NimBLE bluetooth module\n");
NimBLEDevice::init(getDeviceName()); NimBLEDevice::init(getDeviceName());
NimBLEDevice::setPower(ESP_PWR_LVL_P9); NimBLEDevice::setPower(ESP_PWR_LVL_P9);
@@ -186,7 +186,7 @@ void updateBatteryLevel(uint8_t level)
void NimbleBluetooth::clearBonds() void NimbleBluetooth::clearBonds()
{ {
DEBUG_MSG("Clearing bluetooth bonds!\n"); LOG_INFO("Clearing bluetooth bonds!\n");
NimBLEDevice::deleteAllBonds(); NimBLEDevice::deleteAllBonds();
} }

View File

@@ -46,7 +46,7 @@ class ESP32CryptoEngine : public CryptoEngine
static uint8_t scratch[MAX_BLOCKSIZE]; static uint8_t scratch[MAX_BLOCKSIZE];
size_t nc_off = 0; 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); initNonce(fromNode, packetId);
assert(numBytes <= MAX_BLOCKSIZE); assert(numBytes <= MAX_BLOCKSIZE);
memcpy(scratch, bytes, numBytes); memcpy(scratch, bytes, numBytes);

View File

@@ -1,6 +1,6 @@
#include "SimpleAllocator.h"
#include "assert.h" #include "assert.h"
#include "configuration.h"
#include "SimpleAllocator.h"
SimpleAllocator::SimpleAllocator() { reset(); } SimpleAllocator::SimpleAllocator() { reset(); }
@@ -9,7 +9,7 @@ void *SimpleAllocator::alloc(size_t size)
assert(nextFree + size <= sizeof(bytes)); assert(nextFree + size <= sizeof(bytes));
void *res = &bytes[nextFree]; void *res = &bytes[nextFree];
nextFree += size; nextFree += size;
Serial.printf("Total simple allocs %u\n", nextFree); LOG_DEBUG("Total simple allocs %u\n", nextFree);
return res; return res;
} }
@@ -52,7 +52,7 @@ void *operator new(size_t sz) throw(std::bad_alloc)
void operator delete(void *ptr) throw() void operator delete(void *ptr) throw()
{ {
if (activeAllocator) 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 else
free(ptr); free(ptr);
} }

View File

@@ -66,17 +66,17 @@ void enableSlowCLK()
uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL); uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL);
if (cal_32k == 0) { 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 { } else {
rtc_clk_slow_freq_set(RTC_SLOW_FREQ_32K_XTAL); 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_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_32K_XTAL); CALIBRATE_ONE(RTC_CAL_32K_XTAL);
} }
CALIBRATE_ONE(RTC_CAL_RTC_MUX); CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_32K_XTAL); CALIBRATE_ONE(RTC_CAL_32K_XTAL);
if (rtc_clk_slow_freq_get() != RTC_SLOW_FREQ_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 #endif
@@ -85,21 +85,21 @@ void enableSlowCLK()
void esp32Setup() void esp32Setup()
{ {
uint32_t seed = esp_random(); 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 randomSeed(seed); // ESP docs say this is fairly random
DEBUG_MSG("Total heap: %d\n", ESP.getHeapSize()); LOG_DEBUG("Total heap: %d\n", ESP.getHeapSize());
DEBUG_MSG("Free heap: %d\n", ESP.getFreeHeap()); LOG_DEBUG("Free heap: %d\n", ESP.getFreeHeap());
DEBUG_MSG("Total PSRAM: %d\n", ESP.getPsramSize()); LOG_DEBUG("Total PSRAM: %d\n", ESP.getPsramSize());
DEBUG_MSG("Free PSRAM: %d\n", ESP.getFreePsram()); LOG_DEBUG("Free PSRAM: %d\n", ESP.getFreePsram());
nvs_stats_t nvs_stats; nvs_stats_t nvs_stats;
auto res = nvs_get_stats(NULL, &nvs_stats); auto res = nvs_get_stats(NULL, &nvs_stats);
assert(res == ESP_OK); 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); 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 // Create object to store our persistant data
Preferences preferences; Preferences preferences;
@@ -109,12 +109,12 @@ void esp32Setup()
rebootCounter++; rebootCounter++;
preferences.putUInt("rebootCounter", rebootCounter); preferences.putUInt("rebootCounter", rebootCounter);
preferences.end(); preferences.end();
DEBUG_MSG("Number of Device Reboots: %d\n", rebootCounter); LOG_DEBUG("Number of Device Reboots: %d\n", rebootCounter);
String BLEOTA=BleOta::getOtaAppVersion(); String BLEOTA=BleOta::getOtaAppVersion();
if (BLEOTA.isEmpty()) { if (BLEOTA.isEmpty()) {
DEBUG_MSG("No OTA firmware available\n"); LOG_DEBUG("No OTA firmware available\n");
}else{ }else{
DEBUG_MSG("OTA firmware version %s\n", BLEOTA.c_str()); LOG_DEBUG("OTA firmware version %s\n", BLEOTA.c_str());
} }
// enableModemSleep(); // enableModemSleep();
@@ -141,13 +141,13 @@ void esp32Setup()
uint32_t axpDebugRead() uint32_t axpDebugRead()
{ {
axp.debugCharging(); axp.debugCharging();
DEBUG_MSG("vbus current %f\n", axp.getVbusCurrent()); LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent());
DEBUG_MSG("charge current %f\n", axp.getBattChargeCurrent()); LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent());
DEBUG_MSG("bat voltage %f\n", axp.getBattVoltage()); LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage());
DEBUG_MSG("batt pct %d\n", axp.getBattPercentage()); LOG_DEBUG("batt pct %d\n", axp.getBattPercentage());
DEBUG_MSG("is battery connected %d\n", axp.isBatteryConnect()); LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect());
DEBUG_MSG("is USB connected %d\n", axp.isVBUSPlug()); LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug());
DEBUG_MSG("is charging %d\n", axp.isChargeing()); LOG_DEBUG("is charging %d\n", axp.isChargeing());
return 30 * 1000; return 30 * 1000;
} }

View File

@@ -33,7 +33,7 @@ class BluetoothPhoneAPI : public PhoneAPI
{ {
PhoneAPI::onNowHasData(fromRadioNum); PhoneAPI::onNowHasData(fromRadioNum);
DEBUG_MSG("BLE notify fromNum\n"); LOG_INFO("BLE notify fromNum\n");
fromNum.notify32(fromRadioNum); fromNum.notify32(fromRadioNum);
} }
@@ -55,7 +55,7 @@ void onConnect(uint16_t conn_handle)
char central_name[32] = {0}; char central_name[32] = {0};
connection->getPeerName(central_name, sizeof(central_name)); connection->getPeerName(central_name, sizeof(central_name));
DEBUG_MSG("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) void onDisconnect(uint16_t conn_handle, uint8_t reason)
{ {
// FIXME - we currently assume only one active connection // FIXME - we currently assume only one active connection
DEBUG_MSG("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) void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value)
{ {
// Display the raw request packet // Display the raw request packet
DEBUG_MSG("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 // Check the characteristic this CCCD update is associated with in case
// this handler is used for multiple CCCD records. // this handler is used for multiple CCCD records.
if (chr->uuid == fromNum.uuid) { if (chr->uuid == fromNum.uuid) {
if (chr->notifyEnabled(conn_hdl)) { if (chr->notifyEnabled(conn_hdl)) {
DEBUG_MSG("fromNum 'Notify' enabled\n"); LOG_INFO("fromNum 'Notify' enabled\n");
} else { } else {
DEBUG_MSG("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 // or make empty if the queue is empty
fromRadio.write(fromRadioBytes, numBytes); fromRadio.write(fromRadioBytes, numBytes);
} else { } else {
// DEBUG_MSG("Ignoring successor read\n"); // LOG_INFO("Ignoring successor read\n");
} }
authorizeRead(conn_hdl); authorizeRead(conn_hdl);
} }
void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, uint16_t len) 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_INFO("toRadioWriteCb data %p, len %u\n", data, len);
bluetoothPhoneAPI->handleToRadio(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) void onFromNumAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_evt_read_t *request)
{ {
DEBUG_MSG("fromNumAuthorizeCb\n"); LOG_INFO("fromNumAuthorizeCb\n");
authorizeRead(conn_hdl); authorizeRead(conn_hdl);
} }
@@ -204,14 +204,14 @@ static uint32_t configuredPasskey;
void NRF52Bluetooth::shutdown() void NRF52Bluetooth::shutdown()
{ {
// Shutdown bluetooth for minimum power draw // Shutdown bluetooth for minimum power draw
DEBUG_MSG("Disable NRF52 bluetooth\n"); LOG_INFO("Disable NRF52 bluetooth\n");
Bluefruit.Advertising.stop(); Bluefruit.Advertising.stop();
} }
void NRF52Bluetooth::setup() void NRF52Bluetooth::setup()
{ {
// Initialise the Bluefruit module // Initialise the Bluefruit module
DEBUG_MSG("Initialize the Bluefruit nRF52 module\n"); LOG_INFO("Initialize the Bluefruit nRF52 module\n");
Bluefruit.autoConnLed(false); Bluefruit.autoConnLed(false);
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin(); Bluefruit.begin();
@@ -225,7 +225,7 @@ void NRF52Bluetooth::setup()
configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ? configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ?
config.bluetooth.fixed_pin : random(100000, 999999); config.bluetooth.fixed_pin : random(100000, 999999);
auto pinString = std::to_string(configuredPasskey); auto pinString = std::to_string(configuredPasskey);
DEBUG_MSG("Bluetooth pin set to '%i'\n", configuredPasskey); LOG_INFO("Bluetooth pin set to '%i'\n", configuredPasskey);
Bluefruit.Security.setPIN(pinString.c_str()); Bluefruit.Security.setPIN(pinString.c_str());
Bluefruit.Security.setIOCaps(true, false, false); Bluefruit.Security.setIOCaps(true, false, false);
Bluefruit.Security.setPairPasskeyCallback(NRF52Bluetooth::onPairingPasskey); Bluefruit.Security.setPairPasskeyCallback(NRF52Bluetooth::onPairingPasskey);
@@ -248,30 +248,30 @@ void NRF52Bluetooth::setup()
bledfu.begin(); // Install the DFU helper bledfu.begin(); // Install the DFU helper
// Configure and Start the Device Information Service // Configure and Start the Device Information Service
DEBUG_MSG("Configuring the Device Information Service\n"); LOG_INFO("Configuring the Device Information Service\n");
bledis.setModel(optstr(HW_VERSION)); bledis.setModel(optstr(HW_VERSION));
bledis.setFirmwareRev(optstr(APP_VERSION)); bledis.setFirmwareRev(optstr(APP_VERSION));
bledis.begin(); bledis.begin();
// Start the BLE Battery Service and set it to 100% // Start the BLE Battery Service and set it to 100%
DEBUG_MSG("Configuring the Battery Service\n"); LOG_INFO("Configuring the Battery Service\n");
blebas.begin(); blebas.begin();
blebas.write(0); // Unknown battery level for now blebas.write(0); // Unknown battery level for now
// Setup the Heart Rate Monitor service using // Setup the Heart Rate Monitor service using
// BLEService and BLECharacteristic classes // BLEService and BLECharacteristic classes
DEBUG_MSG("Configuring the Mesh bluetooth service\n"); LOG_INFO("Configuring the Mesh bluetooth service\n");
setupMeshService(); setupMeshService();
// Supposedly debugging works with soft device if you disable advertising // Supposedly debugging works with soft device if you disable advertising
if (isSoftDeviceAllowed) if (isSoftDeviceAllowed)
{ {
// Setup the advertising packet(s) // Setup the advertising packet(s)
DEBUG_MSG("Setting up the advertising payload(s)\n"); LOG_INFO("Setting up the advertising payload(s)\n");
startAdv(); startAdv();
DEBUG_MSG("Advertising\n"); LOG_INFO("Advertising\n");
} }
} }
@@ -283,7 +283,7 @@ void updateBatteryLevel(uint8_t level)
void NRF52Bluetooth::clearBonds() void NRF52Bluetooth::clearBonds()
{ {
DEBUG_MSG("Clearing bluetooth bonds!\n"); LOG_INFO("Clearing bluetooth bonds!\n");
bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_PERIPH);
bond_print_list(BLE_GAP_ROLE_CENTRAL); bond_print_list(BLE_GAP_ROLE_CENTRAL);
@@ -293,12 +293,12 @@ void NRF52Bluetooth::clearBonds()
void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle) void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle)
{ {
DEBUG_MSG("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) 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_INFO("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3);
screen->startBluetoothPinScreen(configuredPasskey); screen->startBluetoothPinScreen(configuredPasskey);
if (match_request) if (match_request)
@@ -309,16 +309,16 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke
if (!Bluefruit.connected(conn_handle)) break; if (!Bluefruit.connected(conn_handle)) break;
} }
} }
DEBUG_MSG("BLE passkey pairing: match_request=%i\n", match_request); LOG_INFO("BLE passkey pairing: match_request=%i\n", match_request);
return true; return true;
} }
void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_status) void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_status)
{ {
if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS) if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS)
DEBUG_MSG("BLE pairing success\n"); LOG_INFO("BLE pairing success\n");
else else
DEBUG_MSG("BLE pairing failed\n"); LOG_INFO("BLE pairing failed\n");
screen->stopBluetoothPinScreen(); screen->stopBluetoothPinScreen();
} }

View File

@@ -17,13 +17,13 @@ class NRF52CryptoEngine : public CryptoEngine
virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) override virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) override
{ {
if (key.length > 16) { 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; AES_ctx ctx;
initNonce(fromNode, packetId); initNonce(fromNode, packetId);
AES_init_ctx_iv(&ctx, key.bytes, nonce); AES_init_ctx_iv(&ctx, key.bytes, nonce);
AES_CTR_xcrypt_buffer(&ctx, bytes, numBytes); AES_CTR_xcrypt_buffer(&ctx, bytes, numBytes);
} else if (key.length > 0) { } 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.begin();
nRFCrypto_AES ctx; nRFCrypto_AES ctx;
uint8_t myLen = ctx.blockLen(numBytes); uint8_t myLen = ctx.blockLen(numBytes);

View File

@@ -5,7 +5,7 @@
enum { r0, r1, r2, r3, r12, lr, pc, psr }; 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 // segger in memory tool
#define FAULT_MSG(...) SEGGER_MSG(__VA_ARGS__) #define FAULT_MSG(...) SEGGER_MSG(__VA_ARGS__)

View File

@@ -32,7 +32,7 @@ bool loopCanSleep() {
// handle standard gcc assert failures // handle standard gcc assert failures
void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *failedexpr) 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_ERROR("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr);
// debugger_break(); FIXME doesn't work, possibly not for segger // debugger_break(); FIXME doesn't work, possibly not for segger
// Reboot cpu // Reboot cpu
NVIC_SystemReset(); NVIC_SystemReset();
@@ -73,7 +73,7 @@ void setBluetoothEnable(bool on)
if (on) { if (on) {
if (!nrf52Bluetooth) { if (!nrf52Bluetooth) {
if (!useSoftDevice) if (!useSoftDevice)
DEBUG_MSG("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); LOG_INFO("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n");
else { else {
nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth = new NRF52Bluetooth();
nrf52Bluetooth->setup(); nrf52Bluetooth->setup();
@@ -112,7 +112,7 @@ void checkSDEvents()
break; break;
default: default:
DEBUG_MSG("Unexpected SDevt %d\n", evt); LOG_DEBUG("Unexpected SDevt %d\n", evt);
break; break;
} }
} }
@@ -132,7 +132,7 @@ void nrf52Setup()
auto why = NRF_POWER->RESETREAS; auto why = NRF_POWER->RESETREAS;
// per // per
// https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.nrf52832.ps.v1.1%2Fpower.html // 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 // Per
// https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/monitor-mode-debugging-with-j-link-and-gdbeclipse // 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 #ifdef BQ25703A_ADDR
auto *bq = new BQ25713(); auto *bq = new BQ25713();
if (!bq->setup()) if (!bq->setup())
DEBUG_MSG("ERROR! Charge controller init failed\n"); LOG_ERROR("ERROR! Charge controller init failed\n");
#endif #endif
// Init random seed // Init random seed
@@ -152,7 +152,7 @@ void nrf52Setup()
} seed; } seed;
nRFCrypto.begin(); nRFCrypto.begin();
nRFCrypto.Random.generate(seed.seed8, sizeof(seed.seed8)); 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); randomSeed(seed.seed32);
nRFCrypto.end(); nRFCrypto.end();
} }
@@ -178,15 +178,14 @@ void cpuDeepSleep(uint64_t msecToWake)
auto ok = sd_power_system_off(); auto ok = sd_power_system_off();
if (ok != NRF_SUCCESS) { if (ok != NRF_SUCCESS) {
DEBUG_MSG("FIXME: Ignoring soft device (EasyDMA pending?) and forcing " LOG_ERROR("FIXME: Ignoring soft device (EasyDMA pending?) and forcing system-off!\n");
"system-off!\n");
NRF_POWER->SYSTEMOFF = 1; NRF_POWER->SYSTEMOFF = 1;
} }
// The following code should not be run, because we are off // The following code should not be run, because we are off
while (1) { while (1) {
delay(5000); delay(5000);
DEBUG_MSG("."); LOG_DEBUG(".");
} }
} }

View File

@@ -27,7 +27,7 @@ class CrossPlatformCryptoEngine : public CryptoEngine
virtual void setKey(const CryptoKey &k) override virtual void setKey(const CryptoKey &k) override
{ {
CryptoEngine::setKey(k); 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) { if (ctr) {
delete ctr; delete ctr;
ctr = NULL; ctr = NULL;
@@ -54,7 +54,7 @@ class CrossPlatformCryptoEngine : public CryptoEngine
static uint8_t scratch[MAX_BLOCKSIZE]; static uint8_t scratch[MAX_BLOCKSIZE];
//size_t nc_off = 0; //size_t nc_off = 0;
// DEBUG_MSG("ESP32 encrypt!\n"); // LOG_DEBUG("ESP32 encrypt!\n");
initNonce(fromNode, packetId); initNonce(fromNode, packetId);
assert(numBytes <= MAX_BLOCKSIZE); assert(numBytes <= MAX_BLOCKSIZE);
memcpy(scratch, bytes, numBytes); memcpy(scratch, bytes, numBytes);

View File

@@ -22,7 +22,7 @@ ErrorCode SimRadio::send(MeshPacket *p)
// set (random) transmit delay to let others reconfigure their radio, // set (random) transmit delay to let others reconfigure their radio,
// to avoid collisions and implement timing-based flooding // 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(); setTransmitDelay();
return res; return res;
} }
@@ -42,7 +42,7 @@ void SimRadio::setTransmitDelay()
startTransmitTimer(true); startTransmitTimer(true);
} else { } else {
// If there is a SNR, start a timer scaled based on that SNR. // 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); 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 we have work to do and the timer wasn't already scheduled, schedule it now
if (!txQueue.empty()) { if (!txQueue.empty()) {
uint32_t delayMsec = !withDelay ? 1 : getTxDelayMsec(); uint32_t delayMsec = !withDelay ? 1 : getTxDelayMsec();
// DEBUG_MSG("xmit timer %d\n", delay); // LOG_DEBUG("xmit timer %d\n", delay);
delay(delayMsec); delay(delayMsec);
onNotify(TRANSMIT_DELAY_COMPLETED); onNotify(TRANSMIT_DELAY_COMPLETED);
} else { } 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 we have work to do and the timer wasn't already scheduled, schedule it now
if (!txQueue.empty()) { if (!txQueue.empty()) {
uint32_t delayMsec = getTxDelayMsecWeighted(snr); uint32_t delayMsec = getTxDelayMsecWeighted(snr);
// DEBUG_MSG("xmit timer %d\n", delay); // LOG_DEBUG("xmit timer %d\n", delay);
delay(delayMsec); delay(delayMsec);
onNotify(TRANSMIT_DELAY_COMPLETED); onNotify(TRANSMIT_DELAY_COMPLETED);
} }
@@ -92,7 +92,7 @@ void SimRadio::completeSending()
// We are done sending that packet, release it // We are done sending that packet, release it
packetPool.release(p); 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 || busyRx) {
if (busyTx) if (busyTx)
DEBUG_MSG("Can not send yet, busyTx\n"); LOG_WARN("Can not send yet, busyTx\n");
if (busyRx) if (busyRx)
DEBUG_MSG("Can not send yet, busyRx\n"); LOG_WARN("Can not send yet, busyRx\n");
return false; return false;
} else } else
return true; return true;
@@ -134,7 +134,7 @@ bool SimRadio::cancelSending(NodeNum from, PacketId id)
packetPool.release(p); // free the packet we just removed packetPool.release(p); // free the packet we just removed
bool result = (p != NULL); 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; return result;
} }
@@ -144,24 +144,24 @@ void SimRadio::onNotify(uint32_t notification)
switch (notification) { switch (notification) {
case ISR_TX: case ISR_TX:
handleTransmitInterrupt(); handleTransmitInterrupt();
DEBUG_MSG("tx complete - starting timer\n"); LOG_DEBUG("tx complete - starting timer\n");
startTransmitTimer(); startTransmitTimer();
break; break;
case ISR_RX: case ISR_RX:
DEBUG_MSG("rx complete - starting timer\n"); LOG_DEBUG("rx complete - starting timer\n");
break; break;
case TRANSMIT_DELAY_COMPLETED: 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 // 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? // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode?
if (!txQueue.empty()) { if (!txQueue.empty()) {
if (!canSendImmediately()) { 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 setTransmitDelay(); // currently Rx/Tx-ing: reset random delay
} else { } else {
if (isChannelActive()) { // check if there is currently a LoRa packet on the channel 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 setTransmitDelay(); // reset random delay
} else { } else {
// Send any outgoing packets we have ready // Send any outgoing packets we have ready
@@ -177,7 +177,7 @@ void SimRadio::onNotify(uint32_t notification)
} }
} }
} else { } else {
// DEBUG_MSG("done with txqueue\n"); // LOG_DEBUG("done with txqueue\n");
} }
break; break;
default: default:
@@ -194,12 +194,12 @@ void SimRadio::startSend(MeshPacket * txp)
perhapsDecode(p); perhapsDecode(p);
Compressed c = Compressed_init_default; Compressed c = Compressed_init_default;
c.portnum = p->decoded.portnum; 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)) { if (p->decoded.payload.size <= sizeof(c.data.bytes)) {
memcpy(&c.data.bytes, p->decoded.payload.bytes, p->decoded.payload.size); memcpy(&c.data.bytes, p->decoded.payload.bytes, p->decoded.payload.size);
c.data.size = p->decoded.payload.size; c.data.size = p->decoded.payload.size;
} else { } else {
DEBUG_MSG("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.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Compressed_msg, &c);
p->decoded.portnum = PortNum_SIMULATOR_APP; p->decoded.portnum = PortNum_SIMULATOR_APP;
@@ -218,7 +218,7 @@ void SimRadio::startReceive(MeshPacket *p) {
void SimRadio::handleReceiveInterrupt(MeshPacket *p) void SimRadio::handleReceiveInterrupt(MeshPacket *p)
{ {
DEBUG_MSG("HANDLE RECEIVE INTERRUPT\n"); LOG_DEBUG("HANDLE RECEIVE INTERRUPT\n");
uint32_t xmitMsec; uint32_t xmitMsec;
assert(isReceiving); assert(isReceiving);
isReceiving = false; isReceiving = false;
@@ -226,7 +226,7 @@ void SimRadio::handleReceiveInterrupt(MeshPacket *p)
// read the number of actually received bytes // read the number of actually received bytes
size_t length = getPacketLength(p); size_t length = getPacketLength(p);
xmitMsec = getPacketTime(length); 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 MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packtPool
mp->which_payload_variant = MeshPacket_decoded_tag; // Mark that the payload is already decoded mp->which_payload_variant = MeshPacket_decoded_tag; // Mark that the payload is already decoded

View File

@@ -7,14 +7,14 @@
void powerCommandsCheck() void powerCommandsCheck()
{ {
if (rebootAtMsec && millis() > rebootAtMsec) { if (rebootAtMsec && millis() > rebootAtMsec) {
DEBUG_MSG("Rebooting\n"); LOG_INFO("Rebooting\n");
#if defined(ARCH_ESP32) #if defined(ARCH_ESP32)
ESP.restart(); ESP.restart();
#elif defined(ARCH_NRF52) #elif defined(ARCH_NRF52)
NVIC_SystemReset(); NVIC_SystemReset();
#else #else
rebootAtMsec = -1; rebootAtMsec = -1;
DEBUG_MSG("FIXME implement reboot for this platform. Skipping for now.\n"); LOG_WARN("FIXME implement reboot for this platform. Skipping for now.\n");
#endif #endif
} }
@@ -35,7 +35,7 @@ void powerCommandsCheck()
#endif #endif
if (shutdownAtMsec && millis() > shutdownAtMsec) { if (shutdownAtMsec && millis() > shutdownAtMsec) {
DEBUG_MSG("Shutting down from admin command\n"); LOG_INFO("Shutting down from admin command\n");
#ifdef HAS_PMU #ifdef HAS_PMU
if (pmu_found == true) { if (pmu_found == true) {
playShutdownMelody(); playShutdownMelody();
@@ -45,7 +45,7 @@ void powerCommandsCheck()
playShutdownMelody(); playShutdownMelody();
power->shutdown(); power->shutdown();
#else #else
DEBUG_MSG("FIXME implement shutdown for this platform"); LOG_WARN("FIXME implement shutdown for this platform");
#endif #endif
} }
} }

View File

@@ -60,7 +60,7 @@ void setCPUFast(bool on)
* all WiFi use cases. * all WiFi use cases.
* (Added: Dec 23, 2021 by Jm Casler) * (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); setCpuFrequencyMhz(240);
return; return;
} }
@@ -90,7 +90,7 @@ void setLed(bool ledOn)
void setGPSPower(bool on) void setGPSPower(bool on)
{ {
DEBUG_MSG("Setting GPS power=%d\n", on); LOG_INFO("Setting GPS power=%d\n", on);
#ifdef HAS_PMU #ifdef HAS_PMU
if (pmu_found && PMU){ if (pmu_found && PMU){
@@ -136,7 +136,7 @@ void initDeepSleep()
if (wakeCause == ESP_SLEEP_WAKEUP_TIMER) if (wakeCause == ESP_SLEEP_WAKEUP_TIMER)
reason = "timeout"; reason = "timeout";
DEBUG_MSG("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 #endif
} }
@@ -174,13 +174,13 @@ void doGPSpowersave(bool on)
#ifdef HAS_PMU #ifdef HAS_PMU
if (on) if (on)
{ {
DEBUG_MSG("Turning GPS back on\n"); LOG_INFO("Turning GPS back on\n");
gps->forceWake(1); gps->forceWake(1);
setGPSPower(1); setGPSPower(1);
} }
else else
{ {
DEBUG_MSG("Turning off GPS chip\n"); LOG_INFO("Turning off GPS chip\n");
notifyGPSSleep.notifyObservers(NULL); notifyGPSSleep.notifyObservers(NULL);
setGPSPower(0); setGPSPower(0);
} }
@@ -188,12 +188,12 @@ void doGPSpowersave(bool on)
#ifdef PIN_GPS_WAKE #ifdef PIN_GPS_WAKE
if (on) if (on)
{ {
DEBUG_MSG("Waking GPS"); LOG_INFO("Waking GPS");
gps->forceWake(1); gps->forceWake(1);
} }
else else
{ {
DEBUG_MSG("GPS entering sleep"); LOG_INFO("GPS entering sleep");
notifyGPSSleep.notifyObservers(NULL); notifyGPSSleep.notifyObservers(NULL);
} }
#endif #endif
@@ -201,7 +201,7 @@ void doGPSpowersave(bool on)
void doDeepSleep(uint64_t msecToWake) void doDeepSleep(uint64_t msecToWake)
{ {
DEBUG_MSG("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 // not using wifi yet, but once we are this is needed to shutoff the radio hw
// esp_wifi_stop(); // 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 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(); 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(); esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
#ifdef BUTTON_PIN #ifdef BUTTON_PIN
if (cause == ESP_SLEEP_WAKEUP_GPIO) if (cause == ESP_SLEEP_WAKEUP_GPIO)
DEBUG_MSG("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN)); LOG_INFO("Exit light sleep gpio: btn=%d\n", !digitalRead(BUTTON_PIN));
#endif #endif
return cause; return cause;
@@ -340,6 +340,6 @@ void enableModemSleep()
esp32_config.min_freq_mhz = 20; // 10Mhz is minimum recommended esp32_config.min_freq_mhz = 20; // 10Mhz is minimum recommended
esp32_config.light_sleep_enable = false; esp32_config.light_sleep_enable = false;
int rv = esp_pm_configure(&esp32_config); int rv = esp_pm_configure(&esp32_config);
DEBUG_MSG("Sleep request result %x\n", rv); LOG_DEBUG("Sleep request result %x\n", rv);
} }
#endif #endif