#include "UITask.h" #include #include #if defined(NRF52_POWER_MANAGEMENT) #include #endif #include #include #include #include #ifdef HAS_TOUCH #include #endif #include #if UI_SMALL_MESSAGE_FONT == 1 #include #endif #include #include #include #include #include "../MyMesh.h" #include "../CompanionWiFi.h" #include "target.h" #include #include #if UI_POCKET_GUI #include "PocketGui.h" #include #endif #if defined(ENABLE_WIFI_INTERFACE) || defined(WIFI_SSID) #include #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 #include #include #include #endif #if defined(ESP32) #include #endif #ifndef AUTO_OFF_MILLIS #define AUTO_OFF_MILLIS 15000 // 15 seconds #endif #ifndef UI_RADIO_REFRESH_MILLIS #define UI_RADIO_REFRESH_MILLIS 2000UL #endif #ifndef BLE_PAIRING_DISPLAY_MILLIS #define BLE_PAIRING_DISPLAY_MILLIS 120000UL #endif #define BOOT_SCREEN_MILLIS 3000 // 3 seconds #ifdef PIN_STATUS_LED #define LED_ON_MILLIS 20 #define LED_ON_MSG_MILLIS 200 #define LED_CYCLE_MILLIS 4000 #endif #define LONG_PRESS_MILLIS 1200 #if defined(HELTEC_V4_DISPLAY_UNIFIED) && HELTEC_V4_DISPLAY_UNIFIED \ && !defined(AUTO_SHUTDOWN_MILLIVOLTS) // The original TFT Full recipe includes this battery protection. Retain it // when the canonical V4 image detects that assembly without changing the // historical OLED/headless Full policy. #define AUTO_SHUTDOWN_MILLIVOLTS 3400 #define HELTEC_V4_TFT_SHUTDOWN_ONLY 1 #endif static uint64_t companionMessageNowMillis() { #if defined(ESP32) // Unlike Arduino millis(), this does not wrap after roughly 49.7 days. return static_cast(esp_timer_get_time()) / 1000ULL; #else return static_cast(millis()); #endif } static uint64_t companionMessageElapsedMillis(uint64_t heard_millis) { #if defined(ESP32) return companionMessageNowMillis() - heard_millis; #else // Preserve Arduino's rollover-safe 32-bit subtraction on other platforms. return static_cast(millis() - static_cast(heard_millis)); #endif } static mesh::ui::RadioProfileSystemStatus radioProfileSystemStatus( const CompanionNodePrefs& prefs) { mesh::ui::RadioProfileSystemStatus status; const auto* radio = the_mesh.getProfileRadio(); const mesh::RadioProfiles* profiles = radio ? radio->profiles() : NULL; status.public_key = the_mesh.self_id.pub_key; status.powersaving_enabled = prefs.powersaving_enabled != 0; #if ENV_INCLUDE_GPS == 1 status.gps_enabled = prefs.gps_enabled != 0; #endif status.fem_enabled = board.canControlLoRaFemLna() && board.isLoRaFemLnaEnabled(); status.rx_boosted_gain = prefs.rx_boosted_gain != 0; status.rx_powersaving_enabled = prefs.rx_powersaving_enabled != 0; status.cad_enabled = prefs.cad_enabled != 0; status.dual_radio_enabled = profiles != NULL && profiles->enabled(); if (status.dual_radio_enabled) { status.secondary_temporary = profiles->secondary_temporary; status.secondary_mode = profiles->secondary.mode; status.cross = profiles->cross; } status.noise_floor_1 = radio_driver.getNoiseFloorDbm(0); status.noise_floor_1_seconds = radio_driver.getNoiseFloorCalibrationSecondsRemaining(0); if (status.dual_radio_enabled) { status.noise_floor_2 = radio_driver.getNoiseFloorDbm(1); status.noise_floor_2_seconds = radio_driver.getNoiseFloorCalibrationSecondsRemaining(1); } return status; } #ifndef UI_RECENT_LIST_SIZE #define UI_RECENT_LIST_SIZE 4 #endif #ifdef HAS_TOUCH #define PRESS_LABEL "tap center" #define SELECT_LABEL "TAP" #elif UI_HAS_JOYSTICK || defined(UI_HAS_NAV_INPUT) #define PRESS_LABEL "press Enter" #define SELECT_LABEL "ENTER" #else #define PRESS_LABEL "hold button" #define SELECT_LABEL "HOLD" #endif #ifndef UI_BUTTON_READER_HINT #if !defined(HAS_TOUCH) && !UI_HAS_JOYSTICK && !defined(UI_HAS_NAV_INPUT) \ && (defined(PIN_USER_BTN) || defined(PIN_USER_BTN_ANA)) #define UI_BUTTON_READER_HINT 1 #else #define UI_BUTTON_READER_HINT 0 #endif #endif #if COMPANION_FEATURE_READER #include "ReaderScreen.h" #if UI_POCKET_GUI #include "PocketReaderDisplay.h" #endif #include #endif #ifdef COMPANION_EXCLUSIVE_WIFI_BLE static void drawCompanionTransportChoice(DisplayDriver& display, int x, int y, int width, int height, const char* label, bool active, bool selected) { if (active) { display.setColor(UIColor::corp_blue); display.fillRect(x, y, width, height); display.setColor(UIColor::window_bkg); } else { display.setColor(UIColor::secondary_txt); display.drawRect(x, y, width, height); display.setColor(UIColor::primary_txt); } const bool large_transport_text = display.height() >= 96; const bool show_status_label = height >= 44; if (large_transport_text && width < 76) { // Fit choices inside the central tap zone without consuming page arrows. int size = 2; display.setTextSize(size); while (size > 1 && display.getTextWidth(label) > width - 4) display.setTextSize(--size); display.drawTextCentered(x + width / 2, y + 20, label); } else if (large_transport_text) { display.setTextSize(4); if (strcmp(label, "WiFi") == 0) { // A single size-4 "WiFi" row is wider than one half of the screen. // Reflow it into two large rows instead of shrinking both choices. display.drawTextCentered(x + width / 2, y + 2, "Wi"); display.drawTextCentered(x + width / 2, y + 36, "Fi"); } else { display.drawTextCentered(x + width / 2, y + 25, label); } } else { display.setTextSize(1); const int label_y = show_status_label ? y + 12 : y + (height - 8) / 2; display.drawTextCentered(x + width / 2, label_y, label); } if (show_status_label && (active || selected)) { display.setTextSize(large_transport_text ? 3 : 1); const char* status = active ? (large_transport_text ? "ON" : "ACTIVE") : (large_transport_text ? "NEXT" : "NEXT BOOT"); if (large_transport_text) { int size = 3; while (size > 1 && display.getTextWidth(status) > width - 4) display.setTextSize(--size); } display.drawTextCentered( x + width / 2, y + height - (large_transport_text ? 25 : 17), active ? (large_transport_text ? "ON" : "ACTIVE") : (large_transport_text ? "NEXT" : "NEXT BOOT")); } } #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 static bool drawCompactCompanionWiFiSetupPage( DisplayDriver& display, bool setup_active, const char* setup_ssid, const char* setup_ip, const char* wifi_ip, bool wifi_enabled, bool wifi_connected, bool wifi_configured) { if (display.width() > 128 || display.height() > 64) return false; // Use the whole compact screen for an active setup QR. Clear the shared // title/page dots first so they cannot overlap its one-pixel white border. if (setup_active) { display.setCompactText(false); display.setColor(UIColor::window_bkg); display.fillRect(0, 0, display.width(), display.height()); if (mesh::ui::drawWiFiSetupQr( display, setup_ssid, setup_ip, true, "HOLD STOP")) return true; } // Keep the readable text fallback for unsupported panels or QR payloads. display.setCompactText(true); display.setTextSize(1); display.setColor(UIColor::primary_txt); // Put the connection and its address above the setup AP controls. if (setup_active) { display.drawTextEllipsized(0, 20, display.width(), setup_ssid); char open_ip[22]; snprintf(open_ip, sizeof(open_ip), "OPEN %s", setup_ip); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 31, open_ip); } else { const bool show_ip = wifi_connected && wifi_ip[0] != 0; const char* wifi_status = !wifi_enabled ? "WIFI OFF" : wifi_connected ? "WIFI CONNECTED" : wifi_configured ? "WIFI CONNECTING" : "WIFI NOT CONFIGURED"; display.drawTextCentered(display.width() / 2, 20, wifi_status); display.setColor(UIColor::secondary_txt); if (show_ip) { char ip_line[19]; // "IP " plus the longest IPv4 address and terminator snprintf(ip_line, sizeof(ip_line), "IP %s", wifi_ip); display.drawTextCentered(display.width() / 2, 31, ip_line); } } display.drawTextCentered( display.width() / 2, 42, setup_active ? "SETUP AP ACTIVE" : "SETUP AP INACTIVE"); display.setColor(UIColor::warning_txt); display.drawTextCentered( display.width() / 2, 53, setup_active ? "HOLD STOP AP" : "HOLD START AP"); display.setCompactText(false); return true; } static void drawCompanionWiFiSetupPage(DisplayDriver& display) { char setup_ssid[33] = {0}; char setup_ip[16] = {0}; const bool setup_active = WebConfigServer::getSetupInfo( setup_ssid, sizeof(setup_ssid), setup_ip, sizeof(setup_ip)); const bool wifi_enabled = isCompanionWiFiEnabled(); const bool wifi_connected = isCompanionWiFiConnected(); const bool wifi_configured = hasCompanionWiFiCredentials(); char wifi_ip[16] = {0}; if (wifi_connected) { // localIP() can retain the previous lease after a disconnect. Show only // an address from a live station link, after DHCP has supplied one. const IPAddress ip = WiFi.localIP(); if (static_cast(ip) != 0) { snprintf(wifi_ip, sizeof(wifi_ip), "%s", ip.toString().c_str()); } } const CompanionWiFiDisplayState state = setup_active ? CompanionWiFiDisplayState::Setup : !wifi_enabled ? CompanionWiFiDisplayState::Off : wifi_connected ? CompanionWiFiDisplayState::Ready : !wifi_configured ? CompanionWiFiDisplayState::NotConfigured : CompanionWiFiDisplayState::Connecting; static CompanionWiFiDisplayState previous_state = CompanionWiFiDisplayState::NotRendered; // Frame hashing normally suppresses identical LCD transfers. Explicitly // invalidate that cache on a network-state transition so a retained // CONNECTING frame can never survive a READY render. if (state != previous_state) { display.clear(); previous_state = state; } noteCompanionWiFiDisplayState(state); if (drawCompactCompanionWiFiSetupPage( display, setup_active, setup_ssid, setup_ip, wifi_ip, wifi_enabled, wifi_connected, wifi_configured)) { return; } // Keep the setup content below the shared title bar and page dots. Compact // text makes its physical size identical on the 480 canvas and the // 320-to-480 emergency canvas. display.setCompactText(true); display.setColor(UIColor::primary_txt); if (setup_active) { display.setTextSize(2); display.drawTextCentered(display.width() / 2, 20, "WIFI SETUP"); display.drawTextCentered(display.width() / 2, 37, setup_ssid); char payload[256]; if (mesh::ui::buildCurrentWiFiSetupQrPayload( payload, sizeof(payload), setup_ssid)) { static constexpr int qr_size = 105; const int qr_x = (display.width() - qr_size) / 2; if (display.drawQrCode(payload, qr_x, 55, qr_size)) { display.setCompactText(false); return; } } display.setColor(UIColor::warning_txt); display.setTextSize(2); display.drawTextCentered(display.width() / 2, 70, "QR UNAVAILABLE"); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 100, setup_ip); } else if (!wifi_enabled) { display.setTextSize(3); display.drawTextCentered(display.width() / 2, 45, "WIFI OFF"); display.setTextSize(2); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 90, "SELECT WIFI"); display.drawTextCentered(display.width() / 2, 112, "THEN REBOOT"); } else if (wifi_connected) { display.setTextSize(2); if (display.getTextWidth("WIFI CONNECTED") > display.width()) { display.setTextSize(1); } display.drawTextCentered(display.width() / 2, 25, "WIFI CONNECTED"); display.setTextSize(2); const String ssid = WiFi.SSID(); display.drawTextEllipsized(4, 60, display.width() - 8, ssid.c_str()); if (wifi_ip[0]) { display.drawTextCentered(display.width() / 2, 95, wifi_ip); } } else if (!wifi_configured) { display.setTextSize(3); display.drawTextCentered(display.width() / 2, 45, "WIFI SETUP"); display.setTextSize(2); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 90, SELECT_LABEL " TO START"); } else { display.setTextSize(3); display.drawTextCentered(display.width() / 2, 45, "WIFI"); display.setTextSize(2); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 90, "CONNECTING"); } display.setCompactText(false); } #endif #include "icons.h" class SplashScreen : public UIScreen { UITask* _task; unsigned long dismiss_after; char _version_info[12]; public: SplashScreen(UITask* task) : _task(task) { // strip off dash and commit hash by changing dash to null terminator // e.g: v1.2.3-abcdef -> v1.2.3 const char *ver = FIRMWARE_VERSION; const char *dash = strchr(ver, '-'); int len = dash ? dash - ver : strlen(ver); if (len >= sizeof(_version_info)) len = sizeof(_version_info) - 1; memcpy(_version_info, ver, len); _version_info[len] = 0; dismiss_after = millis() + BOOT_SCREEN_MILLIS; } int render(DisplayDriver& display) override { // meshcore logo display.setColor(UIColor::corp_blue); int logoWidth = 128; display.drawXbm((display.width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; display.setColor(UIColor::primary_txt); display.setTextSize(1); uint16_t websiteWidth = display.getTextWidth(website); display.setCursor((display.width() - websiteWidth) / 2, 22); display.print(website); // version info display.setColor(UIColor::primary_txt); display.setTextSize(1); display.drawTextCentered(display.width()/2, 35, _version_info); display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width()/2, 48, FIRMWARE_BUILD_DATE); return 1000; } void poll() override { if (millis() >= dismiss_after) { _task->gotoHomeScreen(); } } }; class HomeScreen : public UIScreen { enum HomePage { FIRST, #if UI_POCKET_GUI MAP, STATUS, SETTINGS, #endif #if UI_MESSAGES_HOME_PAGE == 1 MESSAGES, #endif RECENT, RADIO, // Only visible when the secondary radio profile is configured. RADIO2, RADIO_STATUS, #ifdef COMPANION_EXCLUSIVE_WIFI_BLE TRANSPORT, #elif defined(BLE_PIN_CODE) BLUETOOTH, #endif ADVERT, #if ENV_INCLUDE_GPS == 1 GPS, #endif #if UI_SENSORS_PAGE == 1 SENSORS, #endif #ifndef UI_NO_HIBERNATE SHUTDOWN, #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 WIFI_SETUP, #endif #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) DISCOVERY, #endif Count // keep as last }; UITask* _task; mesh::RTCClock* _rtc; SensorManager* _sensors; CompanionNodePrefs* _node_prefs; uint8_t _page; bool _shutdown_init; bool _pairing_pin_visible = false; #if UI_WIFI_SETUP_HOME_PAGE == 1 bool _wifi_setup_was_active; bool _wifi_was_connected; #endif uint32_t _uptime_last_millis; uint64_t _uptime_millis; uint32_t _radio_profile_page_started_at = 0; uint8_t _radio_status_page = 0; bool _dual_radio_enabled_seen = false; #if UI_POCKET_GUI mesh::ui::pocket::PocketGui _pocket; bool _pocket_editing = false; bool _pocket_browsing = false; bool _pocket_zooming = false; bool _pocket_map_located = false; bool _pocket_dirty = false; uint8_t _pocket_setting = 0; uint32_t _pocket_last_input = 0; uint32_t _pocket_save_retry = 0; #endif AdvertPath recent[UI_RECENT_LIST_SIZE]; #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) DiscoveredNode discovered[UI_RECENT_LIST_SIZE]; uint32_t discovery_req_time = 0; bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) #endif int renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { // Convert millivolts to percentage #ifndef BATT_MIN_MILLIVOLTS #define BATT_MIN_MILLIVOLTS 3000 #endif #ifndef BATT_MAX_MILLIVOLTS #define BATT_MAX_MILLIVOLTS 4200 #endif const int minMilliVolts = BATT_MIN_MILLIVOLTS; const int maxMilliVolts = BATT_MAX_MILLIVOLTS; const bool showBattery = batteryMilliVolts != 0; int batteryPercentage = showBattery ? ((batteryMilliVolts - minMilliVolts) * 100) / (maxMilliVolts - minMilliVolts) : 0; #if defined(NRF52_POWER_MANAGEMENT) batteryPercentage = showBattery ? mesh::power::configuredBatteryPercent(batteryMilliVolts) : 0; #endif if (batteryPercentage < 0) batteryPercentage = 0; // Clamp to 0% if (batteryPercentage > 100) batteryPercentage = 100; // Clamp to 100% // battery icon int iconWidth = 24; int iconHeight = 10; int iconX = showBattery ? display.width() - iconWidth - 5 : display.width() - 5; int iconY = 0; display.setColor(UIColor::title_txt); // Track uptime across the 32-bit millis() rollover and show the two most // useful units beside the battery icon. uint32_t now = millis(); _uptime_millis += (uint32_t)(now - _uptime_last_millis); _uptime_last_millis = now; uint64_t uptime_minutes = _uptime_millis / 60000ULL; unsigned long days = (unsigned long)(uptime_minutes / 1440ULL); unsigned long hours = (unsigned long)((uptime_minutes % 1440ULL) / 60ULL); unsigned long minutes = (unsigned long)(uptime_minutes % 60ULL); char uptime[16]; if (days > 0) { snprintf(uptime, sizeof(uptime), "%lud %luh", days, hours); } else if (hours > 0) { snprintf(uptime, sizeof(uptime), "%luh %lum", hours, minutes); } else { snprintf(uptime, sizeof(uptime), "%lum", minutes); } display.setTextSize(1); bool charging = board.isExternalPowered(); #ifdef PIN_BUZZER bool muted = _task->isBuzzerQuiet(); #endif int uptimeWidth = display.getTextWidth(uptime); int spaceWidth = display.getTextWidth(" "); int statusWidth = charging ? 9 : 0; #ifdef PIN_BUZZER if (muted) statusWidth += 9; #endif int statusStartX = iconX - statusWidth - uptimeWidth - spaceWidth; display.setCursor(statusStartX, iconY); display.print(uptime); if (showBattery) { // battery outline display.drawRect(iconX, iconY, iconWidth, iconHeight); // battery "cap" display.fillRect(iconX + iconWidth, iconY + (iconHeight / 4), 3, iconHeight / 2); // fill the battery based on the percentage int fillWidth = (batteryPercentage * (iconWidth - 4)) / 100; display.fillRect(iconX + 2, iconY + 2, fillWidth, iconHeight - 4); } // Show external power beside the battery. Most boards have no // charge-complete signal, so use a high percentage band for the plug. if (charging) { static constexpr int BATT_FULL_PCT = 95; const uint8_t* symbol = !showBattery || batteryPercentage >= BATT_FULL_PCT ? plug_icon : charging_icon; display.setColor(UIColor::title_txt); display.drawXbm(iconX - 9, iconY + 1, symbol, 8, 8); } // Keep the mute icon left of the charging icon when both are present. #ifdef PIN_BUZZER if (muted) { display.setColor(UIColor::warning_txt); display.drawXbm(iconX - (charging ? 18 : 9), iconY + 1, muted_icon, 8, 8); } #endif return statusStartX; } CayenneLPP sensors_lpp; int sensors_nb = 0; bool sensors_scroll = false; int sensors_scroll_offset = 0; uint32_t last_sensors_refresh = 0; void refresh_sensors() { // CayenneLPP retains its requested capacity even if its allocation fails. // Its add methods would then write through NULL when this page is opened. if (sensors_lpp.getBuffer() == nullptr) { sensors_nb = 0; sensors_scroll = false; sensors_scroll_offset = 0; return; } #if AUTO_OFF_MILLIS > 0 const uint32_t refresh_interval = 5000; #else const uint32_t refresh_interval = 60000; #endif // Empty data requests an initial/forced sample. Elapsed time also handles // returning to this page after more than half a millis() cycle. if (sensors_lpp.getSize() == 0 || static_cast(millis() - last_sensors_refresh) >= refresh_interval) { sensors_lpp.reset(); sensors_nb = 0; sensors_lpp.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); sensors.querySensors(0xFF, sensors_lpp); LPPReader reader (sensors_lpp.getBuffer(), sensors_lpp.getSize()); uint8_t channel, type; while(reader.readHeader(channel, type)) { reader.skipData(type); sensors_nb ++; } sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE; last_sensors_refresh = millis(); } } void resetRadioProfileDisplayPage() { _radio_profile_page_started_at = millis(); _radio_status_page = 0; _dual_radio_enabled_seen = the_mesh.isDualRadioActive(); } bool isPageVisible(uint8_t page) const { return the_mesh.isDualRadioActive() || (page != HomePage::RADIO2 && page != HomePage::RADIO_STATUS); } void movePage(int direction) { #if UI_POCKET_GUI flushPocketSettings(); _pocket_editing = _pocket_browsing = _pocket_zooming = false; displayForceClean(); #endif do { _page = (_page + HomePage::Count + direction) % HomePage::Count; } while (!isPageVisible(_page)); if (_page == HomePage::RADIO || _page == HomePage::RADIO_STATUS) { resetRadioProfileDisplayPage(); } } int radioProfileRefreshMillis() const { const uint32_t elapsed = millis() - _radio_profile_page_started_at; const uint32_t remaining = mesh::ui::RADIO_PROFILE_DISPLAY_PAGE_MILLIS - elapsed % mesh::ui::RADIO_PROFILE_DISPLAY_PAGE_MILLIS; return remaining < UI_RADIO_REFRESH_MILLIS ? (int)remaining : UI_RADIO_REFRESH_MILLIS; } #if UI_POCKET_GUI void displayForceClean() { _task->cleanPocketDisplay(); } void cyclePocketChannel(int direction) { auto& settings = _task->pocketSettings(); const int previous = settings.channel; int selected = previous; for (int attempt = 0; attempt < MAX_GROUP_CHANNELS; ++attempt) { selected = (selected + MAX_GROUP_CHANNELS + direction) % MAX_GROUP_CHANNELS; ChannelDetails channel; if (the_mesh.getChannel(selected, channel) && channel.name[0]) { settings.channel = selected; break; } } _pocket_dirty |= previous != settings.channel; _pocket.resetScroll(); } static bool pocketLocation(double latitude, double longitude) { return isfinite(latitude) && isfinite(longitude) && latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180 && (latitude != 0 || longitude != 0); } __attribute__((noinline)) void renderPocketMap() { using namespace mesh::ui::pocket; const auto& settings = _task->pocketSettings(); const double own_lat = sensors.node_lat, own_lon = sensors.node_lon; const bool have_own = pocketLocation(own_lat, own_lon); double latitude = own_lat, longitude = own_lon; bool located = have_own; ContactInfo contact; if (!located) { auto contacts = the_mesh.startContactsIterator(); while (contacts.hasNext(&the_mesh, contact)) { latitude = contact.gps_lat * 1e-6; longitude = contact.gps_lon * 1e-6; if (pocketLocation(latitude, longitude)) { located = true; break; } } } if (_pocket_map_located != located) displayForceClean(); _pocket_map_located = located; if (!located && _pocket_zooming) { _pocket_zooming = false; if (_pocket_dirty) flushPocketSettings(); } MapView view = {located ? latitude : 0, located ? longitude : 0, mapHeightKm(settings, located), _pocket.width(), _pocket.bodyBottom() - _pocket.bodyTop()}; if (!renderWorldMap(view, [](void* context, int x0, int y0, int x1, int y1) { auto& gui = *static_cast(context); gui.line(x0, y0 + gui.bodyTop(), x1, y1 + gui.bodyTop()); }, &_pocket)) { _pocket.label(3, 40, "Map unavailable"); } int x, y; unsigned shown = 0, labels = 0; auto contacts = the_mesh.startContactsIterator(); while (contacts.hasNext(&the_mesh, contact)) { latitude = contact.gps_lat * 1e-6; longitude = contact.gps_lon * 1e-6; if (!pocketLocation(latitude, longitude) || !projectWorldPoint(view, latitude, longitude, x, y)) continue; _pocket.marker(x, y + _pocket.bodyTop()); ++shown; if (view.height_km <= 50 && labels < 4 && x < view.width - 52 && y >= 10) { char name[12]; sanitizeText(name, sizeof(name), contact.name, strnlen(contact.name, sizeof(contact.name))); truncateCharacters(name, 8); _pocket.label(x + 4, y + _pocket.bodyTop() - 3, name); ++labels; } } if (have_own && projectWorldPoint(view, own_lat, own_lon, x, y)) _pocket.marker(x, y + _pocket.bodyTop(), true); char summary[40]; if (located) snprintf(summary, sizeof(summary), "%u nodes%s", shown, view.height_km < 100 ? " / coarse coast" : ""); else snprintf(summary, sizeof(summary), "%sno node locations", view.height_km == 20000 ? "World / " : ""); _pocket.label(3, _pocket.bodyTop() + 9, summary); _pocket.renderMapChrome((unsigned)view.height_km, located ? (_pocket_zooming ? "1x zoom in 2x out hold done" : "click next 2x back hold zoom") : "click next 2x back"); } int renderPocket(DisplayDriver& display) { using namespace mesh::ui::pocket; const auto& settings = _task->pocketSettings(); Frame frame; const uint32_t uptime_now = millis(); _uptime_millis += uint32_t(uptime_now - _uptime_last_millis); _uptime_last_millis = uptime_now; frame.now = _rtc->getCurrentTime(); frame.heard_millis = companionMessageNowMillis(); frame.tz_offset = _node_prefs->tz_offset; frame.battery_percent = (int(_task->getBattMilliVolts()) - BATT_MIN_MILLIVOLTS) * 100 / (BATT_MAX_MILLIVOLTS - BATT_MIN_MILLIVOLTS); #if defined(NRF52_POWER_MANAGEMENT) frame.battery_percent = mesh::power::configuredBatteryPercent(_task->getBattMilliVolts()); #endif frame.connection = _task->connectedClientLabel(); frame.page_count = frame.page_index = 0; for (unsigned page = 0; page < HomePage::Count; ++page) if (isPageVisible(page)) { if (page < _page) ++frame.page_index; ++frame.page_count; } frame.rotation = DISPLAY_ROTATION; 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"; 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"; else frame.hint = "click next 2x back hold action"; static_cast(display).setMaxPartialRefresh(refreshCount(settings)); _pocket.begin(static_cast(display), settings, frame); ChannelDetails channel; char channel_name[32] = {}; if (the_mesh.getChannel(settings.channel, channel)) StrHelper::strncpy(channel_name, channel.name, sizeof(channel_name)); if (_page == HomePage::FIRST) _task->renderPocketBoard(_pocket); else if (_page == HomePage::MAP) { renderPocketMap(); return 10000; } else if (_page == HomePage::SETTINGS) _pocket.renderSettings(_pocket_setting, _pocket_editing, channel_name); else { char text[80]; int y = _pocket.bodyTop() + 10; auto row = [&](const char* value) { if (y <= _pocket.bodyBottom() - 2) _pocket.label(4, y, value); y += 14; }; if (_page == HomePage::STATUS) { _pocket.header("Status", (_radio_status_page & 1) ? "2 / 2" : "1 / 2"); if ((_radio_status_page & 1) == 0) { snprintf(text, sizeof(text), "Uptime %lu min battery %u mV", (unsigned long)(_uptime_millis / 60000), _task->getBattMilliVolts()); row(text); snprintf(text, sizeof(text), "RX %lu flood / %lu direct", (unsigned long)the_mesh.getNumRecvFlood(), (unsigned long)the_mesh.getNumRecvDirect()); row(text); snprintf(text, sizeof(text), "TX %lu flood / %lu direct", (unsigned long)the_mesh.getNumSentFlood(), (unsigned long)the_mesh.getNumSentDirect()); row(text); snprintf(text, sizeof(text), "Inbox %d / %d errors %04X", _task->getMsgCount(), the_mesh.getOfflineQueueCapacity(), the_mesh.getErrFlags()); row(text); mesh::Utils::toHex(text, the_mesh.self_id.pub_key, 6); row(text); } else { const auto status = radioProfileSystemStatus(*_node_prefs); snprintf(text, sizeof(text), "Power saving %s / GPS %s", status.powersaving_enabled ? "on" : "off", status.gps_enabled ? "on" : "off"); row(text); snprintf(text, sizeof(text), "FEM %s / RX boost %s", status.fem_enabled ? "on" : "off", status.rx_boosted_gain ? "on" : "off"); row(text); snprintf(text, sizeof(text), "RX power saving %s / CAD %s", status.rx_powersaving_enabled ? "on" : "off", status.cad_enabled ? "on" : "off"); row(text); mesh::ui::formatRadioProfileNoiseFloor(text, sizeof(text), "Radio 1 noise", status.noise_floor_1, status.noise_floor_1_seconds); row(text); } } else if (_page == HomePage::RECENT) { _pocket.header("Recently heard"); const int count = the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); for (int i = 0; i < count && y <= _pocket.bodyBottom(); ++i) { char name[40]; sanitizeText(name, sizeof(name), recent[i].name, strnlen(recent[i].name, sizeof(recent[i].name))); snprintf(text, sizeof(text), "%.28s %lum", name, (unsigned long)((frame.now - recent[i].recv_timestamp) / 60)); row(text); } if (!count) row("No adverts heard yet"); } else if (_page == HomePage::RADIO_STATUS) { _pocket.header("Radio status", (_radio_status_page & 1) ? "2 / 2" : "1 / 2"); const auto status = radioProfileSystemStatus(*_node_prefs); if ((_radio_status_page & 1) == 0) { snprintf(text, sizeof(text), "Power saving %s / GPS %s", status.powersaving_enabled ? "on" : "off", status.gps_enabled ? "on" : "off"); row(text); snprintf(text, sizeof(text), "FEM %s / RX boost %s", status.fem_enabled ? "on" : "off", status.rx_boosted_gain ? "on" : "off"); row(text); snprintf(text, sizeof(text), "RX power saving %s / CAD %s", status.rx_powersaving_enabled ? "on" : "off", status.cad_enabled ? "on" : "off"); row(text); } else { mesh::ui::formatRadioProfileNoiseFloor(text, sizeof(text), "Radio 1 noise", status.noise_floor_1, status.noise_floor_1_seconds); row(text); mesh::ui::formatRadioProfileNoiseFloor(text, sizeof(text), "Radio 2 noise", status.noise_floor_2, status.noise_floor_2_seconds); row(text); snprintf(text, sizeof(text), "Radio2 %s%s / cross %s", status.secondary_mode == mesh::RadioProfileMode::RxTx ? "RX/TX" : "RX", status.secondary_temporary ? " temporary" : "", status.cross == mesh::RadioCrossMode::Off ? "off" : status.cross == mesh::RadioCrossMode::On ? "on" : "auto"); row(text); } row("Hold for more status"); } else if (_page == HomePage::RADIO || _page == HomePage::RADIO2) { const auto* radio = the_mesh.getProfileRadio(); const auto* profiles = radio ? radio->profiles() : nullptr; const bool secondary = _page == HomePage::RADIO2 && profiles && profiles->enabled(); _pocket.header(secondary ? "Radio 2" : "Network"); mesh::RadioProfileParams params; if (profiles && profiles->enabled()) params = profiles->params(secondary ? 1 : 0); else { params.freq = _node_prefs->freq; params.bw = _node_prefs->bw; params.sf = _node_prefs->sf; params.cr = _node_prefs->cr; } snprintf(text, sizeof(text), "%.3f MHz / %.2f kHz", params.freq, params.bw); row(text); snprintf(text, sizeof(text), "SF%u CR%u / %d dBm", params.sf, params.cr, _node_prefs->tx_power_dbm); row(text); snprintf(text, sizeof(text), "Noise %.1f dBm / RX boost %s", radio_driver.getNoiseFloorDbm(secondary ? 1 : 0), _node_prefs->rx_boosted_gain ? "on" : "off"); row(text); if (profiles && profiles->enabled()) { snprintf(text, sizeof(text), "Radio2 %s%s / cross %s", profiles->secondary.mode == mesh::RadioProfileMode::RxTx ? "RX/TX" : "RX", profiles->secondary_temporary ? " temporary" : "", profiles->cross == mesh::RadioCrossMode::Off ? "off" : profiles->cross == mesh::RadioCrossMode::On ? "on" : "auto"); row(text); snprintf(text, sizeof(text), "Switches %lu / failures %lu", (unsigned long)profiles->switches, (unsigned long)profiles->switch_failures); row(text); } else row("Radio2 off"); #if UI_MESSAGES_HOME_PAGE == 1 } else if (_page == HomePage::MESSAGES) { _pocket.header(_task->inboxTitle()); _task->renderPocketInbox(_pocket); #endif #if defined(BLE_PIN_CODE) } else if (_page == HomePage::BLUETOOTH) { _pocket.header("Bluetooth"); row(_task->isBluetoothEnabled() ? "Bluetooth enabled" : "Bluetooth disabled"); row(_task->hasBluetoothConnection() ? "App connected" : "Waiting for an app"); row("Hold to toggle Bluetooth"); #endif } else if (_page == HomePage::ADVERT) { _pocket.header("Advert"); row("Hold to send a local advert"); snprintf(text, sizeof(text), "Node: %.31s", _node_prefs->node_name); row(text); #if ENV_INCLUDE_GPS == 1 } else if (_page == HomePage::GPS) { _pocket.header("Location"); snprintf(text, sizeof(text), "Latitude %.6f", sensors.node_lat); row(text); snprintf(text, sizeof(text), "Longitude %.6f", sensors.node_lon); row(text); row(_task->getGPSState() ? "GPS enabled" : "GPS disabled"); row("Hold to toggle GPS"); #endif #if UI_SENSORS_PAGE == 1 } else if (_page == HomePage::SENSORS) { _pocket.header("Sensors"); refresh_sensors(); LPPReader readings(sensors_lpp.getBuffer(), sensors_lpp.getSize()); uint8_t channel_id, type; for (int i = 0; i < sensors_scroll_offset && readings.readHeader(channel_id, type); ++i) readings.skipData(type); while (y <= _pocket.bodyBottom() - 2 && readings.readHeader(channel_id, type)) { float value; switch (type) { case LPP_GPS: { float lat, lon, alt; readings.readGPS(lat, lon, alt); snprintf(text, sizeof(text), "GPS %.4f / %.4f", lat, lon); break; } case LPP_VOLTAGE: readings.readVoltage(value); snprintf(text, sizeof(text), "Voltage %.2f V", value); break; case LPP_CURRENT: readings.readCurrent(value); snprintf(text, sizeof(text), "Current %.3f A", value); break; case LPP_TEMPERATURE: readings.readTemperature(value); snprintf(text, sizeof(text), "Temperature %.2f C", value); break; case LPP_RELATIVE_HUMIDITY: readings.readRelativeHumidity(value); snprintf(text, sizeof(text), "Humidity %.2f %%", value); break; case LPP_BAROMETRIC_PRESSURE: readings.readPressure(value); snprintf(text, sizeof(text), "Pressure %.2f hPa", value); break; case LPP_ALTITUDE: readings.readAltitude(value); snprintf(text, sizeof(text), "Altitude %.0f m", value); break; case LPP_POWER: readings.readPower(value); snprintf(text, sizeof(text), "Power %.2f W", value); break; default: readings.skipData(type); continue; } row(text); } if (y == _pocket.bodyTop() + 10) row("No sensor readings"); if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset + 1) % sensors_nb; #endif #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) } else if (_page == HomePage::DISCOVERY) { _pocket.header("Repeaters nearby"); const int count = the_mesh.getDiscoveredNodes(discovered, UI_RECENT_LIST_SIZE); for (int i = 0; i < count && y <= _pocket.bodyBottom(); ++i) { char name[33]; StrHelper::strncpy(name, discovered[i].name, sizeof(name)); if (!name[0] || !discovery_disp_names) mesh::Utils::toHex(name, discovered[i].pubkey_prefix, 4); snprintf(text, sizeof(text), "%.28s %.1f dB", name, discovered[i].snr_in); row(text); } if (!count) row("Hold to discover nearby repeaters"); #endif #ifndef UI_NO_HIBERNATE } else if (_page == HomePage::SHUTDOWN) { _pocket.header("Power"); row("Hold to shut down"); #endif } else _pocket.header(_node_prefs->node_name); _pocket.footer(); } return 5000; } #endif public: #if UI_POCKET_GUI bool isPocketBoard() const { return _page == HomePage::FIRST; } void pocketMessageAdded(int channel) { if (channel == _task->pocketSettings().channel) _pocket.messageAdded(); } bool flushPocketSettings() { if (!_pocket_dirty) return true; if (!the_mesh.savePocketGuiSettings(_task->pocketSettings())) { _pocket_save_retry = millis() + 30000; _task->showAlert("Settings save failed", 1500); return false; } _pocket_dirty = false; _pocket_save_retry = 0; return true; } #endif HomeScreen(UITask* task, mesh::RTCClock* rtc, SensorManager* sensors, CompanionNodePrefs* node_prefs) : _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0), _shutdown_init(false), #if UI_WIFI_SETUP_HOME_PAGE == 1 _wifi_setup_was_active(false), _wifi_was_connected(false), #endif _uptime_last_millis(millis()), _uptime_millis(0), sensors_lpp(200) { #if UI_WIFI_SETUP_HOME_PAGE == 1 _wifi_setup_was_active = WebConfigServer::getSetupInfo( nullptr, 0, nullptr, 0); _wifi_was_connected = isCompanionWiFiConnected(); if (_wifi_setup_was_active) _page = HomePage::WIFI_SETUP; #endif } void showFirstPage() { #if UI_POCKET_GUI flushPocketSettings(); if (_page != HomePage::FIRST) displayForceClean(); _pocket_editing = _pocket_browsing = _pocket_zooming = false; _pocket.resetScroll(); _pocket_last_input = millis(); #endif _page = HomePage::FIRST; } bool hasPairingPin() const { return _pairing_pin_visible; } #if COMPANION_FEATURE_READER bool isRadioPage() const { return _page == HomePage::RADIO || _page == HomePage::RADIO2; } #endif bool isTransportSelectorPage() const { #ifdef COMPANION_EXCLUSIVE_WIFI_BLE return _page == HomePage::TRANSPORT; #else return false; #endif } #if UI_WIFI_SETUP_HOME_PAGE == 1 bool isWiFiSetupPage() const { return _page == HomePage::WIFI_SETUP; } #endif void poll() override { #if UI_POCKET_GUI const uint32_t pocket_now = millis(); if (_pocket_dirty && _pocket_save_retry && int32_t(pocket_now - _pocket_save_retry) >= 0) flushPocketSettings(); const uint32_t idle = mesh::ui::pocket::idleMillis(_task->pocketSettings()); if (idle && uint32_t(pocket_now - _pocket_last_input) >= idle && (_page != HomePage::FIRST || _pocket_browsing)) { showFirstPage(); _task->gotoHomeScreen(); } #endif if (_dual_radio_enabled_seen != the_mesh.isDualRadioActive()) { resetRadioProfileDisplayPage(); } if (!isPageVisible(_page)) { _page = HomePage::RADIO; #if UI_POCKET_GUI displayForceClean(); #endif resetRadioProfileDisplayPage(); } #if UI_WIFI_SETUP_HOME_PAGE == 1 const bool wifi_setup_active = WebConfigServer::getSetupInfo( nullptr, 0, nullptr, 0); if (wifi_setup_active && !_wifi_setup_was_active) { // Focus a newly opened setup portal once. Keeping this edge-triggered // lets the user swipe away while setup and LoRa continue running. _page = HomePage::WIFI_SETUP; _task->gotoHomeScreen(); } _wifi_setup_was_active = wifi_setup_active; const bool wifi_connected = isCompanionWiFiConnected(); if (wifi_connected != _wifi_was_connected) { // A network transition must invalidate the page immediately. This also // recovers from a previously retained CONNECTING frame even if the // ordinary one-second render deadline was delayed by another service. _wifi_was_connected = wifi_connected; _task->gotoHomeScreen(); } #endif if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released _task->shutdown(); } } int render(DisplayDriver& display) override { _pairing_pin_visible = false; #if UI_POCKET_GUI return renderPocket(display); #endif display.setTextSize(1); const int normal_line = !display.useSmallMessageFont() && display.renderWidth() == display.width() ? display.textLineHeight() : 11; const int row_height = normal_line > 11 ? normal_line : 11; const int header_height = row_height + 1; const int body_top = header_height + 8; display.setColor(UIColor::title_bkg); display.fillRect(0, 0, display.width(), header_height); char tmp[80]; // status indicators display.setTextSize(1); display.setColor(UIColor::title_txt); int statusStartX = renderBatteryIndicator(display, _task->getBattMilliVolts()); // node name char filtered_name[sizeof(_node_prefs->node_name)]; display.translateUTF8ToBlocks(filtered_name, _node_prefs->node_name, sizeof(filtered_name)); int availableNameWidth = statusStartX - 2; if (availableNameWidth > 0) { display.drawTextEllipsized(0, 2, availableNameWidth, filtered_name); } // curr page indicator if (UIColor::title_bkg == UIColor::window_bkg) { display.setColor(UIColor::title_txt); } else { // A dark title panel is only subtly different from a dark page. Use the // high-contrast accent for these tiny dots; monochrome palettes take the // equal-background branch above and retain their light text colour. display.setColor(UIColor::corp_blue); } int y = header_height + 2; int x = 5; for (uint8_t i = 0; i < HomePage::Count; i++) { if (!isPageVisible(i)) continue; if (i == _page) { display.fillRect(x-1, y-1, 4, 4); } else { display.fillRect(x, y, 2, 2); } x += 10; } if (_page == HomePage::FIRST) { display.setColor(UIColor::primary_txt); #ifdef UI_DEDICATED_PAIRING_BLOCK const bool expanded_home = mesh::ui::usesExpandedCompanionHomeTypography( display.width(), display.height(), display.renderWidth(), display.renderHeight()); if (expanded_home) { display.setTextSize(4); if (display.getTextWidth(_task->inboxTitle()) > display.width()) display.setTextSize(3); display.drawTextCentered(display.width() / 2, 20, _task->inboxTitle()); } else { snprintf(tmp, sizeof(tmp), "%s: %d", _task->inboxTitle(), _task->getPreviewCount()); display.setTextSize(2); if (display.getTextWidth(tmp) > display.width()) display.setTextSize(1); display.drawTextCentered(display.width() / 2, body_top + 2, tmp); } #else display.setTextSize(2); snprintf(tmp, sizeof(tmp), "%s: %d", _task->inboxTitle(), _task->getPreviewCount()); if (display.getTextWidth(tmp) > display.width()) display.setTextSize(1); int home_content_top = body_top + 2 + display.textLineHeight() + (display.height() > 64 ? 2 : 0); mesh::ui::drawTextCenteredEllipsized(display, {0, body_top + 2, display.width(), display.textLineHeight()}, body_top + 2, tmp); display.setTextSize(1); display.setColor(UIColor::secondary_txt); snprintf(tmp, sizeof(tmp), "Pending: %d", _task->getMsgCount()); mesh::ui::drawTextCenteredEllipsized(display, {0, home_content_top, display.width(), display.textLineHeight()}, home_content_top, tmp); home_content_top += display.textLineHeight() + 1; #endif #ifdef UI_DEDICATED_PAIRING_BLOCK const mesh::ui::CompanionHomeLayout layout = mesh::ui::makeLargeCompanionHomeLayout(display.width(), display.height(), expanded_home); // These are distinct repaint regions. In particular, removing or // replacing a pairing PIN cannot leave old glyphs behind, and long // instruction/network strings cannot enter the pairing block. display.setColor(UIColor::window_bkg); mesh::ui::clearDisplayRegion(display, layout.info); mesh::ui::clearDisplayRegion(display, layout.pairing); if (expanded_home) { snprintf(tmp, sizeof(tmp), "%d", _task->getPreviewCount()); display.setTextSize(3); if (display.getTextWidth(tmp) > layout.info.width) { display.setTextSize(2); } display.setColor(UIColor::primary_txt); mesh::ui::drawTextCenteredEllipsized( display, layout.info, layout.instruction_y, tmp); display.setTextSize(1); snprintf(tmp, sizeof(tmp), "Pending: %d", _task->getMsgCount()); mesh::ui::drawTextCenteredEllipsized( display, layout.info, layout.info.bottom() - display.textLineHeight(), tmp); } else { display.setTextSize(1); display.setColor(UIColor::secondary_txt); snprintf(tmp, sizeof(tmp), "Pending: %d", _task->getMsgCount()); mesh::ui::drawTextCenteredEllipsized( display, layout.info, layout.instruction_y, tmp); #ifdef WIFI_SSID if (!isCompanionWiFiEnabled()) { strcpy(tmp, "WiFi: OFF"); } else if (isCompanionWiFiConnected()) { IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); } else if (hasCompanionWiFiCredentials()) { strcpy(tmp, "WiFi: CONNECTING"); } else { strcpy(tmp, "WiFi: SETUP"); } display.setTextSize(1); mesh::ui::drawTextCenteredEllipsized( display, layout.info, layout.network_y, tmp); #endif } const bool bluetooth_enabled = _task->isBluetoothEnabled(); const bool bluetooth_connected = _task->hasBluetoothConnection(); const uint32_t bluetooth_pin = the_mesh.getBLEPin(); const char* pairing_label = nullptr; const char* client_label = _task->connectedClientLabel(); const char* pairing_value = nullptr; int pairing_value_size = 2; char pairing_pin[16]; if (mesh::ui::shouldDisplayBluetoothPairingPin( bluetooth_enabled, bluetooth_connected, bluetooth_pin) && (!_task->isPairingPromptActive() || display.height() > 64)) { pairing_label = expanded_home ? "PIN" : "BLUETOOTH PIN"; snprintf(pairing_pin, sizeof(pairing_pin), "%06u", (unsigned int)bluetooth_pin); pairing_value = pairing_pin; pairing_value_size = 3; } else if (client_label != nullptr && !_task->isPairingPromptActive()) { pairing_label = expanded_home && strcmp(client_label, "BLUETOOTH") == 0 ? "BLE" : client_label; pairing_value = expanded_home ? "LINKED" : "CONNECTED"; if (expanded_home) pairing_value_size = 3; } if (pairing_value != nullptr) { display.setColor(UIColor::title_bkg); mesh::ui::clearDisplayRegion(display, layout.pairing); display.setColor(UIColor::title_txt); display.setTextSize(expanded_home ? 3 : 1); mesh::ui::drawTextCenteredEllipsized( display, layout.pairing, layout.pairing_label_y, pairing_label); display.setTextSize(pairing_value_size); const bool value_drawn = mesh::ui::drawTextCenteredEllipsized( display, layout.pairing, layout.pairing_value_y, pairing_value); _pairing_pin_visible = pairing_value == pairing_pin && value_drawn && layout.pairing_value_y + display.textLineHeight() <= display.height(); } else if (expanded_home) { display.setColor(UIColor::secondary_txt); display.setTextSize(3); mesh::ui::drawTextCenteredEllipsized( display, layout.pairing, layout.pairing_label_y, SELECT_LABEL); #ifdef WIFI_SSID if (!isCompanionWiFiEnabled()) { strcpy(tmp, "OFF"); display.setTextSize(3); } else if (isCompanionWiFiConnected()) { IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); display.setTextSize(1); } else if (hasCompanionWiFiCredentials()) { strcpy(tmp, "WAIT"); display.setTextSize(3); } else { strcpy(tmp, "SETUP"); display.setTextSize(2); } mesh::ui::drawTextCenteredEllipsized( display, layout.pairing, layout.pairing_value_y, tmp); #endif } #else const bool bluetooth_enabled = _task->isBluetoothEnabled(); const bool bluetooth_connected = _task->hasBluetoothConnection(); const uint32_t bluetooth_pin = the_mesh.getBLEPin(); const bool show_bluetooth_pin = mesh::ui::shouldDisplayBluetoothPairingPin( bluetooth_enabled, bluetooth_connected, bluetooth_pin) && (!_task->isPairingPromptActive() || display.height() > 64); const char* client_label = _task->connectedClientLabel(); if (client_label != nullptr || show_bluetooth_pin) { char pairing_pin[16]; const bool show_client = client_label != nullptr && !show_bluetooth_pin && !_task->isPairingPromptActive(); const char* pairing_label = show_client ? client_label : "BLUETOOTH PIN"; const char* pairing_value = "CONNECTED"; if (!show_client) { snprintf(pairing_pin, sizeof(pairing_pin), "%06u", (unsigned int)bluetooth_pin); pairing_value = pairing_pin; } const bool value_drawn = mesh::ui::drawBottomPairingBlock(display, home_content_top, pairing_label, pairing_value); _pairing_pin_visible = value_drawn && !show_client; } else { mesh::ui::BoundedTextRows rows(display, {0, home_content_top, display.width(), display.height() - home_content_top}); display.setTextSize(1); display.setColor(UIColor::secondary_txt); rows.draw(PRESS_LABEL ": messages"); #ifdef UI_SHOW_CLOCK display.setTextSize(3); uint32_t now = _rtc->getCurrentTime(); const float tz = _node_prefs->tz_offset; // Keep fractional hours and reject corrupt values before conversion. if (isfinite(tz) && tz >= -12.0f && tz <= 14.0f) { now += static_cast(tz * 3600.0f); } DateTime dt (now); sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); rows.draw(tmp); display.setTextSize(1); sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); rows.draw(tmp); #endif #ifdef WIFI_SSID if (!isCompanionWiFiEnabled()) { strcpy(tmp, "WiFi: OFF"); } else if (isCompanionWiFiConnected()) { IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); } else if (hasCompanionWiFiCredentials()) { strcpy(tmp, "WiFi: CONNECTING"); } else { strcpy(tmp, "WiFi: SETUP"); } display.setTextSize(1); rows.draw(tmp); #endif } #endif #if UI_MESSAGES_HOME_PAGE == 1 } else if (_page == HomePage::MESSAGES) { _task->renderMessageSummary(display); #endif } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); display.setColor(UIColor::primary_txt); int y = body_top; for (int i = 0; i < UI_RECENT_LIST_SIZE && y + row_height <= display.height(); i++, y += row_height) { auto a = &recent[i]; if (a->name[0] == 0) continue; // empty slot int secs = _rtc->getCurrentTime() - a->recv_timestamp; if (secs < 60) { sprintf(tmp, "%ds", secs); } else if (secs < 60*60) { sprintf(tmp, "%dm", secs / 60); } else { sprintf(tmp, "%dh", secs / (60*60)); } int timestamp_width = display.getTextWidth(tmp); int max_name_width = display.width() - timestamp_width - 1; char filtered_recent_name[sizeof(a->name)]; display.translateUTF8ToBlocks(filtered_recent_name, a->name, sizeof(filtered_recent_name)); display.drawTextEllipsized(0, y, max_name_width, filtered_recent_name); display.setCursor(display.width() - timestamp_width - 1, y); display.print(tmp); } } else if (_page == HomePage::RADIO || _page == HomePage::RADIO2 || _page == HomePage::RADIO_STATUS) { display.setColor(UIColor::primary_txt); display.setTextSize(1); const auto* radio = the_mesh.getProfileRadio(); const mesh::RadioProfiles* profiles = radio ? radio->profiles() : NULL; const bool dual_radio = profiles != NULL && profiles->enabled(); const uint8_t status_pages = mesh::ui::radioProfileSystemStatusPageCount( display, dual_radio, body_top); uint8_t status_page_index = 0; const bool status_page = dual_radio ? _page == HomePage::RADIO_STATUS : mesh::ui::showRadioProfileSystemStatusPage( false, status_pages, millis() - _radio_profile_page_started_at, &status_page_index); if (status_page) { if (dual_radio && status_pages != 0) { status_page_index = _radio_status_page % status_pages; } mesh::ui::drawRadioProfileSystemStatusPage(display, radioProfileSystemStatus(*_node_prefs), status_page_index, body_top); return dual_radio ? UI_RADIO_REFRESH_MILLIS : radioProfileRefreshMillis(); } const bool secondary_page = dual_radio && _page == HomePage::RADIO2; float freq = _node_prefs->freq; float bw = _node_prefs->bw; uint8_t sf = _node_prefs->sf; uint8_t cr = _node_prefs->cr; const char* profile_tag = ""; if (dual_radio) { const uint8_t profile = secondary_page ? 1 : 0; const auto& params = profiles->params(profile); freq = params.freq; bw = params.bw; sf = params.sf; cr = params.cr; profile_tag = mesh::ui::radioProfileDisplayTag(profile, profile == 1 ? profiles->secondary_temporary : profiles->primary_temporary); } // freq / sf display.setCursor(0, body_top); if (dual_radio) { snprintf(tmp, sizeof(tmp), "%s F:%06.3f S:%d", profile_tag, freq, sf); } else { snprintf(tmp, sizeof(tmp), "FQ: %06.3f SF: %d", freq, sf); } display.print(tmp); display.setCursor(0, body_top + row_height); if (dual_radio) { snprintf(tmp, sizeof(tmp), "%s B:%03.2f C:%d", profile_tag, bw, cr); } else { snprintf(tmp, sizeof(tmp), "BW: %03.2f CR: %d", bw, cr); } display.print(tmp); // tx power, noise floor display.setCursor(0, body_top + 2 * row_height); sprintf(tmp, "TX: %ddBm", _node_prefs->tx_power_dbm); display.print(tmp); display.setCursor(0, body_top + 3 * row_height); // The RF rows above can be showing R1 or R2. Read the matching // estimator too; otherwise an R2-labelled page silently showed R1's // noise floor. const uint8_t noise_profile = dual_radio && secondary_page ? 1 : 0; const char* noise_label = dual_radio ? (noise_profile == 0 ? "N1" : "N2") : "Noise floor"; float noise_floor = radio_driver.getNoiseFloorDbm(noise_profile); if (noise_floor == 0.0f) { const float seconds = radio_driver .getNoiseFloorCalibrationSecondsRemaining(noise_profile); if (seconds > 0.0f) { snprintf(tmp, sizeof(tmp), "%s: %.1fs", noise_label, seconds); } else { snprintf(tmp, sizeof(tmp), "%s: WAIT", noise_label); } } else { snprintf(tmp, sizeof(tmp), "%s: %.1f", noise_label, noise_floor); } display.print(tmp); #ifdef COMPANION_EXCLUSIVE_WIFI_BLE } else if (_page == HomePage::TRANSPORT) { const bool wifi_active = isCompanionWiFiEnabled(); const bool wifi_selected = getCompanionTransportMode() == CompanionTransportMode::WiFi; const mesh::ui::CompanionTransportSelectorLayout layout = mesh::ui::makeCompanionTransportSelectorLayout( display.width(), display.height() #ifdef HAS_TOUCH , TOUCH_CENTER_ZONE_PERCENT #endif ); // Keep this page independent of the additional native-480 text boost. // Fit the choices inside the center zone at identical physical sizes // in the 320 and 480 render profiles, leaving page edges available. display.setCompactText(true); if (layout.show_title) { display.setColor(UIColor::primary_txt); display.setTextSize(3); display.drawTextCentered( display.width() / 2, layout.title_y, "MODE"); } drawCompanionTransportChoice( display, layout.wifi.x, layout.wifi.y, layout.wifi.width, layout.wifi.height, "WiFi", wifi_active, wifi_selected); drawCompanionTransportChoice( display, layout.bluetooth.x, layout.bluetooth.y, layout.bluetooth.width, layout.bluetooth.height, "BLE", !wifi_active, !wifi_selected); display.setColor(UIColor::secondary_txt); display.setTextSize(layout.show_title ? 2 : 1); #ifdef HAS_TOUCH display.drawTextCentered( display.width() / 2, layout.prompt_y, layout.show_title ? "TAP A BOX" : "tap a box"); #else display.drawTextCentered( display.width() / 2, layout.prompt_y, PRESS_LABEL); #endif display.setCompactText(false); #elif defined(BLE_PIN_CODE) } else if (_page == HomePage::BLUETOOTH) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, body_top - 2, _task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off, 32, 32); display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width() / 2, body_top + 33, "toggle: " PRESS_LABEL); #endif } else if (_page == HomePage::ADVERT) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, body_top - 2, advert_icon, 32, 32); display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, body_top + 33, "advert: " PRESS_LABEL); #if ENV_INCLUDE_GPS == 1 } else if (_page == HomePage::GPS) { LocationProvider* nmea = sensors.getLocationProvider(); char buf[50]; int y = body_top - 2; bool gps_state = _task->getGPSState(); #ifdef PIN_GPS_SWITCH bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } #else strcpy(buf, gps_state ? "gps on" : "gps off"); #endif display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { y += row_height > 12 ? row_height : 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "Can't access GPS"); } else { display.setColor(UIColor::primary_txt); strcpy(buf, nmea->isValid()?"fix":"no fix"); display.drawTextRightAlign(display.width()-1, y, buf); y += row_height > 12 ? row_height : 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "sat"); display.setColor(UIColor::primary_txt); sprintf(buf, "%d", nmea->satellitesCount()); display.drawTextRightAlign(display.width()-1, y, buf); y += row_height > 12 ? row_height : 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "pos"); display.setColor(UIColor::primary_txt); sprintf(buf, "%.4f %.4f", nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.); display.drawTextRightAlign(display.width()-1, y, buf); y += row_height > 12 ? row_height : 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "alt"); display.setColor(UIColor::primary_txt); sprintf(buf, "%.2f", nmea->getAltitude()/1000.); display.drawTextRightAlign(display.width()-1, y, buf); y += row_height > 12 ? row_height : 12; } #endif #if UI_SENSORS_PAGE == 1 } else if (_page == HomePage::SENSORS) { int y = body_top - 2; refresh_sensors(); if (sensors_lpp.getBuffer() == nullptr) { display.setColor(UIColor::warning_txt); display.drawTextCentered(display.width() / 2, 34, "Sensors: low memory"); return 5000; } char buf[30]; char name[30]; LPPReader r(sensors_lpp.getBuffer(), sensors_lpp.getSize()); for (int i = 0; i < sensors_scroll_offset; i++) { uint8_t channel, type; r.readHeader(channel, type); r.skipData(type); } for (int i = 0; i < (sensors_scroll?UI_RECENT_LIST_SIZE:sensors_nb); i++) { uint8_t channel, type; if (!r.readHeader(channel, type)) { // reached end, reset r.reset(); r.readHeader(channel, type); } display.setCursor(0, y); float v; switch (type) { case LPP_GPS: // GPS float lat, lon, alt; r.readGPS(lat, lon, alt); strcpy(name, "gps"); sprintf(buf, "%.4f %.4f", lat, lon); break; case LPP_VOLTAGE: r.readVoltage(v); strcpy(name, "voltage"); sprintf(buf, "%6.2f", v); break; case LPP_CURRENT: r.readCurrent(v); strcpy(name, "current"); sprintf(buf, "%.3f", v); break; case LPP_TEMPERATURE: r.readTemperature(v); strcpy(name, "temperature"); sprintf(buf, "%.2f", v); break; case LPP_RELATIVE_HUMIDITY: r.readRelativeHumidity(v); strcpy(name, "humidity"); sprintf(buf, "%.2f", v); break; case LPP_BAROMETRIC_PRESSURE: r.readPressure(v); strcpy(name, "pressure"); sprintf(buf, "%.2f", v); break; case LPP_ALTITUDE: r.readAltitude(v); strcpy(name, "altitude"); sprintf(buf, "%.0f", v); break; case LPP_POWER: r.readPower(v); strcpy(name, "power"); sprintf(buf, "%6.2f", v); break; default: r.skipData(type); strcpy(name, "unk"); sprintf(buf, ""); } display.setCursor(0, y); display.setColor(UIColor::secondary_txt); display.print(name); display.setColor(UIColor::primary_txt); display.setCursor( display.width()-display.getTextWidth(buf)-1, y ); display.print(buf); y += row_height > 12 ? row_height : 12; } if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; else sensors_scroll_offset = 0; #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 } else if (_page == HomePage::WIFI_SETUP) { drawCompanionWiFiSetupPage(display); #endif #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) } else if (_page == HomePage::DISCOVERY) { int count = the_mesh.getDiscoveredNodes(discovered, UI_RECENT_LIST_SIZE); display.setColor(UIColor::primary_txt); int y = 20; for (int i = 0; i < count; i++, y += 11) { char name[32]; auto a = &discovered[i]; if ((a->name[0] == 0) || !discovery_disp_names) { mesh::Utils::toHex(name, a->pubkey_prefix, 4); } else { StrHelper::strncpy(name, a->name, sizeof(name)); } char filtered_name[sizeof(name)]; char snr_s[24]; if (strlen(name) <= 8) { // display snr_o snprintf(snr_s, sizeof(snr_s), "%02.1f>%02.1f", a->snr_out, a->snr_in); } else { snprintf(snr_s, sizeof(snr_s), "%02.1f", a->snr_in); } int snr_width = display.getTextWidth(snr_s); int max_name_width = display.width() - snr_width - 1; display.translateUTF8ToBlocks(filtered_name, name, sizeof(filtered_name)); display.drawTextEllipsized(0, y, max_name_width, filtered_name); display.setCursor(display.width() - snr_width - 1, y); display.print(snr_s); } if (discovery_req_time && static_cast(millis() - discovery_req_time) < 5000) { return 1000; // more frequent updates just after req } else if (count < UI_RECENT_LIST_SIZE -1) { // show only 5 sec after last disc y = 10 + 11 * UI_RECENT_LIST_SIZE; display.drawTextCentered(display.width() / 2, y, "discover: " PRESS_LABEL); } #endif #ifndef UI_NO_HIBERNATE } else if (_page == HomePage::SHUTDOWN) { display.setColor(UIColor::corp_blue); display.setTextSize(1); if (_shutdown_init) { display.setColor(UIColor::warning_txt); display.drawTextCentered(display.width() / 2, 34, "hibernating..."); } else { display.setColor(UIColor::secondary_txt); display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32); display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL); } #endif } if (_page == HomePage::RADIO && !the_mesh.isDualRadioActive()) { return radioProfileRefreshMillis(); } if (_page == HomePage::RADIO || _page == HomePage::RADIO2 || _page == HomePage::RADIO_STATUS) return UI_RADIO_REFRESH_MILLIS; #if UI_MESSAGES_HOME_PAGE == 1 if (_page == HomePage::MESSAGES) return 1000; #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 if (_page == HomePage::WIFI_SETUP) return 1000; #endif return 5000; } bool handleInput(char c) override { // Navigation codes exceed 0x7f; keep them valid with signed char too. const uint8_t key = static_cast(c); #if UI_POCKET_GUI _pocket_last_input = millis(); auto& settings = _task->pocketSettings(); if (_page == HomePage::SETTINGS && key == KEY_ENTER) { _pocket_editing = !_pocket_editing; if (!_pocket_editing) flushPocketSettings(); return true; } if (_page == HomePage::SETTINGS && _pocket_editing) { if (key == KEY_PREV || key == KEY_LEFT) { _pocket_setting = (_pocket_setting + 1) % mesh::ui::pocket::SETTINGS_COUNT; return true; } if (key == KEY_NEXT || key == KEY_RIGHT) { const uint8_t previous_dark = settings.dark, previous_flip = settings.flip; if (_pocket_setting == 0) cyclePocketChannel(1); else mesh::ui::pocket::cycleSetting(settings, _pocket_setting, MAX_GROUP_CHANNELS); _pocket_dirty = true; if (previous_dark != settings.dark || previous_flip != settings.flip) displayForceClean(); _pocket.resetScroll(); return true; } } if (_page == HomePage::FIRST) { if (key == KEY_ENTER) { _pocket_browsing = !_pocket_browsing; return true; } if (key == KEY_DOWN || key == KEY_UP) { cyclePocketChannel(key == KEY_DOWN ? 1 : -1); flushPocketSettings(); return true; } if (_pocket_browsing) { if (key == KEY_NEXT || key == KEY_RIGHT) { _pocket.scrollOlder(_task->pocketBoardCount()); return true; } if (key == KEY_PREV || key == KEY_LEFT) { _pocket.scrollNewer(); return true; } } } if (_page == HomePage::MAP) { if (key == KEY_ENTER) { if (!_pocket_map_located) { _task->showAlert("Set location in app to zoom", 1500); return true; } _pocket_zooming = !_pocket_zooming; if (!_pocket_zooming) flushPocketSettings(); return true; } if (_pocket_zooming && (key == KEY_NEXT || key == KEY_RIGHT || key == KEY_PREV || key == KEY_LEFT)) { const bool closer = key == KEY_NEXT || key == KEY_RIGHT; if (mesh::ui::pocket::zoomMap(settings, closer, _pocket_map_located)) { _pocket_dirty = true; displayForceClean(); } return true; } } #endif if (key == KEY_LEFT || key == KEY_PREV) { movePage(-1); return true; } #if COMPANION_FEATURE_READER if (key == KEY_ENTER && isRadioPage()) { _task->showReader(); return true; } #endif if (key == KEY_NEXT || key == KEY_RIGHT) { movePage(1); if (_page == HomePage::RECENT) { _task->showAlert("Recent adverts", 800); } #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) if (_page == HomePage::DISCOVERY) { _task->showAlert("Repeater disc", 800); } #endif return true; } if (key == KEY_ENTER && (_page == HomePage::RADIO_STATUS #if UI_POCKET_GUI || _page == HomePage::STATUS #endif )) { _radio_status_page++; #if UI_POCKET_GUI displayForceClean(); #endif return true; } #ifdef COMPANION_EXCLUSIVE_WIFI_BLE if (_page == HomePage::TRANSPORT && (key == KEY_ENTER || key == KEY_UP || key == KEY_DOWN)) { const CompanionTransportMode selected = getCompanionTransportMode(); const CompanionTransportMode active = isCompanionWiFiEnabled() ? CompanionTransportMode::WiFi : CompanionTransportMode::Bluetooth; CompanionTransportMode requested = selected; if (key == KEY_UP) { requested = CompanionTransportMode::WiFi; } else if (key == KEY_DOWN) { requested = CompanionTransportMode::Bluetooth; } else { requested = active == CompanionTransportMode::WiFi ? CompanionTransportMode::Bluetooth : CompanionTransportMode::WiFi; } if (requested != selected && !selectCompanionTransportMode(requested)) { _task->showAlert("Transport save failed", 1500); return true; } if (requested != active) _task->shutdown(true); return true; } #elif defined(BLE_PIN_CODE) if (key == KEY_ENTER && _page == HomePage::BLUETOOTH) { if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off _task->disableBluetooth(); } else { _task->enableBluetooth(); } return true; } #endif if (key == KEY_ENTER && _page == HomePage::FIRST) { _task->showMessages(); return true; } #if UI_MESSAGES_HOME_PAGE == 1 if (key == KEY_ENTER && _page == HomePage::MESSAGES) { _task->showMessages(); return true; } #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 if (key == KEY_ENTER && _page == HomePage::WIFI_SETUP) { if (WebConfigServer::getSetupInfo(nullptr, 0, nullptr, 0)) { requestCompanionWiFiSetupStop(); _task->showAlert("Stopping setup AP", 1000); } else { requestCompanionWiFiSetup(); _task->showAlert("Starting setup AP", 1000); } return true; } #endif if (key == KEY_ENTER && _page == HomePage::ADVERT) { _task->notify(UIEventType::ack); if (the_mesh.advert()) { _task->showAlert("Advert sent!", 1000); } else { _task->showAlert("Advert failed..", 1000); } return true; } #if ENV_INCLUDE_GPS == 1 if (key == KEY_ENTER && _page == HomePage::GPS) { _task->toggleGPS(); return true; } #endif #if UI_SENSORS_PAGE == 1 if (key == KEY_ENTER && _page == HomePage::SENSORS) { _task->toggleGPS(); sensors_lpp.reset(); return true; } #endif #if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) if (key == KEY_ENTER && _page == HomePage::DISCOVERY) { if (!discovery_req_time || static_cast(millis() - discovery_req_time) >= 5000) { the_mesh.requestRepeatersDiscovery(); discovery_req_time = millis(); } return true; } if (key == KEY_SELECT && _page == HomePage::DISCOVERY) { discovery_disp_names = !discovery_disp_names; return true; } #endif #ifndef UI_NO_HIBERNATE if (key == KEY_ENTER && _page == HomePage::SHUTDOWN) { _shutdown_init = true; // need to wait for button to be released return true; } #endif return false; } }; #ifndef UI_MSG_PREVIEW_SIZE #if UI_SMALL_MESSAGE_FONT == 1 #define UI_MSG_PREVIEW_SIZE 161 #else #define UI_MSG_PREVIEW_SIZE 78 #endif #endif #ifndef UI_COMPACT_MESSAGE_STATUS #define UI_COMPACT_MESSAGE_STATUS 0 #endif // Single-button screens use multi-tap hints in place of the taller channel // selector. Three/four taps use the same up/down channel actions. #ifndef UI_MESSAGE_CHANNEL_FOOTER #if defined(MESHCORE_HAS_SMALL_DISPLAY) || UI_BUTTON_READER_HINT == 1 #define UI_MESSAGE_CHANNEL_FOOTER 0 #else #define UI_MESSAGE_CHANNEL_FOOTER 1 #endif #endif class MsgPreviewScreen : public UIScreen { UITask* _task; #if UI_READER_TOUCH_BAR mesh::ui::TouchNavigationBar _touch_bar; #endif static constexpr int CHANNEL_FILTER_ALL = -2; static constexpr int CHANNEL_FILTER_DIRECT = -1; static constexpr size_t MAX_RECENT_MESSAGES = 32; using MessageHistory = mesh::ui::CompanionMessageHistory< MAX_RECENT_MESSAGES, UI_MSG_PREVIEW_SIZE>; using MsgEntry = MessageHistory::Entry; MessageHistory history; int view_offset; int channel_filter; bool visible(const MsgEntry& entry) const { return mesh::ui::displayPowerPrefs().inbox != mesh::ui::DisplayInboxMode::Pending || entry.queue_index >= 0; } bool matchesFilter(const MsgEntry& entry) const { return visible(entry) && (channel_filter == CHANNEL_FILTER_ALL || entry.channel_idx == channel_filter); } int filteredCount() const { int count = 0; for (size_t age = 0; age < history.count(); ++age) { const MsgEntry* entry = history.newest(age); if (entry != nullptr && matchesFilter(*entry)) ++count; } return count; } const MsgEntry* filteredEntry(int offset) const { int match = 0; for (size_t age = 0; age < history.count(); ++age) { const MsgEntry* entry = history.newest(age); if (entry == nullptr || !matchesFilter(*entry)) continue; if (match++ == offset) return entry; } return nullptr; } int buildChannelFilters(int* filters, int capacity) const { int count = 0; if (count < capacity) filters[count++] = CHANNEL_FILTER_ALL; for (int channel_idx = 0; channel_idx < MAX_GROUP_CHANNELS && count < capacity; ++channel_idx) { ChannelDetails details; if (the_mesh.getChannel(channel_idx, details) && details.name[0] != 0) { filters[count++] = channel_idx; } } if (count < capacity) filters[count++] = CHANNEL_FILTER_DIRECT; return count; } void cycleChannelFilter(int direction) { int filters[MAX_GROUP_CHANNELS + 2]; int count = buildChannelFilters( filters, sizeof(filters) / sizeof(filters[0])); if (count == 0) return; int selected = 0; while (selected < count && filters[selected] != channel_filter) { ++selected; } if (selected == count) selected = 0; selected = (selected + direction + count) % count; channel_filter = filters[selected]; view_offset = 0; } void channelFilterLabel(char* label, size_t size) const { if (channel_filter == CHANNEL_FILTER_ALL) { StrHelper::strncpy(label, "All channels", size); return; } if (channel_filter == CHANNEL_FILTER_DIRECT) { StrHelper::strncpy(label, "Direct", size); return; } ChannelDetails details; if (the_mesh.getChannel(channel_filter, details) && details.name[0] != 0) { snprintf(label, size, "Ch %d %s", channel_filter, details.name); return; } for (size_t age = 0; age < history.count(); ++age) { const MsgEntry* entry = history.newest(age); if (entry != nullptr && entry->channel_idx == channel_filter && entry->channel_name[0] != 0) { snprintf(label, size, "Ch %d %s", channel_filter, entry->channel_name); return; } } snprintf(label, size, "Ch %d", channel_filter); } void renderChannelFilter(DisplayDriver& display) const { #if UI_MESSAGE_CHANNEL_FOOTER == 1 display.setTextSize(1); const mesh::ui::CompanionMessageChromeLayout layout = mesh::ui::makeCompanionMessageChromeLayout( UI_COMPACT_MESSAGE_STATUS == 1, !display.useSmallMessageFont() && display.renderWidth() == display.width() ? display.textLineHeight() : 0); const int bar_height = layout.filter_height; const int bar_y = display.height() - bar_height; display.setColor(UIColor::window_bkg); display.fillRect(0, bar_y, display.width(), bar_height); display.setColor(UIColor::corp_blue); display.drawRect(0, bar_y, display.width(), 1); char channel[48]; channelFilterLabel(channel, sizeof(channel)); display.setCompactText(layout.compact_text); display.setTextSize(1); const int text_y = bar_y + layout.filter_text_offset; display.setCursor(8, text_y); display.print("<"); display.drawTextCentered(display.width() / 2, text_y, channel); display.setCursor(display.width() - display.getTextWidth(">") - 8, text_y); display.print(">"); display.setCompactText(false); #else (void)display; #endif } public: #if UI_READER_TOUCH_BAR const mesh::ui::TouchNavigationBar* readerTouchBar() const { return &_touch_bar; } #endif explicit MsgPreviewScreen(UITask* task) : _task(task), view_offset(0), channel_filter(CHANNEL_FILTER_ALL) {} #if UI_POCKET_GUI MessageHistory& pocketHistory() { return history; } const MessageHistory& pocketHistory() const { return history; } void addSent(int channel_idx, const char* channel_name, const char* sender, const char* text, size_t length) { char message[UI_MSG_PREVIEW_SIZE]; if (length >= sizeof(message)) length = sizeof(message) - 1; memcpy(message, text, length); message[length] = 0; history.add(companionMessageNowMillis(), channel_idx, channel_name, sender, message, -1, true); } #endif bool hasMessages() const { for (size_t age = 0; age < history.count(); ++age) if (visible(*history.newest(age))) return true; return false; } int messageCount() const { if (mesh::ui::displayPowerPrefs().inbox == mesh::ui::DisplayInboxMode::Unread) return (int)history.unreadCount(); if (mesh::ui::displayPowerPrefs().inbox == mesh::ui::DisplayInboxMode::Pending) return _task->getMsgCount(); return (int)history.count(); } void queueRemoved(int index) { history.queueRemoved(index); } void addPreview(uint8_t path_len, const char* from_name, const char* msg, int channel_idx, const char* channel_name, int queue_index = -1, bool select = true) { if (channel_idx < CHANNEL_FILTER_DIRECT || channel_idx >= MAX_GROUP_CHANNELS) { channel_idx = CHANNEL_FILTER_DIRECT; channel_name = nullptr; } if (select) { view_offset = 0; channel_filter = channel_idx; } else if ((mesh::ui::displayPowerPrefs().inbox != mesh::ui::DisplayInboxMode::Pending || queue_index >= 0) && (channel_filter == CHANNEL_FILTER_ALL || channel_filter == channel_idx)) { // Retain the message being read when a connected app receives another. if (filteredCount() > 0) ++view_offset; } char origin[62]; if (path_len == 0xFF) { snprintf(origin, sizeof(origin), "%s [direct]:", from_name); } else { snprintf(origin, sizeof(origin), "%s [%uh]:", from_name, (unsigned int)path_len); } history.add(companionMessageNowMillis(), channel_idx, channel_name, origin, msg, queue_index); } void renderSummary(DisplayDriver& display) const { display.setTextSize(1); const mesh::ui::CompanionMessageListLayout layout = mesh::ui::makeCompanionMessageListLayout(display.height(), !display.useSmallMessageFont() && display.renderWidth() == display.width() ? display.textLineHeight() : 10); int rendered = 0; display.setTextSize(1); for (size_t age = 0; age < history.count() && rendered < layout.visible_rows; ++age) { const MsgEntry* entry = history.newest(age); if (entry == nullptr || !visible(*entry)) continue; bool newer_in_thread = false; for (size_t newer = 0; newer < age; ++newer) { const MsgEntry* candidate = history.newest(newer); if (visible(*candidate) && MessageHistory::sameThread(*entry, *candidate)) { newer_in_thread = true; break; } } if (newer_in_thread) continue; const int row_y = layout.top + rendered * layout.row_height; char label[48]; MessageHistory::threadLabel(*entry, label, sizeof(label)); char filtered_label[sizeof(label)]; display.translateUTF8ToBlocks(filtered_label, label, sizeof(filtered_label)); char age_text[16]; mesh::ui::formatCompanionMessageAge( age_text, sizeof(age_text), companionMessageElapsedMillis(entry->heard_millis)); const int age_width = display.getTextWidth(age_text); int label_width = display.width() - age_width - 5; if (label_width < 0) label_width = 0; display.setColor(UIColor::primary_txt); display.drawTextEllipsized(0, row_y + layout.title_offset, label_width, filtered_label); display.setColor(UIColor::secondary_txt); display.setCursor(display.width() - age_width - 1, row_y + layout.title_offset); display.print(age_text); char filtered_message[sizeof(entry->message)]; display.translateUTF8ToBlocks(filtered_message, entry->message, sizeof(filtered_message)); mesh::ui::makeCompanionMessagePreviewSingleLine(filtered_message); display.drawTextEllipsized(0, row_y + layout.preview_offset, display.width() - 1, filtered_message); display.setColor(UIColor::title_bkg); display.drawRect(0, row_y + layout.divider_offset, display.width(), 1); ++rendered; } if (rendered == 0) { display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, layout.top + layout.row_height, "No messages heard"); } } int render(DisplayDriver& display) override { // Native larger panels retain their normal font and line metrics. // Leave the Indicator's scaled chrome unchanged. display.setTextSize(1); const bool native_large = !display.useSmallMessageFont() && display.renderWidth() == display.width(); mesh::ui::CompanionMessageChromeLayout layout = mesh::ui::makeCompanionMessageChromeLayout(UI_COMPACT_MESSAGE_STATUS == 1, native_large ? display.textLineHeight() : 0); int body_bottom = UI_MESSAGE_CHANNEL_FOOTER == 1 ? display.height() - layout.filter_height : display.height(); display.setCompactText(layout.compact_text); int header_text_y = 0; #if UI_BUTTON_READER_HINT == 1 #if UI_SMALL_MESSAGE_FONT == 1 mesh::ui::SmallMessageText compact(display); const bool small = display.useSmallMessageFont(); DisplayDriver& reader_text = small ? static_cast(compact) : display; // Eight-pixel rows for the header and origin leave five message rows and // a navigation row on a 128x64 V4. Keep the 5px font on tiny panels. const int hint_line_height = small ? compact.lineHeight() : display.textLineHeight(); if (small) { layout.header_divider_y = hint_line_height - 1; layout.origin_y = hint_line_height; layout.message_y = 2 * hint_line_height; } #else DisplayDriver& reader_text = display; #if !UI_READER_TOUCH_BAR const int hint_line_height = display.textLineHeight(); #endif #endif #if UI_READER_TOUCH_BAR const int header_extra = mesh::ui::readerTouchHeaderHeight( layout.header_divider_y + 1) - (layout.header_divider_y + 1); header_text_y = header_extra / 2; layout.header_divider_y += header_extra; layout.origin_y += header_extra; layout.message_y += header_extra; _touch_bar = mesh::ui::makeReaderTouchBar(reader_text, body_bottom, layout.header_divider_y + 1); body_bottom = _touch_bar.top; #else const mesh::ui::ButtonReaderHintLayout hint = mesh::ui::makeButtonReaderHintLayout( reader_text, hint_line_height, body_bottom); body_bottom = hint.top; #endif DisplayDriver& header = reader_text; #else DisplayDriver& header = display; #endif char tmp[24]; int filtered_count = filteredCount(); if (view_offset >= filtered_count) view_offset = 0; header.setCursor(0, header_text_y); header.setColor(UIColor::corp_blue); #if UI_BUTTON_READER_HINT == 1 && UI_MESSAGE_CHANNEL_FOOTER == 0 // Keep the selected filter visible even when that channel has no messages. char channel[12]; if (channel_filter == CHANNEL_FILTER_ALL) strcpy(channel, "All"); else if (channel_filter == CHANNEL_FILTER_DIRECT) strcpy(channel, "DM"); else snprintf(channel, sizeof(channel), "Ch %d", channel_filter); snprintf(tmp, sizeof(tmp), "%s %d/%d", channel, filtered_count == 0 ? 0 : view_offset + 1, filtered_count); #else snprintf(tmp, sizeof(tmp), display.width() < 100 ? "%d/%d" : "Message %d/%d", filtered_count == 0 ? 0 : view_offset + 1, filtered_count); #endif const MsgEntry* p = filteredEntry(view_offset); if (p != nullptr && display.isOn()) history.markRead(p); char age[16] = {}; if (p != nullptr) { mesh::ui::formatCompanionMessageAge( age, sizeof(age), companionMessageElapsedMillis(p->heard_millis)); if (display.width() < 100) { char* suffix = strchr(age, ' '); if (suffix != nullptr) *suffix = 0; } } // On narrow rotations the channel and position take priority over age. const bool show_age = age[0] != 0 && header.getTextWidth(tmp) + header.getTextWidth(age) + 4 <= display.width(); const int header_width = display.width() - (show_age ? header.getTextWidth(age) + 4 : 0); header.drawTextEllipsized(0, header_text_y, header_width, tmp); if (p == nullptr) { display.drawRect(0, layout.header_divider_y, display.width(), 1); display.setCompactText(false); display.setColor(UIColor::secondary_txt); #if UI_BUTTON_READER_HINT == 1 display.setCompactText(layout.compact_text); reader_text.drawTextEllipsized(0, layout.origin_y, display.width(), "No buffered messages"); #if UI_READER_TOUCH_BAR mesh::ui::drawReaderTouchBar(reader_text, _touch_bar); #else mesh::ui::drawButtonReaderHint(reader_text, hint); #endif display.setCompactText(false); #else display.drawTextCentered(display.width() / 2, 40, "No buffered messages"); #endif renderChannelFilter(display); return UI_BUTTON_READER_HINT == 1 ? 3000 : 5000; } if (show_age) { header.setCursor(display.width() - header.getTextWidth(age) - 2, header_text_y); header.print(age); } display.drawRect(0, layout.header_divider_y, display.width(), 1); display.setCompactText(false); #if UI_SMALL_MESSAGE_FONT == 1 mesh::ui::drawSmallMessageBody(display, p->origin, p->message, layout.origin_y, body_bottom); #else display.setCursor(0, layout.origin_y); display.setColor(UIColor::secondary_txt); char filtered_origin[sizeof(p->origin)]; display.translateUTF8ToBlocks(filtered_origin, p->origin, sizeof(filtered_origin)); display.drawTextEllipsized(0, layout.origin_y, display.width(), filtered_origin); display.setCursor(0, layout.message_y); display.setColor(UIColor::primary_txt); char filtered_msg[sizeof(p->message)]; display.translateUTF8ToBlocks(filtered_msg, p->message, sizeof(filtered_msg)); if (native_large || UI_BUTTON_READER_HINT == 1) { mesh::ui::drawTextWrapped(display, 0, layout.message_y, display.width(), display.textLineHeight(), (body_bottom - layout.message_y) / display.textLineHeight(), filtered_msg); } else { display.printWordWrap(filtered_msg, display.width()); } #endif #if UI_BUTTON_READER_HINT == 1 display.setCompactText(layout.compact_text); #if UI_READER_TOUCH_BAR mesh::ui::drawReaderTouchBar(reader_text, _touch_bar); #else mesh::ui::drawButtonReaderHint(reader_text, hint); #endif display.setCompactText(false); #endif renderChannelFilter(display); #if AUTO_OFF_MILLIS==0 // probably e-ink return UI_BUTTON_READER_HINT == 1 ? 3000 : 10000; #else return 1000; // next render after 1000 ms #endif } bool handleInput(char c) override { const uint8_t key = static_cast(c); if (key == KEY_NEXT || key == KEY_RIGHT) { if (view_offset + 1 < filteredCount()) { ++view_offset; } else { // The historical inbox flow returned Home after its final item. Keep // that wrap behavior now that previews persist in MessageHistory; // otherwise a valid navigation press is a silent no-op at the end. _task->gotoHomeScreen(); } return true; } if (key == KEY_PREV || key == KEY_LEFT) { if (view_offset > 0) --view_offset; return true; } if (key == KEY_DOWN) { cycleChannelFilter(1); return true; } if (key == KEY_UP) { cycleChannelFilter(-1); return true; } if (key == KEY_ENTER) { _task->gotoHomeScreen(); return true; } return false; } }; #if defined(MESH_COMPANION_SCREEN_STARTUP_BYTES) // The target may replace the generic UI allowance with a tighter measured // bound. Keep the check next to the actual allocations so a future screen // growth cannot silently invalidate its runtime-RAM budget. ESP32's checked // heap allocator can consume up to 16 bytes per allocation. static_assert(sizeof(SplashScreen) + sizeof(HomeScreen) + sizeof(MsgPreviewScreen) + 3 * 16 <= MESH_COMPANION_SCREEN_STARTUP_BYTES, "Increase MESH_COMPANION_SCREEN_STARTUP_BYTES and its RAM budget"); #endif void UITask::begin(DisplayDriver* display, SensorManager* sensors, CompanionNodePrefs* node_prefs) { _display = display; _sensors = sensors; if (_display != NULL) { _display->setRotationDegrees(node_prefs->display_rotation_degrees); } #if defined(PIN_USER_BTN) user_btn.begin(); user_btn.enableQuadrupleClick(); #endif #if UI_HAS_JOYSTICK back_btn.enableQuadrupleClick(); #endif #if defined(TBEAM_1W) && defined(WIFI_SSID) && defined(PIN_WIFI_BTN) wifi_btn.begin(); #endif #if defined(PIN_USER_BTN_ANA) analog_btn.begin(); analog_btn.enableQuadrupleClick(); #endif _node_prefs = node_prefs; #if UI_POCKET_GUI the_mesh.loadPocketGuiSettings(_pocket_settings); if (_display) _display->forceFullRefresh(); #endif if (_display != NULL) { _display->servicePower(_board->isExternalPowered() || _board->isUsbHostConnected(), hasConnection()); } #ifdef PIN_BUZZER buzzer.begin(); buzzer.quiet(_node_prefs->buzzer_quiet); buzzer.startup(); #endif #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) vibration.begin(); vibration.quiet(_node_prefs->vibe_quiet); #endif ui_started_at = millis(); _startup_complete = false; next_batt_chck = _next_refresh = ui_started_at; _alert[0] = 0; _alert_expiry = 0; splash = new SplashScreen(this); home = new HomeScreen(this, &rtc_clock, sensors, node_prefs); msg_preview = new MsgPreviewScreen(this); setCurrScreen(splash); } void UITask::serviceWiFiToggleButton() { #if defined(TBEAM_1W) && defined(WIFI_SSID) && defined(PIN_WIFI_BTN) if (wifi_btn.check() == BUTTON_EVENT_CLICK) { const bool enabled = toggleCompanionWiFi(); showAlert(enabled ? "WiFi: ON" : "WiFi: OFF", 1200); _next_refresh = millis(); } #endif } void UITask::showAlert(const char* text, int duration_millis) { strcpy(_alert, text); _alert_expiry = millis() + duration_millis; } void UITask::showMessages() { setCurrScreen(msg_preview); } #if COMPANION_FEATURE_READER 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); } void UITask::closeReader() { // Home retains the selected radio page while the reader is open. setCurrScreen(home); } #endif int UITask::getPreviewCount() const { return static_cast(msg_preview)->messageCount(); } const char* UITask::inboxTitle() const { switch (mesh::ui::displayPowerPrefs().inbox) { case mesh::ui::DisplayInboxMode::Pending: return "INBOX"; case mesh::ui::DisplayInboxMode::Unread: return "UNREAD"; default: return "HISTORY"; } } void UITask::renderMessageSummary(DisplayDriver& display) const { static_cast(msg_preview)->renderSummary(display); } #if UI_POCKET_GUI void UITask::renderPocketBoard(mesh::ui::pocket::PocketGui& gui) const { ChannelDetails channel; char name[32] = {}; if (the_mesh.getChannel(_pocket_settings.channel, channel)) StrHelper::strncpy(name, channel.name, sizeof(name)); gui.renderBoard(static_cast(msg_preview)->pocketHistory(), name); } unsigned UITask::pocketBoardCount() const { const auto& history = static_cast(msg_preview)->pocketHistory(); unsigned count = 0; for (size_t age = 0; age < history.count(); ++age) if (history.newest(age)->channel_idx == _pocket_settings.channel) ++count; return count; } void UITask::renderPocketInbox(mesh::ui::pocket::PocketGui& gui) const { const auto& history = static_cast(msg_preview)->pocketHistory(); int y = gui.bodyTop() + 10; for (size_t age = 0; age < history.count() && y + 13 <= gui.bodyBottom(); ++age) { const auto* entry = history.newest(age); if (mesh::ui::displayPowerPrefs().inbox == mesh::ui::DisplayInboxMode::Pending && entry->queue_index < 0) continue; if (mesh::ui::displayPowerPrefs().inbox == mesh::ui::DisplayInboxMode::Unread && !entry->unread) continue; char label[48]; mesh::ui::CompanionMessageHistory<32, UI_MSG_PREVIEW_SIZE>::threadLabel(*entry, label, sizeof(label)); mesh::ui::pocket::truncateCharacters(label, 32); gui.label(4, y, label, entry->unread); y += 15; } if (y == gui.bodyTop() + 10) gui.label(4, y, "No messages"); } void UITask::channelMessageSent(int channel_idx, const char* channel_name, const char* sender, const char* text, size_t length) { if (!msg_preview || channel_idx < 0 || channel_idx >= MAX_GROUP_CHANNELS) return; static_cast(msg_preview)->addSent(channel_idx, channel_name, sender, text, length); static_cast(home)->pocketMessageAdded(channel_idx); if (_display && _display->isOn()) _next_refresh = millis(); } #endif void UITask::notify(UIEventType t) { #if defined(PIN_BUZZER) if (_notification_outputs & mesh::notify::Sound) switch(t){ case UIEventType::contactMessage: // gemini's pick buzzer.play("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); break; case UIEventType::channelMessage: buzzer.play("kerplop:d=16,o=6,b=120:32g#,32c#"); break; case UIEventType::ack: buzzer.play("ack:d=32,o=8,b=120:c"); break; case UIEventType::roomMessage: case UIEventType::newContactMessage: case UIEventType::none: default: break; } #endif #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) // Trigger vibration for all UI events except none if ((_notification_outputs & mesh::notify::Vibration) && t != UIEventType::none) { vibration.trigger(); } #endif } void UITask::msgRead(int msgcount) { _msgcount = msgcount; _next_refresh = millis(); } void UITask::syncMessageQueue(int msgcount, int removed_index) { if (msg_preview != nullptr) static_cast(msg_preview)->queueRemoved(removed_index); msgRead(msgcount); } void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount, int channel_idx, const char* channel_name, int queue_index) { _msgcount = msgcount; ((MsgPreviewScreen *)msg_preview) ->addPreview(path_len, from_name, text, channel_idx, channel_name, queue_index, !hasConnection()); #if UI_POCKET_GUI static_cast(home)->pocketMessageAdded(channel_idx); #endif if (hasConnection()) { // Keep history, but do not change the page or wake for a connected client. _deferred_msg_preview = false; } else if (isPairingScreenActive()) { // Keep the PIN visible, but retain the preview so it can be shown after // pairing completes or the pairing display window expires. _deferred_msg_preview = true; } #if COMPANION_FEATURE_READER else if (isReaderActive()) { // Queue incoming messages without stealing the reader's page. _deferred_msg_preview = true; } #endif #if UI_POCKET_GUI else if (channel_idx >= 0 && curr == home && static_cast(home)->isPocketBoard()) { // Keep the live channel board visible while retaining normal notifications. _deferred_msg_preview = false; } #endif else { setCurrScreen(msg_preview); } if (_display != NULL) { if (shouldWakeDisplayForMessage()) { _display->wake(mesh::ui::DisplayWake::Message); } if (_display->isOn()) _next_refresh = millis(); } } void UITask::userLedHandler() { if (!mesh::leds::enabled()) return; if (_notification_led_owned || !(_notification_outputs & mesh::notify::Led)) return; #ifdef PIN_STATUS_LED const uint32_t cur_time = millis(); // Phase age also survives long notification-owned or disabled intervals. if (static_cast(cur_time - last_led_change) > led_phase_millis) { if (led_state == 0) { led_state = 1; if (_msgcount > 0) { led_phase_millis = LED_ON_MSG_MILLIS; } else { led_phase_millis = LED_ON_MILLIS; } } else { led_state = 0; led_phase_millis = LED_CYCLE_MILLIS - led_phase_millis; } last_led_change = cur_time; digitalWrite(PIN_STATUS_LED, led_state == LED_STATE_ON); } #endif } void UITask::setCurrScreen(UIScreen* c) { #if UI_POCKET_GUI if (curr == home && c != home) static_cast(home)->flushPocketSettings(); if (curr != c && _display) _display->forceFullRefresh(); #endif #if COMPANION_FEATURE_READER if (isReaderActive() && c != reader && !static_cast(reader)->flush()) { showAlert("Bookmark save failed", 1500); } #endif curr = c; _next_refresh = millis(); } bool UITask::isPairingScreenActive() const { return mesh::ui::isBluetoothPairingPromptActive( isBluetoothEnabled(), hasBluetoothConnection(), static_cast(_pairing_screen_until), static_cast(millis())); } void UITask::renderPairingBanner() { if (_display == NULL || !isPairingScreenActive()) return; const uint32_t pairing_pin = the_mesh.getBLEPin(); if (pairing_pin == 0) return; // Keep one complete PIN per frame. Other pages and layouts without their // own PIN still need this overlay during pairing. if (curr == home && static_cast(home)->hasPairingPin()) return; char prompt[24]; snprintf(prompt, sizeof(prompt), "PAIR PIN %06u", (unsigned int)pairing_pin); _display->setColor(UIColor::popup_bkg); _display->fillRect(0, 0, _display->width(), 12); _display->setColor(UIColor::popup_txt); _display->setTextSize(1); _display->drawTextCentered(_display->width() / 2, 2, prompt); } void UITask::showPairingPin(bool from_button) { if (!isBluetoothEnabled()) return; const unsigned long now = millis(); _pairing_from_button = from_button; const auto& prefs = mesh::ui::displayPowerPrefs(); const auto& profile = (_board->isExternalPowered() || _board->isUsbHostConnected()) ? prefs.usb : prefs.battery; _pairing_screen_until = now + (from_button ? uint32_t(profile.seconds) * 1000U : BLE_PAIRING_DISPLAY_MILLIS); if (curr == msg_preview && _msgcount > 0) { _deferred_msg_preview = true; } static_cast(home)->showFirstPage(); setCurrScreen(home); if (_display != NULL) { _display->servicePower(_board->isExternalPowered() || _board->isUsbHostConnected(), hasConnection(), true); _next_refresh = millis(); } } void UITask::finishPairingScreen(bool timed_out) { _pairing_screen_until = 0; _pairing_from_button = false; if (_deferred_msg_preview && !hasConnection() && static_cast(msg_preview)->hasMessages()) { _deferred_msg_preview = false; setCurrScreen(msg_preview); } else { _deferred_msg_preview = false; gotoHomeScreen(); if (timed_out && _display != NULL) { _display->dismiss(); } else { _next_refresh = millis(); } } } void UITask::servicePairingState() { if (_interfaceManager->takePairingRequest()) { showPairingPin(); } if (_pairing_screen_until != 0) { const bool timed_out = static_cast(millis() - _pairing_screen_until) >= 0; if (!isPairingScreenActive()) { finishPairingScreen(timed_out); } } if (_display != NULL && _display->servicePower( _board->isExternalPowered() || _board->isUsbHostConnected(), hasConnection(), isPairingScreenActive())) { _next_refresh = millis(); #if COMPANION_FEATURE_READER if (!_display->isOn() && isReaderActive()) static_cast(reader)->flush(); #endif } } /* hardware-agnostic pre-shutdown activity should be done here */ void UITask::shutdown(bool restart){ if (!prepareForShutdown()) return; #if COMPANION_FEATURE_READER if (reader) static_cast(reader)->flush(); #endif #ifdef PIN_BUZZER /* note: we have a choice here - we can do a blocking buzzer.loop() with non-deterministic consequences or we can set a flag and delay the shutdown for a couple of seconds while a non-blocking buzzer.loop() plays out in UITask::loop() */ buzzer.shutdown(); uint32_t buzzer_timer = millis(); // fail-safe shutdown while (buzzer.isPlaying() && (millis() - 2500) < buzzer_timer) buzzer.loop(); #endif // PIN_BUZZER if (restart) { _board->reboot(); } else { display.forceFullRefresh(); display.clear(); display.endFrame(); // Power off board including radio, display, GPS and components _board->powerOff(); } } bool UITask::isButtonPressed() const { #ifdef PIN_USER_BTN return user_btn.isPressed(); #else return false; #endif } bool UITask::isButtonGesturePending() const { #if UI_DEFER_RENDER_DURING_BUTTON_GESTURE && defined(PIN_USER_BTN) // RGB painting/presentation is synchronous. Service the polled button // through debounce and the final multi-click deadline before redrawing. // Check the raw level too, in case an edge arrived since this loop's poll. return user_btn.needsPolling() || user_btn.isPressed(); #else return false; #endif } void UITask::syncAlertPreferences() { if (!_node_prefs) return; #ifdef PIN_BUZZER if (buzzer.isQuiet() != bool(_node_prefs->buzzer_quiet)) buzzer.quiet(_node_prefs->buzzer_quiet); #endif #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) if (vibration.isQuiet() != bool(_node_prefs->vibe_quiet)) vibration.quiet(_node_prefs->vibe_quiet); #endif } void UITask::loop() { syncAlertPreferences(); #if defined(HELTEC_V4_DISPLAY_UNIFIED) && HELTEC_V4_DISPLAY_UNIFIED static uint32_t display_generation = 0; if (display_generation != display.generation()) { display_generation = display.generation(); display.setRotationDegrees(_node_prefs->display_rotation_degrees); _next_refresh = millis(); } // Preserve normal headless button, notification and battery behavior while // retaining the wrapper for a later live display.type change. _display = display.selectedType() == mesh::ui::HeltecV4DisplayType::None ? nullptr : &display; #endif // Observe startup expiry even while display/Morse/input defers rendering. if (!_startup_complete && static_cast(millis() - ui_started_at) >= 8000u) { _startup_complete = true; } const bool morse_timing = mesh::morseTimingActive(&radio_driver); serviceWiFiToggleButton(); servicePairingState(); // Keep an already-due refresh due while drawing is deferred, without // moving a future throttle or letting it age past half the clock range. const uint32_t refresh_now = millis(); if (static_cast(refresh_now - _next_refresh) >= 0) { _next_refresh = refresh_now; } // Retire the popup even while sleep, Morse or input prevents drawing. // Its deadline may be zero after wrapping; empty text means inactive. if (_alert[0] && static_cast(millis() - _alert_expiry) >= 0) { _alert[0] = 0; _next_refresh = millis(); } char c = 0; #if UI_HAS_JOYSTICK int ev = user_btn.check(); if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { c = handleLongPress(KEY_ENTER); // REVISIT: could be mapped to different key code } ev = joystick_left.check(); if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_LEFT); } else if (ev == BUTTON_EVENT_LONG_PRESS) { c = handleLongPress(KEY_LEFT); } ev = joystick_right.check(); if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_RIGHT); } else if (ev == BUTTON_EVENT_LONG_PRESS) { c = handleLongPress(KEY_RIGHT); } ev = back_btn.check(); if (ev == BUTTON_EVENT_TRIPLE_CLICK || ev == BUTTON_EVENT_QUADRUPLE_CLICK) { c = handleMultiClick(KEY_SELECT, ev == BUTTON_EVENT_QUADRUPLE_CLICK); } #elif defined(PIN_USER_BTN) int ev = user_btn.check(); #ifdef UI_HAS_NAV_INPUT if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { if (_display == NULL) { c = handleLongPress(KEY_ENTER); } else { #if COMPANION_FEATURE_READER if (isReaderActive() || (curr == home && static_cast(home)->isRadioPage())) c = handleLongPress(KEY_ENTER); else #endif display.dismiss(); } } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_SELECT); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK || ev == BUTTON_EVENT_QUADRUPLE_CLICK) { c = handleMultiClick(KEY_SELECT, ev == BUTTON_EVENT_QUADRUPLE_CLICK); } #else if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_NEXT); } else if (ev == BUTTON_EVENT_LONG_PRESS) { c = (_display != NULL && !_display->isOn()) ? checkDisplayOn(KEY_ENTER) : handleLongPress(KEY_ENTER); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = (_display != NULL && !_display->isOn()) ? checkDisplayOn(KEY_ENTER) : handleDoubleClick(KEY_PREV); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK || ev == BUTTON_EVENT_QUADRUPLE_CLICK) { c = (_display != NULL && !_display->isOn()) ? checkDisplayOn(KEY_ENTER) : handleMultiClick(KEY_SELECT, ev == BUTTON_EVENT_QUADRUPLE_CLICK); } #endif #endif #if defined(UI_HAS_ROTARY_INPUT) RotaryInputEvent rotaryEv = rotary_input.poll(); if (c == 0 && _display != NULL && _display->isOn()) { if (rotaryEv == RotaryInputEvent::Next) { c = KEY_NEXT; } else if (rotaryEv == RotaryInputEvent::Prev) { c = KEY_PREV; } } #endif #if defined(PIN_USER_BTN_ANA) if (abs(millis() - _analogue_pin_read_millis) > 10) { int ev = analog_btn.check(); if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_NEXT); } else if (ev == BUTTON_EVENT_LONG_PRESS) { c = handleLongPress(KEY_ENTER); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_PREV); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK || ev == BUTTON_EVENT_QUADRUPLE_CLICK) { c = handleMultiClick(KEY_SELECT, ev == BUTTON_EVENT_QUADRUPLE_CLICK); } _analogue_pin_read_millis = millis(); } #endif #ifdef HAS_TOUCH if (_display != NULL && (int32_t)(millis() - next_touch_check) >= 0) { next_touch_check = millis() + 25; int touch_x = -1; int touch_y = -1; const bool touched = _display->getTouch(&touch_x, &touch_y); mesh::ui::TouchSplitSelector transport_touch_selector = {}; const mesh::ui::TouchSplitSelector* split_transport_selector = nullptr; const mesh::ui::TouchNavigationBar* reader_touch_bar = nullptr; getTouchControls(transport_touch_selector, split_transport_selector, reader_touch_bar); // A sleeping reader still accepts an ordinary wake gesture anywhere; // checkDisplayOn consumes it before navigation. Awake readers use their // rendered header/footer targets and page-only body taps. if (!_display->isOn()) reader_touch_bar = nullptr; if (_touch_debug_enabled) { // Highlight the detected visual point, using the same X correction as // stationary input. Redraw on press/release or a region change only, not // every sample, so diagnostics do not continuously stall touch polling. _touch_debug_x = touched ? (TOUCH_MIRROR_TAP_X_ENABLED ? _display->width() - 1 - touch_x : touch_x) : -1; _touch_debug_y = touched ? touch_y : -1; const auto debug_areas = mesh::ui::makeTouchDebugAreas( _display->width(), _display->height(), touch_input.centerZonePercent(), curr == msg_preview && UI_MESSAGE_CHANNEL_FOOTER == 1 && touch_input.hasSeparateVerticalSwipes(), split_transport_selector, reader_touch_bar); const int debug_area = mesh::ui::touchDebugAreaAt(debug_areas, _touch_debug_x, _touch_debug_y); if (debug_area != _touch_debug_area || curr != _touch_debug_screen) _next_refresh = millis(); _touch_debug_area = debug_area; _touch_debug_screen = curr; } const mesh::ui::TouchAction action = touch_input.update( touched, touch_x, touch_y, _display->width(), _display->height(), curr == msg_preview && UI_MESSAGE_CHANNEL_FOOTER == 1, split_transport_selector, reader_touch_bar); const bool on_transport_selector = split_transport_selector != nullptr; if (c == 0) { switch (action) { case mesh::ui::TouchAction::Previous: c = checkDisplayOn(KEY_PREV); break; case mesh::ui::TouchAction::Next: c = checkDisplayOn(KEY_NEXT); break; case mesh::ui::TouchAction::Select: c = checkDisplayOn(KEY_ENTER); break; case mesh::ui::TouchAction::SelectLeft: c = checkDisplayOn(KEY_UP); break; case mesh::ui::TouchAction::SelectRight: c = checkDisplayOn(KEY_DOWN); break; case mesh::ui::TouchAction::VerticalPrevious: if (!on_transport_selector) c = checkDisplayOn(KEY_UP); break; case mesh::ui::TouchAction::VerticalNext: if (!on_transport_selector) c = checkDisplayOn(KEY_DOWN); break; case mesh::ui::TouchAction::None: break; } } } #endif #if defined(BACKLIGHT_BTN) // First-poll state must not collide with a completed poll at timestamp zero. enum class BacklightButtonState : uint8_t { Unseen, Released, Pressed }; static BacklightButtonState button_state = BacklightButtonState::Unseen; const uint32_t backlight_now = millis(); if (button_state == BacklightButtonState::Unseen ? backlight_now > 0 : static_cast(backlight_now - last_backlight_btn_check) > 300) { const bool pressed = digitalRead(PIN_BUTTON2) == LOW; if (pressed && button_state != BacklightButtonState::Pressed && _display != NULL) _display->wake(mesh::ui::DisplayWake::Button); button_state = pressed ? BacklightButtonState::Pressed : BacklightButtonState::Released; last_backlight_btn_check = millis(); } #endif // A button-wake PIN is a preview, not a modal pairing request. The next // navigation gesture must still work; real phone requests retain priority. if (_pairing_from_button && c != 0) { _pairing_screen_until = 0; _pairing_from_button = false; } if (isPairingScreenActive()) { // Pairing has visual priority over navigation and asynchronous screens. static_cast(home)->showFirstPage(); if (curr != home) setCurrScreen(home); c = 0; } if (c != 0 && curr && _display != NULL) { _display->wake(mesh::ui::DisplayWake::Button); curr->handleInput(c); _next_refresh = millis(); // trigger refresh } userLedHandler(); #ifdef PIN_BUZZER if (buzzer.isPlaying()) buzzer.loop(); #endif if (!morse_timing && curr) curr->poll(); #if COMPANION_FEATURE_READER if (!morse_timing && reader && curr != reader) reader->poll(); #endif if (_display != NULL && _display->isOn()) { if (!morse_timing && static_cast(millis() - _next_refresh) >= 0 && curr && !isButtonGesturePending()) { _display->startFrame(); int delay_millis = curr->render(*_display); renderPairingBanner(); if (_alert[0] && static_cast(millis() - _alert_expiry) < 0) { // render alert popup _display->setTextSize(1); int y = _display->height() / 3; int p = _display->height() / 32; _display->setColor(UIColor::popup_bkg); _display->fillRect(p, y, _display->width() - p*2, y); _display->setColor(UIColor::popup_txt); // draw box border _display->drawRect(p, y, _display->width() - p*2, y); _display->drawTextCentered(_display->width() / 2, y + p*3, _alert); _next_refresh = _alert_expiry; // will need refresh when alert is dismissed } else { _next_refresh = millis() + delay_millis; } #ifdef HAS_TOUCH if (_touch_debug_enabled && !isPairingScreenActive()) { mesh::ui::TouchSplitSelector transport = {}; const mesh::ui::TouchSplitSelector* split = nullptr; const mesh::ui::TouchNavigationBar* reader = nullptr; getTouchControls(transport, split, reader); mesh::ui::drawTouchDebugAreas(*_display, mesh::ui::makeTouchDebugAreas(_display->width(), _display->height(), touch_input.centerZonePercent(), curr == msg_preview && UI_MESSAGE_CHANNEL_FOOTER == 1 && touch_input.hasSeparateVerticalSwipes(), split, reader), _touch_debug_screen == curr ? _touch_debug_x : -1, _touch_debug_screen == curr ? _touch_debug_y : -1); } #endif _display->endFrame(); } #if AUTO_OFF_MILLIS > 0 #if MOMENTARY_BUTTON_WAKE_HOLD_MS > 0 && defined(PIN_USER_BTN) if (user_btn.isWakeHoldActive()) _display->wake(mesh::ui::DisplayWake::Button); #endif #endif } #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) vibration.loop(); #endif #ifdef AUTO_SHUTDOWN_MILLIVOLTS if (static_cast(millis() - next_batt_chck) >= 0) { uint16_t milliVolts = getBattMilliVolts(); if (milliVolts > 0 && milliVolts < AUTO_SHUTDOWN_MILLIVOLTS #ifdef HELTEC_V4_TFT_SHUTDOWN_ONLY && display.selectedType() == mesh::ui::HeltecV4DisplayType::Tft #endif ) { if(!board.isExternalPowered()) { if (_display != NULL) { _display->startFrame(); _display->setTextSize(2); _display->setColor(UIColor::warning_txt); _display->drawTextCentered(_display->width() / 2, 20, "Low Battery."); _display->drawTextCentered(_display->width() / 2, 40, "Shutting Down!"); _display->endFrame(); if (_display->isEink() == false) { delay(3000); } } shutdown(); } } next_batt_chck = millis() + 8000; } #endif } #ifdef HAS_TOUCH void UITask::getTouchControls(mesh::ui::TouchSplitSelector& transport_touch_selector, const mesh::ui::TouchSplitSelector*& split_transport_selector, const mesh::ui::TouchNavigationBar*& reader_touch_bar) { split_transport_selector = nullptr; reader_touch_bar = nullptr; #ifdef COMPANION_EXCLUSIVE_WIFI_BLE if (curr == home && static_cast(home)->isTransportSelectorPage()) { const mesh::ui::CompanionTransportSelectorLayout layout = mesh::ui::makeCompanionTransportSelectorLayout( _display->width(), _display->height(), TOUCH_CENTER_ZONE_PERCENT); transport_touch_selector = { layout.wifi.x, layout.wifi.width, layout.bluetooth.x, layout.bluetooth.width, layout.wifi.y, layout.wifi.height, layout.side_nav_width, }; split_transport_selector = &transport_touch_selector; } #endif #if UI_READER_TOUCH_BAR if (curr == msg_preview) reader_touch_bar = static_cast(msg_preview)->readerTouchBar(); #if COMPANION_FEATURE_READER else if (isReaderActive()) reader_touch_bar = static_cast(reader)->readerTouchBar(); #endif #endif } #endif char UITask::checkDisplayOn(char c) { the_mesh.notificationButton(); if (_display != NULL) { const bool was_on = _display->isOn(); _display->wake(mesh::ui::DisplayWake::Button); if (!was_on) { if (_display->isOn() && mesh::ui::shouldDisplayBluetoothPairingPin( isBluetoothEnabled(), hasBluetoothConnection(), the_mesh.getBLEPin())) { showPairingPin(true); } c = 0; } _next_refresh = millis(); // trigger refresh } return _display != NULL ? c : 0; } char UITask::handleLongPress(char c) { // Exit an incoming message preview even during the startup rescue window. // The on-screen reader hint must not unexpectedly enter CLI rescue. if (_display != NULL && curr == msg_preview) return c; #if COMPANION_FEATURE_READER // The radio page's reader gesture, including exit, takes precedence over // the global early-boot rescue gesture just like the WiFi setup page. if (_display != NULL && isReaderActive()) { closeReader(); return 0; } if (_display != NULL && curr == home && static_cast(home)->isRadioPage()) { showReader(); return 0; } #endif #if UI_WIFI_SETUP_HOME_PAGE == 1 // A setup AP may focus this page immediately at boot. Its documented HOLD // action must win over the otherwise-global early-boot CLI rescue gesture. if (_display != NULL && curr == home && static_cast(home)->isWiFiSetupPage()) { return c; } #endif if (!_startup_complete && static_cast(millis() - ui_started_at) < 8000u) { // early-boot CLI/rescue only the_mesh.enterCLIRescue(); c = 0; // consume event } return _display != NULL ? c : 0; } char UITask::handleDoubleClick(char c) { MESH_DEBUG_PRINTLN("UITask: double-click triggered"); checkDisplayOn(c); return _display != NULL ? c : 0; } char UITask::handleMultiClick(char c, bool backwards) { MESH_DEBUG_PRINTLN("UITask: %s-click triggered", backwards ? "quadruple" : "triple"); if (_display != NULL && (curr == msg_preview #if COMPANION_FEATURE_READER || isReaderActive() #endif #if UI_POCKET_GUI || (curr == home && static_cast(home)->isPocketBoard()) #endif )) { return checkDisplayOn(backwards ? KEY_UP : KEY_DOWN); } checkDisplayOn(c); toggleBuzzer(); return 0; } bool UITask::getGPSState() { if (_sensors != NULL) { int num = _sensors->getNumSettings(); for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { return !strcmp(_sensors->getSettingValue(i), "1"); } } } return false; } void UITask::toggleGPS() { if (_sensors != NULL) { // toggle GPS on/off int num = _sensors->getNumSettings(); for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { _sensors->setSettingValue("gps", "0"); _node_prefs->gps_enabled = 0; notify(UIEventType::ack); } else { _sensors->setSettingValue("gps", "1"); _node_prefs->gps_enabled = 1; notify(UIEventType::ack); } the_mesh.savePrefs(); showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); _next_refresh = millis(); break; } } } } void UITask::toggleBuzzer() { // Toggle buzzer quiet mode #ifdef PIN_BUZZER if (buzzer.isQuiet()) { buzzer.quiet(false); notify(UIEventType::ack); } else { buzzer.quiet(true); } _node_prefs->buzzer_quiet = buzzer.isQuiet(); the_mesh.setNotificationOutputMute(mesh::notify::Sound, _node_prefs->buzzer_quiet); the_mesh.savePrefs(); showAlert(buzzer.isQuiet() ? "Buzzer: OFF" : "Buzzer: ON", 800); _next_refresh = millis(); // trigger refresh #endif } uint8_t UITask::notificationCapabilities() const { uint8_t bits = 0; #ifdef PIN_BUZZER bits |= mesh::notify::Sound; #endif #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) bits |= mesh::notify::Vibration; #endif #ifdef MESHCORE_HAS_REAL_DISPLAY if (_display) bits |= mesh::notify::Screen; #endif return bits; } void UITask::notificationMelody(const char* text) { #ifdef PIN_BUZZER if (text) buzzer.playNotification(text); else buzzer.stopNotification(); #endif } void UITask::notificationScreen(int8_t mode) { if (!_display) return; _display->notificationPower(mode); _next_refresh = millis(); } void UITask::notificationVibration(bool on) { #if defined(PIN_VIBRATION) || defined(HAS_DRV2605) vibration.pulse(on); #endif }