Add MeshPocket message board and worldwide map

This commit is contained in:
mikecarper committed 2026-10-21 23:57:14 -07:00
1 parent 7d0709bf03
commit 5d31a839c5
41 files changed
+6852 -7

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <helpers/ui/GxEPDDisplay.h>
#include <cstring>
inline constexpr uint8_t u8g2_font_helvR08_tf[] = {0};
inline constexpr uint8_t u8g2_font_helvB08_tf[] = {1};
inline constexpr uint8_t u8g2_font_helvR10_tf[] = {2};
inline constexpr uint8_t u8g2_font_helvB10_tf[] = {3};
class U8G2_FOR_ADAFRUIT_GFX {
Adafruit_GFX* _gfx = nullptr;
unsigned _font = 0;
uint16_t _foreground = 0, _background = 1;
public:
void begin(Adafruit_GFX& gfx) { _gfx = &gfx; }
void setForegroundColor(uint16_t color) { _foreground = color; }
void setBackgroundColor(uint16_t color) { _background = color; }
void setFont(const uint8_t* font) { _font = *font; }
void setFontMode(int) {}
void setFontDirection(int) {}
// Helvetica 08/10 ascent/descent from the selected u8g2 font metadata.
int getFontAscent() const { return _font >= 2 ? 11 : 8; }
int getFontDescent() const { return _font >= 2 ? -3 : -2; }
int getUTF8Width(const char* text) const {
int width = 0;
for (const auto* next = reinterpret_cast<const unsigned char*>(text); *next; ++next) {
if ((*next & 0xC0) == 0x80) continue;
width += (*next == 'i' || *next == 'l') ? 2 : *next == 'W' ? 8 : _font >= 2 ? 6 : 5;
}
return width;
}
void drawUTF8(int x, int baseline, const char* text) {
const int width = getUTF8Width(text);
assert(x >= 0 && x + width <= _gfx->width());
assert(baseline - getFontAscent() >= 0);
assert(baseline - getFontDescent() <= _gfx->height());
_gfx->labels.push_back({x, baseline, width, getFontAscent(), getFontDescent(), (_font & 1) != 0,
_foreground, _background, text});
}
};
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
constexpr uint16_t GxEPD_BLACK = 0;
constexpr uint16_t GxEPD_WHITE = 1;
class Adafruit_GFX {
public:
struct Text {
int x, baseline, width, ascent, descent;
bool bold;
uint16_t foreground, background;
std::string value;
};
std::vector<Text> labels;
int w = 250, h = 122;
int rotation = 3;
int width() const { return w; }
int height() const { return h; }
void fillScreen(uint16_t) { labels.clear(); }
void fillRect(int x, int y, int width, int height, uint16_t) {
assert(x >= 0 && y >= 0 && width >= 0 && height >= 0);
assert(x + width <= w && y + height <= h);
}
void drawPixel(int x, int y, uint16_t) {
assert(x >= 0 && y >= 0 && x < w && y < h);
}
void drawLine(int x0, int y0, int x1, int y1, uint16_t) {
assert(x0 >= 0 && y0 >= 0 && x1 >= 0 && y1 >= 0);
assert(x0 < w && x1 < w && y0 < h && y1 < h);
}
void fillCircle(int x, int y, int, uint16_t color) { drawPixel(x, y, color); }
void drawCircle(int x, int y, int, uint16_t color) { drawPixel(x, y, color); }
bool contains(const char* value) const {
for (const auto& text : labels) if (text.value == value) return true;
return false;
}
unsigned occurrences(const char* value) const {
unsigned result = 0;
for (const auto& text : labels) if (text.value == value) ++result;
return result;
}
};
class GxEPDDisplay {
Adafruit_GFX _gfx;
public:
bool on = true;
uint32_t hash = 2166136261U;
bool isOn() const { return on; }
Adafruit_GFX& gfx() { return _gfx; }
void setNativeRotation(int rotation) {
_gfx.rotation = rotation;
_gfx.w = (rotation & 1) ? 250 : 122;
_gfx.h = (rotation & 1) ? 122 : 250;
}
void crcAdd(const void* value, size_t size) {
for (size_t i = 0; i < size; ++i) {
hash ^= static_cast<const uint8_t*>(value)[i];
hash *= 16777619U;
}
}
void resetHash() { hash = 2166136261U; }
};
+132
View File
@@ -0,0 +1,132 @@
#include <helpers/ui/CompanionMessageHistory.h>
#include <helpers/ui/DisplayPowerPolicy.h>
#include <cassert>
#include <cstring>
#define UI_MSG_PREVIEW_SIZE 161
#define MAX_GROUP_CHANNELS 40
#define KEY_UP 0xB5
#define KEY_DOWN 0xB6
#define MESH_DEBUG_PRINTLN(...)
static uint32_t now_millis = 12345;
uint32_t millis() { return now_millis; }
uint64_t companionMessageNowMillis() { return now_millis; }
struct Screen { virtual ~Screen() = default; };
struct Display {
bool on = true;
int wakes = 0;
bool isOn() const { return on; }
void wake(mesh::ui::DisplayWake) { ++wakes; }
};
struct MsgPreviewScreen : Screen {
mesh::ui::CompanionMessageHistory<32, UI_MSG_PREVIEW_SIZE> history;
bool selected = false;
void addPreview(uint8_t, const char* sender, const char* text, int channel,
const char* channel_name, int queue_index, bool select) {
selected = select;
history.add(now_millis, channel, channel_name, sender, text, queue_index);
}
// @ADD_SENT@
};
struct HomeScreen : Screen {
bool board = true;
int message_hooks = 0;
bool isPocketBoard() const { return board; }
void pocketMessageAdded(int) { ++message_hooks; }
};
class UITask {
public:
Screen *home, *msg_preview, *reader, *curr;
Display* _display;
int _msgcount = 0, screen_changes = 0, buzzer_changes = 0;
uint32_t _next_refresh = 0;
bool connected = false, pairing = false, allow_wake = true;
bool _deferred_msg_preview = false;
UITask(HomeScreen& h, MsgPreviewScreen& m, Screen& r, Display& d)
: home(&h), msg_preview(&m), reader(&r), curr(&h), _display(&d) {}
bool hasConnection() const { return connected; }
bool isPairingScreenActive() const { return pairing; }
bool isReaderActive() const { return curr == reader; }
bool shouldWakeDisplayForMessage() const { return allow_wake; }
void setCurrScreen(Screen* screen) { curr = screen; ++screen_changes; }
char checkDisplayOn(char key) { return key; }
void toggleBuzzer() { ++buzzer_changes; }
void newMsg(uint8_t path_len, const char* from, const char* text, int count,
int channel, const char* channel_name, int queue_index);
void channelMessageSent(int channel, const char* channel_name, const char* sender,
const char* text, size_t length);
char handleMultiClick(char key, bool backwards);
};
// @TASK_METHODS@
int main() {
HomeScreen home;
MsgPreviewScreen preview;
Screen reader;
Display display;
UITask task(home, preview, reader, display);
auto receive = [&](int channel = 0) {
task.newMsg(1, "Channel Public", "Alice: received", 7, channel, "Public", 3);
};
// A live-board channel arrival updates history without stealing the board.
receive();
assert(task.curr == &home && task.screen_changes == 0);
assert(preview.history.count() == 1 && home.message_hooks == 1);
assert(!task._deferred_msg_preview && task._msgcount == 7);
assert(preview.selected && display.wakes == 1 && task._next_refresh == now_millis);
// Connected apps, the pairing PIN and the Reader keep their existing policy.
task.connected = true;
receive();
assert(task.curr == &home && !preview.selected && !task._deferred_msg_preview);
task.connected = false;
task.pairing = true;
receive();
assert(task.curr == &home && task._deferred_msg_preview);
task.pairing = false;
task.curr = &reader;
receive();
assert(task.curr == &reader && task._deferred_msg_preview);
task.curr = &home;
home.board = false;
receive();
assert(task.curr == &preview);
task.curr = &home;
home.board = true;
receive(-1);
assert(task.curr == &preview); // a direct message retains its normal preview
const int previous_wakes = display.wakes;
task.allow_wake = false;
receive();
assert(display.wakes == previous_wakes);
// The outbound app buffer is length-delimited, not necessarily terminated.
const char raw[] = {'o', 'w', 'n'};
task.curr = &reader;
task.channelMessageSent(0, "Public", "Self", raw, sizeof(raw));
assert(task.curr == &reader);
const auto* sent = preview.history.newest(0);
assert(sent->own_sent && !sent->unread && sent->queue_index == -1);
assert(std::strcmp(sent->message, "own") == 0);
const size_t previous_count = preview.history.count();
task.channelMessageSent(-1, "Public", "Self", raw, sizeof(raw));
task.channelMessageSent(40, "Public", "Self", raw, sizeof(raw));
assert(preview.history.count() == previous_count);
char long_text[200];
std::memset(long_text, 'x', sizeof(long_text));
task.channelMessageSent(0, "Public", "Self", long_text, sizeof(long_text));
assert(std::strlen(preview.history.newest(0)->message) == UI_MSG_PREVIEW_SIZE - 1);
task.curr = &home;
assert(static_cast<uint8_t>(task.handleMultiClick(0, false)) == KEY_DOWN);
assert(static_cast<uint8_t>(task.handleMultiClick(0, true)) == KEY_UP);
assert(task.buzzer_changes == 0);
home.board = false;
assert(task.handleMultiClick(0, false) == 0 && task.buzzer_changes == 1);
}
+131
View File
@@ -0,0 +1,131 @@
#include <helpers/ui/PocketGuiSettings.h>
#include <helpers/ui/UIScreen.h>
#include <cassert>
#include <initializer_list>
#define MAX_GROUP_CHANNELS 40
static uint32_t clock_millis = 123456;
uint32_t millis() { return clock_millis; }
struct Task {
mesh::ui::pocket::Settings settings;
int reader_opens = 0;
mesh::ui::pocket::Settings& pocketSettings() { return settings; }
unsigned pocketBoardCount() const { return 3; }
void showReader() { ++reader_opens; }
void showAlert(const char*, int) {}
};
struct Mesh {
bool dual = true;
bool isDualRadioActive() const { return dual; }
} the_mesh;
class HomeScreen : public UIScreen {
public:
enum HomePage { FIRST, MAP, STATUS, SETTINGS, RECENT, RADIO, RADIO2, RADIO_STATUS, Count };
struct Board {
mesh::ui::pocket::BoardState state;
bool scrollOlder(unsigned count) { return state.scrollOlder(count); }
bool scrollNewer() { return state.scrollNewer(); }
void resetScroll() { state.scroll = 0; }
} _pocket;
Task* _task;
uint8_t _page = FIRST;
bool _pocket_editing = false, _pocket_browsing = false, _pocket_zooming = false;
bool _pocket_dirty = false, _dual_radio_enabled_seen = false;
uint8_t _pocket_setting = 0, _radio_status_page = 0;
uint32_t _pocket_last_input = 0, _radio_profile_page_started_at = 0;
int save_count = 0, clean_count = 0;
explicit HomeScreen(Task& task) : _task(&task) {}
int render(DisplayDriver&) override { return 0; }
bool flushPocketSettings() { ++save_count; _pocket_dirty = false; return true; }
void displayForceClean() { ++clean_count; }
void cyclePocketChannel(int direction) {
_task->settings.channel = (_task->settings.channel + 40 + direction) % 40;
}
// @HOME_IMPLEMENTATION@
};
static void key(HomeScreen& home, uint8_t value) {
assert(home.handleInput(static_cast<char>(value)));
assert(home._pocket_last_input == clock_millis);
}
int main() {
Task task;
HomeScreen home(task);
key(home, KEY_ENTER);
assert(home._page == HomeScreen::FIRST && home._pocket_browsing);
key(home, KEY_NEXT);
assert(home._pocket.state.scroll == 1 && home._page == HomeScreen::FIRST);
key(home, KEY_PREV);
assert(home._pocket.state.scroll == 0);
key(home, KEY_DOWN);
assert(task.settings.channel == 1);
key(home, KEY_UP);
assert(task.settings.channel == 0);
key(home, KEY_ENTER);
assert(!home._pocket_browsing);
key(home, KEY_NEXT);
assert(home._page == HomeScreen::MAP);
key(home, KEY_ENTER);
assert(home._pocket_zooming);
key(home, KEY_NEXT);
assert(task.settings.map_zoom == 4 && home._pocket_dirty);
key(home, KEY_PREV);
assert(task.settings.map_zoom == 3);
key(home, KEY_ENTER);
assert(!home._pocket_zooming && !home._pocket_dirty);
key(home, KEY_NEXT);
key(home, KEY_NEXT);
assert(home._page == HomeScreen::SETTINGS);
key(home, KEY_ENTER);
assert(home._pocket_editing);
key(home, KEY_PREV);
assert(home._pocket_setting == 1);
key(home, KEY_NEXT);
assert(task.settings.text_large == 1 && home._pocket_dirty);
home._pocket_setting = 4;
key(home, KEY_NEXT);
assert(task.settings.dark == 1 && home.clean_count == 1);
key(home, KEY_ENTER);
assert(!home._pocket_editing && !home._pocket_dirty);
key(home, KEY_PREV);
assert(home._page == HomeScreen::STATUS);
key(home, KEY_ENTER);
assert(home._radio_status_page == 1 && task.reader_opens == 0);
// Pairing can interrupt any editing/browsing mode. Returning to the first
// page saves settings and leaves the next click free to navigate normally.
for (const auto interrupted : {HomeScreen::SETTINGS, HomeScreen::MAP, HomeScreen::FIRST}) {
home._page = interrupted;
home._pocket_editing = home._pocket_browsing = home._pocket_zooming = true;
home._pocket_dirty = true;
home._pocket.state.scroll = 2;
home._pocket_last_input = 0;
const int saves = home.save_count;
clock_millis += 1000;
home.showFirstPage();
assert(home._page == HomeScreen::FIRST && home.save_count == saves + 1);
assert(!home._pocket_editing && !home._pocket_browsing && !home._pocket_zooming);
assert(!home._pocket_dirty && home._pocket.state.scroll == 0);
assert(home._pocket_last_input == clock_millis);
key(home, KEY_NEXT);
assert(home._page == HomeScreen::MAP);
}
// The existing Network-page hold remains the Reader action in the new GUI.
home._page = HomeScreen::RADIO;
key(home, KEY_ENTER);
assert(task.reader_opens == 1 && home._page == HomeScreen::RADIO);
home._page = HomeScreen::RADIO2;
key(home, KEY_ENTER);
assert(task.reader_opens == 2 && home._page == HomeScreen::RADIO2);
home._page = HomeScreen::RADIO_STATUS;
key(home, KEY_ENTER);
assert(home._radio_status_page == 2 && task.reader_opens == 2);
the_mesh.dual = false;
home._page = HomeScreen::RADIO;
key(home, KEY_NEXT);
assert(home._page == HomeScreen::FIRST);
}
+237
View File
@@ -0,0 +1,237 @@
#include <examples/companion_radio/ui-new/PocketGui.h>
#include <helpers/ui/CompanionMessageHistory.h>
#include <cassert>
#include <cstring>
#include <initializer_list>
using namespace mesh::ui::pocket;
using History = mesh::ui::CompanionMessageHistory<32, 161>;
static void channelBoard() {
Settings settings;
Frame frame;
frame.now = 1735689600UL + 30 * 60;
frame.heard_millis = 120000;
frame.tz_offset = 5.75f;
frame.battery_percent = 101;
frame.page_count = 11;
frame.connection = "BLE+USB";
GxEPDDisplay display;
PocketGui gui;
History history;
history.add(60000, 0, "Public", "Ch 0 Public [1h]:", "Alice: hello everyone");
history.add(100000, 2, "Private", "Ch 2 Private [1h]:", "secret sender: hidden");
history.add(120000, 0, "Public", "Self", "outgoing", -1, true);
history.add(120000, -1, "", "Bob [direct]:", "direct hidden");
gui.begin(display, settings, frame);
assert(gui.boardCount(history) == 2);
gui.renderBoard(history, "Public");
assert(display.gfx().contains("Alice"));
assert(display.gfx().contains("Self"));
assert(display.gfx().contains("outgoing"));
assert(!display.gfx().contains("secret sender"));
assert(!display.gfx().contains("direct hidden"));
assert(display.gfx().contains("100%"));
// UTC 00:30 plus 05:45 Nepal offset. The previous-minute message gets 06:14.
assert(display.gfx().contains("06:15"));
assert(display.gfx().contains("06:14"));
bool sent_inverted = false;
for (const auto& text : display.gfx().labels)
if (text.value == "Self") sent_inverted = text.foreground == GxEPD_WHITE;
assert(sent_inverted);
display.resetHash();
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
const uint32_t first_hash = display.hash;
display.resetHash();
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(display.hash == first_hash); // unchanged content skips physical redraw
assert(gui.scrollOlder(history) && gui.isScrolled());
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(display.gfx().contains("1 newer") && !display.gfx().contains("Self"));
history.add(120000, 0, "Public", "Ch 0 Public [1h]:", "Carol: new message");
gui.messageAdded();
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(display.gfx().contains("2 newer") && display.gfx().contains("Alice"));
assert(!display.gfx().contains("Carol"));
gui.resetScroll();
assert(!gui.isScrolled());
// Negative fractional offsets also cross midnight correctly.
frame.tz_offset = -3.5f;
gui.begin(display, settings, frame);
gui.renderMapChrome();
gui.header("Map");
assert(display.gfx().contains("21:00"));
// A message received before Arduino millis() wrapped still retains its
// actual age, rather than being relabelled as newly received.
history.clear();
history.add(UINT32_MAX - 59999U, 0, "Public", "Self", "before rollover", -1, true);
frame.now = 0;
frame.heard_millis = 1000;
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(display.gfx().contains("1m"));
}
static void screenBounds() {
History history;
char body[161];
std::memset(body, 'W', sizeof(body) - 1);
body[sizeof(body) - 1] = 0;
history.add(0, 0, "Public", "ExtremelyLongSenderNameWWWWWWWWWWWWWWWWWWWW", body, -1, true);
history.add(0, 0, "Public", "Ch 0 Public [1h]:", "\xc3\x89lise: UTF-8 caf\xc3\xa9 message with words and a long paragraph that wraps onto several rows");
Frame frame;
frame.now = 1735689600UL;
frame.battery_percent = -1;
frame.hint = "click next / 2x back";
for (unsigned large : {0U, 1U})
for (unsigned flip : {0U, 1U})
for (unsigned dark : {0U, 1U})
for (unsigned name : {0U, 1U, 2U, 3U}) {
Settings settings;
settings.text_large = large;
settings.flip = flip;
settings.dark = dark;
settings.name_len = name;
PocketGui gui;
GxEPDDisplay display;
gui.begin(display, settings, frame);
gui.renderBoard(history, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
assert(display.gfx().rotation == (flip ? 1 : 3));
for (unsigned row = 0; row < SETTINGS_COUNT; ++row) {
gui.begin(display, settings, frame);
gui.renderSettings(row, true, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
}
gui.begin(display, settings, frame);
gui.renderMapChrome();
gui.mapEmpty("No valid position");
}
PocketGui gui;
GxEPDDisplay display;
Settings settings;
settings.channel = 39;
gui.begin(display, settings, frame);
gui.renderBoard(history, "Empty");
assert(gui.boardCount(history) == 0);
assert(display.gfx().contains("Listening for messages"));
// Display hints may be supplied by navigation. They must remain inside the
// screen even if a future page supplies more text than fits on one line.
frame.hint = "An extremely long footer WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW";
gui.begin(display, settings, frame);
gui.renderMapChrome();
history.clear();
std::memset(body, 'W', sizeof(body) - 1);
std::strcpy(body + sizeof(body) - 7, " END42");
history.add(0, 0, "Public", "\xc3\x89lise", body, -1, true);
settings.channel = 0;
settings.text_large = 1;
settings.name_len = 3;
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
bool tail_visible = false;
for (const auto& text : display.gfx().labels)
if (text.value.find("END42") != std::string::npos) tail_visible = true;
assert(tail_visible);
}
static void measuredLabels() {
Settings settings;
Frame frame;
GxEPDDisplay display;
PocketGui gui;
gui.begin(display, settings, frame);
gui.label(4, 30, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", true);
assert(display.gfx().labels.size() == 1);
const auto& broad = display.gfx().labels.front();
assert(broad.width <= 246 && broad.value.size() < 31 && broad.bold);
gui.text(4, 45, "Normal again");
assert(!display.gfx().labels.back().bold);
gui.label(240, 60, "\xc3\x89WWWWWWWWW", true);
assert(display.gfx().labels.back().value == "\xc3\x89");
gui.text(4, 75, "Normal again");
assert(!display.gfx().labels.back().bold);
const size_t previous = display.gfx().labels.size();
gui.label(-1, 90, "outside", true);
gui.label(250, 90, "outside", true);
gui.label(4, 90, nullptr, true);
assert(display.gfx().labels.size() == previous);
gui.text(4, 105, "Normal after invalid label");
assert(!display.gfx().labels.back().bold);
gui.begin(display, settings, frame);
gui.renderMapChrome(20000);
assert(display.gfx().contains("20000 km"));
gui.begin(display, settings, frame);
gui.renderMapChrome();
assert(display.gfx().contains("200 km"));
}
static void readOnlyVisibleEntries() {
Settings settings;
Frame frame;
GxEPDDisplay display;
PocketGui gui;
History history;
history.add(0, 0, "Public", "Ch 0 Public", "Alice: oldest hidden", 0);
history.add(0, 0, "Public", "Ch 0 Public", "Bob: older hidden", 1);
history.add(0, 1, "Private", "Ch 1 Private", "Carol: other channel", 2);
char long_body[161];
std::memset(long_body, 'W', sizeof(long_body) - 1);
long_body[sizeof(long_body) - 1] = 0;
history.add(0, 0, "Public", "Ch 0 Public", long_body, 3);
settings.text_large = 1;
gui.begin(display, settings, frame);
assert(history.unreadCount() == 4);
gui.renderBoard(history, "Public");
assert(!history.newest(0)->unread); // the long message's visible tail counts
assert(history.newest(1)->unread); // another channel
assert(history.newest(2)->unread && history.newest(3)->unread); // above the viewport
for (unsigned age = 0; age < history.count(); ++age)
assert(history.newest(age)->queue_index == static_cast<int>(3 - age));
assert(gui.scrollOlder(history));
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(!history.newest(2)->unread && !history.newest(3)->unread);
assert(history.newest(1)->unread && history.unreadCount() == 1);
assert(history.newest(0)->queue_index == 3); // reading never consumes app delivery
// Merely composing a frame while the panel is off does not mark it read.
history.clear();
history.add(0, 0, "Public", "Ch 0 Public", "Alice: sleeping panel", 7);
gui.resetScroll();
display.on = false;
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(history.newest(0)->unread && history.newest(0)->queue_index == 7);
display.on = true;
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(!history.newest(0)->unread && history.newest(0)->queue_index == 7);
// Scrolling to an older entry does not acknowledge the newer skipped one.
history.clear();
history.add(0, 0, "Public", "Ch 0 Public", "Alice: older", 1);
history.add(0, 0, "Public", "Ch 0 Public", "Bob: newer", 2);
gui.resetScroll();
assert(gui.scrollOlder(history));
gui.begin(display, settings, frame);
gui.renderBoard(history, "Public");
assert(history.newest(0)->unread && !history.newest(1)->unread);
assert(history.newest(0)->queue_index == 2 && history.newest(1)->queue_index == 1);
}
int main() {
channelBoard();
screenBounds();
measuredLabels();
readOnlyVisibleEntries();
}
+203
View File
@@ -0,0 +1,203 @@
#include <helpers/ui/PocketGuiSettings.h>
#include <cassert>
#include <cstring>
#include <initializer_list>
#include <limits>
using namespace mesh::ui::pocket;
static bool equal(const Settings& left, const Settings& right) {
return left.channel == right.channel && left.text_large == right.text_large
&& left.name_len == right.name_len && left.flip == right.flip
&& left.dark == right.dark && left.idle == right.idle
&& left.refresh == right.refresh && left.map_zoom == right.map_zoom;
}
static void repairChecksum(uint8_t* bytes) {
const uint16_t crc = settingsChecksum(bytes, 11);
bytes[11] = static_cast<uint8_t>(crc);
bytes[12] = static_cast<uint8_t>(crc >> 8);
}
static void settingsRoundTrip() {
Settings value;
assert(settingsValid(value));
assert(idleMillis(value) == 60000 && refreshCount(value) == 30);
assert(nameCharacters(value) == 5 && mapHeightKm(value) == 200);
uint8_t bytes[SETTINGS_RECORD_SIZE];
for (unsigned channels : {1U, 40U, 256U}) {
for (unsigned choices = 0; choices < 8; ++choices)
for (unsigned name = 0; name < 4; ++name)
for (unsigned idle = 0; idle < 4; ++idle)
for (unsigned refresh = 0; refresh < 4; ++refresh)
for (unsigned zoom = 0; zoom < 9; ++zoom) {
value.channel = static_cast<uint8_t>(channels - 1);
value.text_large = choices & 1;
value.flip = (choices >> 1) & 1;
value.dark = (choices >> 2) & 1;
value.name_len = name;
value.idle = idle;
value.refresh = refresh;
value.map_zoom = zoom;
assert(encodeSettings(value, bytes, sizeof(bytes), channels));
Settings recovered;
assert(decodeSettings(recovered, bytes, sizeof(bytes), channels));
assert(equal(value, recovered));
}
}
value = Settings{};
assert(encodeSettings(value, bytes, sizeof(bytes)));
const Settings sentinel{39, 1, 3, 1, 1, 3, 3, 8};
auto rejects = [&](const uint8_t* input, size_t size, unsigned channels = 40) {
Settings destination = sentinel;
assert(!decodeSettings(destination, input, size, channels));
assert(equal(destination, sentinel));
};
rejects(nullptr, sizeof(bytes));
for (size_t size = 0; size < sizeof(bytes); ++size) rejects(bytes, size);
rejects(bytes, sizeof(bytes) + 1);
rejects(bytes, sizeof(bytes), 0);
rejects(bytes, sizeof(bytes), 257);
// Detect corruption at every bit, including the stored checksum itself.
for (size_t byte = 0; byte < sizeof(bytes); ++byte)
for (unsigned bit = 0; bit < 8; ++bit) {
uint8_t changed[sizeof(bytes)];
std::memcpy(changed, bytes, sizeof(bytes));
changed[byte] ^= 1U << bit;
rejects(changed, sizeof(changed));
}
// A record with a valid CRC still cannot select invalid enum values, a
// missing channel, an unknown format or reserved bits.
const unsigned bad_offsets[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const unsigned bad_values[] = {'X', 'X', 2, 40, 2, 4, 4, 4, 4, 9, 1};
for (size_t test = 0; test < sizeof(bad_offsets) / sizeof(*bad_offsets); ++test) {
uint8_t changed[sizeof(bytes)];
std::memcpy(changed, bytes, sizeof(bytes));
changed[bad_offsets[test]] = bad_values[test];
repairChecksum(changed);
rejects(changed, sizeof(changed));
}
value.channel = 39;
assert(encodeSettings(value, bytes, sizeof(bytes), 40));
rejects(bytes, sizeof(bytes), 39);
for (unsigned row = 0; row < SETTINGS_COUNT; ++row) {
Settings changed;
const Settings initial = changed;
const unsigned periods[] = {40, 2, 4, 2, 2, 4, 4, 9};
for (unsigned step = 0; step < periods[row]; ++step) {
assert(cycleSetting(changed, row));
assert(settingsValid(changed));
}
assert(equal(changed, initial));
}
const Settings initial;
value = initial;
assert(!cycleSetting(value, SETTINGS_COUNT) && equal(value, initial));
assert(!cycleSetting(value, 0, 0) && equal(value, initial));
assert(!cycleSetting(value, 0, 257) && equal(value, initial));
value.channel = 255;
assert(cycleSetting(value, 0, 256) && value.channel == 0);
for (unsigned bad = 4; bad <= 255; ++bad) {
value.idle = value.refresh = value.name_len = static_cast<uint8_t>(bad);
assert(idleMillis(value) == 60000 && refreshCount(value) == 30);
assert(nameCharacters(value) == 5);
}
for (unsigned bad = 9; bad <= 255; ++bad) {
value.map_zoom = static_cast<uint8_t>(bad);
assert(mapHeightKm(value) == 200);
}
}
static void scrollHistory() {
assert(messageAgeSeconds(1000, UINT32_MAX - 999U) == 2);
assert(messageAgeSeconds(180000, 60000) == 120);
for (unsigned count = 0; count <= 32; ++count) {
BoardState state;
assert(!state.scrollNewer());
for (unsigned next = 1; next < count; ++next) {
assert(state.scrollOlder(count));
assert(state.scroll == next);
}
assert(!state.scrollOlder(count));
assert(state.scroll == (count == 0 ? 0 : count - 1));
const unsigned previous = state.scroll;
state.messageAdded();
// At the live end keep following new messages. While reading old messages
// retain the same entry until it falls out of the 32-message ring.
assert(state.scroll == (previous == 0 ? 0 : previous < 31 ? previous + 1 : 31));
state.clamp(0);
assert(state.scroll == 0);
}
BoardState state;
state.scroll = std::numeric_limits<unsigned>::max();
state.clamp(1);
assert(state.scroll == 0 && !state.scrollOlder(1));
state.scroll = 99;
state.clamp(32);
assert(state.scroll == 31 && !state.scrollOlder(32));
for (unsigned left = 31; left > 0; --left) {
assert(state.scrollNewer());
assert(state.scroll == left - 1);
}
assert(!state.scrollNewer());
}
static void messageNamesAndText() {
BoardMessageView result;
parseBoardMessage("Ch 0 Public [1h]:", "Alice: hello: there", false, result);
assert(result.sender_length == 5 && std::strncmp(result.sender, "Alice", 5) == 0);
assert(std::strcmp(result.text, "hello: there") == 0);
parseBoardMessage("My name", "Alice: literal outgoing body", true, result);
assert(result.sender_length == 7 && std::strcmp(result.sender, "My name") == 0);
assert(std::strcmp(result.text, "Alice: literal outgoing body") == 0);
parseBoardMessage("Alice [direct]:", "no sender prefix", false, result);
assert(result.sender_length == 5 && std::strcmp(result.text, "no sender prefix") == 0);
parseBoardMessage(nullptr, nullptr, false, result);
assert(result.sender_length == 0 && *result.text == 0);
parseBoardMessage("fallback [direct]:", ": invalid empty sender", false, result);
assert(result.sender_length == 8);
char long_message[90];
std::memset(long_message, 'a', 70);
std::strcpy(long_message + 70, ": message");
parseBoardMessage("fallback", long_message, false, result);
assert(result.sender_length == 8 && result.text == long_message);
char text[64];
sanitizeText(text, sizeof(text), "caf\xc3\xa9\t\xf0\x9f\x93\xbb\n!", 13);
assert(std::strcmp(text, "caf\xc3\xa9 * !") == 0);
sanitizeText(text, sizeof(text), nullptr, 100);
assert(*text == 0);
sanitizeText(text, 1, "abc", 3);
assert(*text == 0);
// Neither an exact-length nonterminated input nor a truncated multibyte
// input can over-read, and a small output never ends with half of Latin-1.
const char exact[] = {'a', 'b', 'c'};
sanitizeText(text, sizeof(text), exact, sizeof(exact));
assert(std::strcmp(text, "abc") == 0);
const char truncated[] = {'a', '\xc3'};
sanitizeText(text, sizeof(text), truncated, sizeof(truncated));
assert(std::strcmp(text, "a*") == 0);
sanitizeText(text, sizeof(text), "A\xc2\x85" "B", 4);
assert(std::strcmp(text, "A B") == 0);
sanitizeText(text, 3, "a\xc3\xa9", 3);
assert(std::strcmp(text, "a") == 0);
std::strcpy(text, "\xc3\x89lise");
truncateCharacters(text, 3);
assert(std::strcmp(text, "\xc3\x89li") == 0);
truncateCharacters(text, 0);
assert(std::strcmp(text, "\xc3\x89li") == 0);
truncateCharacters(text, 1);
assert(std::strcmp(text, "\xc3\x89") == 0);
}
int main() {
settingsRoundTrip();
scrollHistory();
messageNamesAndText();
}
+47
View File
@@ -0,0 +1,47 @@
#include <helpers/ui/CompanionMessageHistory.h>
#include <cassert>
#include <cstring>
using History = mesh::ui::CompanionMessageHistory<3, 78>;
// Own-message styling uses the Entry's existing alignment padding. Every
// other board retains the same 32-message history allocation.
struct PreviousEntry {
uint64_t heard_millis;
int queue_index;
bool unread;
int channel_idx;
char channel_name[32];
char origin[62];
char message[78];
};
static_assert(sizeof(History::Entry) == sizeof(PreviousEntry),
"own-message metadata changed the shared history RAM budget");
int main() {
History history;
history.add(100, 0, "Public", "Ch 0 Public [1h]:", "Alice: received", 2);
history.add(200, 0, "Public", "Self", "sent", -1, true);
assert(history.count() == 2 && history.unreadCount() == 1);
assert(history.newest(0)->own_sent && !history.newest(0)->unread);
assert(history.newest(0)->queue_index == -1);
assert(!history.newest(1)->own_sent && history.newest(1)->unread);
// App queue reads shift only received-message indices. They do not make a
// locally sent message look pending or mark the received one as read.
history.queueRemoved(0);
assert(history.newest(0)->queue_index == -1);
assert(history.newest(1)->queue_index == 1);
assert(history.unreadCount() == 1);
history.queueRemoved(1);
assert(history.newest(1)->queue_index == -1);
assert(history.unreadCount() == 1);
history.add(300, -1, "", "Bob [direct]:", "direct", 0);
history.add(400, 0, "Public", "Self", "new sent", -1, true);
assert(history.count() == 3 && history.unreadCount() == 1);
assert(std::strcmp(history.newest(0)->message, "new sent") == 0);
assert(history.newest(2)->own_sent && !history.newest(2)->unread);
history.markRead(history.newest(1));
assert(history.unreadCount() == 0);
}
+185
View File
@@ -0,0 +1,185 @@
#include "helpers/ui/PocketWorldMap.h"
#include "helpers/ui/PocketWorldMapData.generated.h"
#include "helpers/ota/tinf/tinf.h"
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <initializer_list>
#include <stdio.h>
#include <string.h>
using namespace mesh::ui::pocket;
struct Canvas {
static constexpr int width = 250, height = 91;
bool pixels[height][width] = {};
unsigned lines = 0;
static void line(void* context, int x0, int y0, int x1, int y1) {
Canvas& canvas = *static_cast<Canvas*>(context);
assert(x0 >= 0 && x0 < width && x1 >= 0 && x1 < width);
assert(y0 >= 0 && y0 < height && y1 >= 0 && y1 < height);
++canvas.lines;
const int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
const int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int error = dx + dy;
for (;;) {
canvas.pixels[y0][x0] = true;
if (x0 == x1 && y0 == y1) break;
const int twice = error * 2;
if (twice >= dy) { error += dy; x0 += sx; }
if (twice <= dx) { error += dx; y0 += sy; }
}
}
bool nearby(int x, int y, int radius) const {
for (int yy = y - radius; yy <= y + radius; ++yy)
for (int xx = x - radius; xx <= x + radius; ++xx)
if (xx >= 0 && xx < width && yy >= 0 && yy < height && pixels[yy][xx]) return true;
return false;
}
};
static MapView view(double latitude, double longitude, double km = 200) {
return {latitude, longitude, km, Canvas::width, Canvas::height};
}
static void testProjection() {
int x, y;
auto v = view(0, 180);
assert(projectWorldPoint(v, 0, 180, x, y) && x == 125 && y == 45);
int east, west;
assert(projectWorldPoint(v, 0, -179.9, east, y));
assert(projectWorldPoint(v, 0, 179.9, west, y));
assert(east > 125 && west < 125 && east - west < 12);
assert(!projectWorldPoint(v, 0, 0, x, y));
assert(!projectWorldPoint(v, 0, 181, x, y));
for (double pole : {-90.0, 90.0}) {
v = view(pole, 0);
assert(projectWorldPoint(v, pole, 170, x, y));
assert(x == 125 && y == 45);
assert(projectWorldPoint(v, pole > 0 ? 89.5 : -89.5, 90, x, y));
}
v = view(NAN, 0);
assert(!projectWorldPoint(v, 0, 0, x, y));
v = view(0, 0); v.width = 0;
assert(!projectWorldPoint(v, 0, 0, x, y));
}
static void testFloatProjectionAccuracyAndWorldOverview() {
constexpr double radians = 3.14159265358979323846 / 180.0;
// Independent double-precision azimuthal reference. The device's float/FPU
// implementation must stay within one pixel at close and continental zooms.
for (double latitude : {-90.0, -78.0, -45.0, 0.0, 37.8, 78.0, 89.9, 90.0}) {
for (double longitude : {-180.0, -122.5, 0.0, 180.0}) {
for (double height : {5.0, 50.0, 200.0, 1000.0, 5000.0}) {
const auto v = view(latitude, longitude, height);
for (int row = -8; row <= 8; ++row) for (int col = -8; col <= 8; ++col) {
const double lat = latitude + row * height / 111.195 / 16;
if (lat < -90 || lat > 90) continue;
double lon = longitude + col * height / 111.195 / 8 / fmax(0.01, cos(latitude * radians));
lon = remainder(lon, 360.0);
const double a = latitude * radians, b = lat * radians;
const double delta = remainder((lon - longitude) * radians, 2 * 3.14159265358979323846);
const double cosine = sin(a) * sin(b) + cos(a) * cos(b) * cos(delta);
if (cosine < 0.00001) continue;
const double distance = acos(fmin(1.0, cosine));
const double factor = (distance < 1e-8 ? 6371.0088 : 6371.0088 * distance / sin(distance)) * 90 / height;
const double px = 124.5 + factor * cos(b) * sin(delta);
const double py = 45 - factor * (cos(a) * sin(b) - sin(a) * cos(b) * cos(delta));
if (px < 1 || px > 248 || py < 1 || py > 89) continue;
int x, y;
assert(projectWorldPoint(v, lat, lon, x, y));
assert(abs(x - int(lround(px))) <= 1 && abs(y - int(lround(py))) <= 1);
}
}
}
}
const auto world = view(0, 0, 20000);
// The full-world fallback must show every continent, not just one hemisphere.
const double continents[][2] = {{37.8,-122.5}, {-23.5,-46.6}, {51.5,-0.1},
{-33.9,18.4}, {35.7,139.7}, {-33.9,151.2}, {-90,0}, {90,0}};
for (const auto& point : continents) {
int x, y;
assert(projectWorldPoint(world, point[0], point[1], x, y));
}
// A 179.9 -> 180.1 degree edge must end on both map edges and never draw a
// horizontal line through the equator's centre.
const uint8_t crossing[] = {2,0, 0xbc,0xbe,2,0, 0,0,0,0, 0x90,3,0};
Canvas canvas;
assert(renderWorldMapChunkForTest(world, crossing, sizeof(crossing), Canvas::line, &canvas));
assert(canvas.lines == 2 && !canvas.pixels[45][125]);
assert(canvas.nearby(36,45,1) && canvas.nearby(214,45,1));
}
static void testRealCoasts() {
Canvas coast;
auto v = view(37.8, -122.5);
assert(renderWorldMap(v, Canvas::line, &coast));
assert(coast.lines > 20);
int x, y;
assert(projectWorldPoint(v, 37.8, -122.5, x, y));
assert(coast.nearby(x, y, 5));
Canvas inland;
assert(renderWorldMap(view(38.5, -98), Canvas::line, &inland));
assert(inland.lines == 0);
Canvas islands;
assert(renderWorldMap(view(-16.5, 180, 500), Canvas::line, &islands));
assert(islands.lines > 10);
Canvas arctic;
assert(renderWorldMap(view(78.2, 15.6), Canvas::line, &arctic));
assert(arctic.lines > 20);
for (auto polar : {view(90, 0, 2000), view(-90, 180, 2000), view(90, -180, 20000)}) {
Canvas canvas;
assert(renderWorldMap(polar, Canvas::line, &canvas));
assert(canvas.lines > 0);
}
Canvas close;
assert(renderWorldMap(view(-16.5, -180, 5), Canvas::line, &close));
auto invalid = view(0, 0); invalid.height_km = 0;
assert(!renderWorldMap(invalid, Canvas::line, &close));
assert(!renderWorldMap(view(0, 0), nullptr, nullptr));
}
static void testChunksAndMalformedData() {
unsigned decoded = 0;
for (const auto& chunk : data::kChunks) {
uint8_t scratch[data::kScratchBytes];
unsigned size = sizeof(scratch);
assert(chunk.offset + chunk.packed <= sizeof(data::kDeflate));
assert(tinf_uncompress_exact(scratch, &size, data::kDeflate + chunk.offset, chunk.packed) == TINF_OK);
assert(size == chunk.raw && size <= sizeof(scratch));
Canvas canvas;
assert(renderWorldMapChunkForTest(view(0, 0, 20000), scratch, size, Canvas::line, &canvas));
// A truncation at every byte must fail unless it ends on a complete fragment.
for (unsigned tail = 1; tail < 10 && tail < size; ++tail) {
Canvas truncated;
(void)renderWorldMapChunkForTest(view(0, 0), scratch, size - tail, Canvas::line, &truncated);
}
++decoded;
}
assert(decoded == 32);
assert(data::kRingCount == 1422);
// Two points at 0,0 and 0.001,0.001 (zigzag delta 2,2).
uint8_t valid[] = {2,0, 0,0,0,0, 0,0,0,0, 2,2};
Canvas canvas;
assert(renderWorldMapChunkForTest(view(0, 0), valid, sizeof(valid), Canvas::line, &canvas));
assert(canvas.lines == 1);
for (size_t size = 1; size < sizeof(valid); ++size)
assert(!renderWorldMapChunkForTest(view(0, 0), valid, size, Canvas::line, &canvas));
valid[0] = 1;
assert(!renderWorldMapChunkForTest(view(0, 0), valid, sizeof(valid), Canvas::line, &canvas));
valid[0] = 97;
assert(!renderWorldMapChunkForTest(view(0, 0), valid, sizeof(valid), Canvas::line, &canvas));
valid[0] = 2;
valid[10] = valid[11] = 255;
assert(!renderWorldMapChunkForTest(view(0, 0), valid, sizeof(valid), Canvas::line, &canvas));
const uint8_t overflow[] = {2,0, 0,0,0,0, 0,0,0,0, 255,255,255,255,255,0};
assert(!renderWorldMapChunkForTest(view(0, 0), overflow, sizeof(overflow), Canvas::line, &canvas));
}
int main() {
testProjection();
testFloatProjectionAccuracyAndWorldOverview();
testRealCoasts();
testChunksAndMalformedData();
puts("world map projection, clipped raster, codec and parser checks passed");
}
+19
View File
@@ -69,6 +69,25 @@ def esp_fixture(path, modern=False, fragmented=False, internal_length=0x10000):
class FirmwareRamTest(unittest.TestCase):
def test_pocket_gui_reserves_expanded_history_without_changing_other_boards(self):
flags = {"DISPLAY_CLASS": "GxEPDDisplay", "HELTEC_MESH_POCKET": 1,
"COMPANION_RADIO_FULL": 1, "UI_MSG_PREVIEW_SIZE": 161}
target = "Mesh_pocket_companion_radio_full"
enabled = ram.requirements("NRF52_PLATFORM", flags, target)
self.assertEqual(enabled["components"]["screen_objects_and_history"], 12288)
self.assertNotIn("expanded_message_previews", enabled["components"])
self.assertGreaterEqual(enabled["required_contiguous_bytes"], 12288)
for changed in ({**flags, "UI_POCKET_GUI": 0},
{key: value for key, value in flags.items()
if key != "HELTEC_MESH_POCKET"}):
policy = ram.requirements("NRF52_PLATFORM", changed, target)
self.assertEqual(policy["components"]["screen_objects_and_history"], 8192)
self.assertEqual(policy["components"]["expanded_message_previews"], 2816)
larger = ram.requirements("NRF52_PLATFORM", {
**flags, "MESH_COMPANION_SCREEN_STARTUP_BYTES": 16384}, target)
self.assertEqual(larger["components"]["screen_objects_and_history"], 16384)
def test_st7789_budget_matches_production_allocation_peak_and_reuses_buffers(self):
ui = ROOT / "src/helpers/ui"
spi = (ui / "ST7789Spi.h").read_text()
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Exercise MeshPocket GUI state and settings with the production headers."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = ROOT / "test/fixtures/pocket_gui"
class PocketGuiTest(unittest.TestCase):
def test_gui_is_only_enabled_for_pocket_full(self):
compiler = shutil.which("g++")
if compiler is None:
self.skipTest("host G++ required")
source = "#include <helpers/ui/PocketGuiConfig.h>\nUI_POCKET_GUI\n"
profiles = [
([], "0"),
(["HELTEC_MESH_POCKET=1"], "0"),
(["COMPANION_RADIO_FULL=1"], "0"),
(["NRF52_PLATFORM=1", "RAK_4631=1", "COMPANION_RADIO_FULL=1"], "0"),
(["ESP32_PLATFORM=1", "LILYGO_T_DECK=1", "COMPANION_RADIO_FULL=1"], "0"),
(["HELTEC_MESH_POCKET=1", "COMPANION_RADIO_FULL=1"], "1"),
(["HELTEC_MESH_POCKET=1", "COMPANION_RADIO_FULL=1", "UI_POCKET_GUI=0"], "0"),
]
for flags, expected in profiles:
with self.subTest(flags=flags):
command = [compiler, "-E", "-P", "-x", "c++", "-",
"-I" + str(ROOT / "src"), *("-D" + flag for flag in flags)]
result = subprocess.run(command, input=source, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), expected)
for flags in ([], ["HELTEC_MESH_POCKET=1"], ["COMPANION_RADIO_FULL=1"]):
command = [compiler, "-E", "-P", "-x", "c++", "-", "-DUI_POCKET_GUI=1",
"-I" + str(ROOT / "src"), *("-D" + flag for flag in flags)]
result = subprocess.run(command, input=source, capture_output=True, text=True)
self.assertNotEqual(result.returncode, 0, "unsupported board accepted Pocket GUI")
self.assertIn("requires MeshPocket Full Companion", result.stderr)
def compile_and_run(self, source, extra_flags=()):
compiler = shutil.which("g++")
if compiler is None:
self.skipTest("host G++ required")
with tempfile.TemporaryDirectory(prefix="mesh-pocket-gui-") as directory:
binary = Path(directory) / "gui-test"
flags = ["-std=c++17", "-Wall", "-Wextra", "-Werror", "-g"]
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer",
"-fno-pie", "-no-pie"]
command = [compiler, *flags, *extra_flags,
"-I" + str(FIXTURE), "-I" + str(ROOT / "src"), "-I" + str(ROOT),
str(source), "-o", str(binary)]
for args in (command, [str(binary)]):
result = subprocess.run(args, capture_output=True, text=True)
self.assertEqual(result.returncode, 0,
" ".join(args) + "\n" + result.stdout + result.stderr)
def test_sent_messages_preserve_history_without_becoming_unread(self):
self.compile_and_run(FIXTURE / "test_sent_history.cpp")
def test_settings_integrity_and_message_board_state(self):
self.compile_and_run(FIXTURE / "test_pocket_state.cpp")
def test_native_board_layout_and_fractional_timezones(self):
self.compile_and_run(FIXTURE / "test_pocket_render.cpp",
["-DHELTEC_MESH_POCKET=1", "-DCOMPANION_RADIO_FULL=1"])
def test_pocket_controls_keep_network_reader_access(self):
source = (ROOT / "examples/companion_radio/ui-new/UITask.cpp").read_text()
home = source[source.index("class HomeScreen :"):]
navigation = home[home.index(" bool handleInput(char c) override {"):]
navigation = navigation.split("#ifdef COMPANION_EXCLUSIVE_WIFI_BLE", 1)[0]
implementation = "\n".join(extract_braced(home, signature) for signature in (
"void resetRadioProfileDisplayPage() {", "bool isPageVisible(uint8_t page) const {",
"void movePage(int direction) {", "void showFirstPage() {",
"bool isRadioPage() const {"))
implementation += "\n" + navigation + "return false; }\n"
fixture = (FIXTURE / "test_pocket_controls.cpp").read_text()
fixture = fixture.replace("// @HOME_IMPLEMENTATION@", implementation)
with tempfile.TemporaryDirectory(prefix="mesh-pocket-controls-") as directory:
generated = Path(directory) / "controls.cpp"
generated.write_text(fixture)
for signedness in ("-fsigned-char", "-funsigned-char"):
with self.subTest(signedness=signedness):
self.compile_and_run(generated, [signedness, "-DUI_POCKET_GUI=1",
"-DCOMPANION_FEATURE_READER=1", "-DUI_NO_DISCOVER_SCREEN=1",
"-Wno-unused-parameter"])
def test_received_and_sent_message_bindings_preserve_screen_policy(self):
source = (ROOT / "examples/companion_radio/ui-new/UITask.cpp").read_text()
methods = "\n".join(extract_braced(source, signature) for signature in (
"void UITask::newMsg(", "void UITask::channelMessageSent(",
"char UITask::handleMultiClick("))
fixture = (FIXTURE / "test_pocket_bindings.cpp").read_text()
fixture = fixture.replace("// @ADD_SENT@", extract_braced(source, "void addSent("))
fixture = fixture.replace("// @TASK_METHODS@", methods)
with tempfile.TemporaryDirectory(prefix="mesh-pocket-bindings-") as directory:
generated = Path(directory) / "bindings.cpp"
generated.write_text(fixture)
self.compile_and_run(generated, ["-DUI_POCKET_GUI=1",
"-DCOMPANION_FEATURE_READER=1", "-Wno-unused-parameter"])
if __name__ == "__main__":
unittest.main()
+171
View File
@@ -0,0 +1,171 @@
"""Qualify and carry GUI/font notices without changing firmware or DFU ZIPs."""
import hashlib
import json
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import package_pocket_gui_license as notice
import firmware_memory_manifest as memory
import firmware_build_recipe as recipe
import package_cascade_release as release
GUI = "_ZN4mesh2ui6pocket9PocketGui6headerEPKcS5_"
FONT = "u8g2_font_helvR08_tf"
def elf32(path, symbols=(GUI, FONT), flags=6, section_type=1, undefined=(), zero=()):
names, table = bytearray(b"\0"), bytearray(16)
data = b"CODE" * max(1, len(symbols))
for i, name in enumerate(symbols):
offset = len(names)
names += name.encode() + b"\0"
table += struct.pack("<IIIBBH", offset, 0x40000000 + i * 4,
0 if name in zero else 4, 0x12, 0, 0 if name in undefined else 1)
payload = 52 + 4 * 40
strings = payload + len(data)
symtab = strings + len(names)
header = b"\x7fELF\x01\x01\x01" + bytes(9)
header += struct.pack("<HH5I6H", 2, 40, 1, 0, 0, 52, 0, 52, 0, 0, 40, 4, 0)
sections = bytes(40)
sections += struct.pack("<10I", 0, section_type, flags, 0x40000000, payload, len(data), 0, 0, 4, 0)
sections += struct.pack("<10I", 0, 3, 0, 0, strings, len(names), 0, 0, 1, 0)
sections += struct.pack("<10I", 0, 2, 0, 0, symtab, len(table), 2, 1, 4, 16)
path.write_bytes(header + sections + data + names + table)
class PocketGuiLicenseTest(unittest.TestCase):
def qualify(self, directory, stem, target="test_companion_radio_usb"):
output = stem.parent / (stem.name + ".capabilities.json")
result = subprocess.run([sys.executable, str(ROOT / "scripts/check_firmware_capabilities.py"),
"--image", str(directory / "firmware.elf"), "--output", str(output),
"--target", target, "--platform", "ESP32_PLATFORM", "--build-profile", "standard"],
capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
return json.loads(output.read_text())
@unittest.skipUnless(sys.platform.startswith("linux"), "requires a Linux ELF compiler")
def test_compiler_produced_gui_and_font_symbols_qualify(self):
compiler = shutil.which("g++")
if compiler is None:
self.skipTest("host g++ required")
source = """
namespace mesh { namespace ui { namespace pocket {
class PocketGui { public: void header(const char*, const char*); };
void PocketGui::header(const char*, const char*) { asm volatile(\"\"); }
}}}
extern const unsigned char u8g2_font_helvR08_tf[] = {1, 2, 3, 4};
extern \"C\" void _start() {}
"""
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "linked.cpp"
input_path.write_text(source)
result = subprocess.run([compiler, "-m32", "-O0", "-fno-pie", "-no-pie",
"-fno-exceptions", "-fno-rtti", "-fno-stack-protector", "-nostdlib",
"-Wl,-e,_start", "-Wl,--build-id=none", str(input_path),
"-o", str(root / "firmware.elf")], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
evidence = notice.pocket_gui_evidence(root / "firmware.elf")
self.assertEqual(len(evidence), 2)
self.assertIn(FONT, evidence)
self.qualify(root, root / "compiled")
self.assertEqual(notice.collect_build_notice(root, root / "compiled").read_bytes(),
notice.notice_bytes())
def test_notice_requires_allocated_gui_or_font_definitions(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "firmware.elf"
elf32(path)
self.assertEqual(notice.pocket_gui_evidence(path), sorted((GUI, FONT)))
# A partially linked font still needs its font license.
elf32(path, symbols=(FONT,), flags=2)
self.assertEqual(notice.pocket_gui_evidence(path), [FONT])
for kwargs in ({"flags": 0}, {"flags": 4}, {"section_type": 8},
{"symbols": (GUI,), "flags": 2},
{"symbols": (FONT, "other"), "undefined": (FONT,)},
{"symbols": (GUI, "other"), "zero": (GUI,)}):
with self.subTest(kwargs=kwargs):
elf32(path, **kwargs)
self.assertEqual(notice.pocket_gui_evidence(path), [])
path.write_bytes((GUI + " " + FONT).encode())
self.assertEqual(notice.pocket_gui_evidence(path), [])
def test_target_name_alone_never_creates_notice_and_stale_notice_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
stem = root / "plain"
elf32(root / "firmware.elf", symbols=("unrelated",))
manifest = self.qualify(root, stem, "Mesh_pocket_companion_radio_full")
self.assertNotIn("third_party_notices", manifest)
self.assertIsNone(notice.collect_build_notice(root, stem))
notice.sidecar(stem).write_bytes(notice.notice_bytes())
with self.assertRaisesRegex(ValueError, "stale"):
notice.collect_build_notice(root, stem)
self.assertTrue(recipe.package_occupied(stem))
def test_notice_is_hashed_with_memory_proof_and_staged_for_release(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
build, output = root / "build", root / "out"
build.mkdir(); output.mkdir()
elf32(build / "firmware.elf")
version = "v1.18.0.1-test-deadbeef"
stem = output / ("test_companion_radio_usb-" + version)
manifest = self.qualify(build, stem)
data = notice.notice_bytes()
self.assertEqual(manifest["third_party_notices"], [notice.notice_record(stem, data)])
# No artifact bytes are rewritten to carry notices.
app = output / (stem.name + ".bin")
merged = output / (stem.name + "-merged.bin")
app.write_bytes(b"unchanged app"); merged.write_bytes(b"unchanged merged")
sidecar = notice.collect_build_notice(build, stem)
self.assertEqual(sidecar.read_bytes(), data)
self.assertEqual(notice.collect_build_notice(build, stem), sidecar)
report = dict(schema_version=1, passed=True, available_internal_bytes=80000,
required_heap_bytes=50000, largest_internal_region_bytes=80000,
required_contiguous_bytes=5120, target="build_env",
elf_sha256=hashlib.sha256((build / "firmware.elf").read_bytes()).hexdigest())
(build / "firmware.memory.json").write_text(json.dumps(report))
memory.package_report(build, stem)
proof = memory.validate_package(stem)
self.assertEqual(proof["files"][sidecar.name], hashlib.sha256(data).hexdigest())
records = release.collect_artifacts(output, version)
self.assertEqual(sum(path == sidecar for path in records[0]["files"]), 1)
self.assertEqual(app.read_bytes(), b"unchanged app")
self.assertEqual(merged.read_bytes(), b"unchanged merged")
sidecar.write_bytes(b"truncated")
with self.assertRaisesRegex(ValueError, "mismatched"):
memory.validate_package(stem)
sidecar.unlink()
with self.assertRaisesRegex(ValueError, "missing"):
memory.validate_package(stem)
with self.assertRaisesRegex(ValueError, "missing"):
release.collect_artifacts(output, version)
def test_metadata_cannot_omit_or_replace_linked_notice(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
stem = root / "gui"
elf32(root / "firmware.elf")
manifest = self.qualify(root, stem)
manifest_path = root / "gui.capabilities.json"
manifest["third_party_notices"] = []
manifest_path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(ValueError, "linked ELF"):
notice.collect_build_notice(root, stem)
manifest["third_party_notices"] = [notice.notice_record(stem, b"wrong")]
manifest_path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(ValueError, "source notice"):
notice.collect_build_notice(root, stem)
self.assertFalse(notice.valid_notice(b"MIT License"))
if __name__ == "__main__":
unittest.main()
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Qualify the real bounded world-map decoder, projection and generated pack."""
import importlib.util
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
import zlib
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location("pack_world_map", ROOT / "tools/meshpocket_map/pack_world_map.py")
packer = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(packer)
def run(command):
result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if result.returncode:
raise AssertionError("command failed: " + " ".join(map(str, command)) + "\n" + result.stdout)
return result.stdout
class PocketWorldMapTests(unittest.TestCase):
def test_generated_pack_bounds_and_roundtrip(self):
header = packer.OUTPUT.read_text(encoding="utf-8")
chunks = [tuple(map(int, row)) for row in re.findall(
r"\{(\d+), (\d+), (\d+), (-?\d+), (-?\d+), (-?\d+), (-?\d+)\}", header)]
data_section = header.split("static const uint8_t kDeflate[] = {", 1)[1].split("};", 1)[0]
packed = bytes(int(byte, 16) for byte in re.findall(r"0x([0-9a-f]{2})", data_section))
self.assertEqual(len(chunks), 32)
self.assertEqual(len(packed) + 24 * len(chunks), 80658)
self.assertIn("kRingCount = 1422;", header)
offset = 0
for start, size, raw_size, west, south, east, north in chunks:
self.assertEqual(start, offset)
self.assertLessEqual(raw_size, 3072)
self.assertLessEqual(west, east)
self.assertLessEqual(south, north)
stream = zlib.decompressobj(wbits=-15)
raw = stream.decompress(packed[start:start + size])
self.assertTrue(stream.eof)
self.assertFalse(stream.unused_data)
self.assertEqual(len(raw), raw_size)
offset += size
self.assertEqual(offset, len(packed))
def test_simplification_retains_tiny_islands_and_dateline(self):
island = [(170.0, -20.0), (170.001, -20.0), (170.001, -20.001),
(170.0, -20.001), (170.0, -20.0)]
simplified = packer.simplify(island)
self.assertGreaterEqual(len(set(simplified)), 3)
self.assertEqual(simplified[0], simplified[-1])
crossing = [(179.8, -20.0), (-179.8, -20.0), (-179.8, -20.4),
(179.8, -20.4), (179.8, -20.0)]
simplified = packer.simplify(crossing)
self.assertLess(max(p[0] for p in simplified) - min(p[0] for p in simplified), 1000)
self.assertEqual(simplified[0], simplified[-1])
with self.assertRaisesRegex(ValueError, "SHA-256"):
list(packer.source_rings(b"incorrect source archive"))
def test_real_renderer_and_parser_under_sanitizers(self):
cc, cxx = shutil.which("gcc"), shutil.which("g++")
if not cc or not cxx:
self.skipTest("GCC/G++ unavailable")
with tempfile.TemporaryDirectory(prefix="mesh-pocket-map-") as temporary:
directory = Path(temporary)
# Windows MinGW commonly has no sanitizer runtime. Linux CI runs
# the same real renderer with both bounds/undefined checks active.
sanitizer = [] if __import__("os").name == "nt" else ["-fsanitize=address,undefined"]
run([cc, "-std=c11", "-DMESHCORE_TINF_IMPLEMENTATION", "-g", "-O1", *sanitizer,
"-c", str(ROOT / "src/helpers/ota/tinf/tinflate.c"), "-o", str(directory / "tinf.o")])
executable = directory / "world_map"
run([cxx, "-std=c++17", "-DPOCKET_WORLD_MAP_TEST", "-I" + str(ROOT / "src"),
"-g", "-O1", *sanitizer, str(ROOT / "test/fixtures/pocket_world_map/test_world_map.cpp"),
str(ROOT / "src/helpers/ui/PocketWorldMap.cpp"), str(directory / "tinf.o"), "-o", str(executable)])
self.assertIn("checks passed", run([str(executable)]))
def test_arm_decode_stack_fits_companion_loop(self):
tool = shutil.which("arm-none-eabi-g++")
if not tool:
candidate = Path.home() / ".platformio/packages/toolchain-gccarmnoneeabi/bin/arm-none-eabi-g++"
if candidate.is_file():
tool = str(candidate)
if not tool:
self.skipTest("ARM compiler unavailable")
cc = str(Path(tool).with_name("arm-none-eabi-gcc"))
with tempfile.TemporaryDirectory(prefix="mesh-pocket-map-stack-") as temporary:
directory = Path(temporary)
flags = ["-mcpu=cortex-m4", "-mthumb", "-Oz", "-fno-inline-small-functions", "-fstack-usage"]
run([tool, "-std=gnu++17", *flags, "-fno-exceptions", "-fno-rtti", "-DPOCKET_WORLD_MAP_TEST",
"-I" + str(ROOT / "src"), "-c", str(ROOT / "src/helpers/ui/PocketWorldMap.cpp"),
"-o", str(directory / "map.o")])
run([cc, "-std=gnu11", *flags, "-DMESHCORE_TINF_IMPLEMENTATION", "-c",
str(ROOT / "src/helpers/ota/tinf/tinflate.c"), "-o", str(directory / "tinf.o")])
def frames(name):
rows = {}
for line in (directory / (name + ".su")).read_text().splitlines():
function, size, kind = line.rsplit("\t", 2)
self.assertEqual(kind, "static", line)
rows[function] = int(size)
return rows
renderer, decoder = frames("map"), frames("tinf")
entry = next(size for name, size in renderer.items() if "::renderWorldMap(" in name)
# Decoder helper sum overbounds mutually exclusive branches.
decode = sum(size for name, size in decoder.items()
if not name.endswith(":tinf_init") and not name.endswith(":tinf_uncompress"))
draw = sum(size for name, size in renderer.items()
if any(signature in name for signature in ("::drawChunk(", "::project(", "::readDelta(")))
peak = entry + max(decode, draw)
self.assertLessEqual(peak + 1536, 8192)
print(f"ARM Pocket map local stack: {peak} bytes + 1536 caller reserve <= 8192")
if __name__ == "__main__":
unittest.main()