fix a lot of low level cppcheck warnings (#9623)

* simplify the observer pattern, since all the called functions are const getters.
* use arduino macro over std: for numerical values and refactor local variables in drawScrollbar()
* oh, so Cppcheck actually complained about const pointers not being const.
* slowly getting out of ifdef hell
* fix inkHUD warnings as well
* last 2 check warnings
* git checks should fail on low defects from now on
This commit is contained in:
Thomas Göttgens
2026-02-16 12:28:07 +01:00
committed by GitHub
parent 32db70037d
commit 56fd9c7813
56 changed files with 217 additions and 226 deletions
+1 -1
View File
@@ -95,7 +95,7 @@ jobs:
with: with:
pio_platform: ${{ matrix.check.platform }} pio_platform: ${{ matrix.check.platform }}
pio_env: ${{ matrix.check.board }} pio_env: ${{ matrix.check.board }}
pio_target: check pio_target: check --fail-on-defect=low
build: build:
needs: [setup, version] needs: [setup, version]
+5 -3
View File
@@ -704,11 +704,11 @@ bool Power::setup()
found = true; found = true;
} else if (analogInit()) { } else if (analogInit()) {
found = true; found = true;
} } else {
#ifdef NRF_APM #ifdef NRF_APM
found = true; found = true;
#endif #endif
}
#ifdef EXT_PWR_DETECT #ifdef EXT_PWR_DETECT
attachInterrupt( attachInterrupt(
EXT_PWR_DETECT, EXT_PWR_DETECT,
@@ -846,8 +846,10 @@ void Power::readPowerStatus()
if (batteryLevel) { if (batteryLevel) {
hasBattery = batteryLevel->isBatteryConnect() ? OptTrue : OptFalse; hasBattery = batteryLevel->isBatteryConnect() ? OptTrue : OptFalse;
#ifndef NRF_APM
usbPowered = batteryLevel->isVbusIn() ? OptTrue : OptFalse; usbPowered = batteryLevel->isVbusIn() ? OptTrue : OptFalse;
isChargingNow = batteryLevel->isCharging() ? OptTrue : OptFalse; isChargingNow = batteryLevel->isCharging() ? OptTrue : OptFalse;
#endif
if (hasBattery) { if (hasBattery) {
batteryVoltageMv = batteryLevel->getBattVoltage(); batteryVoltageMv = batteryLevel->getBattVoltage();
// If the AXP192 returns a valid battery percentage, use it // If the AXP192 returns a valid battery percentage, use it
+1 -1
View File
@@ -312,7 +312,7 @@ const char *RtcName(RTCQuality quality)
* @param t The time to potentially set the RTC to. * @param t The time to potentially set the RTC to.
* @return True if the RTC was set to the provided time, false otherwise. * @return True if the RTC was set to the provided time, false otherwise.
*/ */
RTCSetResult perhapsSetRTC(RTCQuality q, struct tm &t) RTCSetResult perhapsSetRTC(RTCQuality q, const struct tm &t)
{ {
/* Convert to unix time /* Convert to unix time
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
+1 -1
View File
@@ -41,7 +41,7 @@ extern uint32_t lastSetFromPhoneNtpOrGps;
/// If we haven't yet set our RTC this boot, set it from a GPS derived time /// If we haven't yet set our RTC this boot, set it from a GPS derived time
RTCSetResult perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate = false); RTCSetResult perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate = false);
RTCSetResult perhapsSetRTC(RTCQuality q, struct tm &t); RTCSetResult perhapsSetRTC(RTCQuality q, const struct tm &t);
/// Return a string name for the quality /// Return a string name for the quality
const char *RtcName(RTCQuality quality); const char *RtcName(RTCQuality quality);
+11 -12
View File
@@ -539,7 +539,7 @@ void menuHandler::messageResponseMenu()
// If viewing ALL chats, hide “Mute Chat” // If viewing ALL chats, hide “Mute Chat”
if (mode != graphics::MessageRenderer::ThreadMode::ALL && mode != graphics::MessageRenderer::ThreadMode::DIRECT) { if (mode != graphics::MessageRenderer::ThreadMode::ALL && mode != graphics::MessageRenderer::ThreadMode::DIRECT) {
const uint8_t chIndex = (threadChannel != 0) ? (uint8_t)threadChannel : channels.getPrimaryIndex(); const uint8_t chIndex = (threadChannel != 0) ? (uint8_t)threadChannel : channels.getPrimaryIndex();
auto &chan = channels.getByIndex(chIndex); const auto &chan = channels.getByIndex(chIndex);
optionsArray[options] = chan.settings.module_settings.is_muted ? "Unmute Channel" : "Mute Channel"; optionsArray[options] = chan.settings.module_settings.is_muted ? "Unmute Channel" : "Mute Channel";
optionsEnumArray[options++] = MuteChannel; optionsEnumArray[options++] = MuteChannel;
@@ -831,7 +831,7 @@ void menuHandler::messageViewModeMenu()
// Gather unique peers // Gather unique peers
auto dms = messageStore.getDirectMessages(); auto dms = messageStore.getDirectMessages();
std::vector<uint32_t> uniquePeers; std::vector<uint32_t> uniquePeers;
for (auto &m : dms) { for (const auto &m : dms) {
uint32_t peer = (m.sender == nodeDB->getNodeNum()) ? m.dest : m.sender; uint32_t peer = (m.sender == nodeDB->getNodeNum()) ? m.dest : m.sender;
if (peer != nodeDB->getNodeNum() && std::find(uniquePeers.begin(), uniquePeers.end(), peer) == uniquePeers.end()) if (peer != nodeDB->getNodeNum() && std::find(uniquePeers.begin(), uniquePeers.end(), peer) == uniquePeers.end())
uniquePeers.push_back(peer); uniquePeers.push_back(peer);
@@ -1397,7 +1397,7 @@ void menuHandler::manageNodeMenu()
} }
if (selected == Favorite) { if (selected == Favorite) {
auto n = nodeDB->getMeshNode(menuHandler::pickedNodeNum); const auto *n = nodeDB->getMeshNode(menuHandler::pickedNodeNum);
if (!n) { if (!n) {
return; return;
} }
@@ -2292,14 +2292,13 @@ void menuHandler::wifiToggleMenu()
void menuHandler::screenOptionsMenu() void menuHandler::screenOptionsMenu()
{ {
// Check if brightness is supported // Check if brightness is supported
bool hasSupportBrightness = false;
#if defined(ST7789_CS) || defined(USE_OLED) || defined(USE_SSD1306) || defined(USE_SH1106) || defined(USE_SH1107)
hasSupportBrightness = true;
#endif
#if defined(T_DECK) #if defined(T_DECK)
// TDeck Doesn't seem to support brightness at all, at least not reliably // TDeck Doesn't seem to support brightness at all, at least not reliably
hasSupportBrightness = false; bool hasSupportBrightness = false;
#elif defined(ST7789_CS) || defined(USE_OLED) || defined(USE_SSD1306) || defined(USE_SH1106) || defined(USE_SH1107)
bool hasSupportBrightness = true;
#else
bool hasSupportBrightness = false;
#endif #endif
enum optionsNumbers { Back, Brightness, ScreenColor, FrameToggles, DisplayUnits, MessageBubbles }; enum optionsNumbers { Back, Brightness, ScreenColor, FrameToggles, DisplayUnits, MessageBubbles };
@@ -2444,7 +2443,7 @@ void menuHandler::frameTogglesMenu()
nodelist_hopsignal, nodelist_hopsignal,
nodelist_distance, nodelist_distance,
nodelist_bearings, nodelist_bearings,
gps, gps_position,
lora, lora,
clock, clock,
show_favorites, show_favorites,
@@ -2482,7 +2481,7 @@ void menuHandler::frameTogglesMenu()
#endif #endif
optionsArray[options] = screen->isFrameHidden("gps") ? "Show Position" : "Hide Position"; optionsArray[options] = screen->isFrameHidden("gps") ? "Show Position" : "Hide Position";
optionsEnumArray[options++] = gps; optionsEnumArray[options++] = gps_position;
#endif #endif
optionsArray[options] = screen->isFrameHidden("lora") ? "Show LoRa" : "Hide LoRa"; optionsArray[options] = screen->isFrameHidden("lora") ? "Show LoRa" : "Hide LoRa";
@@ -2545,7 +2544,7 @@ void menuHandler::frameTogglesMenu()
screen->toggleFrameVisibility("nodelist_bearings"); screen->toggleFrameVisibility("nodelist_bearings");
menuHandler::menuQueue = menuHandler::FrameToggles; menuHandler::menuQueue = menuHandler::FrameToggles;
screen->runNow(); screen->runNow();
} else if (selected == gps) { } else if (selected == gps_position) {
screen->toggleFrameVisibility("gps"); screen->toggleFrameVisibility("gps");
menuHandler::menuQueue = menuHandler::FrameToggles; menuHandler::menuQueue = menuHandler::FrameToggles;
screen->runNow(); screen->runNow();
+10 -13
View File
@@ -171,7 +171,7 @@ unsigned long getModeCycleIntervalMs()
int calculateMaxScroll(int totalEntries, int visibleRows) int calculateMaxScroll(int totalEntries, int visibleRows)
{ {
return std::max(0, (totalEntries - 1) / (visibleRows * 2)); return max(0, (totalEntries - 1) / (visibleRows * 2));
} }
void drawColumnSeparator(OLEDDisplay *display, int16_t x, int16_t yStart, int16_t yEnd) void drawColumnSeparator(OLEDDisplay *display, int16_t x, int16_t yStart, int16_t yEnd)
@@ -187,13 +187,12 @@ void drawScrollbar(OLEDDisplay *display, int visibleNodeRows, int totalEntries,
if (totalEntries <= visibleNodeRows * columns) if (totalEntries <= visibleNodeRows * columns)
return; return;
int scrollbarX = display->getWidth() - 2;
int scrollbarHeight = display->getHeight() - scrollStartY - 10; int scrollbarHeight = display->getHeight() - scrollStartY - 10;
int thumbHeight = std::max(4, (scrollbarHeight * visibleNodeRows * columns) / totalEntries); int thumbHeight = max(4, (scrollbarHeight * visibleNodeRows * columns) / totalEntries);
int perPage = visibleNodeRows * columns; int thumbY = scrollStartY + (scrollIndex * (scrollbarHeight - thumbHeight)) /
int maxScroll = std::max(0, (totalEntries - 1) / perPage); max(1, max(0, (totalEntries - 1) / (visibleNodeRows * columns)));
int thumbY = scrollStartY + (scrollIndex * (scrollbarHeight - thumbHeight)) / std::max(1, maxScroll);
int scrollbarX = display->getWidth() - 2;
for (int i = 0; i < thumbHeight; i++) { for (int i = 0; i < thumbHeight; i++) {
display->setPixel(scrollbarX, thumbY + i); display->setPixel(scrollbarX, thumbY + i);
} }
@@ -556,13 +555,13 @@ void drawNodeListScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t
int maxScroll = 0; int maxScroll = 0;
if (perPage > 0) { if (perPage > 0) {
maxScroll = std::max(0, (totalEntries - 1) / perPage); maxScroll = max(0, (totalEntries - 1) / perPage);
} }
if (scrollIndex > maxScroll) if (scrollIndex > maxScroll)
scrollIndex = maxScroll; scrollIndex = maxScroll;
int startIndex = scrollIndex * visibleNodeRows * totalColumns; int startIndex = scrollIndex * visibleNodeRows * totalColumns;
int endIndex = std::min(startIndex + visibleNodeRows * totalColumns, totalEntries); int endIndex = min(startIndex + visibleNodeRows * totalColumns, totalEntries);
int yOffset = 0; int yOffset = 0;
int col = 0; int col = 0;
int lastNodeY = y; int lastNodeY = y;
@@ -580,7 +579,7 @@ void drawNodeListScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t
if (extras) if (extras)
extras(display, node, xPos, yPos, columnWidth, heading, lat, lon); extras(display, node, xPos, yPos, columnWidth, heading, lat, lon);
lastNodeY = std::max(lastNodeY, yPos + FONT_HEIGHT_SMALL); lastNodeY = max(lastNodeY, yPos + FONT_HEIGHT_SMALL);
yOffset += rowYOffset; yOffset += rowYOffset;
shownCount++; shownCount++;
rowCount++; rowCount++;
@@ -613,13 +612,11 @@ void drawNodeListScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t
if (millis() - popupTime < POPUP_DURATION_MS) { if (millis() - popupTime < POPUP_DURATION_MS) {
popupTotal = totalEntries; popupTotal = totalEntries;
int perPage = visibleNodeRows * totalColumns;
popupStart = startIndex + 1; popupStart = startIndex + 1;
popupEnd = std::min(startIndex + perPage, totalEntries); popupEnd = min(startIndex + perPage, totalEntries);
popupPage = (scrollIndex + 1); popupPage = (scrollIndex + 1);
popupMaxPage = std::max(1, (totalEntries + perPage - 1) / perPage); popupMaxPage = max(1, (totalEntries + perPage - 1) / perPage);
char buf[32]; char buf[32];
snprintf(buf, sizeof(buf), "%d-%d/%d Pg %d/%d", popupStart, popupEnd, popupTotal, popupPage, popupMaxPage); snprintf(buf, sizeof(buf), "%d-%d/%d Pg %d/%d", popupStart, popupEnd, popupTotal, popupPage, popupMaxPage);
+3 -1
View File
@@ -288,7 +288,8 @@ void UIRenderer::drawNodes(OLEDDisplay *display, int16_t x, int16_t y, const mes
// ********************** // **********************
// * Favorite Node Info * // * Favorite Node Info *
// ********************** // **********************
void UIRenderer::drawNodeInfo(OLEDDisplay *display, const OLEDDisplayUiState *state, int16_t x, int16_t y) // cppcheck-suppress constParameterPointer; signature must match FrameCallback typedef from OLEDDisplayUi library
void UIRenderer::drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y)
{ {
if (favoritedNodes.empty()) if (favoritedNodes.empty())
return; return;
@@ -1388,6 +1389,7 @@ static int8_t lastFrameIndex = -1;
static uint32_t lastFrameChangeTime = 0; static uint32_t lastFrameChangeTime = 0;
constexpr uint32_t ICON_DISPLAY_DURATION_MS = 2000; constexpr uint32_t ICON_DISPLAY_DURATION_MS = 2000;
// cppcheck-suppress constParameterPointer; signature must match OverlayCallback typedef from OLEDDisplayUi library
void UIRenderer::drawNavigationBar(OLEDDisplay *display, OLEDDisplayUiState *state) void UIRenderer::drawNavigationBar(OLEDDisplay *display, OLEDDisplayUiState *state)
{ {
int currentFrame = state->currentFrame; int currentFrame = state->currentFrame;
+1 -1
View File
@@ -49,7 +49,7 @@ class UIRenderer
// Navigation bar overlay // Navigation bar overlay
static void drawNavigationBar(OLEDDisplay *display, OLEDDisplayUiState *state); static void drawNavigationBar(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawNodeInfo(OLEDDisplay *display, const OLEDDisplayUiState *state, int16_t x, int16_t y); static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y);
static void drawDeviceFocused(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y); static void drawDeviceFocused(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y);
@@ -42,7 +42,7 @@ int LatchingBacklight::beforeDeepSleep(void *unused)
{ {
// Contingency only // Contingency only
// - pin wasn't set // - pin wasn't set
if (pin != (uint8_t)-1) { if (pin != static_cast<uint8_t>(-1)) {
off(); off();
pinMode(pin, INPUT); // High impedance - unnecessary? pinMode(pin, INPUT); // High impedance - unnecessary?
} else } else
@@ -55,7 +55,7 @@ int LatchingBacklight::beforeDeepSleep(void *unused)
// The effect on the backlight is the same; peek and latch are separated to simplify short vs long press button handling // The effect on the backlight is the same; peek and latch are separated to simplify short vs long press button handling
void LatchingBacklight::peek() void LatchingBacklight::peek()
{ {
assert(pin != (uint8_t)-1); assert(pin != static_cast<uint8_t>(-1));
digitalWrite(pin, logicActive); // On digitalWrite(pin, logicActive); // On
on = true; on = true;
latched = false; latched = false;
@@ -67,7 +67,7 @@ void LatchingBacklight::peek()
// The effect on the backlight is the same; peek and latch are separated to simplify short vs long press button handling // The effect on the backlight is the same; peek and latch are separated to simplify short vs long press button handling
void LatchingBacklight::latch() void LatchingBacklight::latch()
{ {
assert(pin != (uint8_t)-1); assert(pin != static_cast<uint8_t>(-1));
// Blink if moving from peek to latch // Blink if moving from peek to latch
// Indicates to user that the transition has taken place // Indicates to user that the transition has taken place
@@ -89,7 +89,7 @@ void LatchingBacklight::latch()
// Suitable for ending both peek and latch // Suitable for ending both peek and latch
void LatchingBacklight::off() void LatchingBacklight::off()
{ {
assert(pin != (uint8_t)-1); assert(pin != static_cast<uint8_t>(-1));
digitalWrite(pin, !logicActive); // Off digitalWrite(pin, !logicActive); // Off
on = false; on = false;
latched = false; latched = false;
@@ -40,7 +40,7 @@ class LatchingBacklight
CallbackObserver<LatchingBacklight, void *> deepSleepObserver = CallbackObserver<LatchingBacklight, void *> deepSleepObserver =
CallbackObserver<LatchingBacklight, void *>(this, &LatchingBacklight::beforeDeepSleep); CallbackObserver<LatchingBacklight, void *>(this, &LatchingBacklight::beforeDeepSleep);
uint8_t pin = (uint8_t)-1; uint8_t pin = static_cast<uint8_t>(-1);
bool logicActive = HIGH; // Is light active HIGH or active LOW bool logicActive = HIGH; // Is light active HIGH or active LOW
bool on = false; // Is light on (either peek or latched) bool on = false; // Is light on (either peek or latched)
+15 -15
View File
@@ -34,7 +34,7 @@ void InkHUD::Applet::drawPixel(int16_t x, int16_t y, uint16_t color)
{ {
// Only render pixels if they fall within user's cropped region // Only render pixels if they fall within user's cropped region
if (x >= cropLeft && x < (cropLeft + cropWidth) && y >= cropTop && y < (cropTop + cropHeight)) if (x >= cropLeft && x < (cropLeft + cropWidth) && y >= cropTop && y < (cropTop + cropHeight))
assignedTile->handleAppletPixel(x, y, (Color)color); assignedTile->handleAppletPixel(x, y, static_cast<Color>(color));
} }
// Link our applet to a tile // Link our applet to a tile
@@ -312,7 +312,7 @@ void InkHUD::Applet::printAt(int16_t x, int16_t y, const char *text, HorizontalA
} }
// Print text, specifying the position of any edge / corner of the textbox // Print text, specifying the position of any edge / corner of the textbox
void InkHUD::Applet::printAt(int16_t x, int16_t y, std::string text, HorizontalAlignment ha, VerticalAlignment va) void InkHUD::Applet::printAt(int16_t x, int16_t y, const std::string &text, HorizontalAlignment ha, VerticalAlignment va)
{ {
printAt(x, y, text.c_str(), ha, va); printAt(x, y, text.c_str(), ha, va);
} }
@@ -334,7 +334,7 @@ InkHUD::AppletFont InkHUD::Applet::getFont()
// Parse any text which might have "special characters" // Parse any text which might have "special characters"
// Re-encodes UTF-8 characters to match our 8-bit encoded fonts // Re-encodes UTF-8 characters to match our 8-bit encoded fonts
std::string InkHUD::Applet::parse(std::string text) std::string InkHUD::Applet::parse(const std::string &text)
{ {
return getFont().decodeUTF8(text); return getFont().decodeUTF8(text);
} }
@@ -361,10 +361,10 @@ std::string InkHUD::Applet::parseShortName(meshtastic_NodeInfoLite *node)
} }
// Determine if all characters of a string are printable using the current font // Determine if all characters of a string are printable using the current font
bool InkHUD::Applet::isPrintable(std::string text) bool InkHUD::Applet::isPrintable(const std::string &text)
{ {
// Scan for SUB (0x1A), which is the value assigned by AppletFont::applyEncoding if a unicode character is not handled // Scan for SUB (0x1A), which is the value assigned by AppletFont::applyEncoding if a unicode character is not handled
for (char &c : text) { for (const char &c : text) {
if (c == '\x1A') if (c == '\x1A')
return false; return false;
} }
@@ -387,7 +387,7 @@ uint16_t InkHUD::Applet::getTextWidth(const char *text)
// Gets rendered width of a string // Gets rendered width of a string
// Wrapper for getTextBounds // Wrapper for getTextBounds
uint16_t InkHUD::Applet::getTextWidth(std::string text) uint16_t InkHUD::Applet::getTextWidth(const std::string &text)
{ {
return getTextWidth(text.c_str()); return getTextWidth(text.c_str());
} }
@@ -435,7 +435,7 @@ std::string InkHUD::Applet::hexifyNodeNum(NodeNum num)
// Print text, with word wrapping // Print text, with word wrapping
// Avoids splitting words in half, instead moving the entire word to a new line wherever possible // Avoids splitting words in half, instead moving the entire word to a new line wherever possible
void InkHUD::Applet::printWrapped(int16_t left, int16_t top, uint16_t width, std::string text) void InkHUD::Applet::printWrapped(int16_t left, int16_t top, uint16_t width, const std::string &text)
{ {
// Place the AdafruitGFX cursor to suit our "top" coord // Place the AdafruitGFX cursor to suit our "top" coord
setCursor(left, top + getFont().heightAboveCursor()); setCursor(left, top + getFont().heightAboveCursor());
@@ -492,15 +492,15 @@ void InkHUD::Applet::printWrapped(int16_t left, int16_t top, uint16_t width, std
// Todo: rewrite making use of AdafruitGFX native text wrapping // Todo: rewrite making use of AdafruitGFX native text wrapping
char cstr[] = {0, 0}; char cstr[] = {0, 0};
int16_t l, t; int16_t bx, by;
uint16_t w, h; uint16_t bw, bh;
for (uint16_t c = 0; c < word.length(); c++) { for (uint16_t c = 0; c < word.length(); c++) {
// Shove next char into a c string // Shove next char into a c string
cstr[0] = word[c]; cstr[0] = word[c];
getTextBounds(cstr, getCursorX(), getCursorY(), &l, &t, &w, &h); getTextBounds(cstr, getCursorX(), getCursorY(), &bx, &by, &bw, &bh);
// Manual newline, if next character will spill beyond screen edge // Manual newline, if next character will spill beyond screen edge
if ((l + w) > left + width) if ((bx + bw) > left + width)
setCursor(left, getCursorY() + getFont().lineHeight()); setCursor(left, getCursorY() + getFont().lineHeight());
// Print next character // Print next character
@@ -519,7 +519,7 @@ void InkHUD::Applet::printWrapped(int16_t left, int16_t top, uint16_t width, std
// Simulate running printWrapped, to determine how tall the block of text will be. // Simulate running printWrapped, to determine how tall the block of text will be.
// This is a wasteful way of handling things. Maybe some way to optimize in future? // This is a wasteful way of handling things. Maybe some way to optimize in future?
uint32_t InkHUD::Applet::getWrappedTextHeight(int16_t left, uint16_t width, std::string text) uint32_t InkHUD::Applet::getWrappedTextHeight(int16_t left, uint16_t width, const std::string &text)
{ {
// Cache the current crop region // Cache the current crop region
int16_t cL = cropLeft; int16_t cL = cropLeft;
@@ -649,7 +649,7 @@ uint16_t InkHUD::Applet::getActiveNodeCount()
// For each node in db // For each node in db
for (uint16_t i = 0; i < nodeDB->getNumMeshNodes(); i++) { for (uint16_t i = 0; i < nodeDB->getNumMeshNodes(); i++) {
meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i); const meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i);
// Check if heard recently, and not our own node // Check if heard recently, and not our own node
if (sinceLastSeen(node) < settings->recentlyActiveSeconds && node->num != nodeDB->getNodeNum()) if (sinceLastSeen(node) < settings->recentlyActiveSeconds && node->num != nodeDB->getNodeNum())
@@ -702,7 +702,7 @@ std::string InkHUD::Applet::localizeDistance(uint32_t meters)
} }
// Print text with a "faux bold" effect, by drawing it multiple times, offsetting slightly // Print text with a "faux bold" effect, by drawing it multiple times, offsetting slightly
void InkHUD::Applet::printThick(int16_t xCenter, int16_t yCenter, std::string text, uint8_t thicknessX, uint8_t thicknessY) void InkHUD::Applet::printThick(int16_t xCenter, int16_t yCenter, const std::string &text, uint8_t thicknessX, uint8_t thicknessY)
{ {
// How many times to draw along x axis // How many times to draw along x axis
int16_t xStart; int16_t xStart;
@@ -770,7 +770,7 @@ bool InkHUD::Applet::approveNotification(NicheGraphics::InkHUD::Notification &n)
│ │ │ │
└───────────────────────────────┘ └───────────────────────────────┘
*/ */
void InkHUD::Applet::drawHeader(std::string text) void InkHUD::Applet::drawHeader(const std::string &text)
{ {
// Y position for divider // Y position for divider
// - between header text and messages // - between header text and messages
+9 -8
View File
@@ -125,16 +125,17 @@ class Applet : public GFX
void setFont(AppletFont f); void setFont(AppletFont f);
AppletFont getFont(); AppletFont getFont();
uint16_t getTextWidth(std::string text); uint16_t getTextWidth(const std::string &text);
uint16_t getTextWidth(const char *text); uint16_t getTextWidth(const char *text);
uint32_t getWrappedTextHeight(int16_t left, uint16_t width, std::string text); // Result of printWrapped uint32_t getWrappedTextHeight(int16_t left, uint16_t width, const std::string &text); // Result of printWrapped
void printAt(int16_t x, int16_t y, const char *text, HorizontalAlignment ha = LEFT, VerticalAlignment va = TOP); void printAt(int16_t x, int16_t y, const char *text, HorizontalAlignment ha = LEFT, VerticalAlignment va = TOP);
void printAt(int16_t x, int16_t y, std::string text, HorizontalAlignment ha = LEFT, VerticalAlignment va = TOP); void printAt(int16_t x, int16_t y, const std::string &text, HorizontalAlignment ha = LEFT, VerticalAlignment va = TOP);
void printThick(int16_t xCenter, int16_t yCenter, std::string text, uint8_t thicknessX, uint8_t thicknessY); // Faux bold void printThick(int16_t xCenter, int16_t yCenter, const std::string &text, uint8_t thicknessX,
void printWrapped(int16_t left, int16_t top, uint16_t width, std::string text); // Per-word line wrapping uint8_t thicknessY); // Faux bold
void printWrapped(int16_t left, int16_t top, uint16_t width, const std::string &text); // Per-word line wrapping
void hatchRegion(int16_t x, int16_t y, uint16_t w, uint16_t h, uint8_t spacing, Color color); // Fill with sparse lines void hatchRegion(int16_t x, int16_t y, uint16_t w, uint16_t h, uint8_t spacing, Color color); // Fill with sparse lines
void drawHeader(std::string text); // Draw the standard applet header void drawHeader(const std::string &text); // Draw the standard applet header
// Meshtastic Logo // Meshtastic Logo
@@ -150,9 +151,9 @@ class Applet : public GFX
std::string getTimeString(); // Current time, human readable std::string getTimeString(); // Current time, human readable
uint16_t getActiveNodeCount(); // Duration determined by user, in onscreen menu uint16_t getActiveNodeCount(); // Duration determined by user, in onscreen menu
std::string localizeDistance(uint32_t meters); // Human readable distance, imperial or metric std::string localizeDistance(uint32_t meters); // Human readable distance, imperial or metric
std::string parse(std::string text); // Handle text which might contain special chars std::string parse(const std::string &text); // Handle text which might contain special chars
std::string parseShortName(meshtastic_NodeInfoLite *node); // Get the shortname, or a substitute if has unprintable chars std::string parseShortName(meshtastic_NodeInfoLite *node); // Get the shortname, or a substitute if has unprintable chars
bool isPrintable(std::string); // Check for characters which the font can't print bool isPrintable(const std::string &text); // Check for characters which the font can't print
// Convenient references // Convenient references
+7 -7
View File
@@ -39,11 +39,11 @@ InkHUD::AppletFont::AppletFont(const GFXfont &adafruitGFXFont, Encoding encoding
// Caution: signed and unsigned types // Caution: signed and unsigned types
int8_t glyphAscender = 0 - gfxFont->glyph[i].yOffset; int8_t glyphAscender = 0 - gfxFont->glyph[i].yOffset;
if (glyphAscender > 0) if (glyphAscender > 0)
this->ascenderHeight = max(this->ascenderHeight, (uint8_t)glyphAscender); this->ascenderHeight = max(this->ascenderHeight, static_cast<uint8_t>(glyphAscender));
int8_t glyphDescender = gfxFont->glyph[i].height + gfxFont->glyph[i].yOffset; int8_t glyphDescender = gfxFont->glyph[i].height + gfxFont->glyph[i].yOffset;
if (glyphDescender > 0) if (glyphDescender > 0)
this->descenderHeight = max(this->descenderHeight, (uint8_t)glyphDescender); this->descenderHeight = max(this->descenderHeight, static_cast<uint8_t>(glyphDescender));
} }
// Apply any manual padding to grow or shrink the line size // Apply any manual padding to grow or shrink the line size
@@ -52,7 +52,7 @@ InkHUD::AppletFont::AppletFont(const GFXfont &adafruitGFXFont, Encoding encoding
descenderHeight += paddingBottom; descenderHeight += paddingBottom;
// Find how far the cursor advances when we "print" a space character // Find how far the cursor advances when we "print" a space character
spaceCharWidth = gfxFont->glyph[(uint8_t)' ' - gfxFont->first].xAdvance; spaceCharWidth = gfxFont->glyph[static_cast<uint8_t>(' ') - gfxFont->first].xAdvance;
} }
/* /*
@@ -98,7 +98,7 @@ uint8_t InkHUD::AppletFont::widthBetweenWords()
// Convert a unicode char from set of UTF-8 bytes to UTF-32 // Convert a unicode char from set of UTF-8 bytes to UTF-32
// Used by AppletFont::applyEncoding, which remaps unicode chars for extended ASCII fonts, based on their UTF-32 value // Used by AppletFont::applyEncoding, which remaps unicode chars for extended ASCII fonts, based on their UTF-32 value
uint32_t InkHUD::AppletFont::toUtf32(std::string utf8) uint32_t InkHUD::AppletFont::toUtf32(const std::string &utf8)
{ {
uint32_t utf32 = 0; uint32_t utf32 = 0;
@@ -132,7 +132,7 @@ uint32_t InkHUD::AppletFont::toUtf32(std::string utf8)
// Process a string, collating UTF-8 bytes, and sending them off for re-encoding to extended ASCII // Process a string, collating UTF-8 bytes, and sending them off for re-encoding to extended ASCII
// Not all InkHUD text is passed through here, only text which could potentially contain non-ASCII chars // Not all InkHUD text is passed through here, only text which could potentially contain non-ASCII chars
std::string InkHUD::AppletFont::decodeUTF8(std::string encoded) std::string InkHUD::AppletFont::decodeUTF8(const std::string &encoded)
{ {
// Final processed output // Final processed output
std::string decoded; std::string decoded;
@@ -141,7 +141,7 @@ std::string InkHUD::AppletFont::decodeUTF8(std::string encoded)
std::string utf8Char; std::string utf8Char;
uint8_t utf8CharSize = 0; uint8_t utf8CharSize = 0;
for (char &c : encoded) { for (const char &c : encoded) {
// If first byte // If first byte
if (utf8Char.empty()) { if (utf8Char.empty()) {
@@ -178,7 +178,7 @@ std::string InkHUD::AppletFont::decodeUTF8(std::string encoded)
// Re-encode a single UTF-8 character to extended ASCII // Re-encode a single UTF-8 character to extended ASCII
// Target encoding depends on the font // Target encoding depends on the font
char InkHUD::AppletFont::applyEncoding(std::string utf8) char InkHUD::AppletFont::applyEncoding(const std::string &utf8)
{ {
// ##################################################### Syntactic Sugar ##################################################### // ##################################################### Syntactic Sugar #####################################################
#define REMAP(in, out) \ #define REMAP(in, out) \
+6 -5
View File
@@ -30,20 +30,21 @@ class AppletFont
}; };
AppletFont(); AppletFont();
AppletFont(const GFXfont &adafruitGFXFont, Encoding encoding = ASCII, int8_t paddingTop = 0, int8_t paddingBottom = 0); explicit AppletFont(const GFXfont &adafruitGFXFont, Encoding encoding = ASCII, int8_t paddingTop = 0,
int8_t paddingBottom = 0);
uint8_t lineHeight(); uint8_t lineHeight();
uint8_t heightAboveCursor(); uint8_t heightAboveCursor();
uint8_t heightBelowCursor(); uint8_t heightBelowCursor();
uint8_t widthBetweenWords(); // Width of the space character uint8_t widthBetweenWords(); // Width of the space character
std::string decodeUTF8(std::string encoded); std::string decodeUTF8(const std::string &encoded);
const GFXfont *gfxFont = NULL; // Default value: in-built AdafruitGFX font const GFXfont *gfxFont = nullptr; // Default value: in-built AdafruitGFX font
private: private:
uint32_t toUtf32(std::string utf8); uint32_t toUtf32(const std::string &utf8);
char applyEncoding(std::string utf8); char applyEncoding(const std::string &utf8);
uint8_t height = 8; // Default value: in-built AdafruitGFX font uint8_t height = 8; // Default value: in-built AdafruitGFX font
uint8_t ascenderHeight = 0; // Default value: in-built AdafruitGFX font uint8_t ascenderHeight = 0; // Default value: in-built AdafruitGFX font
@@ -81,25 +81,25 @@ ProcessMessage InkHUD::NodeListApplet::handleReceived(const meshtastic_MeshPacke
uint8_t InkHUD::NodeListApplet::maxCards() uint8_t InkHUD::NodeListApplet::maxCards()
{ {
// Cache result. Shouldn't change during execution // Cache result. Shouldn't change during execution
static uint8_t cards = 0; static uint8_t maxCardCount = 0;
if (!cards) { if (!maxCardCount) {
const uint16_t height = Tile::maxDisplayDimension(); const uint16_t height = Tile::maxDisplayDimension();
// Use a loop instead of arithmetic, because it's easier for my brain to follow // Use a loop instead of arithmetic, because it's easier for my brain to follow
// Add cards one by one, until the latest card extends below screen // Add cards one by one, until the latest card extends below screen
uint16_t y = cardH; // First card: no margin above uint16_t y = cardH; // First card: no margin above
cards = 1; maxCardCount = 1;
while (y < height) { while (y < height) {
y += cardMarginH; y += cardMarginH;
y += cardH; y += cardH;
cards++; maxCardCount++;
} }
} }
return cards; return maxCardCount;
} }
// Draw, using info which derived applet placed into NodeListApplet::cards for us // Draw, using info which derived applet placed into NodeListApplet::cards for us
@@ -137,12 +137,12 @@ void InkHUD::NodeListApplet::onRender(bool full)
// Gather info // Gather info
// ======================================== // ========================================
NodeNum &nodeNum = card->nodeNum; const NodeNum &nodeNum = card->nodeNum;
SignalStrength &signal = card->signal; SignalStrength &signal = card->signal;
std::string longName; // handled below std::string longName; // handled below
std::string shortName; // handled below std::string shortName; // handled below
std::string distance; // handled below; std::string distance; // handled below;
uint8_t &hopsAway = card->hopsAway; const uint8_t &hopsAway = card->hopsAway;
meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeNum); meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeNum);
@@ -29,10 +29,10 @@ int InkHUD::BatteryIconApplet::onPowerStatusUpdate(const meshtastic::Status *sta
// If we get a different type of status, something has gone weird elsewhere // If we get a different type of status, something has gone weird elsewhere
assert(status->getStatusType() == STATUS_TYPE_POWER); assert(status->getStatusType() == STATUS_TYPE_POWER);
meshtastic::PowerStatus *powerStatus = (meshtastic::PowerStatus *)status; const meshtastic::PowerStatus *pwrStatus = (const meshtastic::PowerStatus *)status;
// Get the new state of charge %, and round to the nearest 10% // Get the new state of charge %, and round to the nearest 10%
uint8_t newSocRounded = ((powerStatus->getBatteryChargePercent() + 5) / 10) * 10; uint8_t newSocRounded = ((pwrStatus->getBatteryChargePercent() + 5) / 10) * 10;
// If rounded value has changed, trigger a display update // If rounded value has changed, trigger a display update
// It's okay to requestUpdate before we store the new value, as the update won't run until next loop() // It's okay to requestUpdate before we store the new value, as the update won't run until next loop()
@@ -1176,7 +1176,7 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
items.push_back(MenuItem("Back", previousPage)); items.push_back(MenuItem("Back", previousPage));
for (uint8_t i = 0; i < MAX_NUM_CHANNELS; i++) { for (uint8_t i = 0; i < MAX_NUM_CHANNELS; i++) {
meshtastic_Channel &ch = channels.getByIndex(i); const meshtastic_Channel &ch = channels.getByIndex(i);
if (!ch.has_settings) if (!ch.has_settings)
continue; continue;
@@ -1252,7 +1252,7 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
case NODE_CONFIG_CHANNEL_PRECISION: { case NODE_CONFIG_CHANNEL_PRECISION: {
previousPage = MenuPage::NODE_CONFIG_CHANNEL_DETAIL; previousPage = MenuPage::NODE_CONFIG_CHANNEL_DETAIL;
items.push_back(MenuItem("Back", previousPage)); items.push_back(MenuItem("Back", previousPage));
meshtastic_Channel &ch = channels.getByIndex(selectedChannelIndex); const meshtastic_Channel &ch = channels.getByIndex(selectedChannelIndex);
if (!ch.settings.has_module_settings || ch.settings.module_settings.position_precision == 0) { if (!ch.settings.has_module_settings || ch.settings.module_settings.position_precision == 0) {
items.push_back(MenuItem("Position is Off", MenuPage::NODE_CONFIG_CHANNEL_DETAIL)); items.push_back(MenuItem("Position is Off", MenuPage::NODE_CONFIG_CHANNEL_DETAIL));
break; break;
@@ -1759,7 +1759,7 @@ void InkHUD::MenuApplet::populateRecipientPage()
for (uint8_t i = 0; i < MAX_NUM_CHANNELS; i++) { for (uint8_t i = 0; i < MAX_NUM_CHANNELS; i++) {
// Get the channel, and check if it's enabled // Get the channel, and check if it's enabled
meshtastic_Channel &channel = channels.getByIndex(i); const meshtastic_Channel &channel = channels.getByIndex(i);
if (!channel.has_settings || channel.role == meshtastic_Channel_Role_DISABLED) if (!channel.has_settings || channel.role == meshtastic_Channel_Role_DISABLED)
continue; continue;
@@ -1829,7 +1829,7 @@ void InkHUD::MenuApplet::populateRecipientPage()
items.push_back(MenuItem("Exit", MenuPage::EXIT)); items.push_back(MenuItem("Exit", MenuPage::EXIT));
} }
void InkHUD::MenuApplet::drawInputField(uint16_t left, uint16_t top, uint16_t width, uint16_t height, std::string text) void InkHUD::MenuApplet::drawInputField(uint16_t left, uint16_t top, uint16_t width, uint16_t height, const std::string &text)
{ {
setFont(fontSmall); setFont(fontSmall);
uint16_t wrapMaxH = 0; uint16_t wrapMaxH = 0;
@@ -55,7 +55,7 @@ class MenuApplet : public SystemApplet, public concurrency::OSThread
void populateRecentsPage(); // Create menu items: a choice of values for settings.recentlyActiveSeconds void populateRecentsPage(); // Create menu items: a choice of values for settings.recentlyActiveSeconds
void drawInputField(uint16_t left, uint16_t top, uint16_t width, uint16_t height, void drawInputField(uint16_t left, uint16_t top, uint16_t width, uint16_t height,
std::string text); // Draw input field for free text const std::string &text); // Draw input field for free text
uint16_t getSystemInfoPanelHeight(); uint16_t getSystemInfoPanelHeight();
void drawSystemInfoPanel(int16_t left, int16_t top, uint16_t width, void drawSystemInfoPanel(int16_t left, int16_t top, uint16_t width,
uint16_t *height = nullptr); // Info panel at top of root menu uint16_t *height = nullptr); // Info panel at top of root menu
@@ -228,17 +228,17 @@ std::string InkHUD::NotificationApplet::getNotificationText(uint16_t widthAvaila
Notification::Type::NOTIFICATION_MESSAGE_BROADCAST)) { Notification::Type::NOTIFICATION_MESSAGE_BROADCAST)) {
// Although we are handling DM and broadcast notifications together, we do need to treat them slightly differently // Although we are handling DM and broadcast notifications together, we do need to treat them slightly differently
bool isBroadcast = currentNotification.type == Notification::Type::NOTIFICATION_MESSAGE_BROADCAST; bool msgIsBroadcast = currentNotification.type == Notification::Type::NOTIFICATION_MESSAGE_BROADCAST;
// Pick source of message // Pick source of message
MessageStore::Message *message = const MessageStore::Message *message =
isBroadcast ? &inkhud->persistence->latestMessage.broadcast : &inkhud->persistence->latestMessage.dm; msgIsBroadcast ? &inkhud->persistence->latestMessage.broadcast : &inkhud->persistence->latestMessage.dm;
// Find info about the sender // Find info about the sender
meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(message->sender); meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(message->sender);
// Leading tag (channel vs. DM) // Leading tag (channel vs. DM)
text += isBroadcast ? "From:" : "DM: "; text += msgIsBroadcast ? "From:" : "DM: ";
// Sender id // Sender id
if (node && node->has_user) if (node && node->has_user)
@@ -252,7 +252,7 @@ std::string InkHUD::NotificationApplet::getNotificationText(uint16_t widthAvaila
text.clear(); text.clear();
// Leading tag (channel vs. DM) // Leading tag (channel vs. DM)
text += isBroadcast ? "Msg from " : "DM from "; text += msgIsBroadcast ? "Msg from " : "DM from ";
// Sender id // Sender id
if (node && node->has_user) if (node && node->has_user)
@@ -55,12 +55,12 @@ int InkHUD::PairingApplet::onBluetoothStatusUpdate(const meshtastic::Status *sta
// We'll mimic that behavior, just to keep in line with the other Statuses, // We'll mimic that behavior, just to keep in line with the other Statuses,
// even though I'm not sure what the original reason for jumping through these extra hoops was. // even though I'm not sure what the original reason for jumping through these extra hoops was.
assert(status->getStatusType() == STATUS_TYPE_BLUETOOTH); assert(status->getStatusType() == STATUS_TYPE_BLUETOOTH);
meshtastic::BluetoothStatus *bluetoothStatus = (meshtastic::BluetoothStatus *)status; const auto *btStatus = static_cast<const meshtastic::BluetoothStatus *>(status);
// When pairing begins // When pairing begins
if (bluetoothStatus->getConnectionState() == meshtastic::BluetoothStatus::ConnectionState::PAIRING) { if (btStatus->getConnectionState() == meshtastic::BluetoothStatus::ConnectionState::PAIRING) {
// Store the passkey for rendering // Store the passkey for rendering
passkey = bluetoothStatus->getPasskey(); passkey = btStatus->getPasskey();
// Show pairing screen // Show pairing screen
bringToForeground(); bringToForeground();
@@ -69,9 +69,10 @@ void InkHUD::HeardApplet::populateFromNodeDB()
} }
// Sort the collection by age // Sort the collection by age
std::sort(ordered.begin(), ordered.end(), [](meshtastic_NodeInfoLite *top, meshtastic_NodeInfoLite *bottom) -> bool { std::sort(ordered.begin(), ordered.end(),
return (top->last_heard > bottom->last_heard); [](const meshtastic_NodeInfoLite *top, const meshtastic_NodeInfoLite *bottom) -> bool {
}); return (top->last_heard > bottom->last_heard);
});
// Keep the most recent entries only // Keep the most recent entries only
// Just enough to fill the screen // Just enough to fill the screen
@@ -69,7 +69,7 @@ void InkHUD::ThreadedMessageApplet::onRender(bool full)
while (msgB >= (0 - fontSmall.lineHeight()) && i < store->messages.size()) { while (msgB >= (0 - fontSmall.lineHeight()) && i < store->messages.size()) {
// Grab data for message // Grab data for message
MessageStore::Message &m = store->messages.at(i); const MessageStore::Message &m = store->messages.at(i);
bool outgoing = (m.sender == 0) || (m.sender == myNodeInfo.my_node_num); // Own NodeNum if canned message bool outgoing = (m.sender == 0) || (m.sender == myNodeInfo.my_node_num); // Own NodeNum if canned message
std::string bodyText = parse(m.text); // Parse any non-ascii chars in the message std::string bodyText = parse(m.text); // Parse any non-ascii chars in the message
+15 -13
View File
@@ -12,7 +12,7 @@ using namespace NicheGraphics;
constexpr uint8_t MAX_MESSAGES_SAVED = 10; constexpr uint8_t MAX_MESSAGES_SAVED = 10;
constexpr uint32_t MAX_MESSAGE_SIZE = 250; constexpr uint32_t MAX_MESSAGE_SIZE = 250;
InkHUD::MessageStore::MessageStore(std::string label) InkHUD::MessageStore::MessageStore(const std::string &label)
{ {
filename = ""; filename = "";
filename += "/NicheGraphics"; filename += "/NicheGraphics";
@@ -50,12 +50,13 @@ void InkHUD::MessageStore::saveToFlash()
// For each message // For each message
for (uint8_t i = 0; i < messages.size() && i < MAX_MESSAGES_SAVED; i++) { for (uint8_t i = 0; i < messages.size() && i < MAX_MESSAGES_SAVED; i++) {
Message &m = messages.at(i); Message &m = messages.at(i);
f.write((uint8_t *)&m.timestamp, sizeof(m.timestamp)); // Write timestamp. 4 bytes f.write(reinterpret_cast<const uint8_t *>(&m.timestamp), sizeof(m.timestamp)); // Write timestamp. 4 bytes
f.write((uint8_t *)&m.sender, sizeof(m.sender)); // Write sender NodeId. 4 Bytes f.write(reinterpret_cast<const uint8_t *>(&m.sender), sizeof(m.sender)); // Write sender NodeId. 4 Bytes
f.write((uint8_t *)&m.channelIndex, sizeof(m.channelIndex)); // Write channel index. 1 Byte f.write(reinterpret_cast<const uint8_t *>(&m.channelIndex), sizeof(m.channelIndex)); // Write channel index. 1 Byte
f.write((uint8_t *)m.text.c_str(), min(MAX_MESSAGE_SIZE, m.text.size())); // Write message text. Variable length f.write(reinterpret_cast<const uint8_t *>(m.text.c_str()), min(MAX_MESSAGE_SIZE, m.text.size())); // Write message text
f.write('\0'); // Append null term f.write('\0'); // Append null term
LOG_DEBUG("Wrote message %u, length %u, text \"%s\"", (uint32_t)i, min(MAX_MESSAGE_SIZE, m.text.size()), m.text.c_str()); LOG_DEBUG("Wrote message %u, length %u, text \"%s\"", static_cast<uint32_t>(i), min(MAX_MESSAGE_SIZE, m.text.size()),
m.text.c_str());
} }
// Release firmware's SPI lock, because SafeFile::close needs it // Release firmware's SPI lock, because SafeFile::close needs it
@@ -111,17 +112,17 @@ void InkHUD::MessageStore::loadFromFlash()
// First byte: how many messages are in the flash store // First byte: how many messages are in the flash store
uint8_t flashMessageCount = 0; uint8_t flashMessageCount = 0;
f.readBytes((char *)&flashMessageCount, 1); f.readBytes(reinterpret_cast<char *>(&flashMessageCount), 1);
LOG_DEBUG("Messages available: %u", (uint32_t)flashMessageCount); LOG_DEBUG("Messages available: %u", static_cast<uint32_t>(flashMessageCount));
// For each message // For each message
for (uint8_t i = 0; i < flashMessageCount && i < MAX_MESSAGES_SAVED; i++) { for (uint8_t i = 0; i < flashMessageCount && i < MAX_MESSAGES_SAVED; i++) {
Message m; Message m;
// Read meta data (fixed width) // Read meta data (fixed width)
f.readBytes((char *)&m.timestamp, sizeof(m.timestamp)); f.readBytes(reinterpret_cast<char *>(&m.timestamp), sizeof(m.timestamp));
f.readBytes((char *)&m.sender, sizeof(m.sender)); f.readBytes(reinterpret_cast<char *>(&m.sender), sizeof(m.sender));
f.readBytes((char *)&m.channelIndex, sizeof(m.channelIndex)); f.readBytes(reinterpret_cast<char *>(&m.channelIndex), sizeof(m.channelIndex));
// Read characters until we find a null term // Read characters until we find a null term
char c; char c;
@@ -136,7 +137,8 @@ void InkHUD::MessageStore::loadFromFlash()
// Store in RAM // Store in RAM
messages.push_back(m); messages.push_back(m);
LOG_DEBUG("#%u, timestamp=%u, sender(num)=%u, text=\"%s\"", (uint32_t)i, m.timestamp, m.sender, m.text.c_str()); LOG_DEBUG("#%u, timestamp=%u, sender(num)=%u, text=\"%s\"", static_cast<uint32_t>(i), m.timestamp, m.sender,
m.text.c_str());
} }
f.close(); f.close();
+1 -1
View File
@@ -31,7 +31,7 @@ class MessageStore
}; };
MessageStore() = delete; MessageStore() = delete;
explicit MessageStore(std::string label); // Label determines filename in flash explicit MessageStore(const std::string &label); // Label determines filename in flash
void saveToFlash(); void saveToFlash();
void loadFromFlash(); void loadFromFlash();
+13 -13
View File
@@ -269,42 +269,42 @@ void InkHUD::Renderer::clearTile(Tile *t)
// Rotate the tile dimensions // Rotate the tile dimensions
int16_t left = 0; int16_t left = 0;
int16_t top = 0; int16_t top = 0;
uint16_t width = 0; uint16_t tileW = 0;
uint16_t height = 0; uint16_t tileH = 0;
switch (settings->rotation) { switch (settings->rotation) {
case 0: case 0:
left = t->getLeft(); left = t->getLeft();
top = t->getTop(); top = t->getTop();
width = t->getWidth(); tileW = t->getWidth();
height = t->getHeight(); tileH = t->getHeight();
break; break;
case 1: case 1:
left = driver->width - (t->getTop() + t->getHeight()); left = driver->width - (t->getTop() + t->getHeight());
top = t->getLeft(); top = t->getLeft();
width = t->getHeight(); tileW = t->getHeight();
height = t->getWidth(); tileH = t->getWidth();
break; break;
case 2: case 2:
left = driver->width - (t->getLeft() + t->getWidth()); left = driver->width - (t->getLeft() + t->getWidth());
top = driver->height - (t->getTop() + t->getHeight()); top = driver->height - (t->getTop() + t->getHeight());
width = t->getWidth(); tileW = t->getWidth();
height = t->getHeight(); tileH = t->getHeight();
break; break;
case 3: case 3:
left = t->getTop(); left = t->getTop();
top = driver->height - (t->getLeft() + t->getWidth()); top = driver->height - (t->getLeft() + t->getWidth());
width = t->getHeight(); tileW = t->getHeight();
height = t->getWidth(); tileH = t->getWidth();
break; break;
} }
// Calculate the bounds to clear // Calculate the bounds to clear
uint16_t xStart = (left < 0) ? 0 : left; uint16_t xStart = (left < 0) ? 0 : left;
uint16_t yStart = (top < 0) ? 0 : top; uint16_t yStart = (top < 0) ? 0 : top;
if (xStart >= driver->width || yStart >= driver->height || left + width < 0 || top + height < 0) if (xStart >= driver->width || yStart >= driver->height || left + tileW < 0 || top + tileH < 0)
return; // the box is completely off the screen return; // the box is completely off the screen
uint16_t xEnd = left + width; uint16_t xEnd = left + tileW;
uint16_t yEnd = top + height; uint16_t yEnd = top + tileH;
if (xEnd > driver->width) if (xEnd > driver->width)
xEnd = driver->width; xEnd = driver->width;
if (yEnd > driver->height) if (yEnd > driver->height)
+1 -1
View File
@@ -396,7 +396,7 @@ void InkHUD::WindowManager::autoshow()
{ {
// Don't perform autoshow if a system applet has exclusive use of the display right now // Don't perform autoshow if a system applet has exclusive use of the display right now
// Note: lockRequests prevents autoshow attempting to hide menuApplet // Note: lockRequests prevents autoshow attempting to hide menuApplet
for (SystemApplet *sa : inkhud->systemApplets) { for (const SystemApplet *sa : inkhud->systemApplets) {
if (sa->lockRendering || sa->lockRequests) if (sa->lockRendering || sa->lockRequests)
return; return;
} }
@@ -146,7 +146,7 @@ void CannedMessageStore::handleGet(meshtastic_AdminMessage *response)
std::string merged; std::string merged;
if (!messages.empty()) { // Don't run if no messages: error on pop_back with size=0 if (!messages.empty()) { // Don't run if no messages: error on pop_back with size=0
merged.reserve(201); merged.reserve(201);
for (std::string &s : messages) { for (const std::string &s : messages) {
merged += s; merged += s;
merged += '|'; merged += '|';
} }
+1 -2
View File
@@ -63,7 +63,6 @@ void TCA8418Keyboard::pressed(uint8_t key)
if (state == Init || state == Busy) { if (state == Init || state == Busy) {
return; return;
} }
uint8_t next_key = 0;
int row = (key - 1) / 10; int row = (key - 1) / 10;
int col = (key - 1) % 10; int col = (key - 1) % 10;
@@ -72,7 +71,7 @@ void TCA8418Keyboard::pressed(uint8_t key)
} }
// Compute key index based on dynamic row/column // Compute key index based on dynamic row/column
next_key = row * _TCA8418_COLS + col; next_key = (int8_t)(row * _TCA8418_COLS + col);
// LOG_DEBUG("TCA8418: Key %u -> Next Key %u", key, next_key); // LOG_DEBUG("TCA8418: Key %u -> Next Key %u", key, next_key);
+6 -9
View File
@@ -248,9 +248,8 @@ uint32_t timeLastPowered = 0;
static OSThread *powerFSMthread; static OSThread *powerFSMthread;
OSThread *ambientLightingThread; OSThread *ambientLightingThread;
#ifdef ARCH_PORTDUINO RadioInterface *rIf = NULL;
RadioLibHal *RadioLibHAL = NULL; RadioLibHal *RadioLibHAL = NULL;
#endif
/** /**
* Some platforms (nrf52) might provide an alterate version that suppresses calling delay from sleep. * Some platforms (nrf52) might provide an alterate version that suppresses calling delay from sleep.
@@ -724,17 +723,15 @@ void setup()
playStartMelody(); playStartMelody();
#if HAS_SCREEN #if HAS_SCREEN
// fixed screen override? // fixed screen override?
if (config.display.oled != meshtastic_Config_DisplayConfig_OledType_OLED_AUTO)
screen_model = config.display.oled;
#if defined(USE_SH1107) #if defined(USE_SH1107)
screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1107; // set dimension of 128x128 screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1107; // set dimension of 128x128
screen_geometry = GEOMETRY_128_128; screen_geometry = GEOMETRY_128_128;
#endif #elif defined(USE_SH1107_128_64)
#if defined(USE_SH1107_128_64)
screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1107; // keep dimension of 128x64 screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1107; // keep dimension of 128x64
#else
if (config.display.oled != meshtastic_Config_DisplayConfig_OledType_OLED_AUTO)
screen_model = config.display.oled;
#endif #endif
#endif #endif
+7 -5
View File
@@ -814,26 +814,28 @@ void NodeDB::installDefaultModuleConfig()
moduleConfig.has_store_forward = true; moduleConfig.has_store_forward = true;
moduleConfig.has_telemetry = true; moduleConfig.has_telemetry = true;
moduleConfig.has_external_notification = true; moduleConfig.has_external_notification = true;
#if defined(PIN_BUZZER) #if defined(PIN_BUZZER) || defined(PIN_VIBRATION) || defined(LED_NOTIFICATION)
moduleConfig.external_notification.enabled = true; moduleConfig.external_notification.enabled = true;
#endif
#if defined(PIN_BUZZER)
moduleConfig.external_notification.output_buzzer = PIN_BUZZER; moduleConfig.external_notification.output_buzzer = PIN_BUZZER;
moduleConfig.external_notification.use_pwm = true; moduleConfig.external_notification.use_pwm = true;
moduleConfig.external_notification.alert_message_buzzer = true; moduleConfig.external_notification.alert_message_buzzer = true;
moduleConfig.external_notification.nag_timeout = default_ringtone_nag_secs;
#endif #endif
#if defined(PIN_VIBRATION) #if defined(PIN_VIBRATION)
moduleConfig.external_notification.enabled = true;
moduleConfig.external_notification.output_vibra = PIN_VIBRATION; moduleConfig.external_notification.output_vibra = PIN_VIBRATION;
moduleConfig.external_notification.alert_message_vibra = true; moduleConfig.external_notification.alert_message_vibra = true;
moduleConfig.external_notification.output_ms = 500; moduleConfig.external_notification.output_ms = 500;
moduleConfig.external_notification.nag_timeout = 2;
#endif #endif
#if defined(LED_NOTIFICATION) #if defined(LED_NOTIFICATION)
moduleConfig.external_notification.enabled = true;
moduleConfig.external_notification.output = LED_NOTIFICATION; moduleConfig.external_notification.output = LED_NOTIFICATION;
moduleConfig.external_notification.active = LED_STATE_ON; moduleConfig.external_notification.active = LED_STATE_ON;
moduleConfig.external_notification.alert_message = true; moduleConfig.external_notification.alert_message = true;
moduleConfig.external_notification.output_ms = 1000; moduleConfig.external_notification.output_ms = 1000;
#endif
#if defined(PIN_VIBRATION)
moduleConfig.external_notification.nag_timeout = 2;
#elif defined(PIN_BUZZER) || defined(LED_NOTIFICATION)
moduleConfig.external_notification.nag_timeout = default_ringtone_nag_secs; moduleConfig.external_notification.nag_timeout = default_ringtone_nag_secs;
#endif #endif
+2 -2
View File
@@ -439,7 +439,7 @@ void PacketHistory::removeRelayer(const uint8_t relayer, const uint32_t id, cons
} }
// Getters and setters for hop limit fields packed in hop_limit // Getters and setters for hop limit fields packed in hop_limit
inline uint8_t PacketHistory::getHighestHopLimit(PacketRecord &r) inline uint8_t PacketHistory::getHighestHopLimit(const PacketRecord &r)
{ {
return r.hop_limit & HOP_LIMIT_HIGHEST_MASK; return r.hop_limit & HOP_LIMIT_HIGHEST_MASK;
} }
@@ -449,7 +449,7 @@ inline void PacketHistory::setHighestHopLimit(PacketRecord &r, uint8_t hopLimit)
r.hop_limit = (r.hop_limit & ~HOP_LIMIT_HIGHEST_MASK) | (hopLimit & HOP_LIMIT_HIGHEST_MASK); r.hop_limit = (r.hop_limit & ~HOP_LIMIT_HIGHEST_MASK) | (hopLimit & HOP_LIMIT_HIGHEST_MASK);
} }
inline uint8_t PacketHistory::getOurTxHopLimit(PacketRecord &r) inline uint8_t PacketHistory::getOurTxHopLimit(const PacketRecord &r)
{ {
return (r.hop_limit & HOP_LIMIT_OUR_TX_MASK) >> HOP_LIMIT_OUR_TX_SHIFT; return (r.hop_limit & HOP_LIMIT_OUR_TX_MASK) >> HOP_LIMIT_OUR_TX_SHIFT;
} }
+2 -2
View File
@@ -43,9 +43,9 @@ class PacketHistory
* @return true if node was indeed a relayer, false if not */ * @return true if node was indeed a relayer, false if not */
bool wasRelayer(const uint8_t relayer, const PacketRecord &r, bool *wasSole = nullptr); bool wasRelayer(const uint8_t relayer, const PacketRecord &r, bool *wasSole = nullptr);
uint8_t getHighestHopLimit(PacketRecord &r); uint8_t getHighestHopLimit(const PacketRecord &r);
void setHighestHopLimit(PacketRecord &r, uint8_t hopLimit); void setHighestHopLimit(PacketRecord &r, uint8_t hopLimit);
uint8_t getOurTxHopLimit(PacketRecord &r); uint8_t getOurTxHopLimit(const PacketRecord &r);
void setOurTxHopLimit(PacketRecord &r, uint8_t hopLimit); void setOurTxHopLimit(PacketRecord &r, uint8_t hopLimit);
PacketHistory(const PacketHistory &); // non construction-copyable PacketHistory(const PacketHistory &); // non construction-copyable
+19 -21
View File
@@ -237,9 +237,9 @@ std::unique_ptr<RadioInterface> initLoRa()
std::unique_ptr<RadioInterface> rIf = nullptr; std::unique_ptr<RadioInterface> rIf = nullptr;
#if ARCH_PORTDUINO #if ARCH_PORTDUINO
SPISettings spiSettings(portduino_config.spiSpeed, MSBFIRST, SPI_MODE0); SPISettings loraSpiSettings(portduino_config.spiSpeed, MSBFIRST, SPI_MODE0);
#else #else
SPISettings spiSettings(4000000, MSBFIRST, SPI_MODE0); SPISettings loraSpiSettings(4000000, MSBFIRST, SPI_MODE0);
#endif #endif
#ifdef ARCH_PORTDUINO #ifdef ARCH_PORTDUINO
@@ -280,7 +280,7 @@ std::unique_ptr<RadioInterface> initLoRa()
delete RadioLibHAL; delete RadioLibHAL;
RadioLibHAL = nullptr; RadioLibHAL = nullptr;
} }
RadioLibHAL = new LockingArduinoHal(SPI, spiSettings); RadioLibHAL = new LockingArduinoHal(SPI, loraSpiSettings);
} }
rIf = rIf =
loraModuleInterface((LockingArduinoHal *)RadioLibHAL, portduino_config.lora_cs_pin.pin, portduino_config.lora_irq_pin.pin, loraModuleInterface((LockingArduinoHal *)RadioLibHAL, portduino_config.lora_cs_pin.pin, portduino_config.lora_irq_pin.pin,
@@ -295,16 +295,18 @@ std::unique_ptr<RadioInterface> initLoRa()
} }
#elif defined(HW_SPI1_DEVICE) #elif defined(HW_SPI1_DEVICE)
LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI1, spiSettings); LockingArduinoHal *loraHal = new LockingArduinoHal(SPI1, loraSpiSettings);
RadioLibHAL = loraHal;
#else // HW_SPI1_DEVICE #else // HW_SPI1_DEVICE
LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI, spiSettings); LockingArduinoHal *loraHal = new LockingArduinoHal(SPI, loraSpiSettings);
RadioLibHAL = loraHal;
#endif #endif
// radio init MUST BE AFTER service.init, so we have our radio config settings (from nodedb init) // radio init MUST BE AFTER service.init, so we have our radio config settings (from nodedb init)
#if defined(USE_STM32WLx) #if defined(USE_STM32WLx)
if (!rIf) { if (!rIf) {
rIf = std::unique_ptr<STM32WLE5JCInterface>( rIf = std::unique_ptr<STM32WLE5JCInterface>(
new STM32WLE5JCInterface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY)); new STM32WLE5JCInterface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No STM32WL radio"); LOG_WARN("No STM32WL radio");
rIf = nullptr; rIf = nullptr;
@@ -317,7 +319,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(RF95_IRQ) && RADIOLIB_EXCLUDE_SX127X != 1 #if defined(RF95_IRQ) && RADIOLIB_EXCLUDE_SX127X != 1
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
rIf = std::unique_ptr<RF95Interface>(new RF95Interface(RadioLibHAL, LORA_CS, RF95_IRQ, RF95_RESET, RF95_DIO1)); rIf = std::unique_ptr<RF95Interface>(new RF95Interface(loraHal, LORA_CS, RF95_IRQ, RF95_RESET, RF95_DIO1));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No RF95 radio"); LOG_WARN("No RF95 radio");
rIf = nullptr; rIf = nullptr;
@@ -331,7 +333,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_SX1262) && !defined(ARCH_PORTDUINO) && !defined(TCXO_OPTIONAL) && RADIOLIB_EXCLUDE_SX126X != 1 #if defined(USE_SX1262) && !defined(ARCH_PORTDUINO) && !defined(TCXO_OPTIONAL) && RADIOLIB_EXCLUDE_SX126X != 1
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
auto sxIf = auto sxIf =
std::unique_ptr<SX1262Interface>(new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY)); std::unique_ptr<SX1262Interface>(new SX1262Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
#ifdef SX126X_DIO3_TCXO_VOLTAGE #ifdef SX126X_DIO3_TCXO_VOLTAGE
sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE); sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE);
#endif #endif
@@ -350,7 +352,7 @@ std::unique_ptr<RadioInterface> initLoRa()
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
// try using the specified TCXO voltage // try using the specified TCXO voltage
auto sxIf = auto sxIf =
std::unique_ptr<SX1262Interface>(new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY)); std::unique_ptr<SX1262Interface>(new SX1262Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE); sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE);
if (!sxIf->init()) { if (!sxIf->init()) {
LOG_WARN("No SX1262 radio with TCXO, Vref %fV", SX126X_DIO3_TCXO_VOLTAGE); LOG_WARN("No SX1262 radio with TCXO, Vref %fV", SX126X_DIO3_TCXO_VOLTAGE);
@@ -364,8 +366,7 @@ std::unique_ptr<RadioInterface> initLoRa()
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
// If specified TCXO voltage fails, attempt to use DIO3 as a reference instead // If specified TCXO voltage fails, attempt to use DIO3 as a reference instead
rIf = rIf = std::unique_ptr<SX1262Interface>(new SX1262Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
std::unique_ptr<SX1262Interface>(new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No SX1262 radio with XTAL, Vref 0.0V"); LOG_WARN("No SX1262 radio with XTAL, Vref 0.0V");
rIf = nullptr; rIf = nullptr;
@@ -381,7 +382,7 @@ std::unique_ptr<RadioInterface> initLoRa()
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
// try using the specified TCXO voltage // try using the specified TCXO voltage
auto sxIf = auto sxIf =
std::unique_ptr<SX1268Interface>(new SX1268Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY)); std::unique_ptr<SX1268Interface>(new SX1268Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE); sxIf->setTCXOVoltage(SX126X_DIO3_TCXO_VOLTAGE);
if (!sxIf->init()) { if (!sxIf->init()) {
LOG_WARN("No SX1268 radio with TCXO, Vref %fV", SX126X_DIO3_TCXO_VOLTAGE); LOG_WARN("No SX1268 radio with TCXO, Vref %fV", SX126X_DIO3_TCXO_VOLTAGE);
@@ -394,8 +395,7 @@ std::unique_ptr<RadioInterface> initLoRa()
} }
#endif #endif
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
rIf = rIf = std::unique_ptr<SX1268Interface>(new SX1268Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
std::unique_ptr<SX1268Interface>(new SX1268Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No SX1268 radio"); LOG_WARN("No SX1268 radio");
rIf = nullptr; rIf = nullptr;
@@ -408,8 +408,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_LLCC68) #if defined(USE_LLCC68)
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
rIf = rIf = std::unique_ptr<LLCC68Interface>(new LLCC68Interface(loraHal, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
std::unique_ptr<LLCC68Interface>(new LLCC68Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No LLCC68 radio"); LOG_WARN("No LLCC68 radio");
rIf = nullptr; rIf = nullptr;
@@ -423,7 +422,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_LR1110) && RADIOLIB_EXCLUDE_LR11X0 != 1 #if defined(USE_LR1110) && RADIOLIB_EXCLUDE_LR11X0 != 1
if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) {
rIf = std::unique_ptr<LR1110Interface>( rIf = std::unique_ptr<LR1110Interface>(
new LR1110Interface(RadioLibHAL, LR1110_SPI_NSS_PIN, LR1110_IRQ_PIN, LR1110_NRESET_PIN, LR1110_BUSY_PIN)); new LR1110Interface(loraHal, LR1110_SPI_NSS_PIN, LR1110_IRQ_PIN, LR1110_NRESET_PIN, LR1110_BUSY_PIN));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No LR1110 radio"); LOG_WARN("No LR1110 radio");
rIf = nullptr; rIf = nullptr;
@@ -437,7 +436,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_LR1120) && RADIOLIB_EXCLUDE_LR11X0 != 1 #if defined(USE_LR1120) && RADIOLIB_EXCLUDE_LR11X0 != 1
if (!rIf) { if (!rIf) {
rIf = std::unique_ptr<LR1120Interface>( rIf = std::unique_ptr<LR1120Interface>(
new LR1120Interface(RadioLibHAL, LR1120_SPI_NSS_PIN, LR1120_IRQ_PIN, LR1120_NRESET_PIN, LR1120_BUSY_PIN)); new LR1120Interface(loraHal, LR1120_SPI_NSS_PIN, LR1120_IRQ_PIN, LR1120_NRESET_PIN, LR1120_BUSY_PIN));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No LR1120 radio"); LOG_WARN("No LR1120 radio");
rIf = nullptr; rIf = nullptr;
@@ -451,7 +450,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_LR1121) && RADIOLIB_EXCLUDE_LR11X0 != 1 #if defined(USE_LR1121) && RADIOLIB_EXCLUDE_LR11X0 != 1
if (!rIf) { if (!rIf) {
rIf = std::unique_ptr<LR1121Interface>( rIf = std::unique_ptr<LR1121Interface>(
new LR1121Interface(RadioLibHAL, LR1121_SPI_NSS_PIN, LR1121_IRQ_PIN, LR1121_NRESET_PIN, LR1121_BUSY_PIN)); new LR1121Interface(loraHal, LR1121_SPI_NSS_PIN, LR1121_IRQ_PIN, LR1121_NRESET_PIN, LR1121_BUSY_PIN));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No LR1121 radio"); LOG_WARN("No LR1121 radio");
rIf = nullptr; rIf = nullptr;
@@ -464,8 +463,7 @@ std::unique_ptr<RadioInterface> initLoRa()
#if defined(USE_SX1280) && RADIOLIB_EXCLUDE_SX128X != 1 #if defined(USE_SX1280) && RADIOLIB_EXCLUDE_SX128X != 1
if (!rIf) { if (!rIf) {
rIf = rIf = std::unique_ptr<SX1280Interface>(new SX1280Interface(loraHal, SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY));
std::unique_ptr<SX1280Interface>(new SX1280Interface(RadioLibHAL, SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY));
if (!rIf->init()) { if (!rIf->init()) {
LOG_WARN("No SX1280 radio"); LOG_WARN("No SX1280 radio");
rIf = nullptr; rIf = nullptr;
+2 -2
View File
@@ -27,7 +27,7 @@ int32_t StreamAPI::runOncePart(char *buf, uint16_t bufLen)
/** /**
* Read any rx chars from the link and call handleRecStream * Read any rx chars from the link and call handleRecStream
*/ */
int32_t StreamAPI::readStream(char *buf, uint16_t bufLen) int32_t StreamAPI::readStream(const char *buf, uint16_t bufLen)
{ {
if (bufLen < 1) { if (bufLen < 1) {
// Nothing available this time, if the computer has talked to us recently, poll often, otherwise let CPU sleep a long time // Nothing available this time, if the computer has talked to us recently, poll often, otherwise let CPU sleep a long time
@@ -56,7 +56,7 @@ void StreamAPI::writeStream()
} }
} }
int32_t StreamAPI::handleRecStream(char *buf, uint16_t bufLen) int32_t StreamAPI::handleRecStream(const char *buf, uint16_t bufLen)
{ {
uint16_t index = 0; uint16_t index = 0;
while (bufLen > index) { // Currently we never want to block while (bufLen > index) { // Currently we never want to block
+2 -2
View File
@@ -57,8 +57,8 @@ class StreamAPI : public PhoneAPI
* Read any rx chars from the link and call handleToRadio * Read any rx chars from the link and call handleToRadio
*/ */
int32_t readStream(); int32_t readStream();
int32_t readStream(char *buf, uint16_t bufLen); int32_t readStream(const char *buf, uint16_t bufLen);
int32_t handleRecStream(char *buf, uint16_t bufLen); int32_t handleRecStream(const char *buf, uint16_t bufLen);
/** /**
* call getFromRadio() and deliver encapsulated packets to the Stream * call getFromRadio() and deliver encapsulated packets to the Stream
+1 -1
View File
@@ -33,7 +33,7 @@ static int constant_time_compare(const void *a_, const void *b_, size_t len)
d |= (a[i] ^ b[i]); d |= (a[i] ^ b[i]);
} }
/* Constant time bit arithmetic to convert d > 0 to -1 and d = 0 to 0. */ /* Constant time bit arithmetic to convert d > 0 to -1 and d = 0 to 0. */
return (1 & ((d - 1) >> 8)) - 1; return (1 & (((unsigned int)d - 1) >> 8)) - 1;
} }
static void WPA_PUT_BE16(uint8_t *a, uint16_t val) static void WPA_PUT_BE16(uint8_t *a, uint16_t val)
+1 -1
View File
@@ -17,7 +17,7 @@ class PacketAPI : public PhoneAPI, public concurrency::OSThread
virtual int32_t runOnce(); virtual int32_t runOnce();
protected: protected:
PacketAPI(PacketServer *_server); explicit PacketAPI(PacketServer *_server);
// Check the current underlying physical queue to see if the client is fetching packets // Check the current underlying physical queue to see if the client is fetching packets
bool checkIsConnected() override; bool checkIsConnected() override;
+1 -1
View File
@@ -623,7 +623,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res)
} }
// Helper lambda to create JSON array and clean up memory properly // Helper lambda to create JSON array and clean up memory properly
auto createJSONArrayFromLog = [](uint32_t *logArray, int count) -> JSONValue * { auto createJSONArrayFromLog = [](const uint32_t *logArray, int count) -> JSONValue * {
JSONArray tempArray; JSONArray tempArray;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
tempArray.push_back(new JSONValue((int)logArray[i])); tempArray.push_back(new JSONValue((int)logArray[i]));
+4 -7
View File
@@ -1209,14 +1209,13 @@ int32_t CannedMessageModule::runOnce()
this->cursor = 0; this->cursor = 0;
// Tell Screen to jump straight to the TextMessage frame // Tell Screen to jump straight to the TextMessage frame
UIFrameEvent e;
e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE; e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE;
this->notifyObservers(&e); this->notifyObservers(&e);
// Now deactivate this module // Now deactivate this module
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
return INT32_MAX; // dont fall back into canned list return INT32_MAX; // don't fall back into canned list
} else { } else {
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
} }
@@ -1237,14 +1236,13 @@ int32_t CannedMessageModule::runOnce()
this->cursor = 0; this->cursor = 0;
// Tell Screen to jump straight to the TextMessage frame // Tell Screen to jump straight to the TextMessage frame
UIFrameEvent e;
e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE; e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE;
this->notifyObservers(&e); this->notifyObservers(&e);
// Now deactivate this module // Now deactivate this module
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
return INT32_MAX; // dont fall back into canned list return INT32_MAX; // don't fall back into canned list
} }
} else { } else {
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
@@ -1255,11 +1253,10 @@ int32_t CannedMessageModule::runOnce()
this->freetext = ""; this->freetext = "";
this->cursor = 0; this->cursor = 0;
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET; e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->notifyObservers(&e); this->notifyObservers(&e);
// Immediately stop, dont linger on canned screen // Immediately stop, don't linger on canned screen
return INT32_MAX; return INT32_MAX;
} }
// Highlight [Select Destination] initially when entering the message list // Highlight [Select Destination] initially when entering the message list
@@ -2070,7 +2067,7 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st
// Draw lines with emotes // Draw lines with emotes
int rowHeight = FONT_HEIGHT_SMALL; int rowHeight = FONT_HEIGHT_SMALL;
int yLine = inputY; int yLine = inputY;
for (auto &line : lines) { for (const auto &line : lines) {
int nextX = x; int nextX = x;
for (const auto &token : line) { for (const auto &token : line) {
if (token.first) { if (token.first) {
+1 -1
View File
@@ -367,7 +367,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP
} }
} }
meshtastic_NodeInfoLite *sender = nodeDB->getMeshNode(mp.from); const meshtastic_NodeInfoLite *sender = nodeDB->getMeshNode(mp.from);
meshtastic_Channel ch = channels.getByIndex(mp.channel ? mp.channel : channels.getPrimaryIndex()); meshtastic_Channel ch = channels.getByIndex(mp.channel ? mp.channel : channels.getPrimaryIndex());
// If we receive a broadcast message, apply channel mute setting // If we receive a broadcast message, apply channel mute setting
+9 -14
View File
@@ -23,7 +23,6 @@ int StatusLEDModule::handleStatusUpdate(const meshtastic::Status *arg)
{ {
switch (arg->getStatusType()) { switch (arg->getStatusType()) {
case STATUS_TYPE_POWER: { case STATUS_TYPE_POWER: {
meshtastic::PowerStatus *powerStatus = (meshtastic::PowerStatus *)arg;
if (powerStatus->getHasUSB() || powerStatus->getIsCharging()) { if (powerStatus->getHasUSB() || powerStatus->getIsCharging()) {
power_state = charging; power_state = charging;
if (powerStatus->getBatteryChargePercent() >= 100) { if (powerStatus->getBatteryChargePercent() >= 100) {
@@ -39,7 +38,6 @@ int StatusLEDModule::handleStatusUpdate(const meshtastic::Status *arg)
break; break;
} }
case STATUS_TYPE_BLUETOOTH: { case STATUS_TYPE_BLUETOOTH: {
meshtastic::BluetoothStatus *bluetoothStatus = (meshtastic::BluetoothStatus *)arg;
switch (bluetoothStatus->getConnectionState()) { switch (bluetoothStatus->getConnectionState()) {
case meshtastic::BluetoothStatus::ConnectionState::DISCONNECTED: { case meshtastic::BluetoothStatus::ConnectionState::DISCONNECTED: {
ble_state = unpaired; ble_state = unpaired;
@@ -199,33 +197,30 @@ void StatusLEDModule::setPowerLED(bool LEDon)
PMU->setChargingLedMode(LEDon ? XPOWERS_CHG_LED_ON : XPOWERS_CHG_LED_OFF); PMU->setChargingLedMode(LEDon ? XPOWERS_CHG_LED_ON : XPOWERS_CHG_LED_OFF);
} }
#endif #endif
if (LEDon) uint8_t ledState = LEDon ? LED_STATE_ON : LED_STATE_OFF;
LEDon = LED_STATE_ON;
else
LEDon = LED_STATE_OFF;
#ifdef PCA_LED_POWER #ifdef PCA_LED_POWER
io.digitalWrite(PCA_LED_POWER, LEDon); io.digitalWrite(PCA_LED_POWER, ledState);
#endif #endif
#ifdef PCA_LED_ENABLE #ifdef PCA_LED_ENABLE
io.digitalWrite(PCA_LED_ENABLE, LEDon); io.digitalWrite(PCA_LED_ENABLE, ledState);
#endif #endif
#ifdef LED_POWER #ifdef LED_POWER
digitalWrite(LED_POWER, LEDon); digitalWrite(LED_POWER, ledState);
#endif #endif
#ifdef LED_PAIRING #ifdef LED_PAIRING
digitalWrite(LED_PAIRING, LEDon); digitalWrite(LED_PAIRING, ledState);
#endif #endif
#ifdef Battery_LED_1 #ifdef Battery_LED_1
digitalWrite(Battery_LED_1, LEDon); digitalWrite(Battery_LED_1, ledState);
#endif #endif
#ifdef Battery_LED_2 #ifdef Battery_LED_2
digitalWrite(Battery_LED_2, LEDon); digitalWrite(Battery_LED_2, ledState);
#endif #endif
#ifdef Battery_LED_3 #ifdef Battery_LED_3
digitalWrite(Battery_LED_3, LEDon); digitalWrite(Battery_LED_3, ledState);
#endif #endif
#ifdef Battery_LED_4 #ifdef Battery_LED_4
digitalWrite(Battery_LED_4, LEDon); digitalWrite(Battery_LED_4, ledState);
#endif #endif
} }
+1 -3
View File
@@ -131,9 +131,7 @@ void StoreForwardModule::historySend(uint32_t secAgo, uint32_t to)
uint32_t StoreForwardModule::getNumAvailablePackets(NodeNum dest, uint32_t last_time) uint32_t StoreForwardModule::getNumAvailablePackets(NodeNum dest, uint32_t last_time)
{ {
uint32_t count = 0; uint32_t count = 0;
if (lastRequest.find(dest) == lastRequest.end()) { lastRequest.emplace(dest, 0);
lastRequest.emplace(dest, 0);
}
for (uint32_t i = lastRequest[dest]; i < this->packetHistoryTotalCount; i++) { for (uint32_t i = lastRequest[dest]; i < this->packetHistoryTotalCount; i++) {
if (this->packetHistory[i].time && (this->packetHistory[i].time > last_time)) { if (this->packetHistory[i].time && (this->packetHistory[i].time > last_time)) {
// Client is only interested in packets not from itself and only in broadcast packets or packets towards it. // Client is only interested in packets not from itself and only in broadcast packets or packets towards it.
@@ -8,7 +8,7 @@
static std::forward_list<TelemetrySensor *> sensors; static std::forward_list<TelemetrySensor *> sensors;
template <typename T> void addSensor(ScanI2C *i2cScanner, ScanI2C::DeviceType type) template <typename T> void addSensor(const ScanI2C *i2cScanner, ScanI2C::DeviceType type)
{ {
ScanI2C::FoundDevice dev = i2cScanner->find(type); ScanI2C::FoundDevice dev = i2cScanner->find(type);
if (dev.type != ScanI2C::DeviceType::NONE || type == ScanI2C::DeviceType::NONE) { if (dev.type != ScanI2C::DeviceType::NONE || type == ScanI2C::DeviceType::NONE) {
@@ -86,7 +86,7 @@ bool PMSA003ISensor::getMetrics(meshtastic_Telemetry *measurement)
return false; return false;
} }
auto read16 = [](uint8_t *data, uint8_t idx) -> uint16_t { return (data[idx] << 8) | data[idx + 1]; }; auto read16 = [](const uint8_t *data, uint8_t idx) -> uint16_t { return (data[idx] << 8) | data[idx + 1]; };
computedChecksum = 0; computedChecksum = 0;
+2 -2
View File
@@ -111,7 +111,7 @@ bool SCD4XSensor::getMetrics(meshtastic_Telemetry *measurement)
bool dataReady; bool dataReady;
error = scd4x.getDataReadyStatus(dataReady); error = scd4x.getDataReadyStatus(dataReady);
if (!dataReady) { if (error != SCD4X_NO_ERROR || !dataReady) {
#if defined(SCD4X_I2C_CLOCK_SPEED) && defined(CAN_RECLOCK_I2C) #if defined(SCD4X_I2C_CLOCK_SPEED) && defined(CAN_RECLOCK_I2C)
reClockI2C(currentClock, _bus, false); reClockI2C(currentClock, _bus, false);
#endif #endif
@@ -419,7 +419,7 @@ bool SCD4XSensor::setTemperature(float tempReference)
LOG_INFO("%s: Setting reference temperature at: %.2f", sensorName, tempReference); LOG_INFO("%s: Setting reference temperature at: %.2f", sensorName, tempReference);
error = scd4x.getDataReadyStatus(dataReady); error = scd4x.getDataReadyStatus(dataReady);
if (!dataReady) { if (error != SCD4X_NO_ERROR || !dataReady) {
LOG_ERROR("%s: Data is not ready", sensorName); LOG_ERROR("%s: Data is not ready", sensorName);
return false; return false;
} }
+1 -1
View File
@@ -182,7 +182,7 @@ uint8_t SEN5XSensor::readBuffer(uint8_t *buffer, uint8_t byteNumber)
return receivedBytes; return receivedBytes;
} }
uint8_t SEN5XSensor::sen5xCRC(uint8_t *buffer) uint8_t SEN5XSensor::sen5xCRC(const uint8_t *buffer)
{ {
// This code is based on Sensirion's own implementation // This code is based on Sensirion's own implementation
// https://github.com/Sensirion/arduino-core/blob/41fd02cacf307ec4945955c58ae495e56809b96c/src/SensirionCrc.cpp // https://github.com/Sensirion/arduino-core/blob/41fd02cacf307ec4945955c58ae495e56809b96c/src/SensirionCrc.cpp
+1 -1
View File
@@ -114,7 +114,7 @@ See: https://sensirion.com/resource/application_note/low_power_mode/sen5x
bool sendCommand(uint16_t command); bool sendCommand(uint16_t command);
bool sendCommand(uint16_t command, uint8_t *buffer, uint8_t byteNumber = 0); bool sendCommand(uint16_t command, uint8_t *buffer, uint8_t byteNumber = 0);
uint8_t readBuffer(uint8_t *buffer, uint8_t byteNumber); // Return number of bytes received uint8_t readBuffer(uint8_t *buffer, uint8_t byteNumber); // Return number of bytes received
uint8_t sen5xCRC(uint8_t *buffer); uint8_t sen5xCRC(const uint8_t *buffer);
bool startCleaning(); bool startCleaning();
uint8_t getMeasurements(); uint8_t getMeasurements();
// bool readRawValues(); // bool readRawValues();
+1 -1
View File
@@ -266,7 +266,7 @@ void TraceRouteModule::alterReceivedProtobuf(meshtastic_MeshPacket &p, meshtasti
} }
} }
void TraceRouteModule::updateNextHops(meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r) void TraceRouteModule::updateNextHops(const meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r)
{ {
// E.g. if the route is A->B->C->D and we are B, we can set C as next-hop for C and D // E.g. if the route is A->B->C->D and we are B, we can set C as next-hop for C and D
// Similarly, if we are C, we can set D as next-hop for D // Similarly, if we are C, we can set D as next-hop for D
+1 -1
View File
@@ -62,7 +62,7 @@ class TraceRouteModule : public ProtobufModule<meshtastic_RouteDiscovery>,
void appendMyIDandSNR(meshtastic_RouteDiscovery *r, float snr, bool isTowardsDestination, bool SNRonly); void appendMyIDandSNR(meshtastic_RouteDiscovery *r, float snr, bool isTowardsDestination, bool SNRonly);
// Update next-hops in the routing table based on the returned route // Update next-hops in the routing table based on the returned route
void updateNextHops(meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r); void updateNextHops(const meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r);
// Helper to update next-hop for a single node // Helper to update next-hop for a single node
void maybeSetNextHop(NodeNum target, uint8_t nextHopByte); void maybeSetNextHop(NodeNum target, uint8_t nextHopByte);
+1 -1
View File
@@ -75,7 +75,7 @@ bool getAppDesc(const esp_partition_t *part, esp_app_desc_t *app_desc)
return true; return true;
} }
bool checkOTACapability(esp_app_desc_t *app_desc, uint8_t method) bool checkOTACapability(const esp_app_desc_t *app_desc, uint8_t method)
{ {
// Combined loader supports all (both) transports, BLE and WiFi // Combined loader supports all (both) transports, BLE and WiFi
if (strcmp(app_desc->project_name, combinedAppProjectName) == 0) { if (strcmp(app_desc->project_name, combinedAppProjectName) == 0) {
+1 -1
View File
@@ -16,7 +16,7 @@ void initialize();
bool isUpdated(); bool isUpdated();
const esp_partition_t *getAppPartition(); const esp_partition_t *getAppPartition();
bool getAppDesc(const esp_partition_t *part, esp_app_desc_t *app_desc); bool getAppDesc(const esp_partition_t *part, esp_app_desc_t *app_desc);
bool checkOTACapability(esp_app_desc_t *app_desc, uint8_t method); bool checkOTACapability(const esp_app_desc_t *app_desc, uint8_t method);
void recoverConfig(meshtastic_Config_NetworkConfig *network); void recoverConfig(meshtastic_Config_NetworkConfig *network);
void saveConfig(meshtastic_Config_NetworkConfig *network, meshtastic_OTAMode method, uint8_t *ota_hash); void saveConfig(meshtastic_Config_NetworkConfig *network, meshtastic_OTAMode method, uint8_t *ota_hash);
bool trySwitchToOTA(); bool trySwitchToOTA();
+1 -1
View File
@@ -38,7 +38,7 @@ class AsyncUDP : public Print, private concurrency::OSThread
class AsyncUDPPacket class AsyncUDPPacket
{ {
public: public:
AsyncUDPPacket(EthernetUDP &source); explicit AsyncUDPPacket(EthernetUDP &source);
IPAddress remoteIP(); IPAddress remoteIP();
uint16_t length(); uint16_t length();
+6 -6
View File
@@ -496,7 +496,7 @@ void portduinoSetup()
randomSeed(time(NULL)); randomSeed(time(NULL));
std::string defaultGpioChipName = gpioChipName + std::to_string(portduino_config.lora_default_gpiochip); std::string defaultGpioChipName = gpioChipName + std::to_string(portduino_config.lora_default_gpiochip);
for (auto i : portduino_config.all_pins) { for (const auto *i : portduino_config.all_pins) {
if (i->enabled && i->pin > max_GPIO) if (i->enabled && i->pin > max_GPIO)
max_GPIO = i->pin; max_GPIO = i->pin;
} }
@@ -510,7 +510,7 @@ void portduinoSetup()
// Need to bind all the configured GPIO pins so they're not simulated // Need to bind all the configured GPIO pins so they're not simulated
// TODO: If one of these fails, we should log and terminate // TODO: If one of these fails, we should log and terminate
for (auto i : portduino_config.all_pins) { for (const auto *i : portduino_config.all_pins) {
// In the case of a ch341 Lora device, we don't want to touch the system GPIO lines for Lora // In the case of a ch341 Lora device, we don't want to touch the system GPIO lines for Lora
// Those GPIO are handled in our usermode driver instead. // Those GPIO are handled in our usermode driver instead.
if (i->config_section == "Lora" && portduino_config.lora_spi_dev == "ch341") { if (i->config_section == "Lora" && portduino_config.lora_spi_dev == "ch341") {
@@ -572,7 +572,7 @@ void portduinoSetup()
return; return;
} }
int initGPIOPin(int pinNum, const std::string gpioChipName, int line) int initGPIOPin(int pinNum, const std::string &gpioChipName, int line)
{ {
#ifdef PORTDUINO_LINUX_HARDWARE #ifdef PORTDUINO_LINUX_HARDWARE
std::string gpio_name = "GPIO" + std::to_string(pinNum); std::string gpio_name = "GPIO" + std::to_string(pinNum);
@@ -643,7 +643,7 @@ bool loadConfig(const char *configPath)
if (yamlConfig["Lora"]) { if (yamlConfig["Lora"]) {
if (yamlConfig["Lora"]["Module"]) { if (yamlConfig["Lora"]["Module"]) {
for (auto &loraModule : portduino_config.loraModules) { for (const auto &loraModule : portduino_config.loraModules) {
if (yamlConfig["Lora"]["Module"].as<std::string>("") == loraModule.second) { if (yamlConfig["Lora"]["Module"].as<std::string>("") == loraModule.second) {
portduino_config.lora_module = loraModule.first; portduino_config.lora_module = loraModule.first;
break; break;
@@ -777,7 +777,7 @@ bool loadConfig(const char *configPath)
} }
if (yamlConfig["Display"]) { if (yamlConfig["Display"]) {
for (auto &screen_name : portduino_config.screen_names) { for (const auto &screen_name : portduino_config.screen_names) {
if (yamlConfig["Display"]["Panel"].as<std::string>("") == screen_name.second) if (yamlConfig["Display"]["Panel"].as<std::string>("") == screen_name.second)
portduino_config.displayPanel = screen_name.first; portduino_config.displayPanel = screen_name.first;
} }
@@ -907,7 +907,7 @@ bool loadConfig(const char *configPath)
} }
if (checkConfigPort) { if (checkConfigPort) {
portduino_config.api_port = (yamlConfig["General"]["APIPort"]).as<int>(-1); portduino_config.api_port = (yamlConfig["General"]["APIPort"]).as<int>(-1);
if (portduino_config.api_port != -1 && portduino_config.api_port > 1023 && portduino_config.api_port < 65536) { if (portduino_config.api_port > 1023 && portduino_config.api_port < 65536) {
TCPPort = (portduino_config.api_port); TCPPort = (portduino_config.api_port);
} }
} }
+6 -6
View File
@@ -58,7 +58,7 @@ extern std::ofstream traceFile;
extern std::ofstream JSONFile; extern std::ofstream JSONFile;
extern Ch341Hal *ch341Hal; extern Ch341Hal *ch341Hal;
int initGPIOPin(int pinNum, std::string gpioChipname, int line); int initGPIOPin(int pinNum, const std::string &gpioChipname, int line);
bool loadConfig(const char *configPath); bool loadConfig(const char *configPath);
static bool ends_with(std::string_view str, std::string_view suffix); static bool ends_with(std::string_view str, std::string_view suffix);
void getMacAddr(uint8_t *dmac); void getMacAddr(uint8_t *dmac);
@@ -224,7 +224,7 @@ extern struct portduino_config_struct {
out << YAML::Key << "Lora" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Lora" << YAML::Value << YAML::BeginMap;
out << YAML::Key << "Module" << YAML::Value << loraModules[lora_module]; out << YAML::Key << "Module" << YAML::Value << loraModules[lora_module];
for (auto lora_pin : all_pins) { for (const auto *lora_pin : all_pins) {
if (lora_pin->config_section == "Lora" && lora_pin->enabled) { if (lora_pin->config_section == "Lora" && lora_pin->enabled) {
out << YAML::Key << lora_pin->config_name << YAML::Value << YAML::BeginMap; out << YAML::Key << lora_pin->config_name << YAML::Value << YAML::BeginMap;
out << YAML::Key << "pin" << YAML::Value << lora_pin->pin; out << YAML::Key << "pin" << YAML::Value << lora_pin->pin;
@@ -350,11 +350,11 @@ extern struct portduino_config_struct {
// Display // Display
if (displayPanel != no_screen) { if (displayPanel != no_screen) {
out << YAML::Key << "Display" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Display" << YAML::Value << YAML::BeginMap;
for (auto &screen_name : screen_names) { for (const auto &screen_name : screen_names) {
if (displayPanel == screen_name.first) if (displayPanel == screen_name.first)
out << YAML::Key << "Module" << YAML::Value << screen_name.second; out << YAML::Key << "Module" << YAML::Value << screen_name.second;
} }
for (auto display_pin : all_pins) { for (const auto *display_pin : all_pins) {
if (display_pin->config_section == "Display" && display_pin->enabled) { if (display_pin->config_section == "Display" && display_pin->enabled) {
out << YAML::Key << display_pin->config_name << YAML::Value << YAML::BeginMap; out << YAML::Key << display_pin->config_name << YAML::Value << YAML::BeginMap;
out << YAML::Key << "pin" << YAML::Value << display_pin->pin; out << YAML::Key << "pin" << YAML::Value << display_pin->pin;
@@ -402,7 +402,7 @@ extern struct portduino_config_struct {
case ft5x06: case ft5x06:
out << YAML::Key << "Module" << YAML::Value << "FT5x06"; out << YAML::Key << "Module" << YAML::Value << "FT5x06";
} }
for (auto touchscreen_pin : all_pins) { for (const auto *touchscreen_pin : all_pins) {
if (touchscreen_pin->config_section == "Touchscreen" && touchscreen_pin->enabled) { if (touchscreen_pin->config_section == "Touchscreen" && touchscreen_pin->enabled) {
out << YAML::Key << touchscreen_pin->config_name << YAML::Value << YAML::BeginMap; out << YAML::Key << touchscreen_pin->config_name << YAML::Value << YAML::BeginMap;
out << YAML::Key << "pin" << YAML::Value << touchscreen_pin->pin; out << YAML::Key << "pin" << YAML::Value << touchscreen_pin->pin;
@@ -425,7 +425,7 @@ extern struct portduino_config_struct {
if (pointerDevice != "") if (pointerDevice != "")
out << YAML::Key << "PointerDevice" << YAML::Value << pointerDevice; out << YAML::Key << "PointerDevice" << YAML::Value << pointerDevice;
for (auto input_pin : all_pins) { for (const auto *input_pin : all_pins) {
if (input_pin->config_section == "Input" && input_pin->enabled) { if (input_pin->config_section == "Input" && input_pin->enabled) {
out << YAML::Key << input_pin->config_name << YAML::Value << YAML::BeginMap; out << YAML::Key << input_pin->config_name << YAML::Value << YAML::BeginMap;
out << YAML::Key << "pin" << YAML::Value << input_pin->pin; out << YAML::Key << "pin" << YAML::Value << input_pin->pin;
+1 -1
View File
@@ -29,7 +29,7 @@ class Ch341Hal : public RadioLibHal
{ {
public: public:
// default constructor - initializes the base HAL and any needed private members // default constructor - initializes the base HAL and any needed private members
explicit Ch341Hal(uint8_t spiChannel, std::string serial = "", uint32_t vid = 0x1A86, uint32_t pid = 0x5512, explicit Ch341Hal(uint8_t spiChannel, const std::string &serial = "", uint32_t vid = 0x1A86, uint32_t pid = 0x5512,
uint32_t spiSpeed = 2000000, uint8_t spiDevice = 0, uint8_t gpioDevice = 0) uint32_t spiSpeed = 2000000, uint8_t spiDevice = 0, uint8_t gpioDevice = 0)
: RadioLibHal(PI_INPUT, PI_OUTPUT, PI_LOW, PI_HIGH, PI_RISING, PI_FALLING) : RadioLibHal(PI_INPUT, PI_OUTPUT, PI_LOW, PI_HIGH, PI_RISING, PI_FALLING)
{ {
@@ -43,4 +43,4 @@ lib_ignore =
NonBlockingRTTTL NonBlockingRTTTL
libpax libpax
build_src_filter = build_src_filter =
${esp32c6_base.build_src_filter} +<../variants/esp32c6/m5stack_unitc6l> ${esp32c6_base.build_src_filter} +<../variants/esp32c6/m5stack_unitc6l>