feat: complete Cascade Indicator companion support

Add native-resolution Indicator UI, touch navigation, SD-backed pixel and emoji fonts, LoRa radio support, dual-slot WiFi Companion provisioning, and mesh clock fallback. Harden radio recovery and build defaults, normalize ESP32 setup-AP protocols, and document/test the operator workflows.
This commit is contained in:
mikecarper committed 2026-08-25 18:37:17 -07:00
1 parent 1792acda6a
commit 9d57a3a4f8
55 files changed
+4185 -175

No files matched your search

+3
View File
@@ -94,6 +94,9 @@ public:
}
virtual int getNoiseFloor() const { return 0; }
virtual float getNoiseFloorDbm() const {
return static_cast<float>(getNoiseFloor());
}
virtual void triggerNoiseFloorCalibrate(int threshold) { }
+16 -2
View File
@@ -19,14 +19,22 @@
#ifndef FIRMWARE_BUILD_EPOCH
#define FIRMWARE_BUILD_EPOCH 0UL
#endif
#ifndef MESH_CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT
#define MESH_CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT 9
#endif
#ifndef MESH_CLOCK_SYNC_STARTUP_DELAY_MILLIS
#define MESH_CLOCK_SYNC_STARTUP_DELAY_MILLIS (30ULL * 60ULL * 1000ULL)
#endif
namespace {
constexpr char PREFS_FILE[] = "/clock_sync";
constexpr uint8_t REQUIRED_SAMPLES_MIN = 3;
constexpr uint8_t REQUIRED_SAMPLES_MAX = 16;
constexpr uint8_t REQUIRED_SAMPLES_DEFAULT = 9;
constexpr uint64_t STARTUP_DELAY_MILLIS = 30ULL * 60ULL * 1000ULL;
constexpr uint8_t REQUIRED_SAMPLES_DEFAULT =
MESH_CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT;
constexpr uint64_t STARTUP_DELAY_MILLIS =
MESH_CLOCK_SYNC_STARTUP_DELAY_MILLIS;
constexpr uint64_t RETRY_INTERVAL_MILLIS = 30ULL * 60ULL * 1000ULL;
constexpr uint64_t RESYNC_INTERVAL_MILLIS = 7ULL * 24ULL * 60ULL * 60ULL * 1000ULL;
constexpr uint32_t SAMPLE_MAX_AGE_MILLIS = 2UL * 60UL * 60UL * 1000UL;
@@ -35,6 +43,12 @@ constexpr uint32_t DRIFT_MIN_SECONDS = 30UL;
constexpr uint32_t DRIFT_MAX_SECONDS = 86400UL;
constexpr uint16_t VALID_YEARS = 10;
static_assert(REQUIRED_SAMPLES_DEFAULT >= REQUIRED_SAMPLES_MIN
&& REQUIRED_SAMPLES_DEFAULT <= REQUIRED_SAMPLES_MAX,
"mesh clock-sync sample default is outside the supported range");
static_assert(STARTUP_DELAY_MILLIS > 0,
"mesh clock-sync startup delay must be positive");
// Public-channel AES key, zero-padded to the shared-secret buffer width used
// by Utils::MACThenDecrypt().
const uint8_t PUBLIC_CHANNEL_SECRET[PUB_KEY_SIZE] = {
+10 -1
View File
@@ -5,6 +5,7 @@
#include <WiFi.h>
#include <DNSServer.h>
#include <Preferences.h>
#include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <strings.h>
@@ -296,7 +297,15 @@ bool WiFiSetupPortal::begin(const char* ap_name, SaveCallback save_callback, voi
WiFi.mode(WIFI_AP_STA);
if (!WiFi.softAPConfig(SETUP_IP, SETUP_IP, SETUP_MASK)
|| !WiFi.softAP(impl->ap_name, nullptr)) {
|| !WiFi.softAP(impl->ap_name, nullptr)
|| esp_wifi_set_protocol(
WIFI_IF_AP,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N)
!= ESP_OK
|| esp_wifi_set_protocol(
WIFI_IF_STA,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N)
!= ESP_OK) {
WiFi.softAPdisconnect(true);
return false;
}
+4
View File
@@ -42,6 +42,10 @@ static void OnDataRecv(const uint8_t *mac, const uint8_t *data, int len) {
void ESPNOWRadio::init() {
// Set device as a Wi-Fi Station
// ESP-NOW's LR protocol is local to this radio transport. Keeping WiFi
// driver writes in RAM prevents a later conventional WiFi image from
// inheriting the proprietary protocol bit through NVS.
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
// Long Range mode
esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR);
+23 -1
View File
@@ -603,7 +603,22 @@ bool WebConfigServer::startSetupMode(char reply[]) {
#else
ap_ok = WiFi.softAP(_ap_ssid);
#endif
if (ap_ok) break;
if (ap_ok) {
// ESP-NOW can leave the persistent AP protocol mask with the proprietary
// LR bit set. The driver then reports a healthy SoftAP, but ordinary
// phones and laptops cannot discover its beacon. A WiFi companion must
// advertise using the interoperable 2.4 GHz protocol set.
const esp_err_t ap_protocol_result = esp_wifi_set_protocol(
WIFI_IF_AP,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N);
const esp_err_t sta_protocol_result = esp_wifi_set_protocol(
WIFI_IF_STA,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N);
if (ap_protocol_result == ESP_OK && sta_protocol_result == ESP_OK) break;
Serial.printf("WebConfig protocol reset failed: AP=%d STA=%d\n",
(int)ap_protocol_result, (int)sta_protocol_result);
ap_ok = false;
}
Serial.printf(
"WebConfig AP attempt %u failed: mode_ok=%d disconnect_ok=%d mode=%d heap=%u largest=%u\n",
@@ -677,6 +692,13 @@ bool WebConfigServer::startAutoMode(char reply[]) {
}
WiFi.mode(WIFI_STA);
if (esp_wifi_set_protocol(
WIFI_IF_STA,
WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N)
!= ESP_OK) {
strcpy(reply, "Err: failed to reset WiFi station protocol");
return false;
}
WiFi.setAutoReconnect(true);
_retry_saved_wifi_in_setup = false;
_setup_reconnect_in_progress = false;
+19 -1
View File
@@ -2,7 +2,7 @@
#include <stdint.h>
// AUTO-GENERATED by tools/mota/gen_targets.py - do not edit by hand.
// 577 OTA-capable build targets. Maps target_id (= sha2-256:4 of the target name, LE uint32)
// 594 OTA-capable build targets. Maps target_id (= sha2-256:4 of the target name, LE uint32)
// to the human-readable env name, so a node/tool can name a target seen over the air WITHOUT
// transmitting the string in the .mota / LoRa protocol. Regenerate when the OTA env set changes.
// Size-constrained receivers can set OTA_TARGET_NAME_TABLE=0. They still match targets by ID;
@@ -68,6 +68,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xb12e6e01, "Heltec_E290_room_server" },
{ 0xf6f835ec, "Heltec_mesh_solar_repeater" },
{ 0x7fab017f, "heltec_rc32_companion_radio_ble" },
{ 0x9e23928a, "heltec_rc32_companion_radio_full" },
{ 0xf310a4d1, "heltec_rc32_companion_radio_usb" },
{ 0xdd5953ec, "heltec_rc32_companion_radio_wifi" },
{ 0x97574bc2, "heltec_rc32_kiss_modem" },
@@ -77,6 +78,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x57f69746, "heltec_rc32_sensor" },
{ 0xbc05d6a7, "heltec_rc32_terminal_chat" },
{ 0x5bad80f1, "heltec_rc32_without_display_companion_radio_ble" },
{ 0xb4f727a8, "heltec_rc32_without_display_companion_radio_full" },
{ 0x112d34c4, "heltec_rc32_without_display_companion_radio_usb" },
{ 0xf10a26df, "heltec_rc32_without_display_companion_radio_wifi" },
{ 0xc5409ced, "heltec_rc32_without_display_repeater" },
@@ -120,6 +122,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xa3e8d8ce, "heltec_tracker_v1_1_room_server_observer_mqtt" },
{ 0xb16009a0, "heltec_tracker_v2_companion_radio_ble_femoff" },
{ 0xdc780e80, "heltec_tracker_v2_companion_radio_ble_femon" },
{ 0x28b8007c, "heltec_tracker_v2_companion_radio_full_femon" },
{ 0x4aa63180, "heltec_tracker_v2_companion_radio_usb_femoff" },
{ 0x6fddcbf1, "heltec_tracker_v2_companion_radio_usb_femon" },
{ 0xf4fb5484, "heltec_tracker_v2_companion_radio_wifi_femoff" },
@@ -155,13 +158,16 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xceeddfaf, "Heltec_v3_room_server_observer_mqtt" },
{ 0x21519537, "Heltec_v3_sensor" },
{ 0x382bb181, "Heltec_v3_terminal_chat" },
{ 0xad1bcd63, "heltec_v4_2_v4_3_companion_radio_full_femon" },
{ 0x5a2980e6, "heltec_v4_3_companion_radio_ble_femoff" },
{ 0x90581c83, "heltec_v4_3_companion_radio_ble_ps_femoff" },
{ 0x90a6a854, "heltec_v4_3_companion_radio_full_femoff" },
{ 0x356df17c, "heltec_v4_3_companion_radio_usb_femoff" },
{ 0x99a084fc, "heltec_v4_3_companion_radio_wifi_femoff" },
{ 0x64c9dfc9, "heltec_v4_3_companion_radio_wifi_mqtt_femoff" },
{ 0x2a2ffc92, "heltec_v4_3_expansionkit_tft_companion_radio_ble_femoff" },
{ 0x2c13b8e9, "heltec_v4_3_tft_companion_radio_ble_femoff" },
{ 0x1ee7d867, "heltec_v4_3_tft_companion_radio_full_femoff" },
{ 0xb016979a, "heltec_v4_3_tft_companion_radio_usb_femoff" },
{ 0xb49b6b55, "heltec_v4_3_tft_companion_radio_wifi_femoff" },
{ 0x01d8f124, "heltec_v4_companion_radio_ble" },
@@ -181,6 +187,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xf75feb3e, "heltec_v4_kiss_modem" },
{ 0xbc9cdc70, "heltec_v4_r8_companion_radio_ble" },
{ 0x19e31fc6, "heltec_v4_r8_companion_radio_ble_ps" },
{ 0xa01b330e, "heltec_v4_r8_companion_radio_full" },
{ 0x36c78d86, "heltec_v4_r8_companion_radio_usb" },
{ 0xdf722326, "heltec_v4_r8_companion_radio_wifi" },
{ 0xfa901c87, "heltec_v4_r8_kiss_modem" },
@@ -189,6 +196,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xb4cb035a, "heltec_v4_r8_sensor" },
{ 0xbb429dde, "heltec_v4_r8_terminal_chat" },
{ 0x883e3edc, "heltec_v4_r8_tft_companion_radio_ble" },
{ 0x4a9d1c6c, "heltec_v4_r8_tft_companion_radio_full" },
{ 0xa0965a6b, "heltec_v4_r8_tft_companion_radio_usb" },
{ 0x59ea25fa, "heltec_v4_r8_tft_companion_radio_wifi" },
{ 0x1758bdb9, "heltec_v4_r8_tft_kiss_modem" },
@@ -204,6 +212,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x0b6847ed, "heltec_v4_sensor" },
{ 0xab3e1ad3, "heltec_v4_terminal_chat" },
{ 0x04a8b763, "heltec_v4_tft_companion_radio_ble_femon" },
{ 0xc456437e, "heltec_v4_tft_companion_radio_full_femon" },
{ 0xb3ecafca, "heltec_v4_tft_companion_radio_usb_femon" },
{ 0xf3afcde6, "heltec_v4_tft_companion_radio_wifi_femon" },
{ 0x87513d56, "heltec_v4_tft_repeater" },
@@ -311,6 +320,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x07907102, "LilyGo_T_Impulse_Plus_repeater" },
{ 0x3898ea56, "LilyGo_TBeam_1W_companion_radio_ble" },
{ 0x2fb7e218, "LilyGo_TBeam_1W_companion_radio_ble_ps" },
{ 0x8c61d4c8, "LilyGo_TBeam_1W_companion_radio_full" },
{ 0x4f722e70, "LilyGo_TBeam_1W_companion_radio_usb" },
{ 0x694eed25, "LilyGo_TBeam_1W_companion_radio_wifi" },
{ 0x85b8b9d7, "LilyGo_TBeam_1W_kiss_modem" },
@@ -364,6 +374,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xd45277ff, "Meshimi_companion_radio_ble_" },
{ 0x2cad9a9d, "Meshimi_repeater_" },
{ 0x02a4a8c1, "meshnology_w12_companion_radio_ble" },
{ 0x4a709348, "meshnology_w12_companion_radio_full" },
{ 0x35d960bd, "meshnology_w12_companion_radio_usb" },
{ 0x62977023, "meshnology_w12_companion_radio_wifi" },
{ 0x17a7ed8c, "meshnology_w12_kiss_modem" },
@@ -376,6 +387,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x11b131e7, "Minewsemi_me25ls01_repeater_lora_ota_no_external_sensors" },
{ 0xf8259880, "Nano_G2_Ultra_repeater" },
{ 0x063f1f00, "nibble_screen_connect_companion_radio_ble_" },
{ 0x70d71f92, "nibble_screen_connect_companion_radio_full_" },
{ 0xa8a79da5, "nibble_screen_connect_companion_radio_usb_" },
{ 0xc0d3815b, "nibble_screen_connect_companion_radio_wifi_" },
{ 0x966ac88e, "nibble_screen_connect_kiss_modem_" },
@@ -384,6 +396,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xc42cc90d, "nibble_screen_connect_room_server_" },
{ 0xc24791c3, "nibble_screen_connect_terminal_chat_" },
{ 0x15e11067, "nibble_zero_connect_companion_radio_ble_" },
{ 0x2dbb2669, "nibble_zero_connect_companion_radio_full_" },
{ 0x90799c32, "nibble_zero_connect_companion_radio_usb_" },
{ 0x881a6a48, "nibble_zero_connect_companion_radio_wifi_" },
{ 0xf26af51c, "nibble_zero_connect_repeater_" },
@@ -408,6 +421,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x4d0b1601, "R1Neo_sensor" },
{ 0xab2ac09e, "R1Neo_terminal_chat" },
{ 0xa17fc4f7, "RAK_3112_companion_radio_ble" },
{ 0xe4b2bd22, "RAK_3112_companion_radio_full" },
{ 0x90c4eb3f, "RAK_3112_companion_radio_usb" },
{ 0x19d9ce91, "RAK_3112_companion_radio_wifi" },
{ 0x121cc72f, "RAK_3112_kiss_modem" },
@@ -438,6 +452,8 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x51fa1a49, "RAK_WisMesh_Tag_sensor" },
{ 0xdb73638b, "SenseCap_Solar_repeater" },
{ 0xd904c2d5, "SenseCapIndicator-ESPNow_comp_radio_usb" },
{ 0x620569f4, "SenseCapIndicator-LoRa_comp_radio_usb" },
{ 0x08483f6b, "SenseCapIndicator-LoRa_comp_radio_usb_wifi" },
{ 0x0db48f35, "solarxiao_30S_companion_radio_ble" },
{ 0x20532f6c, "solarxiao_30S_companion_radio_usb" },
{ 0x293ced32, "solarxiao_30S_kiss_modem" },
@@ -455,6 +471,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xf2128c81, "Station_G2_repeater" },
{ 0x1b34e7b4, "Station_G2_repeater_bridge_espnow" },
{ 0x8e549407, "Station_G3_ESP32_companion_radio_ble" },
{ 0x6ca142f4, "Station_G3_ESP32_companion_radio_full" },
{ 0x1deac038, "Station_G3_ESP32_companion_radio_usb" },
{ 0x2a2f303b, "Station_G3_ESP32_companion_radio_wifi" },
{ 0x0ba4453d, "Station_G3_ESP32_kiss_modem" },
@@ -584,6 +601,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x60f5fdc2, "Xiao_S3_sensor" },
{ 0xe8f79d22, "Xiao_S3_WIO_companion_radio_ble" },
{ 0xb97bbb15, "Xiao_S3_WIO_companion_radio_ble_ps" },
{ 0xd466590c, "Xiao_S3_WIO_companion_radio_full" },
{ 0x9f27be15, "Xiao_S3_WIO_companion_radio_serial" },
{ 0x396fecc7, "Xiao_S3_WIO_companion_radio_usb" },
{ 0xf94e3407, "Xiao_S3_WIO_companion_radio_wifi" },
+29 -19
View File
@@ -62,6 +62,7 @@ void RadioLibWrapper::begin() {
}
_noise_floor = 0;
_noise_floor_centi_dbm = 0;
_noise_floor_valid = false;
_threshold = 0;
_cad_enabled = false;
@@ -71,7 +72,7 @@ void RadioLibWrapper::begin() {
// start average out some samples
_num_floor_samples = 0;
_floor_sample_sum = 0;
_floor_sample_sum_centi_dbm = 0;
_nf_calib_active = false;
_nf_last_calib = 0;
_nf_sample_from = 0;
@@ -232,7 +233,7 @@ void RadioLibWrapper::recalibrateNoiseFloor() {
_nf_refresh_requested = true;
_nf_last_calib = 0;
_num_floor_samples = 0;
_floor_sample_sum = 0;
_floor_sample_sum_centi_dbm = 0;
const unsigned long now = millis();
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
@@ -251,7 +252,7 @@ void RadioLibWrapper::requestNoiseFloorRefresh() {
if (_nf_refresh_requested) return;
_nf_refresh_requested = true;
_num_floor_samples = 0;
_floor_sample_sum = 0;
_floor_sample_sum_centi_dbm = 0;
_nf_calib_deadline = 0; // starts when continuous RX is actually available
}
@@ -425,7 +426,7 @@ void RadioLibWrapper::noiseFloorCalibCheck(unsigned long now) {
_nf_calib_deadline = now + NF_CALIB_TIMEOUT_MS;
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
_num_floor_samples = 0; // start a fresh batch for this window
_floor_sample_sum = 0;
_floor_sample_sum_centi_dbm = 0;
if (!isPacketPendingOrReceiving()) {
requestRestartRecv(); // startReceiveMode() selects continuous RX
}
@@ -463,22 +464,29 @@ void RadioLibWrapper::loop() {
_nf_calib_deadline = now + NF_CONTINUOUS_TIMEOUT_MS;
}
if (_nf_refresh_requested && _num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES
&& _floor_sample_sum != 0) {
int16_t sampled_floor = _floor_sample_sum / NUM_NOISE_FLOOR_SAMPLES;
if (sampled_floor < -120) {
sampled_floor = -120; // clamp to lower bound of -120dBi
&& _floor_sample_sum_centi_dbm != 0) {
int32_t sampled_floor_centi_dbm =
_floor_sample_sum_centi_dbm / NUM_NOISE_FLOOR_SAMPLES;
if (sampled_floor_centi_dbm < -12000) {
sampled_floor_centi_dbm = -12000;
}
if (_noise_floor_valid) {
// Favor the fresh high-rate batch while retaining a small amount of
// history: 25% previous floor + 75% newly sampled floor. Round the
// negative dBm result to the nearest integer instead of toward zero.
int32_t weighted_floor = (int32_t)_noise_floor + 3L * sampled_floor;
_noise_floor = weighted_floor < 0 ? (weighted_floor - 2) / 4
: (weighted_floor + 2) / 4;
// history: 25% previous floor + 75% newly sampled floor.
int32_t weighted_floor = _noise_floor_centi_dbm
+ 3L * sampled_floor_centi_dbm;
_noise_floor_centi_dbm = weighted_floor < 0
? (weighted_floor - 2) / 4
: (weighted_floor + 2) / 4;
} else {
_noise_floor = sampled_floor;
_noise_floor_centi_dbm = sampled_floor_centi_dbm;
}
_floor_sample_sum = 0;
// Preserve the existing whole-dB API and wire formats while exposing the
// fractional 64-sample mean to local displays.
_noise_floor = _noise_floor_centi_dbm < 0
? (_noise_floor_centi_dbm - 50) / 100
: (_noise_floor_centi_dbm + 50) / 100;
_floor_sample_sum_centi_dbm = 0;
_noise_floor_valid = true;
_nf_refresh_requested = false;
_nf_last_calib = now;
@@ -503,7 +511,7 @@ void RadioLibWrapper::loop() {
_nf_last_calib = now;
_nf_calib_deadline = 0;
_num_floor_samples = 0;
_floor_sample_sum = 0;
_floor_sample_sum_centi_dbm = 0;
}
if (_nf_refresh_requested && state == STATE_RX
@@ -516,13 +524,15 @@ void RadioLibWrapper::loop() {
if (!_rx_ps_armed
&& !(_nf_sample_from != 0 && (long)(now - _nf_sample_from) < 0)
&& !isReceivingPacket()) {
int rssi = getCurrentRSSI();
if (!_noise_floor_valid || rssi < _noise_floor + SAMPLING_THRESHOLD) {
float rssi = getCurrentRSSI();
if (!_noise_floor_valid
|| rssi < getNoiseFloorDbm() + SAMPLING_THRESHOLD) {
// With no valid baseline (startup, AGC reset, or gain change), seed
// unconditionally. Otherwise reject likely traffic above the current
// floor plus the sampling margin.
_num_floor_samples++;
_floor_sample_sum += rssi;
_floor_sample_sum_centi_dbm +=
static_cast<int32_t>(rssi * 100.0f);
}
}
}
+5 -1
View File
@@ -30,12 +30,13 @@ protected:
mesh::MainBoard* _board;
uint32_t n_recv, n_sent, n_recv_errors;
int16_t _noise_floor, _threshold;
int32_t _noise_floor_centi_dbm;
float _last_rssi, _last_snr;
bool _cad_enabled;
bool _noise_floor_valid;
bool _nf_refresh_requested;
uint16_t _num_floor_samples;
int32_t _floor_sample_sum;
int32_t _floor_sample_sum_centi_dbm;
unsigned long last_recv_millis;
unsigned long last_radio_interrupt_millis; // updated on any ISR event, even CRC errors
bool _rx_ps_enabled;
@@ -203,6 +204,9 @@ public:
virtual int16_t performChannelScan();
int getNoiseFloor() const override { return _noise_floor; }
float getNoiseFloorDbm() const override {
return _noise_floor_centi_dbm / 100.0f;
}
void triggerNoiseFloorCalibrate(int threshold) override;
void recalibrateNoiseFloor() override;
void setCADEnabled(bool enable) override { _cad_enabled = enable; }
@@ -691,12 +691,17 @@ bool EnvironmentSensorManager::begin() {
MESH_DEBUG_PRINTLN("Second I2C initialized on pins SDA: %d SCL: %d", ENV_PIN_SDA, ENV_PIN_SCL);
#endif
_active_sensor_count = 0;
// Avoid touching a shared I2C bus when no environmental drivers were built.
if (SENSOR_TABLE_SIZE == 0) {
return true;
}
// Scan the I2C bus before touching any sensor library.
bool detected[128] = {};
scanI2CBus(TELEM_WIRE, detected);
// Walk the sensor table and initialize only detected devices.
_active_sensor_count = 0;
for (size_t i = 0; i < SENSOR_TABLE_SIZE && _active_sensor_count < MAX_ACTIVE_SENSORS; i++) {
const SensorDef& def = SENSOR_TABLE[i];
// One static driver instance per type: an alternate address is a fallback, not a second device.
+123
View File
@@ -0,0 +1,123 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
namespace ui {
class ColorEmojiAtlas {
static constexpr size_t FOOTER_SIZE = 40;
static constexpr size_t ATLAS_HEADER_SIZE = 12;
static constexpr uint16_t FIRST_EMOJI = 0xE000;
const uint8_t* _pixels = nullptr;
uint16_t _count = 0;
uint16_t _stride = 0;
uint8_t _width = 0;
uint8_t _height = 0;
uint8_t _transparent = 0;
uint8_t _text_scale = 1;
static uint16_t read16(const uint8_t* p) {
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
}
static uint32_t read32(const uint8_t* p) {
return (uint32_t)p[0]
| ((uint32_t)p[1] << 8)
| ((uint32_t)p[2] << 16)
| ((uint32_t)p[3] << 24);
}
static uint32_t crc32(const uint8_t* data, size_t size) {
uint32_t crc = 0xFFFFFFFFUL;
for (size_t i = 0; i < size; ++i) {
crc ^= data[i];
for (uint8_t bit = 0; bit < 8; ++bit) {
crc = (crc >> 1) ^ (0xEDB88320UL & (0U - (crc & 1U)));
}
}
return ~crc;
}
public:
void reset() {
_pixels = nullptr;
_count = 0;
_stride = 0;
_width = 0;
_height = 0;
_transparent = 0;
_text_scale = 1;
}
bool begin(const uint8_t* font_data, size_t font_size) {
reset();
if (font_data == nullptr || font_size < FOOTER_SIZE) return false;
const uint8_t* footer = font_data + font_size - FOOTER_SIZE;
static const uint8_t FOOTER_MAGIC[8] = {
'M', 'C', 'E', 'M', 'A', 'P', '2', 0
};
if (memcmp(footer, FOOTER_MAGIC, sizeof(FOOTER_MAGIC)) != 0) {
return false;
}
uint32_t atlas_offset = read32(footer + 20);
uint32_t atlas_size = read32(footer + 24);
uint32_t atlas_crc = read32(footer + 28);
if (atlas_offset > font_size - FOOTER_SIZE
|| atlas_size > font_size - FOOTER_SIZE - atlas_offset
|| atlas_size < ATLAS_HEADER_SIZE) {
return false;
}
const uint8_t* atlas = font_data + atlas_offset;
if (crc32(atlas, atlas_size) != atlas_crc
|| memcmp(atlas, "CE01", 4) != 0) {
return false;
}
uint16_t count = read16(atlas + 4);
uint8_t width = atlas[6];
uint8_t height = atlas[7];
uint8_t transparent = atlas[8];
uint8_t text_scale = atlas[9];
uint16_t stride = read16(atlas + 10);
if (count == 0 || width == 0 || height == 0
|| width > 64 || height > 64
|| text_scale == 0 || text_scale > 8
|| stride != (uint16_t)width * height
|| (size_t)count * stride != atlas_size - ATLAS_HEADER_SIZE) {
return false;
}
_pixels = atlas + ATLAS_HEADER_SIZE;
_count = count;
_stride = stride;
_width = width;
_height = height;
_transparent = transparent;
_text_scale = text_scale;
return true;
}
bool isReady() const { return _pixels != nullptr; }
uint8_t width() const { return _width; }
uint8_t height() const { return _height; }
uint8_t transparent() const { return _transparent; }
uint8_t textScale() const { return _text_scale; }
uint16_t count() const { return _count; }
const uint8_t* glyph(uint16_t mapped_codepoint) const {
if (!isReady() || mapped_codepoint < FIRST_EMOJI) return nullptr;
uint16_t index = mapped_codepoint - FIRST_EMOJI;
if (index >= _count) return nullptr;
return _pixels + (size_t)index * _stride;
}
};
} // namespace ui
} // namespace mesh
+32 -5
View File
@@ -15,6 +15,14 @@ class DisplayDriver {
int _w, _h;
protected:
DisplayDriver(int w, int h) { _w = w; _h = h; }
static size_t trimLastUTF8Codepoint(char* str, size_t length) {
if (length == 0) return 0;
size_t start = length - 1;
while (start > 0 && ((uint8_t)str[start] & 0xC0) == 0x80) --start;
str[start] = 0;
return start;
}
public:
//enum Color { DARK=0, LIGHT, RED, GREEN, BLUE, YELLOW, ORANGE }; // on b/w screen, colors will be !=0 synonym of light
@@ -37,6 +45,11 @@ public:
virtual void drawRect(int x, int y, int w, int h) = 0;
virtual void drawXbm(int x, int y, const uint8_t* bits, int w, int h) = 0;
virtual uint16_t getTextWidth(const char* str) = 0;
virtual bool getTouch(int* x, int* y) {
(void)x;
(void)y;
return false;
}
virtual void drawTextCentered(int mid_x, int y, const char* str) { // helper method (override to optimise)
int w = getTextWidth(str);
setCursor(mid_x - w/2, y);
@@ -72,9 +85,16 @@ public:
virtual void drawTextEllipsized(int x, int y, int max_width, const char* str) {
char temp_str[256]; // reasonable buffer size
size_t len = strlen(str);
if (len >= sizeof(temp_str)) len = sizeof(temp_str) - 1;
if (len >= sizeof(temp_str)) {
len = sizeof(temp_str) - 1;
// If the fixed buffer cuts through a UTF-8 sequence, omit that whole
// codepoint instead of passing malformed text to the display driver.
while (len > 0 && ((uint8_t)str[len] & 0xC0) == 0x80) --len;
}
memcpy(temp_str, str, len);
temp_str[len] = 0;
if (max_width <= 0) return;
if (getTextWidth(temp_str) <= max_width) {
setCursor(x, y);
@@ -95,12 +115,19 @@ public:
}
int ellipsis_width = getTextWidth(ellipsis);
int str_len = strlen(temp_str);
size_t ellipsis_len = strlen(ellipsis);
size_t str_len = strlen(temp_str);
while (str_len > 0 && getTextWidth(temp_str) > max_width - ellipsis_width) {
temp_str[--str_len] = 0;
while (str_len > 0
&& (getTextWidth(temp_str) > max_width - ellipsis_width
|| str_len + ellipsis_len >= sizeof(temp_str))) {
str_len = trimLastUTF8Codepoint(temp_str, str_len);
}
if (ellipsis_width <= max_width) {
memcpy(temp_str + str_len, ellipsis, ellipsis_len + 1);
} else {
temp_str[0] = 0;
}
strcat(temp_str, ellipsis);
setCursor(x, y);
print(temp_str);
+178
View File
@@ -0,0 +1,178 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
namespace ui {
class EmojiFontMap {
static constexpr size_t MAP_HEADER_SIZE = 12;
static constexpr size_t NODE_SIZE = 6;
static constexpr size_t EDGE_SIZE = 3;
static constexpr size_t FOOTER_V1_SIZE = 24;
static constexpr size_t FOOTER_V2_SIZE = 40;
const uint8_t* _nodes = nullptr;
const uint8_t* _edges = nullptr;
uint16_t _node_count = 0;
uint16_t _edge_count = 0;
static uint16_t read16(const uint8_t* p) {
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
}
static uint32_t read32(const uint8_t* p) {
return (uint32_t)p[0]
| ((uint32_t)p[1] << 8)
| ((uint32_t)p[2] << 16)
| ((uint32_t)p[3] << 24);
}
static uint32_t crc32(const uint8_t* data, size_t size) {
uint32_t crc = 0xFFFFFFFFUL;
for (size_t i = 0; i < size; ++i) {
crc ^= data[i];
for (uint8_t bit = 0; bit < 8; ++bit) {
crc = (crc >> 1) ^ (0xEDB88320UL & (0U - (crc & 1U)));
}
}
return ~crc;
}
const uint8_t* node(uint16_t index) const {
return _nodes + (size_t)index * NODE_SIZE;
}
const uint8_t* edge(uint16_t index) const {
return _edges + (size_t)index * EDGE_SIZE;
}
bool findChild(uint16_t node_index, uint8_t value,
uint16_t& child) const {
const uint8_t* current = node(node_index);
uint16_t first = read16(current);
uint16_t count = read16(current + 2);
uint16_t low = 0;
uint16_t high = count;
while (low < high) {
uint16_t middle = low + (high - low) / 2;
const uint8_t* candidate = edge(first + middle);
if (candidate[0] < value) {
low = middle + 1;
} else {
high = middle;
}
}
if (low >= count) return false;
const uint8_t* match = edge(first + low);
if (match[0] != value) return false;
child = read16(match + 1);
return child < _node_count;
}
public:
void reset() {
_nodes = nullptr;
_edges = nullptr;
_node_count = 0;
_edge_count = 0;
}
bool begin(const uint8_t* font_data, size_t font_size) {
reset();
if (font_data == nullptr || font_size < FOOTER_V1_SIZE) return false;
static const uint8_t FOOTER_V1_MAGIC[8] = {
'M', 'C', 'E', 'M', 'A', 'P', '1', 0
};
static const uint8_t FOOTER_V2_MAGIC[8] = {
'M', 'C', 'E', 'M', 'A', 'P', '2', 0
};
size_t footer_size = FOOTER_V1_SIZE;
const uint8_t* footer = font_data + font_size - footer_size;
if (font_size >= FOOTER_V2_SIZE
&& memcmp(font_data + font_size - FOOTER_V2_SIZE,
FOOTER_V2_MAGIC, sizeof(FOOTER_V2_MAGIC)) == 0) {
footer_size = FOOTER_V2_SIZE;
footer = font_data + font_size - footer_size;
} else if (memcmp(footer, FOOTER_V1_MAGIC,
sizeof(FOOTER_V1_MAGIC)) != 0) {
return false;
}
uint32_t map_offset = read32(footer + 8);
uint32_t map_size = read32(footer + 12);
uint32_t map_crc = read32(footer + 16);
if (map_offset > font_size - footer_size
|| map_size > font_size - footer_size - map_offset
|| map_size < MAP_HEADER_SIZE) {
return false;
}
const uint8_t* map = font_data + map_offset;
if (crc32(map, map_size) != map_crc
|| memcmp(map, "EM01", 4) != 0) {
return false;
}
uint16_t node_count = read16(map + 4);
uint16_t edge_count = read16(map + 6);
size_t expected_size = MAP_HEADER_SIZE
+ (size_t)node_count * NODE_SIZE
+ (size_t)edge_count * EDGE_SIZE;
if (node_count == 0 || expected_size != map_size) return false;
const uint8_t* nodes = map + MAP_HEADER_SIZE;
const uint8_t* edges = nodes + (size_t)node_count * NODE_SIZE;
for (uint16_t i = 0; i < node_count; ++i) {
const uint8_t* current = nodes + (size_t)i * NODE_SIZE;
uint16_t first = read16(current);
uint16_t count = read16(current + 2);
uint16_t output = read16(current + 4);
if (first > edge_count || count > edge_count - first) return false;
if (output != 0 && (output < 0xE000 || output > 0xF8FF)) return false;
int previous = -1;
for (uint16_t j = 0; j < count; ++j) {
const uint8_t* current_edge = edges + (size_t)(first + j) * EDGE_SIZE;
if (current_edge[0] <= previous
|| read16(current_edge + 1) >= node_count) {
return false;
}
previous = current_edge[0];
}
}
_nodes = nodes;
_edges = edges;
_node_count = node_count;
_edge_count = edge_count;
return true;
}
bool isReady() const { return _nodes != nullptr; }
size_t longestMatch(const uint8_t* text, size_t length,
uint16_t& mapped_codepoint) const {
mapped_codepoint = 0;
if (!isReady() || text == nullptr || length == 0) return 0;
uint16_t node_index = 0;
size_t best_length = 0;
for (size_t i = 0; i < length; ++i) {
uint16_t child;
if (!findChild(node_index, text[i], child)) break;
node_index = child;
uint16_t output = read16(node(node_index) + 4);
if (output != 0) {
mapped_codepoint = output;
best_length = i + 1;
}
}
return best_length;
}
};
} // namespace ui
} // namespace mesh
+511 -30
View File
@@ -1,5 +1,108 @@
#include "LGFXDisplay.h"
#ifndef DISPLAY_ROTATION
#define DISPLAY_ROTATION 1
#endif
#ifndef DISPLAY_BRIGHTNESS
#define DISPLAY_BRIGHTNESS 64
#endif
namespace {
uint32_t readBigEndian32(const uint8_t* data) {
return ((uint32_t)data[0] << 24)
| ((uint32_t)data[1] << 16)
| ((uint32_t)data[2] << 8)
| (uint32_t)data[3];
}
uint32_t readLittleEndian32(const uint8_t* data) {
return (uint32_t)data[0]
| ((uint32_t)data[1] << 8)
| ((uint32_t)data[2] << 16)
| ((uint32_t)data[3] << 24);
}
bool validateVlw(const uint8_t* data, size_t size) {
static const size_t HEADER_SIZE = 24;
static const size_t RECORD_SIZE = 28;
static const size_t FOOTER_V1_SIZE = 24;
static const size_t FOOTER_V2_SIZE = 40;
static const uint8_t FOOTER_V1_MAGIC[8] = {
'M', 'C', 'E', 'M', 'A', 'P', '1', 0
};
static const uint8_t FOOTER_V2_MAGIC[8] = {
'M', 'C', 'E', 'M', 'A', 'P', '2', 0
};
if (data == nullptr || size < HEADER_SIZE + FOOTER_V1_SIZE) {
return false;
}
size_t footer_size = FOOTER_V1_SIZE;
const uint8_t* footer = data + size - footer_size;
if (size >= HEADER_SIZE + FOOTER_V2_SIZE
&& memcmp(data + size - FOOTER_V2_SIZE, FOOTER_V2_MAGIC,
sizeof(FOOTER_V2_MAGIC)) == 0) {
footer_size = FOOTER_V2_SIZE;
footer = data + size - footer_size;
} else if (memcmp(footer, FOOTER_V1_MAGIC,
sizeof(FOOTER_V1_MAGIC)) != 0) {
return false;
}
uint32_t glyph_count = readBigEndian32(data);
uint32_t map_offset = readLittleEndian32(footer + 8);
if (glyph_count == 0 || glyph_count > 10000
|| map_offset < HEADER_SIZE
|| map_offset > size - footer_size
|| glyph_count > (map_offset - HEADER_SIZE) / RECORD_SIZE) {
return false;
}
size_t bitmap_offset = HEADER_SIZE + (size_t)glyph_count * RECORD_SIZE;
uint32_t previous_codepoint = 0;
for (uint32_t i = 0; i < glyph_count; ++i) {
const uint8_t* record = data + HEADER_SIZE + (size_t)i * RECORD_SIZE;
uint32_t codepoint = readBigEndian32(record);
uint32_t height = readBigEndian32(record + 4);
uint32_t width = readBigEndian32(record + 8);
uint32_t advance = readBigEndian32(record + 12);
if ((i != 0 && codepoint <= previous_codepoint)
|| codepoint > 0xFFFF
|| width > 64
|| height > 64
|| advance > 64
|| width > SIZE_MAX / (height == 0 ? 1 : height)
|| bitmap_offset > map_offset
|| width * height > map_offset - bitmap_offset) {
return false;
}
previous_codepoint = codepoint;
bitmap_offset += width * height;
}
return bitmap_offset == map_offset;
}
LGFXDisplay* activeEmojiDisplay = nullptr;
static const uint32_t UI_PALETTE[16] = {
0x000000, 0xFFFFFF, 0x0000FF, 0x929292,
0xFFAA00, 0x00FFFF, 0x0000D6, 0xE53935,
0x43A047, 0x1E88E5, 0x8E24AA, 0xFDD835,
0x6D4C41, 0x00ACC1, 0xF06292, 0xFF00FF,
};
static constexpr uint8_t TRANSPARENT_EMOJI_PALETTE_INDEX = 15;
static constexpr uint32_t TRANSPARENT_EMOJI_COLOR = 0xFF00FF;
bool isSequence(const uint8_t* text, size_t remaining,
const uint8_t* sequence, size_t sequence_size) {
return remaining >= sequence_size
&& memcmp(text, sequence, sequence_size) == 0;
}
} // namespace
// Color scheme
ColorVal UIColor::window_bkg = 0xFFFF;
ColorVal UIColor::title_bkg = 0x001F;
@@ -12,31 +115,44 @@ ColorVal UIColor::popup_txt = 0x0000;
ColorVal UIColor::corp_blue = 0x001A;
bool LGFXDisplay::begin() {
turnOn();
display->init();
display->setRotation(1);
display->setBrightness(64);
if (!display->init()) return false;
_isOn = true;
display->setRotation(DISPLAY_ROTATION);
display->setBrightness(DISPLAY_BRIGHTNESS);
display->setColorDepth(8);
display->setTextColor(TFT_WHITE);
buffer.setColorDepth(8);
buffer.setPsram(true);
buffer.createSprite(width(), height());
buffer.setColorDepth(UI_BUFFER_COLOR_DEPTH);
// The RGB scanout framebuffer must live in PSRAM. Keep this much smaller
// logical UI sprite in internal DMA-capable RAM so page redraws do not
// compete with scanout and permanently shift the panel after an underflow.
buffer.setPsram(false);
if (buffer.createSprite(width() * UI_COORD_SCALE,
height() * UI_COORD_SCALE) == nullptr) {
return false;
}
configurePalette();
return true;
}
void LGFXDisplay::turnOn() {
// display->wakeup();
if (!_isOn) {
display->wakeup();
// Keep the panel initialized while blanked so touch remains available as
// a wake source. Restoring brightness is sufficient for RGB panels.
display->setBrightness(DISPLAY_BRIGHTNESS);
#ifdef HAS_TOUCH
if (display->touch() != nullptr) display->touch()->wakeup();
#endif
}
_isOn = true;
}
void LGFXDisplay::turnOff() {
if (_isOn) {
display->sleep();
// Do not use LGFX sleep here: a sleeping touch controller cannot provide
// the event that wakes a touch-capable UI. Blank only the backlight.
display->setBrightness(0);
}
_isOn = false;
}
@@ -44,68 +160,433 @@ void LGFXDisplay::turnOff() {
void LGFXDisplay::clear() {
// display->clearDisplay();
buffer.clearDisplay();
_presentedEmojiOverlayCount = 0;
_hasLastFrame = false;
}
void LGFXDisplay::startFrame(ColorVal bkg) {
// display->startWrite();
// display->getScanLine();
_color = bkg;
_emojiOverlayCount = 0;
_hasTransparentEmojiPixels = false;
_color = renderColor(bkg);
buffer.setBaseColor(_color);
buffer.fillScreen(_color);
buffer.setTextColor(_color = UIColor::primary_txt);
setColor(UIColor::primary_txt);
}
void LGFXDisplay::setTextSize(int sz) {
buffer.setTextSize(sz);
int scaled = (sz * UI_COORD_SCALE + _fontNativeScale / 2)
/ _fontNativeScale;
if (scaled < 1) scaled = 1;
buffer.setTextSize(scaled);
}
void LGFXDisplay::setColor(ColorVal c) {
buffer.setTextColor(_color = c);
_color = renderColor(c);
// Every frame starts from a freshly cleared canvas, so transparent glyph
// backgrounds are both sufficient and unambiguous. In particular,
// primary_txt and popup_txt are both black and cannot be distinguished by
// their RGB565 value alone.
buffer.setTextColor(_color);
}
void LGFXDisplay::setCursor(int x, int y) {
buffer.setCursor(x, y);
buffer.setCursor(x * UI_COORD_SCALE, y * UI_COORD_SCALE);
}
void LGFXDisplay::print(const char* str) {
buffer.println(str);
String mapped = mapText(str);
buffer.println(mapped.c_str());
// Serial.println(str);
}
void LGFXDisplay::fillRect(int x, int y, int w, int h) {
buffer.fillRect(x, y, w, h, _color);
buffer.fillRect(x * UI_COORD_SCALE, y * UI_COORD_SCALE,
w * UI_COORD_SCALE, h * UI_COORD_SCALE, _color);
}
void LGFXDisplay::drawRect(int x, int y, int w, int h) {
buffer.drawRect(x, y, w, h, _color);
if (w <= 0 || h <= 0) return;
if (UI_COORD_SCALE == 1) {
buffer.drawRect(x, y, w, h, _color);
return;
}
int left = x * UI_COORD_SCALE;
int top = y * UI_COORD_SCALE;
int scaled_width = w * UI_COORD_SCALE;
int scaled_height = h * UI_COORD_SCALE;
buffer.fillRect(left, top, scaled_width, UI_COORD_SCALE, _color);
buffer.fillRect(left, top + scaled_height - UI_COORD_SCALE,
scaled_width, UI_COORD_SCALE, _color);
buffer.fillRect(left, top, UI_COORD_SCALE, scaled_height, _color);
buffer.fillRect(left + scaled_width - UI_COORD_SCALE, top,
UI_COORD_SCALE, scaled_height, _color);
}
void LGFXDisplay::drawXbm(int x, int y, const uint8_t* bits, int w, int h) {
buffer.drawBitmap(x, y, bits, w, h, _color);
if (UI_COORD_SCALE == 1) {
buffer.drawBitmap(x, y, bits, w, h, _color);
return;
}
const int row_bytes = (w + 7) / 8;
for (int row = 0; row < h; ++row) {
int column = 0;
while (column < w) {
while (column < w
&& !(bits[row * row_bytes + column / 8]
& (0x80 >> (column & 7)))) {
++column;
}
int first = column;
while (column < w
&& (bits[row * row_bytes + column / 8]
& (0x80 >> (column & 7)))) {
++column;
}
if (first != column) {
buffer.fillRect((x + first) * UI_COORD_SCALE,
(y + row) * UI_COORD_SCALE,
(column - first) * UI_COORD_SCALE,
UI_COORD_SCALE, _color);
}
}
}
}
uint16_t LGFXDisplay::getTextWidth(const char* str) {
return buffer.textWidth(str);
String mapped = mapText(str);
return (buffer.textWidth(mapped.c_str()) + UI_COORD_SCALE - 1)
/ UI_COORD_SCALE;
}
void LGFXDisplay::translateUTF8ToBlocks(char* dest, const char* src,
size_t dest_size) {
if (!_emojiMap.isReady()) {
DisplayDriver::translateUTF8ToBlocks(dest, src, dest_size);
return;
}
if (dest_size == 0) return;
size_t output = 0;
for (size_t input = 0; src[input] != 0 && output + 1 < dest_size;) {
uint8_t first = (uint8_t)src[input];
size_t length = 1;
if (first >= 0xC2 && first <= 0xDF) {
length = 2;
} else if (first >= 0xE0 && first <= 0xEF) {
length = 3;
} else if (first >= 0xF0 && first <= 0xF4) {
length = 4;
} else if (first < 32 || first > 126) {
++input;
continue;
}
bool valid = true;
for (size_t i = 1; i < length; ++i) {
if (src[input + i] == 0
|| ((uint8_t)src[input + i] & 0xC0) != 0x80) {
valid = false;
break;
}
}
if (!valid || output + length >= dest_size) break;
memcpy(dest + output, src + input, length);
output += length;
input += length;
}
dest[output] = 0;
}
void LGFXDisplay::endFrame() {
uint32_t hash = frameHash();
if (_hasLastFrame && hash == _lastFrameHash) return;
_lastFrameHash = hash;
_hasLastFrame = true;
display->startWrite();
if (UI_ZOOM != 1) {
buffer.pushRotateZoom(display, display->width()/2, display->height()/2 , 0, UI_ZOOM, UI_ZOOM);
if (_hasTransparentEmojiPixels) {
buffer.pushRotateZoom(display, display->width() / 2,
display->height() / 2, 0, UI_ZOOM, UI_ZOOM,
TRANSPARENT_EMOJI_COLOR);
} else {
buffer.pushRotateZoom(display, display->width() / 2,
display->height() / 2, 0, UI_ZOOM, UI_ZOOM);
}
} else {
buffer.pushSprite(display, 0, 0);
if (_hasTransparentEmojiPixels) {
buffer.pushSprite(display, 0, 0, TRANSPARENT_EMOJI_COLOR);
} else {
buffer.pushSprite(display, 0, 0);
}
}
if (_emojiAtlas.isReady()) {
const float source_x = (_emojiAtlas.width() - 1) * 0.5f;
const float source_y = (_emojiAtlas.height() - 1) * 0.5f;
for (size_t i = 0; i < _emojiOverlayCount; ++i) {
const EmojiOverlay& overlay = _emojiOverlays[i];
const uint8_t* pixels = _emojiAtlas.glyph(overlay.codepoint);
if (pixels == nullptr) continue;
float size = overlay.size * UI_ZOOM;
float zoom_x = size / _emojiAtlas.width();
float zoom_y = size / _emojiAtlas.height();
float x = overlay.x * UI_ZOOM + (size - 1) * 0.5f;
float y = overlay.y * UI_ZOOM + (size - 1) * 0.5f;
display->pushImageRotateZoom(
x, y, source_x, source_y, 0, zoom_x, zoom_y,
_emojiAtlas.width(), _emojiAtlas.height(),
reinterpret_cast<const lgfx::rgb332_t*>(pixels),
lgfx::rgb332_t(_emojiAtlas.transparent()));
}
}
display->endWrite();
_presentedEmojiOverlayCount = _emojiOverlayCount;
memcpy(_presentedEmojiOverlays, _emojiOverlays,
_emojiOverlayCount * sizeof(EmojiOverlay));
}
bool LGFXDisplay::getTouch(int *x, int *y) {
lgfx::v1::touch_point_t point;
display->getTouch(&point);
if (UI_ZOOM != 1) {
*x = point.x / UI_ZOOM;
*y = point.y / UI_ZOOM;
bool LGFXDisplay::getTouch(int* x, int* y) {
lgfx::v1::touch_point_t point = {};
if (display->getTouch(&point) == 0) return false;
if (UI_ZOOM * UI_COORD_SCALE != 1) {
*x = point.x / (UI_ZOOM * UI_COORD_SCALE);
*y = point.y / (UI_ZOOM * UI_COORD_SCALE);
} else {
*x = point.x;
*y = point.y;
}
return (*x >= 0) && (*y >= 0);
}
return *x >= 0 && *x < width() && *y >= 0 && *y < height();
}
bool LGFXDisplay::installRuntimeFont(uint8_t* data, size_t size) {
mesh::ui::EmojiFontMap map;
mesh::ui::ColorEmojiAtlas atlas;
if (!validateVlw(data, size)
|| !map.begin(data, size)
|| !buffer.loadFont(data)) {
free(data);
return false;
}
if (_fontData != nullptr) free(_fontData);
_fontData = data;
_fontDataSize = size;
_emojiMap = map;
if (atlas.begin(data, size)) {
_emojiAtlas = atlas;
_fontNativeScale = atlas.textScale();
activeEmojiDisplay = this;
buffer.setEmojiCallback(drawEmoji);
} else {
_emojiAtlas.reset();
_fontNativeScale = 1;
buffer.setEmojiCallback(nullptr);
if (activeEmojiDisplay == this) activeEmojiDisplay = nullptr;
}
return true;
}
uint32_t LGFXDisplay::renderColor(ColorVal color) const {
#if UI_BUFFER_COLOR_DEPTH < 8
if (color == UIColor::primary_txt) return 0;
if (color == UIColor::window_bkg || color == UIColor::title_txt) return 1;
if (color == UIColor::title_bkg) return 2;
if (color == UIColor::secondary_txt) return 3;
if (color == UIColor::warning_txt) return 4;
if (color == UIColor::popup_bkg) return 5;
if (color == UIColor::popup_txt) return 0;
if (color == UIColor::corp_blue) return 6;
return color & 0x0F;
#else
return color;
#endif
}
void LGFXDisplay::configurePalette() {
#if UI_BUFFER_COLOR_DEPTH < 8
buffer.createPalette(UI_PALETTE,
sizeof(UI_PALETTE) / sizeof(UI_PALETTE[0]));
#endif
}
uint32_t LGFXDisplay::frameHash() const {
const uint8_t* data = static_cast<const uint8_t*>(buffer.getBuffer());
size_t length = buffer.bufferLength();
uint32_t hash = 2166136261UL;
for (size_t i = 0; i < length; ++i) {
hash = (hash ^ data[i]) * 16777619UL;
}
for (size_t i = 0; i < _emojiOverlayCount; ++i) {
const EmojiOverlay& overlay = _emojiOverlays[i];
const uint16_t values[] = {
overlay.codepoint,
static_cast<uint16_t>(overlay.x),
static_cast<uint16_t>(overlay.y),
overlay.size,
};
for (uint16_t value : values) {
hash = (hash ^ static_cast<uint8_t>(value)) * 16777619UL;
hash = (hash ^ static_cast<uint8_t>(value >> 8)) * 16777619UL;
}
}
return hash;
}
bool LGFXDisplay::wasEmojiPresented(const EmojiOverlay& overlay) const {
for (size_t i = 0; i < _presentedEmojiOverlayCount; ++i) {
const EmojiOverlay& presented = _presentedEmojiOverlays[i];
if (presented.codepoint == overlay.codepoint
&& presented.x == overlay.x
&& presented.y == overlay.y
&& presented.size == overlay.size) {
return true;
}
}
return false;
}
void LGFXDisplay::drawEmojiMask(int32_t x, int32_t y, int32_t size,
const uint8_t* pixels) {
#if UI_BUFFER_COLOR_DEPTH < 8
if (pixels == nullptr || size <= 0) return;
const int source_width = _emojiAtlas.width();
const int source_height = _emojiAtlas.height();
const uint8_t transparent = _emojiAtlas.transparent();
for (int source_y = 0; source_y < source_height; ++source_y) {
int top = y + source_y * size / source_height;
int bottom = y + (source_y + 1) * size / source_height;
for (int source_x = 0; source_x < source_width; ++source_x) {
if (pixels[source_y * source_width + source_x] == transparent) continue;
int left = x + source_x * size / source_width;
int right = x + (source_x + 1) * size / source_width;
buffer.fillRect(left, top, right - left, bottom - top,
TRANSPARENT_EMOJI_PALETTE_INDEX);
}
}
_hasTransparentEmojiPixels = true;
#else
(void)x;
(void)y;
(void)size;
(void)pixels;
#endif
}
void LGFXDisplay::drawEmojiUnderlay(int32_t x, int32_t y, int32_t size,
const uint8_t* pixels) {
#if UI_BUFFER_COLOR_DEPTH < 8
if (pixels == nullptr || size <= 0) return;
const int source_width = _emojiAtlas.width();
const int source_height = _emojiAtlas.height();
const uint8_t transparent = _emojiAtlas.transparent();
for (int source_y = 0; source_y < source_height; ++source_y) {
int top = y + source_y * size / source_height;
int bottom = y + (source_y + 1) * size / source_height;
for (int source_x = 0; source_x < source_width; ++source_x) {
uint8_t color = pixels[source_y * source_width + source_x];
if (color == transparent) continue;
int red = ((color >> 5) & 7) * 255 / 7;
int green = ((color >> 2) & 7) * 255 / 7;
int blue = (color & 3) * 255 / 3;
int best_index = 0;
uint32_t best_distance = UINT32_MAX;
// The final palette entry is reserved as the transparent color used to
// preserve an unchanged full-color emoji in the panel framebuffer.
for (int index = 0; index < TRANSPARENT_EMOJI_PALETTE_INDEX; ++index) {
int delta_red = red - (int)((UI_PALETTE[index] >> 16) & 0xFF);
int delta_green = green - (int)((UI_PALETTE[index] >> 8) & 0xFF);
int delta_blue = blue - (int)(UI_PALETTE[index] & 0xFF);
uint32_t distance = delta_red * delta_red
+ delta_green * delta_green + delta_blue * delta_blue;
if (distance < best_distance) {
best_distance = distance;
best_index = index;
}
}
int left = x + source_x * size / source_width;
int right = x + (source_x + 1) * size / source_width;
buffer.fillRect(left, top, right - left, bottom - top, best_index);
}
}
#else
(void)x;
(void)y;
(void)size;
(void)pixels;
#endif
}
int32_t LGFXDisplay::queueEmoji(lgfx::v1::LGFXBase* gfx,
int32_t x, int32_t y,
uint32_t codepoint,
int32_t font_height) {
if (gfx != &buffer || codepoint > 0xFFFF || font_height <= 0
|| _emojiAtlas.glyph((uint16_t)codepoint) == nullptr) {
return 0;
}
if (_emojiOverlayCount >= MAX_EMOJI_OVERLAYS) return font_height;
EmojiOverlay& overlay = _emojiOverlays[_emojiOverlayCount++];
overlay.codepoint = (uint16_t)codepoint;
overlay.x = x;
overlay.y = y;
overlay.size = (uint16_t)font_height;
const uint8_t* pixels = _emojiAtlas.glyph(overlay.codepoint);
if (wasEmojiPresented(overlay)) {
// Do not overwrite an unchanged full-color emoji with the indexed canvas
// during periodic message-age redraws. The following direct overlay is
// then idempotent instead of visibly blinking once per second.
drawEmojiMask(x, y, font_height, pixels);
} else {
drawEmojiUnderlay(x, y, font_height, pixels);
}
return font_height;
}
int32_t LGFXDisplay::drawEmoji(lgfx::v1::LGFXBase* gfx,
int32_t x, int32_t y,
uint32_t codepoint,
int32_t font_height) {
if (activeEmojiDisplay == nullptr) return 0;
return activeEmojiDisplay->queueEmoji(gfx, x, y, codepoint, font_height);
}
String LGFXDisplay::mapText(const char* str) const {
if (str == nullptr || !_emojiMap.isReady()) return String(str == nullptr ? "" : str);
const uint8_t* text = (const uint8_t*)str;
size_t length = strlen(str);
String mapped;
mapped.reserve(length + 8);
static const uint8_t VS15[] = {0xEF, 0xB8, 0x8E};
static const uint8_t VS16[] = {0xEF, 0xB8, 0x8F};
static const uint8_t ZWJ[] = {0xE2, 0x80, 0x8D};
for (size_t offset = 0; offset < length;) {
uint16_t codepoint;
size_t match = _emojiMap.longestMatch(text + offset, length - offset, codepoint);
if (match != 0) {
mapped += (char)(0xE0 | (codepoint >> 12));
mapped += (char)(0x80 | ((codepoint >> 6) & 0x3F));
mapped += (char)(0x80 | (codepoint & 0x3F));
offset += match;
continue;
}
if (text[offset] == ' ') {
mapped += (char)0xC2;
mapped += (char)0xA0;
++offset;
continue;
}
if (isSequence(text + offset, length - offset, VS15, sizeof(VS15))
|| isSequence(text + offset, length - offset, VS16, sizeof(VS16))
|| isSequence(text + offset, length - offset, ZWJ, sizeof(ZWJ))) {
offset += 3;
continue;
}
mapped += (char)text[offset++];
}
return mapped;
}
+48 -2
View File
@@ -1,6 +1,8 @@
#pragma once
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/ColorEmojiAtlas.h>
#include <helpers/ui/EmojiFontMap.h>
#define LGFX_USE_V1
#include <LovyanGFX.hpp>
@@ -8,6 +10,12 @@
#ifndef UI_ZOOM
#define UI_ZOOM 1
#endif
#ifndef UI_COORD_SCALE
#define UI_COORD_SCALE 1
#endif
#ifndef UI_BUFFER_COLOR_DEPTH
#define UI_BUFFER_COLOR_DEPTH 8
#endif
class LGFXDisplay : public DisplayDriver {
protected:
@@ -16,10 +24,45 @@ protected:
bool _isOn = false;
int _color = TFT_WHITE;
uint8_t* _fontData = nullptr;
size_t _fontDataSize = 0;
mesh::ui::EmojiFontMap _emojiMap;
mesh::ui::ColorEmojiAtlas _emojiAtlas;
uint8_t _fontNativeScale = 1;
struct EmojiOverlay {
uint16_t codepoint;
int16_t x;
int16_t y;
uint16_t size;
};
static constexpr size_t MAX_EMOJI_OVERLAYS = 64;
EmojiOverlay _emojiOverlays[MAX_EMOJI_OVERLAYS];
size_t _emojiOverlayCount = 0;
EmojiOverlay _presentedEmojiOverlays[MAX_EMOJI_OVERLAYS];
size_t _presentedEmojiOverlayCount = 0;
bool _hasTransparentEmojiPixels = false;
uint32_t _lastFrameHash = 0;
bool _hasLastFrame = false;
String mapText(const char* str) const;
uint32_t renderColor(ColorVal color) const;
void configurePalette();
uint32_t frameHash() const;
bool wasEmojiPresented(const EmojiOverlay& overlay) const;
void drawEmojiMask(int32_t x, int32_t y, int32_t size,
const uint8_t* pixels);
void drawEmojiUnderlay(int32_t x, int32_t y, int32_t size,
const uint8_t* pixels);
int32_t queueEmoji(lgfx::v1::LGFXBase* gfx, int32_t x, int32_t y,
uint32_t codepoint, int32_t font_height);
static int32_t drawEmoji(lgfx::v1::LGFXBase* gfx, int32_t x, int32_t y,
uint32_t codepoint, int32_t font_height);
public:
LGFXDisplay(int w, int h, LGFX_Device &disp)
: DisplayDriver(w/UI_ZOOM, h/UI_ZOOM), display(&disp) {}
: DisplayDriver(w/(UI_ZOOM*UI_COORD_SCALE),
h/(UI_ZOOM*UI_COORD_SCALE)), display(&disp) {}
bool begin();
bool isOn() override { return _isOn; }
void turnOn() override;
@@ -34,6 +77,9 @@ public:
void drawRect(int x, int y, int w, int h) override;
void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override;
uint16_t getTextWidth(const char* str) override;
void translateUTF8ToBlocks(char* dest, const char* src,
size_t dest_size) override;
void endFrame() override;
virtual bool getTouch(int *x, int *y);
bool getTouch(int* x, int* y) override;
bool installRuntimeFont(uint8_t* data, size_t size);
};
+135
View File
@@ -0,0 +1,135 @@
#pragma once
#include <stdint.h>
namespace mesh {
namespace ui {
enum class TouchAction : uint8_t {
None,
Previous,
Next,
Select,
VerticalPrevious,
VerticalNext,
};
// Converts one-finger touch samples into the three actions understood by the
// button-oriented companion UI. An action is emitted only after release so a
// drag cannot activate the page under the user's finger.
class TouchInput {
bool _active = false;
bool _reverse_swipes;
bool _separate_vertical_swipes;
uint8_t _center_zone_percent;
uint8_t _touch_samples = 0;
uint8_t _release_samples = 0;
int _start_x = 0;
int _start_y = 0;
int _last_x = 0;
int _last_y = 0;
static int magnitude(int value) { return value < 0 ? -value : value; }
TouchAction swipeAction(bool negative_direction) const {
const bool next = negative_direction != _reverse_swipes;
return next ? TouchAction::Next : TouchAction::Previous;
}
TouchAction verticalSwipeAction(bool negative_direction) const {
if (!_separate_vertical_swipes) return swipeAction(negative_direction);
const bool next = negative_direction != _reverse_swipes;
return next ? TouchAction::VerticalNext
: TouchAction::VerticalPrevious;
}
public:
explicit TouchInput(bool reverse_swipes = false,
bool separate_vertical_swipes = false,
uint8_t center_zone_percent = 34)
: _reverse_swipes(reverse_swipes),
_separate_vertical_swipes(separate_vertical_swipes),
_center_zone_percent(center_zone_percent > 100
? 100
: center_zone_percent) {}
TouchAction update(bool touched, int x, int y, int width, int height,
bool bottom_selector = false) {
if (touched) {
_release_samples = 0;
if (!_active) {
_active = true;
_start_x = x;
_start_y = y;
_touch_samples = 0;
}
if (_touch_samples != UINT8_MAX) ++_touch_samples;
_last_x = x;
_last_y = y;
return TouchAction::None;
}
if (!_active) return TouchAction::None;
// A moving FT5x06-family controller can briefly report no points between
// two valid samples. Require a stable release so that gap cannot split one
// swipe into a swipe followed by an endpoint tap.
if (++_release_samples < 2) return TouchAction::None;
_active = false;
_release_samples = 0;
// A contact seen only once has no measurable direction. Ignoring it is
// safer than treating the endpoint of a fast swipe as an opposite tap.
if (_touch_samples < 2 || width <= 0 || height <= 0) {
return TouchAction::None;
}
const int dx = _last_x - _start_x;
const int dy = _last_y - _start_y;
const int abs_dx = magnitude(dx);
const int abs_dy = magnitude(dy);
const int horizontal_threshold = width / 8 > 8 ? width / 8 : 8;
const int vertical_threshold = height / 8 > 8 ? height / 8 : 8;
if (abs_dx >= abs_dy && abs_dx >= horizontal_threshold) {
return swipeAction(dx < 0);
}
if (abs_dy > abs_dx && abs_dy >= vertical_threshold) {
return verticalSwipeAction(dy < 0);
}
// Message screens may reserve the otherwise empty ends of their bottom
// status bar as forgiving arrow buttons. Keep the label in the middle
// inert so an imprecise arrow tap cannot accidentally close the screen.
if (bottom_selector && _separate_vertical_swipes
&& _start_y >= (height * 3) / 4) {
if (_start_x < width / 4) {
return TouchAction::VerticalPrevious;
}
if (_start_x >= (width * 3) / 4) {
return TouchAction::VerticalNext;
}
return TouchAction::None;
}
// Taps use three broad zones so every companion action remains available:
// left = previous, center = select, right = next.
// Use the initial position for a tap. If a short swipe falls just below
// the movement threshold, its endpoint may be in the opposite tap zone on
// displays whose touch X axis is inverted.
const int side_percent = (100 - _center_zone_percent) / 2;
const int center_left = (width * side_percent) / 100;
const int center_right = width - center_left;
if (_start_x < center_left) return TouchAction::Previous;
if (_start_x >= center_right) return TouchAction::Next;
return TouchAction::Select;
}
void reset() {
_active = false;
_touch_samples = 0;
_release_samples = 0;
}
};
} // namespace ui
} // namespace mesh