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

+1
View File
@@ -6,6 +6,7 @@
#include <cstring>
#include <vector>
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/ColorTheme.h>
#define pgm_read_byte(p) (*(const uint8_t*)(p))
#define PROGMEM
#define HSPI 1
+1
View File
@@ -4,6 +4,7 @@
#include <helpers/ui/ST7735Display.h>
#include <helpers/ui/SmallMessageText.h>
#include <helpers/ui/CompanionHomeLayout.h>
#include <helpers/ui/ColorTheme.h>
ColorVal UIColor::window_bkg = 0, UIColor::title_bkg = 0, UIColor::title_txt = 1;
ColorVal UIColor::primary_txt = 1, UIColor::secondary_txt = 1, UIColor::warning_txt = 1;
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Run the night location cache and verified-advert filter on the host."""
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
MESH = r'''
#pragma once
#include <stdint.h>
#include <string.h>
#define MAX_ADVERT_DATA_SIZE 32
namespace mesh {
class Identity {
public:
uint8_t pub_key[32] = {};
Identity(uint32_t prefix = 0) { memcpy(pub_key, &prefix, sizeof(prefix)); }
bool matches(const Identity& other) const {
return memcmp(pub_key, other.pub_key, sizeof(pub_key)) == 0;
}
};
class Packet {
public:
bool radio_local = false, forwarded = false, transport = false;
uint16_t transport_codes[2] = {};
uint8_t hops = 0;
uint8_t getPathHashCount() const { return hops; }
bool hasTransportCodes() const { return transport; }
};
}
'''
SENSORS = r'''
#pragma once
class SensorManager {
public:
bool valid = false;
double latitude = 0, longitude = 0;
mutable unsigned reads = 0;
bool getCachedGpsPosition(double& lat, double& lon) const {
++reads; lat = latitude; lon = longitude; return valid;
}
};
'''
HARNESS = r'''
#include <cassert>
#include <cmath>
#include <limits>
#include <string>
#include <Mesh.h>
#include <helpers/AdvertDataHelpers.h>
#include <helpers/SensorManager.h>
#include <helpers/ui/DisplayNightLocation.h>
using mesh::ui::DisplayNightLocationCache;
static unsigned updates = 0;
static bool observed_valid = false;
static int32_t observed_lat = 0, observed_lon = 0;
static uint32_t observed_utc = 0;
namespace mesh { namespace ui {
void updateDisplayNightMode(uint32_t utc, bool valid, int32_t lat, int32_t lon) {
++updates; observed_valid = valid; observed_lat = lat; observed_lon = lon;
observed_utc = utc;
}
} }
static void expect(DisplayNightLocationCache& cache, uint32_t now,
int32_t expected_lat, int32_t expected_lon) {
int32_t lat = 123, lon = 123;
assert(cache.average(now, lat, lon));
assert(lat == expected_lat && lon == expected_lon);
}
static void missing(DisplayNightLocationCache& cache, uint32_t now) {
int32_t lat = 123, lon = 123;
assert(!cache.average(now, lat, lon));
assert(lat == 0 && lon == 0);
}
static void advert(mesh::Packet& packet, uint32_t prefix, uint32_t now,
int32_t latitude = 10000000, int32_t longitude = 20000000,
uint8_t type = ADV_TYPE_CHAT) {
uint8_t bytes[9];
bytes[0] = type | ADV_LATLON_MASK;
memcpy(bytes + 1, &latitude, 4); memcpy(bytes + 5, &longitude, 4);
mesh::ui::observeDisplayNightAdvert(&packet, mesh::Identity(prefix),
mesh::Identity(99), bytes, sizeof(bytes), now);
}
int main(int argc, char** argv) {
assert(argc == 2);
const std::string scenario = argv[1];
DisplayNightLocationCache cache;
static_assert(sizeof(cache) == 192, "The 16 observation cache must stay 192 bytes");
const uint32_t max_age = DisplayNightLocationCache::MAX_AGE_MS;
if (scenario == "unique") {
missing(cache, 0);
assert(cache.observe(1, 10000000, 20000000, 0));
assert(cache.observe(2, 30000000, 40000000, 1));
for (unsigned i = 0; i < 1000; ++i)
assert(cache.observe(1, 10000000, 20000000, i + 2));
expect(cache, 1002, 20000000, 30000000);
cache.observe(1, 50000000, 60000000, 1003);
expect(cache, 1003, 40000000, 50000000);
} else if (scenario == "freshness") {
cache.observe(1, 10000000, 20000000, 100);
expect(cache, 100 + max_age, 10000000, 20000000);
missing(cache, 101 + max_age);
missing(cache, 100); // Expiration cannot resurrect after millis wraps.
cache.observe(1, 10000000, 20000000, UINT32_MAX - 100);
expect(cache, 100, 10000000, 20000000);
missing(cache, max_age + 1);
} else if (scenario == "capacity") {
for (unsigned i = 1; i <= 16; ++i)
cache.observe(i, i * 1000000, 20000000, i);
expect(cache, 17, 8500000, 20000000);
cache.observe(17, 17000000, 20000000, 17);
expect(cache, 17, 9500000, 20000000); // Replaced oldest, not a recent peer.
cache.observe(2, 2000000, 20000000, 18);
cache.observe(18, 18000000, 20000000, 19);
expect(cache, 19, 10437500, 20000000); // Identity 2 was refreshed, 3 evicted.
} else if (scenario == "coordinates") {
for (const auto& point : {std::pair<int32_t,int32_t>{0,0},
{90000001,0}, {-90000001,0}, {0,180000001}, {0,-180000001}})
assert(!cache.observe(1, point.first, point.second, 0));
missing(cache, 0);
cache.observe(1, -12345678, 23456789, 0);
expect(cache, 0, -12350000, 23460000);
cache.observe(1, 90000000, 180000000, 1);
expect(cache, 1, 90000000, 180000000);
} else if (scenario == "dateline") {
cache.observe(1, 10000000, 179000000, 0);
cache.observe(2, 30000000, -179000000, 0);
expect(cache, 0, 20000000, 180000000);
DisplayNightLocationCache reversed;
reversed.observe(2, 30000000, -179000000, 0);
reversed.observe(1, 10000000, 179000000, 0);
int32_t lat, lon;
assert(reversed.average(0, lat, lon) && lat == 20000000 && std::abs(lon) == 180000000);
cache.observe(3, 20000000, 180000000, 0);
expect(cache, 0, 20000000, 180000000);
} else if (scenario == "gps") {
SensorManager sensors;
cache.observe(1, 10000000, 20000000, 0);
int32_t lat, lon;
assert(mesh::ui::readDisplayNightLocation(cache, sensors, 0, lat, lon));
assert(lat == 10000000 && lon == 20000000);
sensors.valid = true; sensors.latitude = 47.6062; sensors.longitude = -122.3321;
assert(mesh::ui::readDisplayNightLocation(cache, sensors, 1, lat, lon));
assert(lat == 47606200 && lon == -122332100);
assert(mesh::ui::readDisplayNightLocation(cache, sensors, max_age + 1, lat, lon));
sensors.valid = false;
assert(!mesh::ui::readDisplayNightLocation(cache, sensors, max_age + 2, lat, lon));
cache.observe(1, 10000000, 20000000, max_age + 2);
sensors.valid = true;
for (double invalid : {std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity(), 91.0}) {
sensors.latitude = invalid;
assert(mesh::ui::readDisplayNightLocation(cache, sensors, max_age + 2, lat, lon));
assert(lat == 10000000 && lon == 20000000);
}
} else if (scenario == "filter") {
mesh::Packet packet;
SensorManager sensors;
packet.hops = 1; advert(packet, 1, 0);
packet.hops = 0; packet.transport = true; advert(packet, 2, 0); // Share.
packet.transport = false; packet.forwarded = true; advert(packet, 3, 0); // Bridge.
packet.forwarded = false; packet.radio_local = true; advert(packet, 4, 0); // Import.
packet.radio_local = false; advert(packet, 99, 0); // Self.
advert(packet, 5, 0, 0, 0);
const uint8_t missing_coords[] = {ADV_TYPE_CHAT};
mesh::ui::observeDisplayNightAdvert(&packet, mesh::Identity(6), mesh::Identity(99),
missing_coords, sizeof(missing_coords), 0);
const uint8_t truncated[] = {ADV_TYPE_CHAT | ADV_LATLON_MASK};
mesh::ui::observeDisplayNightAdvert(&packet, mesh::Identity(7), mesh::Identity(99),
truncated, sizeof(truncated), 0);
mesh::ui::refreshDisplayNightLocation(sensors, 123, 0);
assert(updates == 1 && !observed_valid && observed_utc == 123);
// All advertised role types qualify, independent of contact admission.
for (uint8_t type : {ADV_TYPE_CHAT, ADV_TYPE_REPEATER, ADV_TYPE_ROOM, ADV_TYPE_SENSOR})
advert(packet, type, 1, type * 10000000, 20000000, type);
for (unsigned i = 0; i < 100; ++i) advert(packet, 1, 2);
mesh::ui::refreshDisplayNightLocation(sensors, 124, 14999);
assert(updates == 1); // Source refresh is bounded to one pass per 15 seconds.
mesh::ui::refreshDisplayNightLocation(sensors, 125, 15000);
assert(updates == 2 && observed_valid && observed_lat == 25000000 && observed_lon == 20000000);
packet.hops = 1; advert(packet, 1, max_age);
mesh::ui::refreshDisplayNightLocation(sensors, 126, max_age + 3);
assert(updates == 3 && !observed_valid); // Relayed traffic did not extend RF age.
} else assert(false);
}
'''
class DisplayNightLocationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = os.environ.get("CXX", "g++")
if shutil.which(compiler) is None:
raise unittest.SkipTest("C++ compiler unavailable")
cls.temp = tempfile.TemporaryDirectory(prefix="mesh-night-location-")
temp = Path(cls.temp.name)
(temp / "helpers").mkdir()
(temp / "Mesh.h").write_text(MESH, encoding="ascii")
(temp / "Arduino.h").write_text("#pragma once\n", encoding="ascii")
(temp / "helpers/SensorManager.h").write_text(SENSORS, encoding="ascii")
(temp / "main.cpp").write_text(HARNESS, encoding="ascii")
cls.exe = temp / "location"
subprocess.run([
compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", "-Wno-reorder",
"-DDISPLAY_CLASS=ST7735Display",
"-I", str(temp), "-I", str(ROOT / "src"), str(temp / "main.cpp"),
str(ROOT / "src/helpers/ui/DisplayNightLocation.cpp"),
str(ROOT / "src/helpers/AdvertDataHelpers.cpp"), "-o", str(cls.exe),
], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def test_location_sources(self):
for scenario in ("unique", "freshness", "capacity", "coordinates", "dateline", "gps", "filter"):
with self.subTest(scenario=scenario):
subprocess.run([str(self.exe), scenario], check=True)
if __name__ == "__main__":
unittest.main()
+238
View File
@@ -0,0 +1,238 @@
"""Run the real night schedule, saved CLI and redraw policy on the host."""
from datetime import datetime, timezone, timedelta
from pathlib import Path
import math
import os
import subprocess
import tempfile
import unittest
from test_display_power import FS_STUB
ROOT = Path(__file__).resolve().parents[1]
def compile_run(source, files=(), defines=(), stdin=""):
with tempfile.TemporaryDirectory(prefix="mesh-night-") as directory:
work = Path(directory)
(work / "helpers").mkdir()
(work / "helpers/IdentityStore.h").write_text(
FS_STUB.replace("/display_prefs", "/display_night"), encoding="ascii")
(work / "Arduino.h").write_text(
'#pragma once\n#include <stdint.h>\ninline uint32_t millis() { return 0; }\n', encoding="ascii")
(work / "test.cpp").write_text(source, encoding="ascii")
command = [os.environ.get("CXX", "g++"), "-std=c++17", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-I" + str(work), "-I" + str(ROOT / "src"), *defines,
str(work / "test.cpp"), *(str(ROOT / path) for path in files), "-o", str(work / "test")]
built = subprocess.run(command, capture_output=True, text=True)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
ran = subprocess.run([str(work / "test")], input=stdin, capture_output=True, text=True)
if ran.returncode:
raise AssertionError(ran.stdout + ran.stderr)
return ran.stdout
class DisplayNightModeTests(unittest.TestCase):
def test_small_integer_schedule_against_independent_solar_reference(self):
# NOAA's general solar equations provide an independent, more precise
# test oracle, not a firmware dependency:
# https://gml.noaa.gov/grad/solcalc/solareqns.PDF
samples = []
for latitude, longitude in ((47.6, -122.3), (0, 0), (-33.9, 151.2),
(51.5, 0), (-45, 170), (60, 25),
(35, 179.8), (35, -179.8)):
for month in (1, 3, 6, 9, 12):
date = datetime(2028, month, 21, tzinfo=timezone.utc)
gamma = 2 * math.pi / 365 * (date.timetuple().tm_yday - 1)
eqtime = 229.18 * (0.000075 + 0.001868 * math.cos(gamma)
- 0.032077 * math.sin(gamma) - 0.014615 * math.cos(2 * gamma)
- 0.040849 * math.sin(2 * gamma))
decl = (0.006918 - 0.399912 * math.cos(gamma) + 0.070257 * math.sin(gamma)
- 0.006758 * math.cos(2 * gamma) + 0.000907 * math.sin(2 * gamma)
- 0.002697 * math.cos(3 * gamma) + 0.001480 * math.sin(3 * gamma))
lat = math.radians(latitude)
hour = math.degrees(math.acos((math.cos(math.radians(90.833))
- math.sin(lat) * math.sin(decl)) / (math.cos(lat) * math.cos(decl))))
dawn = 720 - 4 * longitude - eqtime - 4 * hour
dusk = 720 - 4 * longitude - eqtime + 4 * hour
for delay in (-120, 0, 60, 180):
# One hour either side of the reference transition: broad
# deliberately, matching this approximate dusk feature.
for minute, expected in ((dawn - 60, True), (dawn + 60, False),
(dusk + delay - 60, False), (dusk + delay + 60, True)):
# Near midsummer at 60N a three-hour dusk delay can
# consume all of the short night. Test ordinary-night
# samples here and exercise that boundary separately.
if 1440 - 8 * hour - delay <= 120 or 8 * hour + delay <= 120:
continue
utc = int((date + timedelta(minutes=minute)).timestamp())
samples.append((utc, round(latitude * 1e6), round(longitude * 1e6), delay, expected))
source = r'''
#include <helpers/ui/DisplayNightPolicy.h>
#include <cstdio>
int main() {
unsigned utc; int lat, lon, delay;
while (scanf("%u %d %d %d", &utc, &lat, &lon, &delay) == 4)
printf("%d\n", mesh::ui::night_policy::active(utc, lat, lon, delay));
}
'''
output = compile_run(source, stdin="".join(
f"{utc} {lat} {lon} {delay}\n" for utc, lat, lon, delay, _ in samples))
for sample, actual in zip(samples, output.splitlines()):
self.assertEqual(actual == "1", sample[-1], sample)
self.assertEqual(len(output.splitlines()), len(samples))
def test_polar_invalid_and_midnight_delay_boundaries(self):
compile_run(r'''
#include <helpers/ui/DisplayNightPolicy.h>
#include <cassert>
using namespace mesh::ui::night_policy;
int main() {
const uint32_t june = 1782000000; // 2026-06-21 midnight UTC
const uint32_t december = 1797811200; // 2026-12-21 midnight UTC
assert(!active(june, 85000000, 0, 60));
assert(active(december, 85000000, 0, 60));
assert(active(june, -85000000, 0, 60));
assert(!active(december, -85000000, 0, 60));
assert(!active(0, 47000000, -122000000, 60));
assert(!active(june, 91000000, 0, 60));
assert(!active(june, 0, -181000000, 60));
// Longitude arithmetic must remain bounded at the uint32 RTC ceiling.
assert(active(UINT32_MAX, 0, 180000000, 60)
== active(UINT32_MAX - 86400, 0, 180000000, 60));
// At 60N a long positive delay crosses midnight. It must not activate
// before that previous sunset's delay, nor remain red after sunrise.
assert(!active(june, 60000000, 0, 180));
assert(active(june + 3600, 60000000, 0, 180));
assert(!active(june + 6 * 3600, 60000000, 0, 180));
}
''')
def test_real_cli_persistence_failed_saves_and_immediate_manual_mode(self):
source = r'''
#include <helpers/ui/DisplayNightSettings.h>
#include <helpers/ui/DisplayPowerSettings.h>
#include <cassert>
#include <string>
#if defined(NRF52_PLATFORM)
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
#include <helpers/AtomicFileWriter.h>
#endif
using namespace mesh::ui;
int main() {
FakeFS fs;
char reply[160];
loadDisplayPowerSettings(&fs, true);
assert(displayNightMode() == NightAuto && displayNightDelayMinutes() == 60);
assert(!displayNightActive());
assert(handleDisplayPowerCommand("set display.night on", reply, sizeof(reply)));
assert(!strcmp(reply, "OK") && displayNightActive()); // no clock/GPS needed
assert(fs.files["/display_night"].size() == 8);
assert(handleDisplayPowerCommand("get display.night", reply, sizeof(reply)));
assert(!strcmp(reply, "> on"));
assert(handleDisplayPowerCommand("set display.night.delay -180", reply, sizeof(reply)));
assert(!strcmp(reply, "OK") && displayNightDelayMinutes() == -180);
assert(handleDisplayPowerCommand("set display.night.delay 0", reply, sizeof(reply)));
assert(!strcmp(reply, "OK") && displayNightDelayMinutes() == 0);
assert(handleDisplayPowerCommand("set display.night off", reply, sizeof(reply)));
assert(!strcmp(reply, "OK") && !displayNightActive());
loadDisplayNightSettings(&fs);
assert(displayNightMode() == NightOff && displayNightDelayMinutes() == 0);
for (const char* cmd : {"set display.night AUTO", "set display.night.delay 181",
"set display.night.delay -181", "set display.night.delay 1junk",
"set display.night.delay ", "get display.night 1"}) {
assert(handleDisplayPowerCommand(cmd, reply, sizeof(reply)));
assert(std::string(reply).find("Error:") == 0);
assert(displayNightMode() == NightOff && displayNightDelayMinutes() == 0);
}
fs.fail_write = true;
assert(handleDisplayPowerCommand("set display.night on", reply, sizeof(reply)));
assert(std::string(reply).find("Error:") == 0 && !displayNightActive());
fs.fail_write = false;
assert(handleDisplayPowerCommand("set display.night auto", reply, sizeof(reply)));
updateDisplayNightMode(1797811200, true, 85000000, 0);
assert(displayNightActive());
updateDisplayNightMode(1797811201, false);
assert(!displayNightActive()); // lost/expired location is not permanent GPS
updateDisplayNightMode(1797811202, true, 85000000, 0);
assert(displayNightActive());
fs.files["/display_night"][7] ^= 1;
loadDisplayNightSettings(&fs);
assert(displayNightMode() == NightAuto && displayNightDelayMinutes() == 60);
// Recovery followed by a failed update must preserve the recovered record.
assert(handleDisplayPowerCommand("set display.night on", reply, sizeof(reply)));
fs.files["/display_night.bak"] = fs.files["/display_night"];
fs.files["/display_night"][0] ^= 1;
loadDisplayNightSettings(&fs);
assert(displayNightMode() == NightOn);
fs.fail_publish = true;
handleDisplayPowerCommand("set display.night off", reply, sizeof(reply));
assert(std::string(reply).find("Error:") == 0);
fs.fail_publish = false;
loadDisplayNightSettings(&fs);
assert(displayNightMode() == NightOn && displayNightActive());
}
'''
files = ("src/helpers/ui/DisplayNightMode.cpp", "src/helpers/ui/DisplayPowerSettings.cpp")
for platform in ((), ("-DNRF52_PLATFORM",)):
with self.subTest(platform=platform):
compile_run(source, files, ("-DDISPLAY_CLASS=ST7735Display", *platform))
def test_monochrome_has_no_night_runtime_or_store(self):
compile_run(r'''
#include <helpers/ui/DisplayNightSettings.h>
#include <cassert>
int main() {
FakeFS fs;
mesh::ui::loadDisplayNightSettings(&fs);
mesh::ui::updateDisplayNightMode(1797811200, true, 85000000, 0);
assert(!mesh::ui::displayNightActive() && fs.calls == 0);
}
''', ("src/helpers/ui/DisplayNightMode.cpp",), ("-DDISPLAY_CLASS=SSD1306Display",))
def test_palette_transition_invalidates_cached_ui_without_power_cycling(self):
compile_run(r'''
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/DisplayNightSettings.h>
#include <cassert>
struct Screen : DisplayDriver {
Screen() : DisplayDriver(160, 80) {}
bool on = true;
unsigned starts = 0, stops = 0;
bool isOn() override { return on; }
void turnOn() override { on = true; ++starts; }
void turnOff() override { on = false; ++stops; }
void clear() override {}
void startFrame(ColorVal) override {}
void endFrame() override {}
void setTextSize(int) override {}
void setColor(ColorVal) override {}
void setCursor(int, int) override {}
void print(const char*) override {}
void fillRect(int, int, int, int) override {}
void drawRect(int, int, int, int) override {}
void drawXbm(int, int, const uint8_t*, int, int) override {}
uint16_t getTextWidth(const char*) override { return 6; }
};
int main() {
FakeFS fs;
mesh::ui::loadDisplayNightSettings(&fs);
mesh::ui::displayPowerPrefs().battery.mode = mesh::ui::DisplayMode::On;
Screen display;
assert(!display.servicePower(false));
char reply[160];
mesh::ui::handleDisplayNightCommand("set display.night on", reply, sizeof(reply));
assert(display.servicePower(false)); // existing UI power hook forces redraw
assert(!display.servicePower(false));
mesh::ui::handleDisplayNightCommand("set display.night off", reply, sizeof(reply));
assert(display.servicePower(false));
assert(!display.servicePower(false));
assert(display.starts == 0 && display.stops == 0);
}
''', ("src/helpers/ui/DisplayNightMode.cpp", "src/helpers/ui/DisplayDriver.cpp"),
("-DDISPLAY_CLASS=ST7735Display",))
if __name__ == "__main__":
unittest.main()
+291
View File
@@ -0,0 +1,291 @@
"""Execute actual color boundaries, indexed palettes and night emoji rendering."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
from cpp_source import body
ROOT = Path(__file__).resolve().parents[1]
UI = ROOT / 'src/helpers/ui'
PREFIX = r'''
#include <helpers/ui/ColorTheme.h>
#include <cassert>
#include <cstdint>
#include <vector>
#include <type_traits>
static bool night = false;
namespace mesh { namespace ui { bool displayNightActive() { return night; } } }
ColorVal UIColor::window_bkg=0x0885, UIColor::title_bkg=0x1299, UIColor::title_txt=0xffff;
ColorVal UIColor::primary_txt=0xe73c, UIColor::secondary_txt=0x8d59, UIColor::warning_txt=0xfd20;
ColorVal UIColor::popup_bkg=0x1299, UIColor::popup_txt=0xffff, UIColor::corp_blue=0x5dbf;
struct Canvas {
uint32_t fill=0, text=0;
std::vector<uint32_t> marks;
void fillScreen(uint32_t c) { fill=c; }
void setTextColor(uint32_t c) { text=c; }
void setBaseColor(uint32_t) {}
void setTextSize(int) {}
void setTextWrap(bool) {}
void setFreeFont() {}
void cp437(bool) {}
void fillRect(int,int,int,int,uint32_t c) { marks.push_back(c); }
};
'''
class DisplayNightRenderingTests(unittest.TestCase):
def run_cpp(self, source, *defines):
with tempfile.TemporaryDirectory(prefix='meshcore-night-render-') as directory:
executable = Path(directory) / 'render'
compiled = subprocess.run([
os.environ.get('CXX', 'c++'), '-std=c++11', '-Wall', '-Wextra', '-Werror',
'-Wno-unused-parameter', '-Wno-unused-function', '-Wno-unused-variable',
'-DDISPLAY_CLASS=LGFXDisplay', *('-D' + value for value in defines),
'-I', str(ROOT / 'src'), '-x', 'c++', '-', '-o', str(executable),
], input=source, text=True, capture_output=True)
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
ran = subprocess.run([str(executable)], text=True, capture_output=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
def test_all_rgb565_values_and_variant_semantic_backgrounds(self):
self.run_cpp(PREFIX + r'''
int main() {
using namespace mesh::ui::color_theme;
for (unsigned c=0;c<65536;++c) assert(render(c)==c && background(c)==c);
night=true;
for (unsigned c=0;c<65536;++c) {
const bool b=c==0 || c==0x0885 || c==0x1299 || c==WINDOW_BACKGROUND
|| c==TITLE_BACKGROUND || c==POPUP_BACKGROUND;
assert(render(c)==(b ? NIGHT_BACKGROUND : NIGHT_FOREGROUND));
assert(background(c)==NIGHT_BACKGROUND);
}
assert(render(TOUCH_OUTLINE)==0xf800 && render(TOUCH_PRESSED)==0xf800);
assert(UIColor::window_bkg==0x0885 && UIColor::primary_txt==0xe73c);
night=false;
assert(render(UIColor::window_bkg)==0x0885 && render(UIColor::primary_txt)==0xe73c);
}
''')
def test_actual_direct_and_buffered_color_boundaries(self):
for driver in ('ST7735Display', 'ST7789LCDDisplay', 'NV3001BDisplay'):
with self.subTest(driver=driver):
source = (UI / (driver + '.cpp')).read_text()
if driver == 'ST7735Display':
harness = r'''
static Canvas canvas; static Canvas* sprite=&canvas; static ColorVal curr_color;
bool spriteReady() { return true; }
struct ST7735Display {
void startFrame(ColorVal); void setColor(ColorVal); void fillRect(int,int,int,int);
};
'''
inspect = 'canvas'
elif driver == 'ST7789LCDDisplay':
harness = r'''
struct ST7789LCDDisplay {
Canvas display, canvas; Canvas* _canvas=&canvas;
bool buffered=false, _isOn=true, _frame_active=false; ColorVal _color=0;
bool isBufferedRendering() const { return buffered; }
int width() const { return 8; } int height() const { return 8; }
void serviceRender(bool) {} void finishCanvasPrimitive(int,int,int,int) {}
void startFrame(ColorVal); void setColor(ColorVal); void fillRect(int,int,int,int);
};
'''
inspect = '(d.buffered ? d.canvas : d.display)'
else:
harness = r'''
static const int NV3001B_SCREEN_WIDTH=8, NV3001B_SCREEN_HEIGHT=8;
struct NV3001BDisplay {
Canvas canvas; ColorVal color=0; int text_size=1,cursor_x=0,cursor_y=0;
void fillPhysicalRect(int x,int y,int w,int h) {
canvas.fillRect(x,y,w,h,color); if (w==8 && h==8) canvas.fill=color;
}
void startFrame(ColorVal); void setColor(ColorVal); void fillRect(int,int,int,int);
};
'''
inspect = 'd.canvas'
harness += '\n'.join(body(source, f'void {driver}::{name}(')
for name in ('startFrame', 'setColor', 'fillRect'))
harness += '\nint main() { ' + driver + ' d;\n'
if driver == 'ST7789LCDDisplay':
harness += 'for (bool buffered : {false,true}) { d.buffered=buffered;\n'
harness += 'auto& c=' + inspect + ';\n'
harness += r'''
night=false; d.startFrame(0x3456); assert(c.fill==0x3456);
d.setColor(0x07e0); d.fillRect(1,1,1,1); assert(c.marks.back()==0x07e0);
night=true; d.startFrame(0x3456); assert(c.fill==0);
d.setColor(UIColor::primary_txt); d.fillRect(1,1,1,1); assert(c.marks.back()==0xf800);
d.setColor(0xffe0); d.fillRect(1,1,1,1); assert(c.marks.back()==0xf800);
d.setColor(UIColor::popup_bkg); d.fillRect(1,1,1,1); assert(c.marks.back()==0);
night=false; d.startFrame(0x3456); assert(c.fill==0x3456);
'''
if driver == 'ST7789LCDDisplay':
harness += '}\n'
harness += '}\n'
self.run_cpp(PREFIX + harness, 'LILYGO_TDECK=1')
def test_actual_lgfx_indexed_and_truecolor_emoji_paths(self):
source = (UI / 'LGFXDisplay.cpp').read_text()
palette = body(source, 'static const uint32_t UI_PALETTE[16]') + ';\n'
harness = r'''
namespace lgfx { namespace v1 { struct LGFXBase {}; } }
struct Sprite : Canvas, lgfx::v1::LGFXBase {
uint32_t palette[16]={};
void setPaletteColor(unsigned i,uint32_t c) { palette[i]=c; }
template<class T> void fillRect(int,int,int,int,T c) {
// LovyanGFX treats signed32 as RGB565, unsigned32 as RGB888.
#if UI_BUFFER_COLOR_DEPTH < 8
marks.push_back(c);
#else
marks.push_back(std::is_signed<T>::value
? mesh::ui::color_theme::rgb888(static_cast<ColorVal>(c)) : c);
#endif
}
};
struct Atlas {
const uint8_t* glyph(uint16_t) const { static uint8_t p[]={255,0xe0,0x1c,3}; return p; }
int width() const { return 2; } int height() const { return 2; }
uint8_t transparent() const { return 255; }
};
struct LGFXDisplay {
Canvas panel; Canvas* display=&panel; Sprite buffer; Atlas _emojiAtlas;
struct EmojiOverlay { uint16_t codepoint; int16_t x,y; uint16_t size; } _emojiOverlays[2];
static const unsigned MAX_EMOJI_OVERLAYS=2;
unsigned _emojiOverlayCount=0,_presentedEmojiOverlayCount=0;
bool _hasTransparentEmojiPixels=false,_nightFrame=false,_hasLastFrame=true;
uint32_t _color=0;
bool wasEmojiPresented(const EmojiOverlay&) { return false; }
void drawEmojiMask(int,int,int,const uint8_t*) { assert(false); }
void drawEmojiUnderlay(int,int,int,const uint8_t*) {}
void startFrame(ColorVal); void setColor(ColorVal); void applyNightPalette();
uint32_t renderColor(ColorVal) const;
int32_t queueEmoji(lgfx::v1::LGFXBase*,int32_t,int32_t,uint32_t,int32_t);
};
'''
harness += '\n'.join(body(source, signature) for signature in (
'void LGFXDisplay::startFrame(', 'void LGFXDisplay::setColor(',
'void LGFXDisplay::applyNightPalette(', 'uint32_t LGFXDisplay::renderColor(',
'int32_t LGFXDisplay::queueEmoji('))
harness += r'''
int main() {
LGFXDisplay d; night=true; d.startFrame(0xffff);
assert(!d._hasLastFrame && d.panel.fill==0 && d.buffer.fill==0);
#if UI_BUFFER_COLOR_DEPTH < 8
assert(d.buffer.palette[0]==0 && d.buffer.palette[1]==0xff0000);
for (unsigned i=1;i<16;++i) assert(d.buffer.palette[i]==0xff0000);
const uint32_t red=1;
const uint32_t physical_red=1;
#else
const uint32_t red=0xf800;
const uint32_t physical_red=0xff0000;
#endif
assert(d.buffer.text==red && d.renderColor(0x07e0)==red);
assert(d.queueEmoji(&d.buffer,0,0,0x1234,4)==4);
assert(d._emojiOverlayCount==0 && !d._hasTransparentEmojiPixels);
assert(d.buffer.marks.size()==3);
for (uint32_t color : d.buffer.marks) assert(color==physical_red);
night=false; d.startFrame(0x3456);
assert(!d._hasLastFrame && d.panel.fill==UIColor::window_bkg);
#if UI_BUFFER_COLOR_DEPTH < 8
assert(d.buffer.palette[0]==UI_PALETTE[0] && d.buffer.palette[1]==UI_PALETTE[1]);
for (unsigned i=0;i<16;++i) assert(d.buffer.palette[i]==UI_PALETTE[i]);
#else
assert(d.buffer.fill==0x3456);
#endif
assert(d.queueEmoji(&d.buffer,0,0,0x1234,4)==4 && d._emojiOverlayCount==1);
}
'''
for depth in (4, 8, 16):
with self.subTest(depth=depth):
self.run_cpp(PREFIX + palette + harness, f'UI_BUFFER_COLOR_DEPTH={depth}')
def test_color_capability_excludes_monochrome_eink_and_null(self):
colors = ('ST7735Display', 'ST7789Display', 'ST7789LCDDisplay', 'NV3001BDisplay',
'LGFXDisplay', 'SCIndicatorDisplay', 'WioTrackerL2Display')
others = ('SSD1306Display', 'SH1106Display', 'SH1107Display', 'U8g2Display',
'GxEPDDisplay', 'E213Display', 'E290Display', 'NullDisplayDriver')
for driver in colors + others:
with self.subTest(driver=driver):
code = '#define DISPLAY_CLASS ' + driver + '\n#include <helpers/ui/DisplayBuildFlags.h>\n'
code += '#ifdef MESHCORE_HAS_COLOR_DISPLAY\nconstexpr bool color=true;\n#else\nconstexpr bool color=false;\n#endif\n'
code += 'static_assert(color == ' + ('true' if driver in colors else 'false') + ', "capability");\n'
compiled = subprocess.run(['c++', '-std=c++11', '-fsyntax-only', '-I', str(ROOT / 'src'),
'-x', 'c++', '-'], input=code, text=True, capture_output=True)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
def test_actual_qr_paths_keep_red_quiet_zone_and_black_modules_at_night(self):
qr_common = r'''
struct QRCode { uint8_t size=21; };
const int ECC_LOW=0;
int qrcode_initText(QRCode* qr,uint8_t*,uint8_t,int,const char*) { qr->size=21;return 0; }
bool qrcode_getModule(const QRCode*,unsigned col,unsigned row) { return col==row || col==0; }
int lgfx_qrcode_initText(QRCode* q,uint8_t* b,uint8_t v,int e,const char* t) { return qrcode_initText(q,b,v,e,t); }
bool lgfx_qrcode_getModule(const QRCode* q,unsigned c,unsigned r) { return qrcode_getModule(q,c,r); }
'''
source = (UI / 'DisplayDriver.cpp').read_text()
generic = r'''
struct QrDisplay {
Canvas canvas; uint32_t color=0;
int width() const { return 128; } int height() const { return 128; }
bool isEink() const { return false; }
void setColor(ColorVal c) { color=mesh::ui::color_theme::render(c); }
void fillRect(int x,int y,int w,int h) { canvas.fillRect(x,y,w,h,color); }
bool drawQrCodeWithBorder(const char*,int,int,int,int);
};
'''
generic += body(source, 'bool DisplayDriver::drawQrCodeWithBorder(').replace('DisplayDriver::', 'QrDisplay::')
generic += r'''
int main() {
for (bool active : {false,true}) {
night=active; QrDisplay d;
assert(d.drawQrCodeWithBorder("X",0,0,64,-1));
assert(d.canvas.marks.size()==42);
assert(d.canvas.marks[0]==(night ? 0xf800 : UIColor::popup_txt));
for (unsigned i=1;i<d.canvas.marks.size();++i)
assert(d.canvas.marks[i]==(night ? 0 : UIColor::window_bkg));
}
}
'''
self.run_cpp(PREFIX + qr_common + generic)
source = (UI / 'LGFXDisplay.cpp').read_text()
lgfx = r'''
struct LGFXDisplay {
Canvas buffer; int _coordinateScale=2;
int width() const { return 128; } int height() const { return 128; }
uint32_t renderColor(ColorVal c) const;
bool drawQrCode(const char*,int,int,int);
};
'''
lgfx += body(source, 'uint32_t LGFXDisplay::renderColor(')
lgfx += body(source, 'bool LGFXDisplay::drawQrCode(')
lgfx += r'''
int main() {
for (bool active : {false,true}) {
night=active; LGFXDisplay d;
assert(d.drawQrCode("X",0,0,64));
assert(d.buffer.marks.size()==42);
#if UI_BUFFER_COLOR_DEPTH < 8
const uint32_t light = 1u;
#else
const uint32_t light = night ? 0xff0000u : UIColor::primary_txt;
#endif
#if UI_BUFFER_COLOR_DEPTH < 8
const uint32_t dark = 0u;
#else
const uint32_t dark = night ? 0u : UIColor::window_bkg;
#endif
assert(d.buffer.marks[0]==light);
for (unsigned i=1;i<d.buffer.marks.size();++i)
assert(d.buffer.marks[i]==dark);
}
}
'''
for depth in (4, 8, 16):
with self.subTest(qr_depth=depth):
self.run_cpp(PREFIX + qr_common + lgfx, f'UI_BUFFER_COLOR_DEPTH={depth}')
if __name__ == '__main__':
unittest.main()
+148
View File
@@ -0,0 +1,148 @@
"""Exercise color-display night controls through real config handlers and UI."""
import json
from pathlib import Path
import unittest
import test_webconfig_lost_reply as web_fixture
ROOT = Path(__file__).resolve().parents[1]
class DisplayNightWebConfigTest(unittest.TestCase):
compile_run = web_fixture.LostReplyWebConfigTest.compile_run
setup_values = web_fixture.LostReplyWebConfigTest.setup_values
run_page = web_fixture.LostReplyWebConfigTest.run_page
def test_actual_snapshot_and_authenticated_cli_batch(self):
fixture = web_fixture.LostReplyWebConfigTest.fixture(self)
fixture = fixture[:fixture.index('String writeBody(')]
for color in (False, True):
with self.subTest(color=color):
source = r'''
#include <cstdint>
#define MESHCORE_HAS_REAL_DISPLAY 1
@COLOR@
namespace mesh { namespace ui {
struct Profile { uint8_t mode=0; uint16_t seconds=15; };
struct Prefs { Profile battery, usb; };
const Prefs& displayPowerPrefs() { static Prefs prefs; return prefs; }
const char* displayModeName(uint8_t) { return "button"; }
bool displayPairingSupported() { return false; }
uint8_t night_mode=2;
int16_t night_delay=60;
bool night_active=false;
uint8_t displayNightMode() { return night_mode; }
int16_t displayNightDelayMinutes() { return night_delay; }
bool displayNightActive() { return night_active; }
}}
'''.replace('@COLOR@', '#define MESHCORE_HAS_COLOR_DISPLAY 1' if color else '') + fixture + r'''
int main() {
assert(mesh::esp32::managementPassword::publish("password"));
for(unsigned mode=0;mode<3;++mode) {
WebConfigServer server;
mesh::ui::night_mode=mode;mesh::ui::night_delay=mode?0:-30;mesh::ui::night_active=mode==1;
AsyncWebServerRequest get;server.handleConfigGet(&get);
JsonDocument snapshot;
assert(get.status==200 && deserializeJson(snapshot,get.output)==DeserializationError::Ok);
#ifdef MESHCORE_HAS_COLOR_DISPLAY
const char* names[]={"off","on","auto"};
assert(snapshot["display"]["night_supported"].as<bool>());
assert(strcmp(snapshot["display"]["night"].as<const char*>(),names[mode])==0);
assert(snapshot["display"]["night_delay"].as<int>()==(mode?0:-30));
assert(snapshot["display"]["night_active"].as<bool>()==(mode==1));
#else
assert(snapshot["display"]["night_supported"].isNull());
assert(snapshot["display"]["night"].isNull());
#endif
}
for(const char* key:{"display.night","display.night.delay"}) {
assert(wcIsAllowedSetKey(key) && !wcSetKeyRequiresReboot(key));
WebConfigServer server;
const char* value=strcmp(key,"display.night")==0?"auto":"-30";
String body=String("{\"reqid\":\"0123456789abcdef\",\"set\":{\"")+key+"\":\""+value+"\"}}";
AsyncWebServerRequest unauthenticated(body);unauthenticated.header.cookies.clear();
server.handleConfigPost(&unauthenticated);
assert(unauthenticated.status==401 && !server._batch_count);
AsyncWebServerRequest save(body);server.handleConfigPost(&save);
assert(save.status==202 && server._batch_count==1 && !server._batch_reboot);
assert(String(server._batch[0].cmd)==String("set ")+key+" "+value);
}
for(const char* key:{"display.night.extra","display.night.delay.extra"})assert(!wcIsAllowedSetKey(key));
}
'''
self.compile_run(source)
def test_color_form_preserves_zero_and_saves_only_changed_night_fields(self):
status, config = self.setup_values()
status.update(mode="lan")
config["display"] = {"mode": "button", "timeout": 15, "usb_mode": "on", "usb_timeout": 15,
"night_supported": True, "night": "auto", "night_delay": 0, "night_active": False}
prelude = r'''<script>
(function(){
var status=%s,config=%s,submitted=null;
function reply(value,code){return Promise.resolve({ok:true,status:code||200,json:function(){return Promise.resolve(value)}})}
window.fetch=function(path,options){
if(path==="/api/status")return reply(status);
if(path==="/api/config"&&(!options||options.method!=="POST"))return reply(config);
if(path==="/api/config"){
submitted=JSON.parse(options.body);config.display.night=submitted.set["display.night"];
config.display.night_delay=Number(submitted.set["display.night.delay"]);
return reply({state:"pending",reqid:submitted.reqid,count:2},202);
}
if(path.indexOf("/api/config/result?")===0)return reply({state:"done",reqid:submitted.reqid,results:[{key:"display.night",reply:"OK"},{key:"display.night.delay",reply:"OK"}]});
return reply({});
};
function mark(key,value){document.body.setAttribute("data-test-night-"+key,String(value))}
window.addEventListener("load",function(){
setTimeout(function(){enterApp()},50);
setTimeout(function(){
var group=document.getElementById("display-night-settings"),mode=group.querySelector('select'),delay=group.querySelector('input');
mark("visible",!group.classList.contains("hide"));mark("enabled",!mode.disabled&&!delay.disabled);
mark("mode",mode.value);mark("delay",delay.value);mark("bounds",delay.min+","+delay.max);
mark("choices",Array.from(mode.options).map(function(o){return o.value}).join(","));
mode.value="on";mode.dispatchEvent(new Event("input",{bubbles:true}));
delay.value="-30";delay.dispatchEvent(new Event("input",{bubbles:true}));appSave();
},650);
setTimeout(function(){
mark("keys",submitted?Object.keys(submitted.set).sort().join(","):"missing");
mark("saved",submitted?submitted.set["display.night"]+","+submitted.set["display.night.delay"]:"missing");
mark("no-reboot",submitted&&!submitted.reboot);mark("clean",!st.dirty["display.night"]&&!st.dirty["display.night.delay"]);
},1800);
});
})();
</script>''' % (json.dumps(status), json.dumps(config))
dom = self.run_page(prelude, virtual_time=2400)
for key, value in (("visible", "true"), ("enabled", "true"), ("mode", "auto"), ("delay", "0"),
("bounds", "-180,180"), ("choices", "auto,on,off"),
("keys", "display.night,display.night.delay"), ("saved", "on,-30"),
("no-reboot", "true"), ("clean", "true")):
self.assertIn('data-test-night-%s="%s"' % (key, value), dom)
def test_monochrome_and_headless_forms_hide_and_disable_night_controls(self):
for display in (None, {"mode": "button", "timeout": 15, "usb_mode": "on", "usb_timeout": 15}):
with self.subTest(display=display):
status, config = self.setup_values()
status.update(mode="lan")
if display is None:
config.pop("display", None)
else:
config["display"] = display
prelude = r'''<script>
window.fetch=function(path){var value=path==="/api/status"?%s:%s;return Promise.resolve({ok:true,status:200,json:function(){return Promise.resolve(value)}})};
window.addEventListener("load",function(){
setTimeout(function(){enterApp()},50);
setTimeout(function(){
var group=document.getElementById("display-night-settings"),body=document.body;
body.setAttribute("data-test-night-hidden",group.classList.contains("hide"));
body.setAttribute("data-test-night-disabled",Array.from(group.querySelectorAll('[data-k]')).every(function(e){return e.disabled}));
body.setAttribute("data-test-night-dirty",Object.keys(st.dirty).length);
},650);
});
</script>''' % (json.dumps(status), json.dumps(config))
dom = self.run_page(prelude)
for key, value in (("hidden", "true"), ("disabled", "true"), ("dirty", "0")):
self.assertIn('data-test-night-%s="%s"' % (key, value), dom)
if __name__ == "__main__":
unittest.main()
+3
View File
@@ -27,6 +27,9 @@ HARNESS = r'''
#include <cstdint>
#include <cstring>
#include <vector>
namespace mesh { namespace ui { namespace color_theme {
constexpr uint16_t render(uint16_t color) { return color; }
}}}
constexpr int INPUT = 0, OUTPUT = 1, LOW = 0, HIGH = 1;
constexpr int PIN_TFT_RST = 1, PIN_TFT_CS = 2, PIN_TFT_DC = 3;
+8 -1
View File
@@ -33,7 +33,7 @@ struct Bus {
class Panel {
public:
int displayWidth,displayHeight,_buffheight;
uint16_t _RGB=0xffff;
uint16_t _RGB=0xffff, _lastRGB=0xffff;
int _spiSettings=0;
Bus bus; Bus* _spi=&bus;
std::vector<uint8_t> front,back;
@@ -57,6 +57,13 @@ int main() {
for(int row:p.rows) assert(row==1);
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
p.display(); assert(p.bus.transfers==p.displayHeight);
// A tint-only night transition must flush even if every monochrome
// framebuffer bit is unchanged, then return to normal dirty suppression.
p._RGB=0xf800; p.display();
assert(p.bus.transfers==2*p.displayHeight);
p.display(); assert(p.bus.transfers==2*p.displayHeight);
p._RGB=0xffff; p.display();
assert(p.bus.transfers==3*p.displayHeight);
#endif
}
}
@@ -16,6 +16,8 @@ TEST(WebConfigKeys, AllowsKnownScalarKeys) {
EXPECT_TRUE(wcIsAllowedSetKey("powersaving"));
EXPECT_TRUE(wcIsAllowedSetKey("repeat"));
EXPECT_TRUE(wcIsAllowedSetKey("display.rotation"));
EXPECT_TRUE(wcIsAllowedSetKey("display.night"));
EXPECT_TRUE(wcIsAllowedSetKey("display.night.delay"));
EXPECT_TRUE(wcIsAllowedSetKey("radio.fem.rxgain")); // Board::handleCommand(), not CommonCLI
EXPECT_TRUE(wcIsAllowedSetKey("radio.fem.txgain"));
EXPECT_TRUE(wcIsAllowedSetKey("wifi.ssid"));
@@ -41,6 +43,8 @@ TEST(WebConfigKeys, RejectsDangerousOrUnknownKeys) {
EXPECT_FALSE(wcIsAllowedSetKey("reboot"));
EXPECT_FALSE(wcIsAllowedSetKey("bogus"));
EXPECT_FALSE(wcIsAllowedSetKey("display.rotation.extra"));
EXPECT_FALSE(wcIsAllowedSetKey("display.night.extra"));
EXPECT_FALSE(wcIsAllowedSetKey("display.night.delay.extra"));
EXPECT_FALSE(wcIsAllowedSetKey("bluetooth.stealth.extra"));
EXPECT_FALSE(wcIsAllowedSetKey("mqtt1.bogus")); // unknown slot field
EXPECT_FALSE(wcIsAllowedSetKey(""));
+1 -1
View File
@@ -193,7 +193,7 @@ window.addEventListener("load",function(){
</script>''' % (json.dumps(status), json.dumps(config))
dom = self.run_page(prelude)
for attribute, value in (
("display-visible", "true"), ("display-count", "5"),
("display-visible", "true"), ("display-count", "7"),
("battery-timeout", "23"), ("usb-timeout", "55"),
("usb-disabled", "true"), ("pairing-disabled", "true"),
("rotation-hidden", "true"), ("rotation-disabled", "true"),
@@ -17,6 +17,9 @@ ARDUINO = r'''
#include <cstdint>
#include <string>
#include <vector>
namespace mesh { namespace ui { namespace color_theme {
constexpr uint16_t render(uint16_t color) { return color; }
}}}
#define LOW 0
#define HIGH 1
#define INPUT 0