diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 06efa06a2..d689703f3 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -854,7 +854,7 @@ jobs: run: >- python3 -B -m unittest test_message_navigation test_companion_reader test_reader_touch_coordinates - test_pocket_gui test_pocket_world_map test_pocket_eink_refresh + test_pocket_gui test_pocket_world_map test_pocket_eink_refresh test_pocket_panel_spi test_touch_debug_overlay test_touch_debug_cli test_color_theme test_indicator_messages_profile test_t096_message_footer_profile test_indicator_display_profile test_indicator_render_profile diff --git a/docs/mesh_pocket_gui.md b/docs/mesh_pocket_gui.md index 74fae4519..99c9b8edb 100644 --- a/docs/mesh_pocket_gui.md +++ b/docs/mesh_pocket_gui.md @@ -28,7 +28,9 @@ Existing node, channel and contact formats are unchanged. Timezone comes from the existing node preferences. Changing pages or map zoom uses a full clean refresh to clear the previous -image. Updates within the same page keep the faster partial refresh. +image. Updates within the same page keep the faster partial refresh, with a +clean refresh after at most ten partial updates. Settings allow shorter +intervals of one, three or five updates. The idle screen-off timer defaults to 15 minutes on battery and USB. Existing saved timeouts are retained; set `display.timeout` and `display.usb.timeout` to diff --git a/examples/companion_radio/ui-new/PocketGui.h b/examples/companion_radio/ui-new/PocketGui.h index e075301ba..8965bab6f 100644 --- a/examples/companion_radio/ui-new/PocketGui.h +++ b/examples/companion_radio/ui-new/PocketGui.h @@ -335,7 +335,7 @@ public: header("Settings", editing ? "editing" : nullptr); static const char* const names[] = {"Channel", "Text", "Names", "Screen", "Theme", "Return", "Clean", "Map zoom"}; static const char* const idle[] = {"30 seconds", "1 minute", "5 minutes", "Never"}; - static const char* const clean[] = {"10 updates", "30 updates", "60 updates", "Manual"}; + static const char* const clean[] = {"1 update", "3 updates", "5 updates", "10 updates"}; for (unsigned row = 0; row < SETTINGS_COUNT; ++row) { const int y = bodyTop() + row * 11; if (row == selected && editing) { fill(1, y - 1, _width - 2, 11); inverse(); } @@ -357,7 +357,7 @@ public: case 3: snprintf(value, sizeof(value), "%s", _settings.flip ? "Flipped" : "Normal"); break; case 4: snprintf(value, sizeof(value), "%s", _settings.dark ? "Dark" : "Light"); break; case 5: snprintf(value, sizeof(value), "%s", idle[_settings.idle <= 3 ? _settings.idle : 1]); break; - case 6: snprintf(value, sizeof(value), "%s", clean[_settings.refresh <= 3 ? _settings.refresh : 1]); break; + case 6: snprintf(value, sizeof(value), "%s", clean[_settings.refresh <= 3 ? _settings.refresh : 3]); break; default: snprintf(value, sizeof(value), "%u km", (unsigned)mapHeightKm(_settings)); break; } textRight(_width - 4, y + 8, value); diff --git a/examples/companion_radio/ui-new/PocketReaderDisplay.h b/examples/companion_radio/ui-new/PocketReaderDisplay.h new file mode 100644 index 000000000..6cc8a59d2 --- /dev/null +++ b/examples/companion_radio/ui-new/PocketReaderDisplay.h @@ -0,0 +1,95 @@ +#pragma once + +#include + +#if UI_POCKET_GUI + +#include +#include +#include + +namespace mesh { +namespace ui { +namespace pocket { + +// Reader pagination and drawing share the Pocket UI's small Helvetica font. +// Keep this adapter persistent: the Reader already decodes on the loop stack. +class PocketReaderDisplay : public DisplayDriver { + GxEPDDisplay& _display; + U8G2_FOR_ADAFRUIT_GFX _font; + int _x = 0, _y = 0; + ColorVal _color = UIColor::primary_txt; + +public: + explicit PocketReaderDisplay(GxEPDDisplay& display) + : DisplayDriver(display.width(), display.height()), _display(display) { + _font.begin(display.gfx()); + _font.setFont(u8g2_font_helvR08_tf); + _font.setFontMode(1); + _font.setFontDirection(0); + } + + bool isOn() override { return _display.isOn(); } + bool isEink() override { return true; } + void forceFullRefresh() override { _display.forceFullRefresh(); } + void turnOn() override { _display.turnOn(); } + void turnOff() override { _display.turnOff(); } + void clear() override { _display.clear(); } + void startFrame(ColorVal background = UIColor::window_bkg) override { + _display.startFrame(background); + } + void endFrame() override { _display.endFrame(); } + void setTextSize(int) override { + // Reader headings, body and controls use one small font. Sync dimensions + // before measuring too, including when resuming after a rotation change. + setDimensions(_display.width(), _display.height()); + } + int textLineHeight() override { + return _font.getFontAscent() - _font.getFontDescent() + 3; + } + void setColor(ColorVal color) override { + _color = color; + _display.setColor(color); + _font.setForegroundColor(color); + _font.setBackgroundColor(UIColor::window_bkg); + } + void setCursor(int x, int y) override { _x = x; _y = y; } + uint16_t getTextWidth(const char* text) override { + // Helvetica's j can extend one pixel before its cursor. Reserve that + // bearing in both wrapping and drawing so a new row never clips it. + return text && *text ? _font.getUTF8Width(text) + 1 : 0; + } + void print(const char* text) override { + if (!text) return; + // U8g2 draws directly into GFX; include its font, geometry and content in + // the display CRC so text-only changes still trigger a panel update. + const int geometry[] = {0x508, _x, _y, _color}; + _display.crcAdd(geometry, sizeof(geometry)); + _display.crcAdd(text, strlen(text)); + _font.drawUTF8(_x + 1, _y + _font.getFontAscent(), text); + _x += getTextWidth(text); + } + void printWordWrap(const char* text, int max_width) override { + if (max_width > width() - _x) max_width = width() - _x; + const int glyph_height = _font.getFontAscent() - _font.getFontDescent(); + const int available = height() - _y; + const int rows = available < glyph_height ? 0 + : 1 + (available - glyph_height) / textLineHeight(); + drawTextWrapped(*this, _x, _y, max_width, textLineHeight(), rows, text); + } + void fillRect(int x, int y, int width, int height) override { + _display.fillRect(x, y, width, height); + } + void drawRect(int x, int y, int width, int height) override { + _display.drawRect(x, y, width, height); + } + void drawXbm(int x, int y, const uint8_t* bits, int width, int height) override { + _display.drawXbm(x, y, bits, width, height); + } +}; + +} // namespace pocket +} // namespace ui +} // namespace mesh + +#endif diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 658b45e2d..c28b93ff8 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -136,6 +136,9 @@ static mesh::ui::RadioProfileSystemStatus radioProfileSystemStatus( #if COMPANION_FEATURE_READER #include "ReaderScreen.h" +#if UI_POCKET_GUI +#include "PocketReaderDisplay.h" +#endif #include #endif @@ -761,7 +764,7 @@ class HomeScreen : public UIScreen { if (_pocket_browsing) frame.hint = "1x older 2x newer hold exit"; else if (_pocket_zooming) frame.hint = "1x zoom in 2x out hold done"; else if (_pocket_editing) frame.hint = "1x value 2x field hold save"; - else if (isRadioPage()) frame.hint = "click next 2x back hold Reader"; + else if (isRadioPage()) frame.hint = "click next 2x back"; else if (_page == HomePage::FIRST) frame.hint = "click next 2x back hold browse"; else if (_page == HomePage::MAP) frame.hint = "click next 2x back hold zoom"; else if (_page == HomePage::SETTINGS) frame.hint = "click next 2x back hold edit"; @@ -2390,7 +2393,13 @@ void UITask::showMessages() { void UITask::showReader() { if (!_display || isPairingScreenActive()) return; if (!_display->isOn()) _display->wake(mesh::ui::DisplayWake::Button); +#if UI_POCKET_GUI + static mesh::ui::pocket::PocketReaderDisplay reader_display( + *static_cast(_display)); + if (!reader) reader = new (std::nothrow) ReaderScreen(this, &reader_display); +#else if (!reader) reader = new (std::nothrow) ReaderScreen(this, _display); +#endif if (!reader) { showAlert("Reader: no memory", 1500); return; } static_cast(reader)->open(); setCurrScreen(reader); diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index b105f8607..82ec9ee2d 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -120,13 +120,20 @@ void GxEPDDisplay::turnOff() { expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); #endif _isOn = false; - // do full refresh before powering off to clear screen - // no full refresh needed at wakeup - display.clearScreen(0xFF); // Clears microcontroller side RAM - display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers + // Clear the visible image when the idle screen timer expires. +#if UI_POCKET_GUI + display.epd2.prepareRefresh(false); +#endif + display.clearScreen(0xFF); // Clear the panel and both controller image banks. + display.writeScreenBuffer(0xFF); resetPartialRefreshCounter(); last_display_crc_value=0; +#if UI_POCKET_GUI + _full_frame = false; + display.epd2.finishRefresh(); +#else display.hibernate(); +#endif } void GxEPDDisplay::clear() { @@ -264,15 +271,17 @@ void GxEPDDisplay::endFrame() { uint32_t crc = display_crc.finalize(); #if UI_POCKET_GUI if (_full_frame) { + display.epd2.prepareRefresh(false); display.display(false); display.setPartialWindow(0, 0, display.width(), display.height()); resetPartialRefreshCounter(); _full_frame = false; - display.powerOff(); + display.epd2.finishRefresh(); } else if (crc != last_display_crc_value) { + display.epd2.prepareRefresh(true); display.display(true); if (_cycles_before_full_refresh > 0) --_cycles_before_full_refresh; - display.powerOff(); + display.epd2.finishRefresh(); } #else if (crc != last_display_crc_value) { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 1ac062043..6ed7055f9 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -16,6 +16,9 @@ #include "DisplayDriver.h" #include "PocketGuiConfig.h" +#if UI_POCKET_GUI + #include "MeshPocketEinkPanel.h" +#endif #ifndef EINK_MAX_PARTIAL_REFRESH // 60 to prevent ghosting when refreshing every minute ... @@ -34,16 +37,15 @@ class GxEPDDisplay : public DisplayDriver { -#if defined(EINK_DISPLAY_MODEL) - GxEPD2_BW display; -#else - GxEPD2_BW display; -#endif -#if defined(EINK_DISPLAY_MODEL) +#if UI_POCKET_GUI + using Panel = MeshPocketEinkPanel; + static int partialRefreshLimit(int count) { return count < 0 || count > 10 ? 10 : count; } +#elif defined(EINK_DISPLAY_MODEL) using Panel = EINK_DISPLAY_MODEL; #else using Panel = GxEPD2_150_BN; #endif + GxEPD2_BW display; static constexpr int kWidth = (DISPLAY_ROTATION & 1) ? Panel::HEIGHT : Panel::WIDTH; static constexpr int kHeight = (DISPLAY_ROTATION & 1) ? Panel::WIDTH : Panel::HEIGHT; int _text_ascent = 13; @@ -57,15 +59,20 @@ class GxEPDDisplay : public DisplayDriver { uint16_t _curr_color; CRC32 display_crc; int last_display_crc_value = 0; +#if UI_POCKET_GUI + int _cycles_before_full_refresh = partialRefreshLimit(EINK_MAX_PARTIAL_REFRESH); + int max_partial_refresh = partialRefreshLimit(EINK_MAX_PARTIAL_REFRESH); +#else int _cycles_before_full_refresh = EINK_MAX_PARTIAL_REFRESH; - int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; // so this can be changed by an option after + int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; +#endif #if UI_POCKET_GUI bool _full_frame = false; #endif public: #if defined(EINK_DISPLAY_MODEL) - GxEPDDisplay() : DisplayDriver(kWidth, kHeight), display(EINK_DISPLAY_MODEL(PIN_DISPLAY_CS, PIN_DISPLAY_DC, PIN_DISPLAY_RST, PIN_DISPLAY_BUSY)) {} + GxEPDDisplay() : DisplayDriver(kWidth, kHeight), display(Panel(PIN_DISPLAY_CS, PIN_DISPLAY_DC, PIN_DISPLAY_RST, PIN_DISPLAY_BUSY)) {} #else GxEPDDisplay() : DisplayDriver(kWidth, kHeight), display(GxEPD2_150_BN(DISP_CS, DISP_DC, DISP_RST, DISP_BUSY)) {} #endif @@ -77,6 +84,7 @@ public: display_crc.update(static_cast(bytes), length); } void setMaxPartialRefresh(int count) { + count = partialRefreshLimit(count); if (count == max_partial_refresh) return; max_partial_refresh = count; // Keep a clean refresh that is already due or explicitly requested. diff --git a/src/helpers/ui/MeshPocketEinkPanel.h b/src/helpers/ui/MeshPocketEinkPanel.h new file mode 100644 index 000000000..796ee12fe --- /dev/null +++ b/src/helpers/ui/MeshPocketEinkPanel.h @@ -0,0 +1,61 @@ +#pragma once + +#include + +// MeshPocket's SSD1680 glass needs its own refresh/power sequence. Register +// values and settling times are documented by the LCMEN2R13ECC1 profile in +// https://github.com/meshtastic/firmware/tree/develop/src/graphics/niche/Drivers/EInk +// Keep GxEPD2's tested bitmap transfer and 128 x 250 RAM / 122-pixel geometry. +class MeshPocketEinkPanel : public GxEPD2_213_B74 { +public: + MeshPocketEinkPanel(int16_t cs, int16_t dc, int16_t rst, int16_t busy) + : GxEPD2_213_B74(cs, dc, rst, busy) {} + + void prepareRefresh(bool partial) { + // Reset only the controller. BW::init() would also erase the drawn canvas. + // initial=false preserves the previous image RAM instead of writing white. + GxEPD2_EPD::init(0, false, 10, false); + _waitWhileBusy(nullptr, 1000); + _using_partial_mode = partial; + } + + void refresh(bool partial = false) override { + _writeCommand(0x3C); // Border waveform + _writeData(partial ? 0x85 : 0x05); + _writeCommand(0x22); // Load OTP waveform, update, then disable panel power + _writeData(partial ? 0xFF : 0xF7); + _writeCommand(0x20); + // BUSY can initially read low. Do not overwrite image history or sleep + // until the panel has had its minimum settling time, then honor BUSY. + delay(partial ? 800 : 2500); + _waitWhileBusy(nullptr, partial ? 800 : 2500); + _initial_refresh = false; + _power_is_on = false; + } + + void refresh(int16_t, int16_t, int16_t w, int16_t h) override { + // The Pocket uses a full-screen canvas, including for differential updates. + if (w > 0 && h > 0) refresh(true); + } + + void powerOff() override { + // 0xFF / 0xF7 already disable panel power. An extra 0x83 / 0x20 sequence + // between the refresh and image-history synchronization is unnecessary. + _power_is_on = false; + } + + void hibernate() override { + if (_rst < 0) return; + _writeCommand(0x10); + _writeData(0x01); // Deep sleep mode 1 retains current / previous image RAM. + _hibernating = true; + _init_display_done = false; + } + + void finishRefresh() { + // Call after BW::display() has synchronized both image RAM banks. + _writeCommand(0x7F); // Terminate image write without another update. + _waitWhileBusy(nullptr, 1000); + hibernate(); + } +}; diff --git a/src/helpers/ui/PocketGuiSettings.h b/src/helpers/ui/PocketGuiSettings.h index 9f416d51d..9e7cfb146 100644 --- a/src/helpers/ui/PocketGuiSettings.h +++ b/src/helpers/ui/PocketGuiSettings.h @@ -16,7 +16,7 @@ struct Settings { uint8_t flip = 0; uint8_t dark = 0; uint8_t idle = 1; - uint8_t refresh = 1; + uint8_t refresh = 3; uint8_t map_zoom = 3; }; @@ -44,7 +44,7 @@ inline uint16_t settingsChecksum(const uint8_t* bytes, size_t length) { inline bool encodeSettings(const Settings& value, uint8_t* bytes, size_t size, unsigned channel_count = 40) { if (bytes == nullptr || size != SETTINGS_RECORD_SIZE || !settingsValid(value, channel_count)) return false; - bytes[0] = 'P'; bytes[1] = 'G'; bytes[2] = 1; + bytes[0] = 'P'; bytes[1] = 'G'; bytes[2] = 2; bytes[3] = value.channel; bytes[4] = value.text_large; bytes[5] = value.name_len; @@ -62,7 +62,7 @@ inline bool encodeSettings(const Settings& value, uint8_t* bytes, size_t size, inline bool decodeSettings(Settings& value, const uint8_t* bytes, size_t size, unsigned channel_count = 40) { if (bytes == nullptr || size != SETTINGS_RECORD_SIZE - || bytes[0] != 'P' || bytes[1] != 'G' || bytes[2] != 1 + || bytes[0] != 'P' || bytes[1] != 'G' || (bytes[2] != 1 && bytes[2] != 2) || (bytes[6] & ~3U) != 0 || bytes[10] != 0 || settingsChecksum(bytes, 11) != (uint16_t)(bytes[11] | (uint16_t)bytes[12] << 8)) return false; Settings next; @@ -70,6 +70,9 @@ inline bool decodeSettings(Settings& value, const uint8_t* bytes, size_t size, next.flip = bytes[6] & 1; next.dark = (bytes[6] >> 1) & 1; next.idle = bytes[7]; next.refresh = bytes[8]; next.map_zoom = bytes[9]; if (!settingsValid(next, channel_count)) return false; + // Older choices were 10/30/60/manual. Keep their other preferences while + // applying the Pocket panel's ten-partial-update cleanup limit. + if (bytes[2] == 1) next.refresh = 3; value = next; return true; } @@ -80,8 +83,8 @@ inline uint32_t idleMillis(const Settings& value) { } inline int refreshCount(const Settings& value) { - static const int values[] = {10, 30, 60, -1}; - return values[value.refresh <= 3 ? value.refresh : 1]; + static const int values[] = {1, 3, 5, 10}; + return values[value.refresh <= 3 ? value.refresh : 3]; } inline unsigned nameCharacters(const Settings& value) { diff --git a/test/fixtures/pocket_eink_refresh/GxEPD2_BW.h b/test/fixtures/pocket_eink_refresh/GxEPD2_BW.h index 8e7776b3e..20b306ac1 100644 --- a/test/fixtures/pocket_eink_refresh/GxEPD2_BW.h +++ b/test/fixtures/pocket_eink_refresh/GxEPD2_BW.h @@ -5,7 +5,8 @@ #define GxEPD_WHITE 1 namespace panel { -enum class Call { Full, Partial, PowerOff, Clear, WriteWhite, Hibernate }; +enum class Call { Full, Partial, PowerOff, Clear, WriteWhite, Hibernate, + PrepareFull, PreparePartial, Finish }; inline std::vector calls; inline std::vector images; inline bool valid_history = false; @@ -56,6 +57,9 @@ public: void drawRect(int, int, int, int, int) {} void drawBitmap(int, int, const uint8_t*, int, int, int) {} void display(bool partial) { + assert(!panel::calls.empty()); + assert(panel::calls.back() == (partial ? panel::Call::PreparePartial : panel::Call::PrepareFull) + && "reset / configure immediately before uploading the drawn canvas"); if (partial) assert(panel::valid_history && "partial refresh must follow a clean image after wake"); panel::calls.push_back(partial ? panel::Call::Partial : panel::Call::Full); diff --git a/test/fixtures/pocket_eink_refresh/MeshPocketEinkPanel.h b/test/fixtures/pocket_eink_refresh/MeshPocketEinkPanel.h new file mode 100644 index 000000000..5068fbc97 --- /dev/null +++ b/test/fixtures/pocket_eink_refresh/MeshPocketEinkPanel.h @@ -0,0 +1,18 @@ +#pragma once +#include + +// This fixture checks the adapter's decisions. test_pocket_panel_spi.py runs +// the production profile against the real GxEPD2 register/bitmap implementation. +struct MeshPocketEinkPanel : GxEPD2_213_B74 { + using GxEPD2_213_B74::GxEPD2_213_B74; + void prepareRefresh(bool partial) { + panel::calls.push_back(partial ? panel::Call::PreparePartial : panel::Call::PrepareFull); + } + void finishRefresh() { + assert(!panel::calls.empty()); + const auto previous = panel::calls.back(); + assert(previous == panel::Call::Full || previous == panel::Call::Partial + || previous == panel::Call::WriteWhite); + panel::calls.push_back(panel::Call::Finish); + } +}; diff --git a/test/fixtures/pocket_eink_refresh/main.cpp b/test/fixtures/pocket_eink_refresh/main.cpp index a5968c4a8..a9787bb7c 100644 --- a/test/fixtures/pocket_eink_refresh/main.cpp +++ b/test/fixtures/pocket_eink_refresh/main.cpp @@ -22,6 +22,8 @@ static void cleanBaseline(GxEPDDisplay& display, int interval = 2) { frame(display, "Network"); assert(panel::updates(Call::Full) == 1 && panel::updates(Call::Partial) == 0); assert(panel::images.back() == "Network"); + assert(panel::updates(Call::PrepareFull) == 1 && panel::updates(Call::Finish) == 1); + assert(panel::updates(Call::PowerOff) == 0); } int main(int argc, char** argv) { @@ -96,11 +98,11 @@ int main(int argc, char** argv) { const std::string value = "tick " + std::to_string(i); frame(display, value.c_str()); } - assert(panel::updates(Call::Full) == full && "manual mode allows partial updates until explicitly cleaned"); - assert(panel::updates(Call::Partial) == 70); + assert(panel::updates(Call::Full) == full + 6 && "manual mode must also honor the ten-partial hardware limit"); + assert(panel::updates(Call::Partial) == 64); } else if (scenario == "wake") { display.turnOff(); - assert(!display.isOn() && panel::updates(Call::Hibernate) == 1); + assert(!display.isOn() && panel::updates(Call::Finish) == 2); const auto full = panel::updates(Call::Full); const auto partial = panel::updates(Call::Partial); display.turnOn(); diff --git a/test/fixtures/pocket_gui/test_pocket_state.cpp b/test/fixtures/pocket_gui/test_pocket_state.cpp index 4b708cc7a..5ac34f9e8 100644 --- a/test/fixtures/pocket_gui/test_pocket_state.cpp +++ b/test/fixtures/pocket_gui/test_pocket_state.cpp @@ -22,7 +22,7 @@ static void repairChecksum(uint8_t* bytes) { static void settingsRoundTrip() { Settings value; assert(settingsValid(value)); - assert(idleMillis(value) == 60000 && refreshCount(value) == 30); + assert(idleMillis(value) == 60000 && refreshCount(value) == 10); assert(nameCharacters(value) == 5 && mapHeightKm(value) == 200); uint8_t bytes[SETTINGS_RECORD_SIZE]; @@ -73,7 +73,7 @@ static void settingsRoundTrip() { // 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}; + const unsigned bad_values[] = {'X', 'X', 3, 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)); @@ -82,6 +82,23 @@ static void settingsRoundTrip() { rejects(changed, sizeof(changed)); } + // Migrate each old cleanup choice without resetting any other settings. + for (unsigned old_refresh = 0; old_refresh < 4; ++old_refresh) { + Settings old{39, 1, 3, 1, 1, 2, static_cast(old_refresh), 8}; + assert(encodeSettings(old, bytes, sizeof(bytes))); + bytes[2] = 1; + repairChecksum(bytes); + Settings migrated; + assert(decodeSettings(migrated, bytes, sizeof(bytes))); + old.refresh = 3; + assert(equal(migrated, old) && refreshCount(migrated) == 10); + } + const int cleanup_counts[] = {1, 3, 5, 10}; + for (unsigned choice = 0; choice < 4; ++choice) { + value.refresh = choice; + assert(refreshCount(value) == cleanup_counts[choice]); + } + value.channel = 39; assert(encodeSettings(value, bytes, sizeof(bytes), 40)); rejects(bytes, sizeof(bytes), 39); @@ -105,7 +122,7 @@ static void settingsRoundTrip() { for (unsigned bad = 4; bad <= 255; ++bad) { value.idle = value.refresh = value.name_len = static_cast(bad); - assert(idleMillis(value) == 60000 && refreshCount(value) == 30); + assert(idleMillis(value) == 60000 && refreshCount(value) == 10); assert(nameCharacters(value) == 5); } for (unsigned bad = 9; bad <= 255; ++bad) { diff --git a/test/fixtures/pocket_panel_spi/Adafruit_GFX.h b/test/fixtures/pocket_panel_spi/Adafruit_GFX.h new file mode 100644 index 000000000..889c9db4c --- /dev/null +++ b/test/fixtures/pocket_panel_spi/Adafruit_GFX.h @@ -0,0 +1,21 @@ +#pragma once +#include +// Only GFX geometry is stubbed; GxEPD2_BW supplies the real canvas/drawPixel. +class Adafruit_GFX { + public: + const int16_t WIDTH, HEIGHT; + Adafruit_GFX(int16_t w, int16_t h) : WIDTH(w), HEIGHT(h), w_(w), h_(h) {} + virtual ~Adafruit_GFX() = default; + virtual void drawPixel(int16_t, int16_t, uint16_t) = 0; + int16_t width() const { return w_; } + int16_t height() const { return h_; } + uint8_t getRotation() const { return rotation_; } + void setRotation(uint8_t value) { + rotation_ = value & 3; + w_ = rotation_ & 1 ? HEIGHT : WIDTH; + h_ = rotation_ & 1 ? WIDTH : HEIGHT; + } + private: + int16_t w_, h_; + uint8_t rotation_ = 0; +}; diff --git a/test/fixtures/pocket_panel_spi/Arduino.h b/test/fixtures/pocket_panel_spi/Arduino.h new file mode 100644 index 000000000..22582c245 --- /dev/null +++ b/test/fixtures/pocket_panel_spi/Arduino.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include +#include +#define LOW 0 +#define HIGH 1 +#define INPUT 0 +#define OUTPUT 1 +#define INPUT_PULLUP 2 +void delay(unsigned long ms); +unsigned long micros(); +unsigned long millis(); +void digitalWrite(int pin, int value); +int digitalRead(int pin); +void pinMode(int pin, int mode); +struct RecordingSerial { + void begin(unsigned long) {} + template void print(const T&) {} + template void println(const T&) {} +}; +inline RecordingSerial Serial; diff --git a/test/fixtures/pocket_panel_spi/SPI.h b/test/fixtures/pocket_panel_spi/SPI.h new file mode 100644 index 000000000..403d34538 --- /dev/null +++ b/test/fixtures/pocket_panel_spi/SPI.h @@ -0,0 +1,13 @@ +#pragma once +#include +#define MSBFIRST 1 +#define SPI_MODE0 0 +struct SPISettings { SPISettings(unsigned long, int, int) {} }; +struct SPIClass { + void begin() {} + void end() {} + void beginTransaction(SPISettings) {} + void endTransaction() {} + uint8_t transfer(uint8_t value); +}; +inline SPIClass SPI; diff --git a/test/fixtures/pocket_panel_spi/avr/pgmspace.h b/test/fixtures/pocket_panel_spi/avr/pgmspace.h new file mode 100644 index 000000000..127b1148b --- /dev/null +++ b/test/fixtures/pocket_panel_spi/avr/pgmspace.h @@ -0,0 +1,3 @@ +#pragma once +#define PROGMEM +#define pgm_read_byte(p) (*reinterpret_cast(p)) diff --git a/test/fixtures/pocket_panel_spi/main.cpp b/test/fixtures/pocket_panel_spi/main.cpp new file mode 100644 index 000000000..592e11aff --- /dev/null +++ b/test/fixtures/pocket_panel_spi/main.cpp @@ -0,0 +1,188 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int CS = 1, DC = 2, RST = 3, BUSY = 4; +using Bitmap = std::array; +struct Command { + uint8_t value; + uint64_t time; + std::vector data; +}; +std::vector commands; +std::vector resets; +int pins[5] = {HIGH, HIGH, HIGH, HIGH, LOW}; +uint64_t time_ms = 0, refresh_started = 0; +bool late_busy = false, updating = false; +unsigned busy_reads = 0; +uint8_t update_mode = 0; +Bitmap current{}, previous{}, expected{}, old_frame{}; +uint64_t history_time = 0; + +void checkCommandData() { + if (commands.empty()) return; + const auto& command = commands.back(); + if (command.value == 0x24 || command.value == 0x26) { + assert(command.data.size() == 4000); + // Any automatic all-white controller clear would fail for these patterns. + assert(std::equal(command.data.begin(), command.data.end(), expected.begin())); + auto& destination = command.value == 0x24 ? current : previous; + std::copy(command.data.begin(), command.data.end(), destination.begin()); + if (updating) history_time = command.time; + } +} + +uint64_t busyEnd() { + return refresh_started + (update_mode == 0xFF ? 1100 : 2900); +} + +void recordCommand(uint8_t value) { + checkCommandData(); + if (value == 0x20) { + assert(!commands.empty()); + assert(commands.back().value == 0x22 && commands.back().data.size() == 1); + update_mode = commands.back().data[0]; + assert(update_mode == 0xFF || update_mode == 0xF7); + assert(current == expected); + if (update_mode == 0xFF) assert(previous == old_frame); + else assert(previous == expected); + refresh_started = time_ms; + updating = true; + } + if (value == 0x7F || value == 0x10) { + assert(updating); + const auto minimum = update_mode == 0xFF ? 800u : 2500u; + assert(time_ms >= refresh_started + minimum); + if (late_busy) assert(time_ms >= busyEnd()); + assert(current == expected && previous == expected); + assert(history_time >= refresh_started + minimum); + } + commands.push_back({value, time_ms, {}}); +} + +using Display = GxEPD2_BW; + +Bitmap drawPattern(Display& display, unsigned pattern) { + display.fillScreen(GxEPD_WHITE); + Bitmap bitmap; + bitmap.fill(0xFF); + // Exercise actual BW rotation and visible 122px versus 128px controller RAM. + for (int y = 0; y < 122; ++y) { + for (int x = 0; x < 250; ++x) { + if (((x * 7 + y * 11 + pattern * 13) % 29) >= 7) continue; + display.drawPixel(x, y, GxEPD_BLACK); + const int controller_x = y; + const int controller_y = 249 - x; + bitmap[controller_y * 16 + controller_x / 8] &= ~(1u << (7 - controller_x % 8)); + } + } + return bitmap; +} + +void frame(Display& display, unsigned pattern, bool partial, bool late) { + old_frame = current; + expected = drawPattern(display, pattern); + late_busy = late; + updating = false; + commands.clear(); + resets.clear(); + busy_reads = 0; + const auto frame_start = time_ms; + display.epd2.prepareRefresh(partial); + assert(commands.empty()); // prepare must never upload white or other image data + assert(resets.size() == 1 && resets.front() >= frame_start); + display.display(partial); // actual BW current upload / refresh / history sync + display.epd2.finishRefresh(); + checkCommandData(); + assert(display.width() == 250 && display.height() == 122); + assert(resets.size() == 1); + assert(!commands.empty() && commands.front().value == 0x12); + assert(resets.front() < commands.front().time); + assert(commands.back().value == 0x10 && commands.back().data == std::vector{1}); + assert(busy_reads > 0); + + std::vector uploads; + std::vector modes; + uint64_t refresh_time = 0, first_sync_time = 0; + size_t final_border = 0, refresh_index = 0, sync_index = 0, nop_index = 0; + for (size_t i = 0; i < commands.size(); ++i) { + const auto& command = commands[i]; + if (command.value == 0x24 || command.value == 0x26) { + uploads.push_back(command.value); + assert(command.data.size() == expected.size()); + assert(std::equal(command.data.begin(), command.data.end(), expected.begin())); + if (refresh_time && !first_sync_time) { + first_sync_time = command.time; + sync_index = i; + } + } + if (command.value == 0x3C) final_border = i; + if (command.value == 0x22) { + assert(command.data.size() == 1); + modes.push_back(command.data[0]); + } + if (command.value == 0x20) { refresh_time = command.time; refresh_index = i; } + if (command.value == 0x7F) nop_index = i; + if (command.value == 0x44) assert((command.data == std::vector{0, 15})); + if (command.value == 0x45) assert((command.data == std::vector{0, 0, 249, 0})); + } + assert((uploads == (partial ? std::vector{0x24, 0x26, 0x24} + : std::vector{0x26, 0x24, 0x26, 0x24}))); + assert(modes == std::vector{static_cast(partial ? 0xFF : 0xF7)}); + assert(commands[final_border].data == std::vector{static_cast(partial ? 0x85 : 0x05)}); + assert(final_border < refresh_index && refresh_index < sync_index && sync_index < nop_index); + assert(first_sync_time >= refresh_time + (partial ? 800 : 2500)); + if (late) assert(first_sync_time >= busyEnd()); + assert(current == expected && previous == expected); +} +} // namespace + +void delay(unsigned long ms) { time_ms += ms; } +unsigned long micros() { return static_cast(time_ms * 1000); } +unsigned long millis() { return static_cast(time_ms); } +void pinMode(int, int) {} +void digitalWrite(int pin, int value) { + assert(pin >= 0 && pin < 5); + if (pin == RST && value == LOW && pins[RST] == HIGH) resets.push_back(time_ms); + pins[pin] = value; +} +int digitalRead(int pin) { + assert(pin == BUSY); + ++busy_reads; + // A LOW pin immediately after triggering refresh must not shorten safe delay; + // a delayed BUSY assertion lasting beyond that delay must still be honored. + if (updating && late_busy && time_ms >= refresh_started + 50 && time_ms < busyEnd()) return HIGH; + return LOW; +} +uint8_t SPIClass::transfer(uint8_t value) { + assert(pins[CS] == LOW); + if (pins[DC] == LOW) recordCommand(value); + else { + assert(!commands.empty()); + commands.back().data.push_back(value); + } + return 0; +} + +int main() { + static_assert(MeshPocketEinkPanel::WIDTH == 128); + static_assert(MeshPocketEinkPanel::WIDTH_VISIBLE == 122); + static_assert(MeshPocketEinkPanel::HEIGHT == 250); + Display display(MeshPocketEinkPanel(CS, DC, RST, BUSY)); + display.init(); + display.setRotation(3); + current.fill(0xA5); + previous.fill(0xA5); + // Alternating patterns prove reset/deep sleep retained previous image RAM and + // that differential refresh never sees a white or stale history buffer. + frame(display, 1, false, false); + frame(display, 2, true, false); + frame(display, 3, true, true); + frame(display, 4, false, true); + std::puts("Pocket actual GxEPD2 SPI: full/partial/history/reset/sleep checks passed"); +} diff --git a/test/fixtures/pocket_reader/Adafruit_GFX.h b/test/fixtures/pocket_reader/Adafruit_GFX.h new file mode 100644 index 000000000..85d499819 --- /dev/null +++ b/test/fixtures/pocket_reader/Adafruit_GFX.h @@ -0,0 +1,39 @@ +#pragma once +#include +#include +#include +#include +#include + +class Print { public: virtual ~Print() = default; virtual size_t write(uint8_t) = 0; }; + +// Record the pixels emitted by the real U8g2 font decoder, including clipping. +class Adafruit_GFX { +public: + int w = 250, h = 122, clipped = 0; + std::vector pixels = std::vector(w * h, 1); + int width() const { return w; } + int height() const { return h; } + void resize(int width, int height) { + w = width; h = height; pixels.assign(w * h, 1); clipped = 0; + } + void fillScreen(uint16_t color) { + std::fill(pixels.begin(), pixels.end(), color != 0); clipped = 0; + } + void drawPixel(int x, int y, uint16_t color) { + if (x < 0 || y < 0 || x >= w || y >= h) { + if (!clipped) std::fprintf(stderr, "clipped %d,%d on %dx%d\n", x, y, w, h); + ++clipped; return; + } + pixels[y * w + x] = color != 0; + } + void drawFastHLine(int x, int y, int width, uint16_t color) { + for (int i = 0; i < width; ++i) drawPixel(x + i, y, color); + } + void drawFastVLine(int x, int y, int height, uint16_t color) { + for (int i = 0; i < height; ++i) drawPixel(x, y + i, color); + } + void fillRect(int x, int y, int width, int height, uint16_t color) { + for (int row = 0; row < height; ++row) drawFastHLine(x, y + row, width, color); + } +}; diff --git a/test/fixtures/pocket_reader/helpers/ui/GxEPDDisplay.h b/test/fixtures/pocket_reader/helpers/ui/GxEPDDisplay.h new file mode 100644 index 000000000..5d7645b45 --- /dev/null +++ b/test/fixtures/pocket_reader/helpers/ui/GxEPDDisplay.h @@ -0,0 +1,46 @@ +#pragma once +#include +#include + +constexpr uint16_t GxEPD_BLACK = 0, GxEPD_WHITE = 1; + +class GxEPDDisplay : public DisplayDriver { + Adafruit_GFX _gfx; + ColorVal _color = 0; +public: + bool on = true; + uint32_t hash = 2166136261U; + GxEPDDisplay() : DisplayDriver(250, 122) {} + Adafruit_GFX& gfx() { return _gfx; } + void resize(int width, int height) { + setDimensions(width, height); _gfx.resize(width, height); + } + bool isOn() override { return on; } + void turnOn() override { on = true; } + void turnOff() override { on = false; } + void clear() override { startFrame(); } + void startFrame(ColorVal background = 1) override { + hash = 2166136261U; _gfx.fillScreen(background); + } + void endFrame() override {} + void setTextSize(int) override {} + void setColor(ColorVal color) override { _color = color; } + void setCursor(int, int) override {} + void print(const char*) override { __builtin_trap(); } + uint16_t getTextWidth(const char*) override { __builtin_trap(); } + void fillRect(int x, int y, int width, int height) override { + _gfx.fillRect(x, y, width, height, _color); + } + void drawRect(int x, int y, int width, int height) override { + _gfx.drawFastHLine(x, y, width, _color); + _gfx.drawFastHLine(x, y + height - 1, width, _color); + _gfx.drawFastVLine(x, y, height, _color); + _gfx.drawFastVLine(x + width - 1, y, height, _color); + } + void drawXbm(int, int, const uint8_t*, int, int) override {} + void crcAdd(const void* value, size_t size) { + for (size_t i = 0; i < size; ++i) { + hash ^= static_cast(value)[i]; hash *= 16777619U; + } + } +}; diff --git a/test/fixtures/pocket_reader/test_pocket_reader.cpp b/test/fixtures/pocket_reader/test_pocket_reader.cpp new file mode 100644 index 000000000..281b52c28 --- /dev/null +++ b/test/fixtures/pocket_reader/test_pocket_reader.cpp @@ -0,0 +1,135 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace mesh::bible; +static uint32_t test_now = 100; +uint32_t millis() { return test_now; } +ColorVal UIColor::window_bkg = 1, UIColor::title_bkg = 1, UIColor::title_txt = 0; +ColorVal UIColor::primary_txt = 0, UIColor::secondary_txt = 0, UIColor::warning_txt = 0; +ColorVal UIColor::popup_bkg = 1, UIColor::popup_txt = 0, UIColor::corp_blue = 0; +struct FakeMesh { + Position saved = {}; + bool loadReaderBookmark(Position& p) { p = saved; return true; } + bool saveReaderBookmark(Position p) { saved = p; return true; } +} the_mesh; +class UITask { +public: + bool closed = false; + void closeReader() { closed = true; } + void showAlert(const char*, int) { assert(false); } +}; +#include + +struct Line { Position pos; std::string text; }; + +// Independent word wrapping, measured by the same real library used on-device. +static std::vector expectedLines(int width, U8G2_FOR_ADAFRUIT_GFX& font) { + std::vector lines; + for (uint16_t verse = 0; verse < kVerseCount; ++verse) { + char scratch[kBlockSize]; const char* text; + assert(mesh::readReaderVerse(referenceAt(verse), scratch, sizeof(scratch), text) + == LookupResult::Found); + const std::string source(text); + for (size_t offset = 0; offset < source.size();) { + const std::string prefix = offset == 0 ? std::to_string(referenceAt(verse).verse) + " " : ""; + size_t count = 0; + while (offset + count < source.size() && prefix.size() + count < kReaderLineBytes - 1) { + const auto candidate = prefix + source.substr(offset, count + 1); + if (count && font.getUTF8Width(candidate.c_str()) + 1 > width) break; + ++count; + } + assert(count); + if (offset + count < source.size()) { + const size_t space = source.rfind(' ', offset + count - 1); + if (space != std::string::npos && space > offset) count = space - offset; + } + lines.push_back({{verse, static_cast(offset)}, prefix + source.substr(offset, count)}); + offset += count; + while (offset < source.size() && source[offset] == ' ') ++offset; + } + } + return lines; +} + +int main() { + GxEPDDisplay display; + mesh::ui::pocket::PocketReaderDisplay reader_display(display); + UITask task; + Adafruit_GFX expected; + U8G2_FOR_ADAFRUIT_GFX font; + font.begin(expected); font.setFont(u8g2_font_helvR08_tf); + font.setFontMode(1); font.setFontDirection(0); + font.setForegroundColor(0); font.setBackgroundColor(1); + assert(font.getFontAscent() == 8 && font.getFontDescent() == -2); + assert(reader_display.textLineHeight() == 13); + assert(reader_display.getTextWidth("Willing") == font.getUTF8Width("Willing") + 1); + assert(reader_display.getTextWidth("iiii") < reader_display.getTextWidth("WWWW")); + + for (const auto& dimensions : {std::pair{250, 122}, {122, 250}}) { + display.resize(dimensions.first, dimensions.second); + expected.resize(dimensions.first, dimensions.second); + reader_display.setTextSize(1); + assert(reader_display.width() == display.width() && reader_display.height() == display.height()); + const auto lines = expectedLines(display.width(), font); + const int top = 15; + auto hint = mesh::ui::makeButtonReaderHintLayout(reader_display, 13, display.height()); + const int rows = (hint.top - top) / 13; + assert(rows >= 7); + + auto check = [&](ReaderScreen& reader, size_t first) { + display.startFrame(); reader.render(display); + assert(display.gfx().clipped == 0); + expected.fillScreen(1); + for (int row = 0; row < rows && first + row < lines.size(); ++row) + font.drawUTF8(1, top + row * 13 + 8, lines[first + row].text.c_str()); + assert(expected.clipped == 0); + for (int y = top; y < hint.top; ++y) + for (int x = 0; x < display.width(); ++x) + assert(display.gfx().pixels[y * display.width() + x] == expected.pixels[y * display.width() + x]); + assert(reader.flush()); + assert(the_mesh.saved.verse == lines[first].pos.verse && the_mesh.saved.offset == lines[first].pos.offset); + }; + + // Every subsection can resume a previous raw-text bookmark, fill the + // page across boundaries, advance, and return using the smaller font. + uint16_t previous = kVerseCount; + for (size_t first = 0; first < lines.size(); ++first) { + if (lines[first].pos.verse == previous) continue; + previous = lines[first].pos.verse; + the_mesh.saved = lines[first].pos; + ReaderScreen reader(&task, &reader_display); reader.open(); + check(reader, first); + if (first + rows < lines.size()) { + reader.handleInput(KEY_NEXT); check(reader, first + rows); + reader.handleInput(KEY_PREV); check(reader, first); + } + // Saved offsets inside a word still normalize to its containing line. + the_mesh.saved = lines[first].pos; + the_mesh.saved.offset += 2; + ReaderScreen resumed(&task, &reader_display); resumed.open(); + check(resumed, first); + } + } + + // Direct GFX text must contribute to the panel CRC on otherwise equal frames. + auto hash = [&](const char* text, int x, int y, ColorVal color) { + display.startFrame(); reader_display.setTextSize(1); reader_display.setColor(color); + reader_display.setCursor(x, y); reader_display.print(text); return display.hash; + }; + const auto original = hash("Reader", 0, 0, 0); + assert(original == hash("Reader", 0, 0, 0)); + assert(original != hash("Reader!", 0, 0, 0)); + assert(original != hash("Reader", 1, 0, 0)); + assert(original != hash("Reader", 0, 1, 0)); + assert(original != hash("Reader", 0, 0, 1)); + display.startFrame(); reader_display.setColor(0); reader_display.setCursor(0, 0); + reader_display.printWordWrap("A long line of words to wrap within the narrow reader viewport.", 50); + assert(display.gfx().clipped == 0); + std::puts("Pocket Reader: real Helvetica 08, all 879 subsections, pagination, resume, rotation and CRC passed"); +} diff --git a/test/test_pocket_panel_spi.py b/test/test_pocket_panel_spi.py new file mode 100644 index 000000000..b9948a613 --- /dev/null +++ b/test/test_pocket_panel_spi.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Run the Pocket panel profile through the pinned, real GxEPD2 SPI code. + +Only Arduino/SPI and the GFX base geometry are simulated. The production +GxEPD2 canvas, bitmap upload, register setup, refresh and history writes run. +No PlatformIO or hardware is needed; missing pinned sources are downloaded. +""" + +import hashlib +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +import urllib.request + + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = ROOT / "test/fixtures/pocket_panel_spi" +PINNED = { + "GxEPD2.h": "fd8f66f593ba9ec249249aa5d010f3e5fb951f8521635227e768218b2318b42d", + "GxEPD2_BW.h": "4073c085d2d5ab2c6178570ac49f1b65b0a71125b1b164645d75f5e57922adfc", + "GxEPD2_EPD.cpp": "0ce4a5030fdcd07b337fb1c932727e1cd11f8f6556b59cfd732e51e39fa4df03", + "GxEPD2_EPD.h": "2b51ad2e47afdea65d8de424055a76d1a61fd097bffc2f485f3511e96a3b496d", + "epd/GxEPD2_213_B74.cpp": "cbd162ac4d9d5abcc53eb3b0538366e6257cfafc911274f9b4e23bb5ec4eb94a", + "epd/GxEPD2_213_B74.h": "f98af064e8ab2c51110b58ffbf97151756cf7a3290da2f279ec6409a490a434f", +} + + +class PocketPanelSpiTest(unittest.TestCase): + def test_real_panel_preserves_bitmap_history_and_waits_before_sleep(self): + compiler = shutil.which(os.environ.get("CXX", "g++")) + if compiler is None: + self.skipTest("host G++ required") + cache = Path(os.environ.get("MESHCORE_GXEPD2_TEST_CACHE", + str(Path(tempfile.gettempdir()) / "meshcore-gxepd2-1.6.2"))) + for name, expected in PINNED.items(): + target = cache / name + if not target.is_file(): + url = "https://raw.githubusercontent.com/ZinggJM/GxEPD2/1.6.2/src/" + name + try: + with urllib.request.urlopen(url, timeout=30) as response: + data = response.read() + except OSError as error: + self.fail(f"Cannot fetch pinned GxEPD2 source {name}: {error}; " + "set MESHCORE_GXEPD2_TEST_CACHE to a verified offline cache") + self.assertEqual(hashlib.sha256(data).hexdigest(), expected, name) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + self.assertEqual(hashlib.sha256(target.read_bytes()).hexdigest(), expected, name) + with tempfile.TemporaryDirectory(prefix="pocket-panel-spi-") as directory: + binary = Path(directory) / "panel-test" + overrides = Path(directory) / "include" + 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, "-DDISABLE_DIAGNOSTIC_OUTPUT=1", + "-I" + str(overrides), "-I" + str(FIXTURE), + "-I" + str(cache), "-I" + str(ROOT / "src"), + str(FIXTURE / "main.cpp"), str(cache / "GxEPD2_EPD.cpp"), + str(cache / "epd/GxEPD2_213_B74.cpp"), "-o", str(binary)] + for args in (command, [str(binary)]): + result = subprocess.run(args, capture_output=True, text=True, + timeout=90 if args is command else 10) + self.assertEqual(result.returncode, 0, + " ".join(args) + "\n" + result.stdout + result.stderr) + # The recorder must detect the old panel waveform, premature + # completion on an initially LOW BUSY pin, and sleeping before BW + # has synchronized the previous-image bank. + header = (ROOT / "src/helpers/ui/MeshPocketEinkPanel.h").read_text() + mutations = { + "old B74 partial waveform": ( + "_writeData(partial ? 0xFF : 0xF7);", + "_writeData(partial ? 0xFC : 0xF7);"), + "missing minimum settling time": ( + "delay(partial ? 800 : 2500);", "delay(0);"), + "sleep before history sync": ( + "_initial_refresh = false;", "finishRefresh();\n _initial_refresh = false;"), + } + override = overrides / "helpers/ui/MeshPocketEinkPanel.h" + override.parent.mkdir(parents=True) + for label, (before, after) in mutations.items(): + with self.subTest(negative_control=label): + self.assertEqual(header.count(before), 1) + override.write_text(header.replace(before, after)) + result = subprocess.run(command, capture_output=True, text=True, timeout=90) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + self.assertNotEqual(result.returncode, 0, "recorder accepted " + label) + self.assertIn("Assertion", result.stderr, result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_pocket_reader.py b/test/test_pocket_reader.py new file mode 100644 index 000000000..dad6a82d9 --- /dev/null +++ b/test/test_pocket_reader.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Run Pocket Reader against the actual installed U8g2 font and decoder.""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = ROOT / "test/fixtures/pocket_reader" + + +class PocketReaderTest(unittest.TestCase): + def test_reader_with_real_helvetica_font(self): + compiler, cc = shutil.which("g++"), shutil.which("gcc") + if not compiler or not cc: + self.skipTest("host GCC and G++ required") + candidates = [Path(os.environ.get("U8G2_GFX_ROOT", "/nonexistent"))] + candidates += list((ROOT / ".pio/libdeps").glob("*/U8g2_for_Adafruit_GFX")) + library = next((path / "src" for path in candidates + if (path / "src/U8g2_for_Adafruit_GFX.cpp").is_file()), None) + if library is None: + self.skipTest("installed U8g2_for_Adafruit_GFX required (or set U8G2_GFX_ROOT)") + with tempfile.TemporaryDirectory(prefix="mesh-pocket-reader-") as directory: + directory = Path(directory) + # Compile the production font, without all the unrelated 40 MB of fonts. + source = (library / "u8g2_fonts.c").read_text(encoding="latin-1") + font = re.search(r"const uint8_t u8g2_font_helvR08_tf\[[^]]+\].*?;\n", source, re.S) + self.assertIsNotNone(font) + selected = directory / "font.c" + selected.write_text('#include "u8g2_fonts.h"\n' + font.group()) + flags = ["-g", "-O1", "-DHELTEC_MESH_POCKET=1", "-DCOMPANION_RADIO_FULL=1", + "-DNRF52_PLATFORM=1", "-DENABLE_USB_INTERFACE=1", "-DUI_POCKET_GUI=1", + "-DUI_SMALL_MESSAGE_FONT=0", "-DUI_BUTTON_READER_HINT=1", "-DUI_READER_TOUCH_BAR=0", + "-I" + str(FIXTURE), "-I" + str(ROOT / "src"), "-I" + str(ROOT), + "-I" + str(ROOT / "test/fixtures/companion_reader"), "-I" + str(library)] + if os.name != "nt": + flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie"] + commands = [ + [cc, "-std=c11", *flags, "-c", str(selected), "-o", str(directory / "font.o")], + [cc, "-std=c11", *flags, "-c", str(ROOT / "src/helpers/ota/OtaTinf.c"), "-o", str(directory / "tinf.o")], + [compiler, "-std=c++17", *flags, str(FIXTURE / "test_pocket_reader.cpp"), + str(ROOT / "src/helpers/CompanionReader.cpp"), str(library / "U8g2_for_Adafruit_GFX.cpp"), + str(directory / "font.o"), str(directory / "tinf.o"), "-o", str(directory / "reader")], + [str(directory / "reader")], + ] + for command in commands: + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, " ".join(command) + "\n" + result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main()