Add automatic red and black night mode for color screens

Default to one hour after sunset through sunrise, using fresh cached GPS or recent direct RF neighbor locations. Provide saved CLI and WebConfig controls with a small integer solar approximation and no additional framebuffer.
This commit is contained in:
mikecarper committed 2026-10-25 14:41:14 -07:00
1 parent 94139c79be
commit fb73e3afac
49 files changed
+4072 -2421

No files matched your search

+3
View File
@@ -108,6 +108,9 @@ class BaseChatMesh : public mesh::Mesh {
int sendContactPacket(const ContactInfo& recipient, mesh::Packet* packet, uint32_t& est_timeout);
protected:
bool isLocalContactImport(const mesh::Packet* packet) const {
return packet == _pendingLoopback;
}
void sendAckTo(const ContactInfo& dest, const uint8_t* ack_hash, uint8_t ack_len=4);
// Autonomous replies have independent ACK tracking and must preserve the
// application/terminal send's shared timeout.
+1
View File
@@ -25,6 +25,7 @@ static const char* const WC_ALLOWED_SET_KEYS[] = {
"repeat",
"display.mode", "display.timeout", "display.usb.mode", "display.usb.timeout",
"display.inbox", "display.rotation",
"display.night", "display.night.delay",
"advert.interval", "flood.advert.interval",
"flood.max", "flood.max.advert", "flood.max.unscoped", "loop.detect",
// MQTTPrefs (WiFi / MQTT / misc observer)
File diff suppressed because it is too large. Load diff
+8
View File
@@ -13,6 +13,7 @@ static_assert(sizeof(WEBCONFIG_AP_PREFIX) <= 28,
#include <ArduinoJson.h>
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/ui/DisplayBuildFlags.h>
#include <helpers/ui/DisplayNightMode.h>
#include <helpers/RegulatorSettings.h>
#include <Preferences.h>
#include <esp_wifi.h>
@@ -2443,6 +2444,13 @@ void WebConfigServer::handleConfigGet(AsyncWebServerRequest* req) {
screen["usb_mode"] = mesh::ui::displayModeName(display_prefs.usb.mode);
screen["usb_timeout"] = display_prefs.usb.seconds;
screen["pairing"] = mesh::ui::displayPairingSupported();
#ifdef MESHCORE_HAS_COLOR_DISPLAY
screen["night_supported"] = true;
const uint8_t night_mode = mesh::ui::displayNightMode();
screen["night"] = night_mode == 0 ? "off" : night_mode == 1 ? "on" : "auto";
screen["night_delay"] = mesh::ui::displayNightDelayMinutes();
screen["night_active"] = mesh::ui::displayNightActive();
#endif
screen["rotation_supported"] = node.display_rotation_supported;
if (node.display_rotation_supported) {
screen["rotation"] = node.display_rotation_degrees;
+22
View File
@@ -1,6 +1,7 @@
#pragma once
#include "DisplayDriver.h"
#include "DisplayNightMode.h"
// Shared default palette for displays that can render real colour. Monochrome
// OLED and e-paper drivers deliberately keep their own black/white palettes:
@@ -35,6 +36,27 @@ constexpr ColorVal ACCENT = rgb565(64, 176, 240);
constexpr ColorVal TOUCH_OUTLINE = rgb565(255, 255, 0);
constexpr ColorVal TOUCH_PRESSED = rgb565(0, 255, 0);
constexpr ColorVal NIGHT_BACKGROUND = 0x0000;
constexpr ColorVal NIGHT_FOREGROUND = 0xF800;
inline bool isBackground(ColorVal color) {
return color == 0 || color == UIColor::window_bkg
|| color == UIColor::title_bkg || color == UIColor::popup_bkg
|| color == WINDOW_BACKGROUND || color == TITLE_BACKGROUND
|| color == POPUP_BACKGROUND;
}
// Leave the saved daytime palette intact, including variant-specific themes.
// Mapping at the drawing boundary also covers raw colors and touch overlays.
inline ColorVal render(ColorVal color) {
return displayNightActive()
? (isBackground(color) ? NIGHT_BACKGROUND : NIGHT_FOREGROUND) : color;
}
inline ColorVal background(ColorVal color) {
return displayNightActive() ? NIGHT_BACKGROUND : color;
}
enum IndexedColor : uint8_t {
INDEX_BACKGROUND = 0,
INDEX_TEXT = 1,
+19
View File
@@ -11,6 +11,13 @@
#define MESHCORE_EINK_DISPLAY_CLASS_GxEPDDisplay 1
#define MESHCORE_EINK_DISPLAY_CLASS_E213Display 1
#define MESHCORE_EINK_DISPLAY_CLASS_E290Display 1
#define MESHCORE_COLOR_DISPLAY_CLASS_ST7735Display 1
#define MESHCORE_COLOR_DISPLAY_CLASS_ST7789Display 1
#define MESHCORE_COLOR_DISPLAY_CLASS_ST7789LCDDisplay 1
#define MESHCORE_COLOR_DISPLAY_CLASS_NV3001BDisplay 1
#define MESHCORE_COLOR_DISPLAY_CLASS_LGFXDisplay 1
#define MESHCORE_COLOR_DISPLAY_CLASS_SCIndicatorDisplay 1
#define MESHCORE_COLOR_DISPLAY_CLASS_WioTrackerL2Display 1
#define MESHCORE_DISPLAY_TOKEN_JOIN_INNER(prefix, name) prefix##name
#define MESHCORE_DISPLAY_TOKEN_JOIN(prefix, name) \
MESHCORE_DISPLAY_TOKEN_JOIN_INNER(prefix, name)
@@ -26,6 +33,11 @@
#define MESHCORE_HAS_EINK_DISPLAY 1
#endif
#if defined(DISPLAY_CLASS) \
&& MESHCORE_DISPLAY_TOKEN_JOIN(MESHCORE_COLOR_DISPLAY_CLASS_, DISPLAY_CLASS)
#define MESHCORE_HAS_COLOR_DISPLAY 1
#endif
// These drivers back physically compact panels where the message-channel
// selector consumes too much of the useful text area. Do not infer this from
// DisplayDriver::height(): the 160x80 ST7735 is still physically compact.
@@ -46,6 +58,13 @@
#undef MESHCORE_DISPLAY_TOKEN_JOIN
#undef MESHCORE_DISPLAY_TOKEN_JOIN_INNER
#undef MESHCORE_COLOR_DISPLAY_CLASS_WioTrackerL2Display
#undef MESHCORE_COLOR_DISPLAY_CLASS_SCIndicatorDisplay
#undef MESHCORE_COLOR_DISPLAY_CLASS_LGFXDisplay
#undef MESHCORE_COLOR_DISPLAY_CLASS_NV3001BDisplay
#undef MESHCORE_COLOR_DISPLAY_CLASS_ST7789LCDDisplay
#undef MESHCORE_COLOR_DISPLAY_CLASS_ST7789Display
#undef MESHCORE_COLOR_DISPLAY_CLASS_ST7735Display
#undef MESHCORE_SMALL_DISPLAY_CLASS_U8g2Display
#undef MESHCORE_SMALL_DISPLAY_CLASS_ST7735Display
#undef MESHCORE_SMALL_DISPLAY_CLASS_SSD1306Display
+6 -1
View File
@@ -1,11 +1,16 @@
#include "DisplayDriver.h"
#include "DisplayNightMode.h"
#include <Arduino.h>
bool DisplayDriver::servicePower(bool usb_power, bool app_connected, bool pairing) {
_power_policy.update(mesh::ui::displayPowerPrefs(), usb_power, app_connected, pairing, millis());
const bool desired = _notification_power < 0 ? _power_policy.on() : _notification_power != 0;
const bool changed = isOn() != desired;
bool changed = isOn() != desired;
if (changed) { if (desired) turnOn(); else turnOff(); }
#ifdef MESHCORE_HAS_COLOR_DISPLAY
const bool night = mesh::ui::displayNightActive();
if (_night_seen != night) { _night_seen = night; changed = true; }
#endif
return changed;
}
+4 -1
View File
@@ -18,6 +18,9 @@ class DisplayDriver {
int _w, _h;
mesh::ui::DisplayPowerPolicy _power_policy;
int8_t _notification_power = -1;
#ifdef MESHCORE_HAS_COLOR_DISPLAY
bool _night_seen = false;
#endif
protected:
DisplayDriver(int w, int h) { _w = w; _h = h; }
void setDimensions(int w, int h) { _w = w; _h = h; }
@@ -55,7 +58,7 @@ public:
virtual void forceFullRefresh() {} // next refresh will be full for eink
virtual void turnOn() = 0;
virtual void turnOff() = 0;
// Returns whether the panel state changed, allowing cached UIs to redraw.
// Returns whether power or palette changed, allowing cached UIs to redraw.
bool servicePower(bool usb_power, bool app_connected = false, bool pairing = false);
bool wake(mesh::ui::DisplayWake reason);
void dismiss();
+50
View File
@@ -0,0 +1,50 @@
#include "DisplayNightLocation.h"
#if defined(MESHCORE_HAS_COLOR_DISPLAY)
#include <Mesh.h>
#include <helpers/AdvertDataHelpers.h>
#include <helpers/SensorManager.h>
#include "DisplayNightMode.h"
namespace mesh {
namespace ui {
namespace {
DisplayNightLocationCache locations;
uint32_t last_refresh_ms = 0;
bool refreshed = false;
}
void observeDisplayNightAdvert(const mesh::Packet* packet,
const mesh::Identity& identity,
const mesh::Identity& self,
const uint8_t* app_data, size_t app_data_len,
uint32_t now_ms) {
if (packet == nullptr || packet->radio_local || packet->forwarded
|| app_data_len > MAX_ADVERT_DATA_SIZE
|| identity.matches(self)
|| packet->getPathHashCount() != 0
|| (packet->hasTransportCodes() && packet->transport_codes[0] == 0
&& packet->transport_codes[1] == 0)) return;
// Each role invokes this from its verified-advert callback, before contact
// admission. Shared or relayed contact data cannot refresh local RF age.
AdvertDataParser advert(app_data, app_data_len);
if (!advert.isValid() || !advert.hasLatLon()) return;
uint32_t prefix;
memcpy(&prefix, identity.pub_key, sizeof(prefix));
locations.observe(prefix, advert.getIntLat(), advert.getIntLon(), now_ms);
}
void refreshDisplayNightLocation(const SensorManager& sensors,
uint32_t utc, uint32_t now_ms) {
if (refreshed && static_cast<uint32_t>(now_ms - last_refresh_ms) < 15000UL) return;
refreshed = true;
last_refresh_ms = now_ms;
int32_t latitude_e6, longitude_e6;
const bool has_location = readDisplayNightLocation(
locations, sensors, now_ms, latitude_e6, longitude_e6);
updateDisplayNightMode(utc, has_location, latitude_e6, longitude_e6);
}
} // namespace ui
} // namespace mesh
#endif
+133
View File
@@ -0,0 +1,133 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <math.h>
#include "DisplayBuildFlags.h"
#if defined(MESHCORE_HAS_COLOR_DISPLAY)
class SensorManager;
namespace mesh {
class Packet;
class Identity;
namespace ui {
// Solar timing needs only an approximate position. Keep one observation per
// identity prefix, at roughly 1 km resolution, rather than copying contacts.
class DisplayNightLocationCache {
struct Entry {
uint32_t identity;
uint32_t heard_at;
int16_t latitude_e2;
int16_t longitude_e2;
bool empty() const { return latitude_e2 == 0 && longitude_e2 == 0; }
void clear() { latitude_e2 = longitude_e2 = 0; }
};
static_assert(sizeof(Entry) == 12, "Night location observations must stay compact");
Entry entries[16] = {};
static int16_t quantize(int32_t value) {
return (value + (value < 0 ? -5000 : 5000)) / 10000;
}
static int32_t meanE6(int32_t sum, uint8_t count) {
// Split the multiplication to keep the whole average in 32-bit math.
return (sum / count) * 10000 + ((sum % count) * 10000) / count;
}
public:
static constexpr uint32_t MAX_AGE_MS = 12UL * 60UL * 60UL * 1000UL;
static bool valid(int32_t latitude_e6, int32_t longitude_e6) {
return latitude_e6 >= -90000000L && latitude_e6 <= 90000000L
&& longitude_e6 >= -180000000L && longitude_e6 <= 180000000L
&& (latitude_e6 != 0 || longitude_e6 != 0);
}
bool observe(uint32_t identity, int32_t latitude_e6, int32_t longitude_e6,
uint32_t now_ms) {
if (!valid(latitude_e6, longitude_e6)) return false;
const int16_t latitude_e2 = quantize(latitude_e6);
const int16_t longitude_e2 = quantize(longitude_e6);
if (latitude_e2 == 0 && longitude_e2 == 0) return false;
Entry* selected = &entries[0];
uint32_t oldest_age = 0;
for (auto& entry : entries) {
if (!entry.empty() && entry.identity == identity) {
selected = &entry;
break;
}
const uint32_t age = now_ms - entry.heard_at;
if (entry.empty() || age > oldest_age) {
selected = &entry;
oldest_age = entry.empty() ? UINT32_MAX : age;
}
}
selected->identity = identity;
selected->heard_at = now_ms;
selected->latitude_e2 = latitude_e2;
selected->longitude_e2 = longitude_e2;
return true;
}
bool average(uint32_t now_ms, int32_t& latitude_e6, int32_t& longitude_e6) {
int32_t latitude_sum = 0, longitude_sum = 0, anchor = 0;
uint8_t count = 0;
for (auto& entry : entries) {
if (entry.empty()) continue;
if (static_cast<uint32_t>(now_ms - entry.heard_at) > MAX_AGE_MS) {
entry.clear();
continue;
}
if (count == 0) anchor = entry.longitude_e2;
int32_t longitude = entry.longitude_e2;
if (longitude - anchor > 18000) longitude -= 36000;
else if (longitude - anchor < -18000) longitude += 36000;
latitude_sum += entry.latitude_e2;
longitude_sum += longitude;
++count;
}
latitude_e6 = longitude_e6 = 0;
if (count == 0) return false;
latitude_e6 = meanE6(latitude_sum, count);
longitude_e6 = meanE6(longitude_sum, count);
if (longitude_e6 > 180000000L) longitude_e6 -= 360000000L;
else if (longitude_e6 <= -180000000L) longitude_e6 += 360000000L;
return true;
}
};
template<class Sensors>
bool readDisplayNightLocation(DisplayNightLocationCache& cache,
const Sensors& sensors, uint32_t now_ms,
int32_t& latitude_e6, int32_t& longitude_e6) {
// Retire expired neighbors even while GPS supplies the preferred position.
const bool has_neighbors = cache.average(now_ms, latitude_e6, longitude_e6);
double latitude = 0, longitude = 0;
if (sensors.getCachedGpsPosition(latitude, longitude)
&& isfinite(latitude) && isfinite(longitude)
&& latitude >= -90.0 && latitude <= 90.0
&& longitude >= -180.0 && longitude <= 180.0) {
const int32_t gps_latitude = static_cast<int32_t>(latitude * 1000000.0
+ (latitude < 0 ? -0.5 : 0.5));
const int32_t gps_longitude = static_cast<int32_t>(longitude * 1000000.0
+ (longitude < 0 ? -0.5 : 0.5));
if (DisplayNightLocationCache::valid(gps_latitude, gps_longitude)) {
latitude_e6 = gps_latitude;
longitude_e6 = gps_longitude;
return true;
}
}
return has_neighbors;
}
void observeDisplayNightAdvert(const mesh::Packet* packet,
const mesh::Identity& identity,
const mesh::Identity& self,
const uint8_t* app_data, size_t app_data_len,
uint32_t now_ms);
void refreshDisplayNightLocation(const SensorManager& sensors,
uint32_t utc, uint32_t now_ms);
} // namespace ui
} // namespace mesh
#endif
+168
View File
@@ -0,0 +1,168 @@
#include "DisplayNightSettings.h"
#ifdef MESHCORE_HAS_COLOR_DISPLAY
#include "DisplayNightPolicy.h"
#include <helpers/CheckedSettingsFile.h>
#include <stdio.h>
#include <string.h>
namespace mesh { namespace ui {
namespace {
FILESYSTEM* settings_fs = nullptr;
constexpr char path[] = "/display_night";
constexpr char backup[] = "/display_night.bak";
uint8_t mode = NightAuto;
int16_t delay_minutes = 60;
bool active = false, has_position = false;
uint32_t observed_utc = 0, evaluated_minute = UINT32_MAX;
int32_t latitude = 0, longitude = 0;
void evaluate() {
active = mode == NightOn || (mode == NightAuto && has_position
&& night_policy::active(observed_utc, latitude, longitude, delay_minutes));
}
void encode(uint8_t selected, int16_t delay, uint8_t (&data)[8]) {
data[0] = 'D'; data[1] = 'N'; data[2] = 1; data[3] = selected;
const uint16_t encoded = uint16_t(delay + 180);
data[4] = encoded & 255; data[5] = encoded >> 8;
data[6] = data[7] = 0;
for (unsigned i = 0; i < 7; ++i) data[7] ^= data[i];
}
bool read(const char* name, uint8_t (&data)[8]) {
if (!mesh::storage::readFixedSettingsFile(settings_fs, name, data, sizeof(data))) return false;
const uint16_t encoded = uint16_t(data[4]) | (uint16_t(data[5]) << 8);
uint8_t expected[8];
encode(data[3], int16_t(encoded) - 180, expected);
return data[3] <= NightAuto && encoded <= 360
&& memcmp(data, expected, sizeof(data)) == 0;
}
bool recoverBackup() {
uint8_t current[8], saved[8];
if (read(path, current) || !read(backup, saved)) return true;
// Never rotate a corrupt primary over the only valid record on a later save.
if (settings_fs->exists(path) && !settings_fs->remove(path)) return false;
if (!settings_fs->rename(backup, path)) return false;
return read(path, current) && !memcmp(current, saved, sizeof(current));
}
bool save(uint8_t selected, int16_t delay) {
if (!settings_fs || !recoverBackup()) return false;
uint8_t data[8];
encode(selected, delay, data);
#if defined(NRF52_PLATFORM)
const bool committed = mesh::storage::writeCheckedSettingsFile(settings_fs, path, data, sizeof(data))
== mesh::AtomicFileWriter::Outcome::Committed;
if (committed) settings_fs->remove(backup);
return committed;
#else
constexpr char temporary[] = "/display_night.tmp";
settings_fs->remove(temporary);
if (settings_fs->exists(temporary)) return false;
#if defined(STM32_PLATFORM)
File file(*settings_fs);
if (!file.open(temporary, FILE_O_WRITE)) return false;
#elif defined(RP2040_PLATFORM)
File file = settings_fs->open(temporary, "w");
#else
File file = settings_fs->open(temporary, "w", true);
#endif
if (!file) return false;
const bool written = file.write(data, sizeof(data)) == sizeof(data);
file.close();
uint8_t checked[8];
if (!written || !read(temporary, checked) || memcmp(data, checked, sizeof(data))) return false;
if (settings_fs->exists(backup) && !settings_fs->remove(backup)) return false;
if (settings_fs->exists(path) && !settings_fs->rename(path, backup)) return false;
if (!settings_fs->rename(temporary, path)) {
if (settings_fs->exists(backup)) settings_fs->rename(backup, path);
return false;
}
if (!read(path, checked) || memcmp(data, checked, sizeof(data))) return false;
settings_fs->remove(backup);
return true;
#endif
}
} // namespace
uint8_t displayNightMode() { return mode; }
int16_t displayNightDelayMinutes() { return delay_minutes; }
bool displayNightActive() { return active; }
void loadDisplayNightSettings(FILESYSTEM* fs) {
settings_fs = fs;
mode = NightAuto;
delay_minutes = 60;
if (fs) recoverBackup();
uint8_t data[8];
if (read(path, data) || read(backup, data)) {
mode = data[3];
delay_minutes = int16_t(uint16_t(data[4]) | (uint16_t(data[5]) << 8)) - 180;
}
evaluated_minute = UINT32_MAX;
evaluate();
}
void updateDisplayNightMode(uint32_t utc, bool has_location, int32_t latitude_e6,
int32_t longitude_e6) {
observed_utc = utc;
const bool usable = has_location && night_policy::validLocation(latitude_e6, longitude_e6);
const bool changed = usable != has_position;
has_position = usable;
latitude = latitude_e6;
longitude = longitude_e6;
if (!changed && evaluated_minute == utc / 60) return;
evaluated_minute = utc / 60;
evaluate();
}
bool handleDisplayNightCommand(const char* command, char* reply, size_t capacity) {
const bool get = strncmp(command, "get ", 4) == 0;
if (!get && strncmp(command, "set ", 4) != 0) return false;
const char* key = command + 4;
bool delay = false;
size_t length = 13;
if (!strncmp(key, "display.night.delay", 19)) { delay = true; length = 19; }
else if (strncmp(key, "display.night", 13)) return false;
if (key[length] && key[length] != ' ') return false;
const char* value = key + length;
static const char* const names[] = {"off", "on", "auto"};
if (get) {
if (*value) snprintf(reply, capacity, "Error: unexpected argument");
else if (delay) snprintf(reply, capacity, "> %d", int(delay_minutes));
else snprintf(reply, capacity, "> %s", names[mode]);
return true;
}
while (*value == ' ') ++value;
uint8_t selected = mode;
int16_t minutes = delay_minutes;
if (delay) {
const bool negative = *value == '-';
if (negative || *value == '+') ++value;
unsigned magnitude = 0;
bool valid = *value != 0;
for (; valid && *value; ++value) {
valid = *value >= '0' && *value <= '9';
if (valid) { magnitude = magnitude * 10 + (*value - '0'); valid = magnitude <= 180; }
}
if (!valid) { snprintf(reply, capacity, "Error: delay must be -180..180 minutes"); return true; }
minutes = negative ? -int(magnitude) : int(magnitude);
} else {
for (selected = NightOff; selected <= NightAuto; ++selected)
if (!strcmp(value, names[selected])) break;
if (selected > NightAuto) { snprintf(reply, capacity, "Error: use auto|on|off"); return true; }
}
if (!save(selected, minutes)) snprintf(reply, capacity, "Error: night settings save failed");
else {
mode = selected;
delay_minutes = minutes;
evaluate();
snprintf(reply, capacity, "OK");
}
return true;
}
} }
#endif
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "DisplayBuildFlags.h"
#include <stddef.h>
#include <stdint.h>
namespace mesh { namespace ui {
// These values are also the small on-disk mode encoding.
enum DisplayNightMode : uint8_t { NightOff = 0, NightOn = 1, NightAuto = 2 };
#ifdef MESHCORE_HAS_COLOR_DISPLAY
uint8_t displayNightMode();
int16_t displayNightDelayMinutes();
bool displayNightActive();
bool handleDisplayNightCommand(const char* command, char* reply, size_t capacity);
// UTC and position are observations only; refreshing them never writes flash.
void updateDisplayNightMode(uint32_t utc, bool has_location,
int32_t latitude_e6 = 0, int32_t longitude_e6 = 0);
#else
inline uint8_t displayNightMode() { return NightOff; }
inline int16_t displayNightDelayMinutes() { return 60; }
inline bool displayNightActive() { return false; }
inline bool handleDisplayNightCommand(const char*, char*, size_t) { return false; }
inline void updateDisplayNightMode(uint32_t, bool, int32_t = 0, int32_t = 0) {}
#endif
} }
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <stdint.h>
namespace mesh { namespace ui { namespace night_policy {
// A seven-entry quarter-wave table avoids floating-point trig or an astronomy
// library. Linear interpolation is sufficient for a display's dusk schedule.
inline int32_t sine(int degrees10) {
static const uint16_t values[] = {0, 259, 500, 707, 866, 966, 1000};
degrees10 %= 3600;
if (degrees10 < 0) degrees10 += 3600;
const bool negative = degrees10 > 1800;
if (negative) degrees10 -= 1800;
if (degrees10 > 900) degrees10 = 1800 - degrees10;
const unsigned index = degrees10 / 150;
int32_t value = values[index];
if (index < 6) value += ((values[index + 1] - value) * (degrees10 % 150) + 75) / 150;
return negative ? -value : value;
}
inline bool validLocation(int32_t latitude_e6, int32_t longitude_e6) {
return latitude_e6 >= -90000000 && latitude_e6 <= 90000000
&& longitude_e6 >= -180000000 && longitude_e6 <= 180000000;
}
inline bool active(uint32_t utc, int32_t latitude_e6, int32_t longitude_e6,
int16_t delay_minutes) {
if (utc < 1577836800UL || !validLocation(latitude_e6, longitude_e6)) return false;
// Longitude supplies local solar time, so neither a time zone nor DST is
// needed. Omitting the equation of time costs at most roughly 16 minutes.
int solar_minute = int(utc % 86400UL / 60) + longitude_e6 / 250000;
uint32_t day = utc / 86400UL - 10957UL; // days since 2000-01-01
if (solar_minute < 0) { solar_minute += 1440; --day; }
else if (solar_minute >= 1440) { solar_minute -= 1440; ++day; }
unsigned year = 2000;
for (;;) {
const unsigned length = 365 + (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day < length) break;
day -= length;
++year;
}
const int declination = (234 * sine((int(day) - 80) * 3600 / 365)) / 1000;
const int latitude = latitude_e6 / 100000;
const int32_t numerator = -15000 - sine(latitude) * sine(declination);
const int32_t denominator = sine(latitude + 900) * sine(declination + 900);
// Include the conventional approximately -0.83 degree sunrise altitude.
// Polar day/night has no crossing and must not divide by a vanishing cosine.
if (numerator <= -denominator) return false;
if (numerator >= denominator) return true;
int low = 0, high = 1800;
while (low < high) {
const int middle = (low + high) / 2;
if (sine(middle + 900) * denominator / 1000 > numerator) low = middle + 1;
else high = middle;
}
const int half_day = (low * 4 + 5) / 10;
const int dawn = 720 - half_day;
const int dusk = 720 + half_day;
// Work in the solar day beginning at sunrise. This handles a positive
// sunset delay crossing midnight without turning night mode on too early.
int since_dawn = solar_minute - dawn;
if (since_dawn < 0) since_dawn += 1440;
const int start = dusk - dawn + delay_minutes;
if (start <= 0) return true;
return start < 1440 && since_dawn >= start;
}
} } }
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <helpers/IdentityStore.h>
#include "DisplayNightMode.h"
namespace mesh { namespace ui {
#ifdef MESHCORE_HAS_COLOR_DISPLAY
void loadDisplayNightSettings(FILESYSTEM* fs);
#else
inline void loadDisplayNightSettings(FILESYSTEM*) {}
#endif
} }
+4
View File
@@ -1,5 +1,7 @@
#include "DisplayPowerSettings.h"
#include "DisplayBuildFlags.h"
#include "DisplayNightMode.h"
#include "DisplayNightSettings.h"
#include <helpers/CheckedSettingsFile.h>
#include <stdio.h>
@@ -94,6 +96,7 @@ bool savePrefs(const DisplayPowerPrefs& prefs) {
}
bool loadDisplayPowerSettings(FILESYSTEM* fs, bool pairing_supported, bool wake_on_boot) {
loadDisplayNightSettings(fs);
#ifdef MESHCORE_HAS_REAL_DISPLAY
settings_fs = fs;
#else
@@ -141,6 +144,7 @@ void migrateLegacyDisplayTimeout(uint16_t seconds) {
bool handleDisplayPowerCommand(const char* command, char* reply, size_t reply_size,
bool inbox_supported) {
if (handleDisplayNightCommand(command, reply, reply_size)) return true;
#ifndef MESHCORE_HAS_REAL_DISPLAY
(void)inbox_supported;
if ((command[0] != 'g' && command[0] != 's')
+1
View File
@@ -2,6 +2,7 @@
#include <helpers/IdentityStore.h>
#include "DisplayPowerPolicy.h"
#include "DisplayBuildFlags.h"
namespace mesh { namespace ui {
+55 -3
View File
@@ -132,7 +132,7 @@ bool LGFXDisplay::begin() {
display->setRotation(DISPLAY_ROTATION);
display->setBrightness(DISPLAY_BRIGHTNESS);
display->setColorDepth(8);
display->setTextColor(TFT_WHITE);
display->setTextColor(mesh::ui::color_theme::render(TFT_WHITE));
buffer.setColorDepth(UI_BUFFER_COLOR_DEPTH);
// The RGB scanout framebuffer must live in PSRAM. Keep the UI sprite in
@@ -228,6 +228,7 @@ void LGFXDisplay::turnOff() {
void LGFXDisplay::clear() {
// display->clearDisplay();
applyNightPalette();
buffer.clearDisplay();
_presentedEmojiOverlayCount = 0;
_hasLastFrame = false;
@@ -238,7 +239,15 @@ void LGFXDisplay::startFrame(ColorVal bkg) {
// display->getScanLine();
_emojiOverlayCount = 0;
_hasTransparentEmojiPixels = false;
_color = renderColor(bkg);
const bool night = mesh::ui::displayNightActive();
if (_nightFrame != night) {
_nightFrame = night;
_hasLastFrame = false;
_presentedEmojiOverlayCount = 0;
display->fillScreen(mesh::ui::color_theme::background(UIColor::window_bkg));
}
applyNightPalette();
_color = night ? renderColor(UIColor::window_bkg) : renderColor(bkg);
buffer.setBaseColor(_color);
buffer.fillScreen(_color);
setColor(UIColor::primary_txt);
@@ -380,7 +389,12 @@ bool LGFXDisplay::drawQrCode(const char* text, int x, int y, int size) {
const int used_size = module_size * (qr.size + quiet_zone * 2);
const int left = x * _coordinateScale + (scaled_size - used_size) / 2;
const int top = y * _coordinateScale + (scaled_size - used_size) / 2;
const uint32_t light = renderColor(UIColor::primary_txt);
uint32_t light = renderColor(UIColor::primary_txt);
#if UI_BUFFER_COLOR_DEPTH >= 8
// These QR locals use LovyanGFX's uint32 RGB888 overload. The ordinary
// drawing state is signed RGB565; preserve existing daytime QR values.
if (mesh::ui::displayNightActive()) light = mesh::ui::color_theme::rgb888(static_cast<ColorVal>(light));
#endif
const uint32_t dark = renderColor(UIColor::window_bkg);
buffer.fillRect(x * _coordinateScale, y * _coordinateScale,
@@ -539,6 +553,14 @@ bool LGFXDisplay::installRuntimeFont(uint8_t* data, size_t size) {
}
uint32_t LGFXDisplay::renderColor(ColorVal color) const {
if (mesh::ui::displayNightActive()) {
#if UI_BUFFER_COLOR_DEPTH < 8
return mesh::ui::color_theme::isBackground(color)
? mesh::ui::color_theme::INDEX_BACKGROUND : mesh::ui::color_theme::INDEX_TEXT;
#else
return mesh::ui::color_theme::render(color);
#endif
}
#if UI_BUFFER_COLOR_DEPTH < 8
using namespace mesh::ui::color_theme;
if (color == UIColor::window_bkg) return INDEX_BACKGROUND;
@@ -557,6 +579,17 @@ uint32_t LGFXDisplay::renderColor(ColorVal color) const {
#endif
}
void LGFXDisplay::applyNightPalette() {
#if UI_BUFFER_COLOR_DEPTH < 8
const bool night = mesh::ui::displayNightActive();
// Smooth glyph blending can choose any palette entry, not only the two
// explicit drawing indices. Keep every possible output red or black.
for (unsigned i = 0; i < 16; ++i) {
buffer.setPaletteColor(i, night ? (i ? 0xFF0000u : 0x000000u) : UI_PALETTE[i]);
}
#endif
}
bool LGFXDisplay::configurePalette() {
#if UI_BUFFER_COLOR_DEPTH < 8
return buffer.createPalette(UI_PALETTE,
@@ -681,6 +714,25 @@ int32_t LGFXDisplay::queueEmoji(lgfx::v1::LGFXBase* gfx,
|| _emojiAtlas.glyph((uint16_t)codepoint) == nullptr) {
return 0;
}
if (mesh::ui::displayNightActive()) {
// Keep only the opaque silhouette; no full-color overlay may bypass the
// red/black canvas. Work directly from the existing atlas without a copy.
const uint8_t* pixels = _emojiAtlas.glyph((uint16_t)codepoint);
const int source_width = _emojiAtlas.width();
const int source_height = _emojiAtlas.height();
const int32_t red = renderColor(UIColor::primary_txt);
for (int row = 0; row < source_height; ++row) {
const int top = y + row * font_height / source_height;
const int bottom = y + (row + 1) * font_height / source_height;
for (int col = 0; col < source_width; ++col) {
if (pixels[row * source_width + col] == _emojiAtlas.transparent()) continue;
const int left = x + col * font_height / source_width;
const int right = x + (col + 1) * font_height / source_width;
buffer.fillRect(left, top, right - left, bottom - top, red);
}
}
return font_height;
}
if (_emojiOverlayCount >= MAX_EMOJI_OVERLAYS) return font_height;
EmojiOverlay& overlay = _emojiOverlays[_emojiOverlayCount++];
+2
View File
@@ -44,6 +44,7 @@ protected:
bool _hasTransparentEmojiPixels = false;
uint32_t _lastFrameHash = 0;
bool _hasLastFrame = false;
bool _nightFrame = false;
int _logicalTextSize = 1;
bool _compactText = false;
uint8_t _coordinateScale = UI_COORD_SCALE;
@@ -52,6 +53,7 @@ protected:
String mapText(const char* str) const;
uint32_t renderColor(ColorVal color) const;
bool configurePalette();
void applyNightPalette();
uint32_t frameHash() const;
bool wasEmojiPresented(const EmojiOverlay& overlay) const;
void drawEmojiMask(int32_t x, int32_t y, int32_t size,
+5 -5
View File
@@ -421,7 +421,7 @@ bool NV3001BDisplay::begin() {
is_on = true;
color = 0x0000;
fillPhysicalRect(0, 0, NV3001B_SCREEN_WIDTH, NV3001B_SCREEN_HEIGHT);
color = 0xffff;
color = mesh::ui::color_theme::render(0xffff);
text_size = 1;
cursor_x = 0;
cursor_y = 0;
@@ -452,15 +452,15 @@ void NV3001BDisplay::turnOff() {
void NV3001BDisplay::clear() {
uint16_t saved = color;
color = UIColor::window_bkg;
color = mesh::ui::color_theme::background(UIColor::window_bkg);
fillPhysicalRect(0, 0, NV3001B_SCREEN_WIDTH, NV3001B_SCREEN_HEIGHT);
color = saved;
}
void NV3001BDisplay::startFrame(ColorVal bkg) {
color = bkg;
color = mesh::ui::color_theme::background(bkg);
fillPhysicalRect(0, 0, NV3001B_SCREEN_WIDTH, NV3001B_SCREEN_HEIGHT);
color = UIColor::primary_txt;
color = mesh::ui::color_theme::render(UIColor::primary_txt);
text_size = 1;
cursor_x = 0;
cursor_y = 0;
@@ -471,7 +471,7 @@ void NV3001BDisplay::setTextSize(int sz) {
}
void NV3001BDisplay::setColor(ColorVal c) {
color = c;
color = mesh::ui::color_theme::render(c);
}
void NV3001BDisplay::setCursor(int x, int y) {
+5 -4
View File
@@ -1,4 +1,5 @@
#include "ST7735Display.h"
#include "ColorTheme.h"
#include "../UsbLogging.h"
#if defined(NRF52_PLATFORM) && defined(MESH_NRF52_FLASH_TRIM) && MESH_NRF52_FLASH_TRIM
#include "Nrf52TftFontTrim.h"
@@ -512,7 +513,7 @@ bool ST7735Display::begin() {
return false;
}
sprite->fillScreen(ST77XX_BLACK);
sprite->setTextColor(curr_color = ST77XX_WHITE);
sprite->setTextColor(curr_color = mesh::ui::color_theme::render(ST77XX_WHITE));
}
if (!spriteReady()) {
@@ -671,8 +672,8 @@ void ST7735Display::clear() {
void ST7735Display::startFrame(ColorVal bkg) {
if (!spriteReady()) return;
sprite->fillScreen(bkg);
sprite->setTextColor(curr_color = UIColor::primary_txt);
sprite->fillScreen(mesh::ui::color_theme::background(bkg));
sprite->setTextColor(curr_color = mesh::ui::color_theme::render(UIColor::primary_txt));
sprite->setFreeFont();
sprite->setTextSize(1); // This one affects size of Please wait... message
sprite->setTextWrap(false);
@@ -690,7 +691,7 @@ int ST7735Display::textLineHeight() {
void ST7735Display::setColor(ColorVal c) {
if (!spriteReady()) return;
curr_color = c;
curr_color = mesh::ui::color_theme::render(c);
sprite->setTextColor(curr_color);
}
+6 -2
View File
@@ -1,6 +1,7 @@
#ifdef ST7789
#include "ST7789Display.h"
#include "ColorTheme.h"
#if defined(HELTEC_T114) && defined(T114_DISPLAY_AUTODETECT) && T114_DISPLAY_AUTODETECT
#include "T114DisplayProbe.h"
@@ -159,8 +160,11 @@ void ST7789Display::setTextSize(int sz) {
void ST7789Display::setColor(ColorVal c) {
if (!canDraw()) return;
_color = c;
display.setColor((OLEDDISPLAY_COLOR)_color);
display.setRGB(_color == OLEDDISPLAY_COLOR::WHITE ? ST77XX_WHITE : ST77XX_BLACK);
display.setColor(mesh::ui::displayNightActive()
? (mesh::ui::color_theme::isBackground(c) ? OLEDDISPLAY_COLOR::BLACK : OLEDDISPLAY_COLOR::WHITE)
: (OLEDDISPLAY_COLOR)_color);
display.setRGB(mesh::ui::displayNightActive() ? mesh::ui::color_theme::NIGHT_FOREGROUND
: _color == OLEDDISPLAY_COLOR::WHITE ? ST77XX_WHITE : ST77XX_BLACK);
}
void ST7789Display::setCursor(int x, int y) {
+5 -3
View File
@@ -331,7 +331,7 @@ bool ST7789LCDDisplay::begin() {
display.setSPISpeed(40e6);
display.fillScreen(ST77XX_BLACK);
display.setTextColor(ST77XX_WHITE);
display.setTextColor(mesh::ui::color_theme::render(ST77XX_WHITE));
display.setTextSize(1);
display.setTextWrap(false);
display.cp437(true); // Use full 256 char 'Code Page 437' font
@@ -400,6 +400,7 @@ void ST7789LCDDisplay::clear() {
}
void ST7789LCDDisplay::startFrame(ColorVal bkg) {
bkg = mesh::ui::color_theme::background(bkg);
#if defined(LILYGO_TDECK) || defined(MESHCORE_HELTEC_R8_TFT_DETECTION)
if (!_isOn) return;
#endif
@@ -409,14 +410,14 @@ void ST7789LCDDisplay::startFrame(ColorVal bkg) {
_frame_active = true;
serviceRender(true);
_canvas->fillScreen(bkg);
_canvas->setTextColor(_color = UIColor::primary_txt);
_canvas->setTextColor(_color = mesh::ui::color_theme::render(UIColor::primary_txt));
_canvas->setTextSize(1);
_canvas->cp437(true);
return;
}
#endif
display.fillScreen(bkg);
display.setTextColor(_color = UIColor::primary_txt);
display.setTextColor(_color = mesh::ui::color_theme::render(UIColor::primary_txt));
display.setTextSize(1);
display.cp437(true); // Use full 256 char 'Code Page 437' font
}
@@ -435,6 +436,7 @@ void ST7789LCDDisplay::setTextSize(int sz) {
}
void ST7789LCDDisplay::setColor(ColorVal c) {
c = mesh::ui::color_theme::render(c);
#if defined(LILYGO_TDECK) || defined(MESHCORE_HELTEC_R8_TFT_DETECTION)
if (!_isOn) return;
#endif
+4 -1
View File
@@ -105,6 +105,7 @@ class ST7789Spi : public OLEDDisplay {
SPIClass * _spi;
SPISettings _spiSettings;
uint16_t _RGB=0xFFFF;
uint16_t _lastRGB=0xFFFF;
uint8_t _buffheight;
public:
/* pass _cs as -1 to indicate "do not use CS pin", for cases where it is hard wired low */
@@ -157,6 +158,8 @@ class ST7789Spi : public OLEDDisplay {
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
const bool tint_changed = _lastRGB != _RGB;
_lastRGB = _RGB;
uint16_t minBoundY = UINT16_MAX;
uint16_t maxBoundY = 0;
@@ -172,7 +175,7 @@ class ST7789Spi : public OLEDDisplay {
for (x = 0; x < displayWidth; x++) {
//Serial.printf("x %d y %d\r\n",x,y);
uint16_t pos = x + y * displayWidth;
if (buffer[pos] != buffer_back[pos]) {
if (buffer[pos] != buffer_back[pos] || tint_changed) {
minBoundY = min(minBoundY, y);
maxBoundY = max(maxBoundY, y);
minBoundX = min(minBoundX, x);