Add Dark mode for a screen beside the bed, with every colour in one table (0.2.63)
Dark mode is a new switch under Brightness on the screen's settings page, in the Screen settings of ESP Screens and as switch.<screen>_dark_mode in Home Assistant, so an automation can turn it on at bedtime. The screen changes look at once, open cards and an alert included, and keeps it after a restart. The design stays the same: a black page, graphite cards with a hairline, soft white text, Home Assistant's state colours where they tell something, and pastel card colours as deeper versions of themselves. Every colour the firmware chooses now lives in components/smart_display/ theme.h: roles with a light and a dark value, the named card colours and Home Assistant's state colours. The board profiles give widgets colourless shared styles that theme.h fills, so a change of look refills those styles and draws again what code painted by state. The light look is unchanged apart from merges below one panel step. Dark mode costs 440 bytes of static RAM on the CYD, and the LVGL tree of the host build is 416 bytes smaller; tests keep colours out of every other file. Comparing a screen that switched looks with one that booted in it also found two older bugs, now fixed: a settings switch that was on showed its knob at the left whenever its page was drawn, and the sun card's sunlit area turned orange after a palette change. Firmware 0.2.54. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
#define THEME_TEST
|
||||
#include "components/smart_display/alert_overlay.h"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
@@ -12,11 +13,13 @@ int main() {
|
||||
// Unknown names, a codepoint the fonts lack and junk draw the warning triangle.
|
||||
for (const char *icon : {"", "unknown", "mdi:", "F0000", "F12E", "\xF0\x9F\x94\x94", "mdi:not-in-the-set"})
|
||||
assert(screen_alert::icon_codepoint(icon) == 0xF002A);
|
||||
// Colour: palette names in any case; empty, none and anything unknown keep the white card.
|
||||
// Colour: palette names in any case; empty, none and anything unknown keep the normal card.
|
||||
assert(make("x", "", "", "Red", "", 0, false, 48, 160, 12).color == 0xFADADD);
|
||||
assert(make("x", "", "", " mint ", "", 0, false, 48, 160, 12).color == 0xD5F0EA);
|
||||
for (const char *color : {"", "none", "auto", "#ff0000", "0xFF0000"})
|
||||
assert(make("x", "", "", color, "", 0, false, 48, 160, 12).color == 0xFFFFFF);
|
||||
assert(make("x", "", "", color, "", 0, false, 48, 160, 12).color == screen_alert::DEFAULT_CARD_COLOR);
|
||||
// The normal card is no colour of its own: the look draws it (theme::surface(0)).
|
||||
assert(screen_alert::DEFAULT_CARD_COLOR == 0);
|
||||
// Timeout: 0 and negatives wait for OK; a day is the ceiling.
|
||||
assert(make("x", "", "", "", "", 0, false, 48, 160, 12).timeout_seconds == 0);
|
||||
assert(make("x", "", "", "", "", -5, false, 48, 160, 12).timeout_seconds == 0);
|
||||
|
||||
@@ -34,10 +34,10 @@ class ReferenceTests(unittest.TestCase):
|
||||
|
||||
def test_colours_icons_and_fallback_match_the_firmware_headers(self):
|
||||
reference = alert_reference()
|
||||
palette = (ROOT / 'components/smart_display/tile_palette.h').read_text()
|
||||
self.assertEqual([c['name'] for c in reference['colors']], re.findall(r'if\(name=="(\w+)"\)return 0x', palette))
|
||||
palette = (ROOT / 'components/smart_display/theme.h').read_text()
|
||||
self.assertEqual([c['name'] for c in reference['colors']], re.findall(r'\{"(\w+)", 0x[0-9A-F]{6}, 0x[0-9A-F]{6}\}', palette))
|
||||
for colour in reference['colors']:
|
||||
self.assertIn(f'if(name=="{colour["name"]}")return 0x{colour["color"][1:]};', palette)
|
||||
self.assertRegex(palette, rf'\{{"{colour["name"]}", 0x{colour["color"][1:]}, 0x[0-9A-F]{{6}}\}}')
|
||||
self.assertEqual(colour['label'], TILE_BACKGROUNDS[colour['name']]['label'])
|
||||
header = (ROOT / 'components/smart_display/alert_overlay.h').read_text()
|
||||
self.assertIn(f'FALLBACK_ICON = "{reference["fallback_icon"]}"', header)
|
||||
|
||||
@@ -13,7 +13,7 @@ import claude_skill # noqa: E402
|
||||
import tile_icons # noqa: E402
|
||||
from core import (ALERT_EVENT, ALERT_FIELDS, ALERT_LIMITS, ALERT_MIN_FIRMWARE, AUTO_STANDBY_MIN_FIRMWARE, BROADCAST_DISMISS, # noqa: E402
|
||||
BROADCAST_SHOW, CONTROLS, DISPLAYS, TILE_BACKGROUNDS, TILE_EVENTS, TILE_RESULT_EVENT,
|
||||
WAKE_SLEEP_MIN_FIRMWARE)
|
||||
WAKE_SLEEP_MIN_FIRMWARE, DARK_MODE_MIN_FIRMWARE)
|
||||
|
||||
HAS_YAML = importlib.util.find_spec('yaml') is not None
|
||||
HAS_AIOHTTP = importlib.util.find_spec('aiohttp') is not None
|
||||
@@ -56,6 +56,9 @@ class SkillText(unittest.TestCase):
|
||||
for entity in ('button.<screen>_wake', 'button.<screen>_sleep'):
|
||||
self.assertIn(f'`{entity}`', standby)
|
||||
self.assertIn(f'Firmware {WAKE_SLEEP_MIN_FIRMWARE} or newer', standby)
|
||||
# Dark mode (0.2.63): the switch and the firmware that has it.
|
||||
self.assertIn('`switch.<screen>_dark_mode`', standby)
|
||||
self.assertIn(f'Firmware {DARK_MODE_MIN_FIRMWARE} or newer', standby)
|
||||
self.assertIn('`button.press`', standby)
|
||||
self.assertIn('(#standby-and-brightness)', text, 'the intro links to the section')
|
||||
# Tiles (0.2.51): the events, what a tile can do per domain, how to read a screen and the rule to ask first.
|
||||
@@ -78,7 +81,7 @@ class SkillText(unittest.TestCase):
|
||||
def test_every_yaml_example_parses(self):
|
||||
import yaml
|
||||
blocks = re.findall(r'```yaml\n(.*?)```', claude_skill.text(), re.S)
|
||||
self.assertEqual(len(blocks), 9)
|
||||
self.assertEqual(len(blocks), 10)
|
||||
parsed = [yaml.safe_load(block) for block in blocks]
|
||||
# Tiles first (0.2.51): putting one on a screen, and ordering a page.
|
||||
self.assertEqual(parsed[0]['actions'][0]['event'], 'esp_screens_add_tile')
|
||||
@@ -112,6 +115,14 @@ class SkillText(unittest.TestCase):
|
||||
watched = set(awake['triggers'][0]['entity_id'])
|
||||
conditions = {branch['if'][0]['entity_id']} | {c['entity_id'] for c in branch['if'][1]['conditions']}
|
||||
self.assertEqual(watched, conditions, 'the automation reacts to every entity its condition reads')
|
||||
# Dark mode at night (0.2.63): one automation that turns the switch on at one time and off at the other.
|
||||
night = parsed[8]
|
||||
self.assertEqual({trigger['id'] for trigger in night['triggers']}, {'night', 'day'})
|
||||
branch = night['actions'][0]
|
||||
self.assertEqual((branch['if'][0]['condition'], branch['if'][0]['id']), ('trigger', 'night'))
|
||||
self.assertEqual((branch['then'][0]['action'], branch['else'][0]['action']), ('switch.turn_on', 'switch.turn_off'))
|
||||
for step in (branch['then'][0], branch['else'][0]):
|
||||
self.assertTrue(step['target']['entity_id'].endswith('_dark_mode'))
|
||||
|
||||
|
||||
class Archive(unittest.TestCase):
|
||||
|
||||
@@ -13,6 +13,7 @@ import header_bar # noqa: E402
|
||||
import tile_icons # noqa: E402
|
||||
|
||||
TILES = (ROOT / 'components/smart_display/runtime_tiles.h').read_text()
|
||||
THEME = (ROOT / 'components/smart_display/theme.h').read_text()
|
||||
|
||||
|
||||
class OffLook(unittest.TestCase):
|
||||
@@ -23,7 +24,9 @@ class OffLook(unittest.TestCase):
|
||||
|
||||
def test_the_screen_crosses_out_its_own_bulb_and_greys_what_is_off(self):
|
||||
self.assertIn('if (d == "light" && tile.state == "off") return "\\U000F0E4F";', TILES)
|
||||
self.assertIn('(t.is_switch()||d=="light"||d=="binary_sensor"||d=="person"||d=="timer") && !on ? 0x9E9E9E : accent', TILES)
|
||||
self.assertIn('(t.is_switch()||d=="light"||d=="binary_sensor"||d=="person"||d=="timer") && !on ? theme::STATE_OFF : accent', TILES)
|
||||
self.assertIn('constexpr uint32_t STATE_OFF = ha::GREY;', THEME)
|
||||
self.assertIn('constexpr uint32_t GREY = 0x9E9E9E;', THEME)
|
||||
|
||||
def test_the_top_bar_does_the_same(self):
|
||||
light = lambda state, **attrs: {'state': state, 'attributes': attrs}
|
||||
|
||||
@@ -47,11 +47,12 @@ ENTITY_IDS = {
|
||||
'clock_24h': 'switch.office_1_24_hour_clock', 'auto_home': 'switch.office_1_back_to_page_1',
|
||||
'auto_home_seconds': 'number.office_1_back_to_page_1_after', 'home_on_standby': 'switch.office_1_back_to_page_1_on_standby',
|
||||
'swipe_pages': 'switch.office_1_swipe_between_pages', 'rotation': 'select.office_1_rotation',
|
||||
'dark_mode': 'switch.office_1_dark_mode',
|
||||
}
|
||||
STATES = {'brightness': '80.0', 'standby_enabled': 'on', 'standby_seconds': '600.0', 'standby_brightness': '20.0',
|
||||
'night_enabled': 'on', 'night_start': '22:30:00', 'night_end': '07:00:00', 'night_brightness': '5.0',
|
||||
'clock_24h': 'on', 'auto_home': 'on', 'auto_home_seconds': '120.0', 'home_on_standby': 'off',
|
||||
'swipe_pages': 'on', 'rotation': '90°'}
|
||||
'swipe_pages': 'on', 'rotation': '90°', 'dark_mode': 'off'}
|
||||
|
||||
|
||||
def top_block(text, key):
|
||||
@@ -296,6 +297,34 @@ class OlderFirmware(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual([message['op'] for message, _ in m.ha.messages], ['layout'], 'the tiles are not sent again')
|
||||
self.assertEqual(m.ha.messages[0][0]['settings']['standby_seconds'], 1800)
|
||||
|
||||
async def test_dark_mode_needs_a_screen_that_owns_its_settings(self):
|
||||
# Firmware that gets its settings with the layout has no dark look: no row, no key on the wire, no change.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
m = Manager(fake_ha(firmware='0.2.48', owned=False), Path(tmp) / 'screens.json')
|
||||
m.save('text.screen', {'title': 'Office 1', 'tiles': [{'entity': 'light.a', 'name': ''}],
|
||||
'settings': validate_settings({'dark_mode': True})})
|
||||
screen = m.screen('text.screen')
|
||||
self.assertNotIn('dark_mode', m.settings_view(screen)['keys'])
|
||||
message = m.layout_message('text.screen', m.layouts['text.screen'], screen)
|
||||
self.assertNotIn('dark_mode', message)
|
||||
self.assertNotIn('dark_mode', message['settings'], 'never inside the frozen eleven-key block')
|
||||
self.assertEqual(len(message['settings']), 11)
|
||||
with self.assertRaises(ValueError):
|
||||
await m.change_settings('text.screen', {'dark_mode': True})
|
||||
# Firmware 0.2.49-0.2.53 owns its settings but lacks the switch: left out, not unknown.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
m = Manager(fake_ha(firmware='0.2.53'), Path(tmp) / 'screens.json')
|
||||
m.ha.registry = [item for item in m.ha.registry if item['entity_id'] != ENTITY_IDS['dark_mode']]
|
||||
view = m.settings_view(m.screen('text.screen'))
|
||||
self.assertNotIn('dark_mode', view['keys'] + view['unavailable'])
|
||||
# Firmware 0.2.54: the switch of the screen itself.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
m = Manager(fake_ha(), Path(tmp) / 'screens.json')
|
||||
m.save('text.screen', {'title': 'Office 1', 'tiles': [{'entity': 'light.a', 'name': ''}]})
|
||||
self.assertFalse(m.settings_view(m.screen('text.screen'))['values']['dark_mode'])
|
||||
await m.change_settings('text.screen', {'dark_mode': True})
|
||||
self.assertEqual(m.ha.calls, [('switch.turn_on', {'entity_id': ENTITY_IDS['dark_mode']})])
|
||||
|
||||
async def test_back_to_page_1_needs_firmware_0_2_44(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
m = Manager(fake_ha(firmware='0.2.43', owned=False, guition=False), Path(tmp) / 'screens.json')
|
||||
|
||||
@@ -43,6 +43,11 @@ int main() {
|
||||
assert(moment_text(1320, false) == "10:00 PM" && moment_text(0, false) == "12:00 AM");
|
||||
assert(moment_text(750, false) == "12:30 PM" && moment_text(60, false) == "1:00 AM");
|
||||
|
||||
// ---- a switch's knob: inset at the left when off, flush with the same inset at the right when on ----
|
||||
// The Guition switch is 62 by 34 (a 28 px knob), the CYD one 40 by 22 (an 18 px knob).
|
||||
assert(knob_x(62, 34, false) == 3 && knob_x(62, 34, true) == 31 && 31 + 28 + 3 == 62);
|
||||
assert(knob_x(40, 22, false) == 2 && knob_x(40, 22, true) == 20 && 20 + 18 + 2 == 40);
|
||||
|
||||
// ---- rows read and write the real settings ----
|
||||
screen_settings::current = screen_settings::Settings{};
|
||||
const Page &light = pages[1];
|
||||
@@ -58,6 +63,14 @@ int main() {
|
||||
standby.write(90);
|
||||
assert(screen_settings::current.standby_brightness == 30); // never above the normal brightness
|
||||
assert(screen_settings::current.valid());
|
||||
// Dark mode (firmware 0.2.54+) sits right under Brightness, a switch of its own outside the frozen block.
|
||||
assert(light.count == 5 && light.rows[1].kind == Kind::toggle && std::string(light.rows[1].label) == "Dark mode");
|
||||
const Row &dark = row_named(light, "Dark mode");
|
||||
assert(value_text(dark) == "Off");
|
||||
dark.write(1);
|
||||
assert(dark_mode == 1 && value_text(dark) == "On");
|
||||
dark.write(0);
|
||||
assert(dark_mode == 0 && value_text(dark) == "Off");
|
||||
|
||||
const Page &screen = pages[3];
|
||||
const Row &clock = row_named(screen, "Clock");
|
||||
@@ -138,6 +151,7 @@ int main() {
|
||||
{"night_start", -5, 0}, {"night_end", 2000, 1439}, {"night_brightness", 7, 7}, {"clock_24h", 0, 0},
|
||||
{"home_on_standby", 1, 1}, {"swipe_pages", 2, 1}, {"rotation", 100, 90}, {"rotation", 400, 270},
|
||||
{"auto_home", 0, 0}, {"auto_home_seconds", 5, 30}, {"auto_home_seconds", 99999, 3600},
|
||||
{"dark_mode", 7, 1},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
result = set(c.key, c.value);
|
||||
@@ -146,8 +160,15 @@ int main() {
|
||||
}
|
||||
assert(screen_settings::current.standby_seconds == 86400 && screen_settings::current.brightness == 100);
|
||||
assert(screen_settings::current.night_start == 0 && screen_settings::current.night_end == 1439);
|
||||
assert(swipe_pages == 1 && rotation == 270 && auto_home == 0 && auto_home_seconds == 3600);
|
||||
assert(swipe_pages == 1 && rotation == 270 && auto_home == 0 && auto_home_seconds == 3600 && dark_mode == 1);
|
||||
assert(screen_settings::current.valid());
|
||||
// Dark mode again is the same look: nothing stored, applied or reported; off is a change.
|
||||
{
|
||||
const int stored_before = stored, applied_before = applied;
|
||||
assert(set("dark_mode", 1) == SetResult::same && stored == stored_before && applied == applied_before);
|
||||
assert(set("dark_mode", 0) == SetResult::changed && last_key == "dark_mode" && last_value == 0 && dark_mode == 0);
|
||||
set("dark_mode", 1);
|
||||
}
|
||||
// A lower brightness pulls both dim levels down, and reports the brightness itself.
|
||||
set("standby_brightness", 60);
|
||||
set("night_brightness", 50);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// The colour table (firmware 0.2.54): the light look stays the design it was, the dark look reads well beside a bed.
|
||||
// clang++ -std=c++17 -Wall -Wextra -Werror -I. tests/test_theme.cpp -o /tmp/test_theme && /tmp/test_theme
|
||||
#define THEME_TEST
|
||||
#include "components/smart_display/theme.h"
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace theme;
|
||||
|
||||
static double channel(uint32_t value) {
|
||||
const double c = value / 255.0;
|
||||
return c <= 0.04045 ? c / 12.92 : std::pow((c + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
static double luminance(uint32_t color) {
|
||||
return 0.2126 * channel(color >> 16 & 0xFF) + 0.7152 * channel(color >> 8 & 0xFF) + 0.0722 * channel(color & 0xFF);
|
||||
}
|
||||
// WCAG contrast ratio of two colours.
|
||||
static double contrast(uint32_t a, uint32_t b) {
|
||||
double la = luminance(a), lb = luminance(b);
|
||||
if (la < lb) std::swap(la, lb);
|
||||
return (la + 0.05) / (lb + 0.05);
|
||||
}
|
||||
static int channel_gap(uint32_t a, uint32_t b) {
|
||||
int gap = 0;
|
||||
for (int shift = 0; shift <= 16; shift += 8) gap = std::max(gap, std::abs(int(a >> shift & 0xFF) - int(b >> shift & 0xFF)));
|
||||
return gap;
|
||||
}
|
||||
static void look(bool on) { dark = on; }
|
||||
|
||||
int main() {
|
||||
// ---- the light look is the design as it was
|
||||
assert(ROLES[PAGE].light == 0xE7E7E7 && ROLES[CARD].light == 0xFFFFFF && ROLES[LINE].light == 0xDDDDDD);
|
||||
assert(ROLES[INK].light == 0x1B1B1B && ROLES[MUTED].light == 0x616161 && ROLES[SLATE].light == 0x46525E);
|
||||
assert(ROLES[ACCENT].light == 0x009FE3 && ROLES[OFF].light == ha::GREY && ROLES[KNOB].light == 0xFFFFFF);
|
||||
look(false);
|
||||
assert(hex(PAGE) == 0xE7E7E7 && hex(INK) == 0x1B1B1B);
|
||||
|
||||
// ---- mixing is LVGL's own: the ends are the two colours, the middle rounds down
|
||||
assert(mix(0x123456, 0xABCDEF, 255) == 0x123456 && mix(0x123456, 0xABCDEF, 0) == 0xABCDEF);
|
||||
assert(mix(0xFFFFFF, 0x000000, 128) == 0x808080);
|
||||
// The old tile circle (the state colour at 38 over white) and icon (at 205 over #333333) are exactly what tint() and
|
||||
// icon() give in the light look.
|
||||
for (uint32_t accent : {ha::AMBER, ha::TEAL, ha::INDIGO, ha::DEEP_ORANGE, ha::GREY}) {
|
||||
assert(tint(accent, 38) == mix(accent, 0xFFFFFF, 38));
|
||||
assert(icon(accent) == mix(accent, 0x333333, 205));
|
||||
assert(state(accent) == accent && foreground(accent) == accent);
|
||||
}
|
||||
// The halos and cover tracks that were written out by hand before are the same colours within two steps.
|
||||
assert(channel_gap(tint(ha::TEAL, 36), 0xDCF0EE) <= 2 && channel_gap(tint(ha::BLUE, 36), 0xE1EFFD) <= 2);
|
||||
assert(channel_gap(tint(ha::ORANGE, 36), 0xFFF0DA) <= 2 && channel_gap(tint(ha::RED, 36), 0xFDE4E2) <= 2);
|
||||
assert(channel_gap(tint(ha::SKY, 22), 0xEAF5FC) <= 2);
|
||||
assert(channel_gap(tint(ha::PURPLE, 37), 0xEFE8F7) <= 2 && channel_gap(tint(ha::PURPLE, 80), 0xDDD0EF) <= 2);
|
||||
assert(fill_opacity() == 51);
|
||||
|
||||
// ---- named card colours: identity in light, deep in dark, the normal card for none or an unknown colour
|
||||
assert(SWATCH_COUNT == 9 && swatch("red") == 0xFADADD && swatch("gray") == 0xE5E7EB && swatch("none") == 0 && swatch("") == 0);
|
||||
assert(surface(0) == 0xFFFFFF && surface(0xFADADD) == 0xFADADD && surface(0x123456) == 0x123456);
|
||||
assert(outline(0) == 0xDDDDDD && outline(0xFADADD) == mix(0xFADADD, 0x000000, 220));
|
||||
assert(key_on(0xFFFFFF, 236) == mix(0xFFFFFF, 0x000000, 236));
|
||||
|
||||
// ---- the dark look
|
||||
look(true);
|
||||
assert(hex(PAGE) == 0x000000);
|
||||
assert(surface(0) == ROLES[CARD].dark && surface(0x123456) == ROLES[CARD].dark);
|
||||
for (const auto &s : SWATCHES) {
|
||||
assert(surface(s.light) == s.dark);
|
||||
// Light words read on every dark card colour, the slate of a value too.
|
||||
assert(contrast(ROLES[INK].dark, s.dark) >= 7.0);
|
||||
assert(contrast(ROLES[SLATE].dark, s.dark) >= 4.5);
|
||||
assert(contrast(ROLES[INK].light, s.light) >= 7.0);
|
||||
}
|
||||
// Text reads in both looks: names and values, secondary and quiet words, the top bar on the page.
|
||||
for (bool on : {false, true}) {
|
||||
look(on);
|
||||
assert(contrast(hex(INK), hex(CARD)) >= 7.0 && contrast(hex(INK), hex(PAGE)) >= 7.0);
|
||||
assert(contrast(hex(MUTED), hex(CARD)) >= 4.5 && contrast(hex(SUBTLE), hex(CARD)) >= 4.5);
|
||||
assert(contrast(hex(SLATE), hex(PAGE)) >= 4.5 && contrast(hex(INK_SOFT), hex(RAISED)) >= 4.5);
|
||||
assert(contrast(hex(INK), hex(RAISED)) >= 7.0 && contrast(hex(INK), hex(TRACK)) >= 7.0);
|
||||
assert(contrast(hex(ON_ACCENT), hex(BUTTON_DARK)) >= 4.5);
|
||||
}
|
||||
// The blue keys keep at least the contrast they always had (white on #009FE3, just under 3:1).
|
||||
look(false);
|
||||
const double blue_light = contrast(hex(ON_ACCENT), hex(ACCENT));
|
||||
look(true);
|
||||
assert(blue_light > 2.9 && contrast(hex(ON_ACCENT), hex(ACCENT)) >= blue_light);
|
||||
look(true);
|
||||
// Surfaces step up from the black page, a raised card and a key under a finger stand out.
|
||||
assert(lightness(hex(PAGE)) < lightness(hex(CARD)) && lightness(hex(CARD)) < lightness(hex(LINE)));
|
||||
assert(lightness(hex(CARD)) < lightness(hex(RAISED)) && lightness(hex(KEY)) < lightness(hex(KEY_PRESSED)));
|
||||
assert(lightness(hex(CARD)) < 40 && lightness(hex(INK)) > 200);
|
||||
// Dark greys land on the same step of red, green and blue on the panel (RGB565), so they stay grey.
|
||||
for (int role = 0; role < ROLE_COUNT; ++role) {
|
||||
const uint32_t c = ROLES[role].dark;
|
||||
const uint32_t r = c >> 16 & 0xFF, g = c >> 8 & 0xFF, b = c & 0xFF;
|
||||
if (r == g && g == b && r > 0 && r < 0xFF) assert((r >> 3) * 2 == (g >> 2));
|
||||
}
|
||||
|
||||
// ---- Home Assistant's colours in the dark look
|
||||
assert(state(ha::GREY) == ROLES[OFF].dark && state(0xCFCFCF) == ROLES[HISTORY_OFF].dark && state(0xE6E6E6) == ROLES[HISTORY_EMPTY].dark);
|
||||
assert(state(ha::AMBER) == ha::AMBER && state(ha::TEAL) == ha::TEAL);
|
||||
// Bright state colours stay themselves; the deep ones are lifted until they read on graphite.
|
||||
assert(foreground(ha::AMBER) == ha::AMBER && foreground(ha::LIGHT_BLUE) == ha::LIGHT_BLUE);
|
||||
for (uint32_t deep : {ha::INDIGO, ha::DEEP_PURPLE, uint32_t{0}}) {
|
||||
assert(lightness(foreground(deep)) > lightness(deep));
|
||||
assert(contrast(foreground(deep), hex(CARD)) >= 3.0);
|
||||
}
|
||||
// A circle stays dark and tinted, its icon light; a slider track stays dark.
|
||||
for (uint32_t accent : {ha::AMBER, ha::TEAL, ha::INDIGO, ha::GREY, ha::DEEP_ORANGE}) {
|
||||
assert(lightness(tint(accent, 38)) < 110 && lightness(tint(accent, 51)) < 120);
|
||||
assert(contrast(icon(accent), tint(accent, 38)) >= 3.0);
|
||||
}
|
||||
// Keys in a card are lighter than the card, its hairline too.
|
||||
assert(lightness(key_on(hex(CARD), 236)) > lightness(hex(CARD)));
|
||||
assert(lightness(outline(0xFADADD)) > lightness(surface(0xFADADD)));
|
||||
assert(fill_opacity() < 51);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Colours live in one place, and Dark mode reaches every screen (app 0.2.63 / firmware 0.2.54).
|
||||
|
||||
components/smart_display/theme.h holds every colour the firmware chooses: roles with a light and a dark value, the named
|
||||
card colours and Home Assistant's state colours. The board profiles name paints (shared LVGL styles theme.h fills) and
|
||||
the firmware asks theme.h for roles, so a new look is a refill of a few styles plus one redraw. These tests keep it that
|
||||
way: no colour written anywhere else, every paint defined and filled, and the look applied at boot and after
|
||||
every settings change. tests/test_theme.cpp checks the values themselves.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'screen_manager/app'))
|
||||
from core import DARK_MODE_MIN_FIRMWARE, FIRMWARE_VERSION, SETTING_ENTITIES, SETTING_RULES, SETTINGS_BESIDE_BLOCK # noqa: E402
|
||||
|
||||
COMPONENT = ROOT / 'components/smart_display'
|
||||
THEME = (COMPONENT / 'theme.h').read_text()
|
||||
PROFILES = [ROOT / 'home-like-2432s028.yaml', ROOT / 'guition-4848s040.yaml', ROOT / 'packages/cyd.yaml', ROOT / 'packages/guition.yaml']
|
||||
HEX = re.compile(r'0x[0-9A-Fa-f]{6}\b')
|
||||
# What may still carry a number that looks like a colour: the light's colour picker shows the colours a light can take,
|
||||
# a mask and a codepoint check are no colours, and the value card's colour key is a wheel of fixed hues.
|
||||
ALLOWED_IN_FIRMWARE = {
|
||||
'light_controls.h': ('constexpr uint32_t WARM = 0xFF9C32, COOL = 0xC6E6FF;',
|
||||
'inline constexpr uint32_t RAINBOW[] = {0xFF0000, 0xFFFF00, 0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, 0xFF0000};'),
|
||||
'tile_icon.h': ('if (cp < 0x10000 || cp > 0x10FFFF) return {};',),
|
||||
'runtime_tiles.h': ('state_color=lv_color_to_u32(lv_color_hsv_to_rgb(t.hue%360,t.saturation,100))&0xFFFFFF;',),
|
||||
}
|
||||
COLOUR_WHEEL = {'0xFF3B30', '0xFF9500', '0xFFD60A', '0x30D158', '0x32D6FF', '0x0A84FF', '0x5856D6', '0xBF5AF2'}
|
||||
|
||||
|
||||
def paint_names():
|
||||
block = re.search(r'enum class Paint : uint8_t \{(.*?)\};', THEME, re.S)[1]
|
||||
return [name.strip() for name in block.replace('\n', ' ').split(',') if name.strip() and name.strip() != 'COUNT']
|
||||
|
||||
|
||||
class OnePlace(unittest.TestCase):
|
||||
def test_no_header_writes_a_colour_of_its_own(self):
|
||||
for path in sorted(COMPONENT.glob('*.h')):
|
||||
if path.name == 'theme.h':
|
||||
continue
|
||||
for number, line in enumerate(path.read_text().splitlines(), 1):
|
||||
if HEX.search(line):
|
||||
self.assertIn(line.strip(), ALLOWED_IN_FIRMWARE.get(path.name, ()), f'{path.name}:{number}: a colour outside theme.h')
|
||||
|
||||
def test_no_profile_writes_a_colour_of_its_own(self):
|
||||
for path in PROFILES:
|
||||
text = path.read_text()
|
||||
wheel = re.findall(r'^\s+arc_color: (0x[0-9A-F]{6})$', text, re.M)
|
||||
self.assertEqual(set(wheel), COLOUR_WHEEL, path.name)
|
||||
everything = HEX.findall(text)
|
||||
self.assertEqual(sorted(everything), sorted(wheel), f'{path.name}: only the colour wheel keeps fixed hues')
|
||||
self.assertNotIn('BG_TOP_COLOR', text)
|
||||
self.assertNotIn('ACCENT_AUTO', text)
|
||||
self.assertNotRegex(text, r'^\s+(bg|text|border|bg_grad|line|outline|shadow)_color:', path.name)
|
||||
|
||||
def test_every_role_has_a_light_and_a_dark_value(self):
|
||||
roles = re.search(r'enum Role : uint8_t \{(.*?)ROLE_COUNT', THEME, re.S)[1]
|
||||
names = re.findall(r'^\s+([A-Z_]+),', roles, re.M)
|
||||
values = re.findall(r'/\* (\w+) \*/\s+\{0x([0-9A-F]{6}), 0x([0-9A-F]{6})\}', THEME)
|
||||
self.assertEqual(names, [name for name, _, _ in values], 'the table follows the enum, one row per role')
|
||||
self.assertGreater(len(names), 40)
|
||||
|
||||
|
||||
class Paints(unittest.TestCase):
|
||||
def test_every_paint_is_defined_adopted_and_used_in_every_profile(self):
|
||||
paints = paint_names()
|
||||
for path in PROFILES:
|
||||
text = path.read_text()
|
||||
defined = re.findall(r'^ - id: (paint_\w+)$', text, re.M)
|
||||
used = set(re.findall(r'styles: (paint_\w+)$', text, re.M))
|
||||
filling = text.split('theme::paints = []() {', 1)[1].split('\n };', 1)[0]
|
||||
explicit = re.findall(r'theme::fill\(id\((\w+)\), Paint::(\w+)\);', filling)
|
||||
listed = re.search(r'for \(auto \*style : \{([^}]*)\}\) theme::fill\(style, Paint::(\w+)\);', filling)
|
||||
looped = [(name, listed[2]) for name in re.findall(r'id\((\w+)\)', listed[1])]
|
||||
adopted = dict(explicit + looped)
|
||||
self.assertEqual(len(adopted), len(explicit) + len(looped), f'{path.name}: every style is filled once')
|
||||
self.assertEqual(text.count('theme::fill('), len(explicit) + 1, f'{path.name}: styles are filled in theme::paints only')
|
||||
self.assertEqual(set(defined), used, f'{path.name}: every paint style is used, every used one defined')
|
||||
for style in defined + ['style_page', 'style_tile', 'style_icon_circle', 'style_room', 'style_time', 'style_title',
|
||||
'style_value', 'style_value_big']:
|
||||
self.assertIn(style, adopted, f'{path.name}: {style} takes its colours from theme.h')
|
||||
self.assertIn(adopted[style], paints, f'{path.name}: {style}')
|
||||
for style, paint in adopted.items():
|
||||
if style.startswith('paint_'):
|
||||
self.assertEqual(style, f'paint_{paint}', f'{path.name}: a paint style is named after its paint')
|
||||
# The styles that carry colours have none written down.
|
||||
styles = re.search(r'^ style_definitions:\n(.*?)^ # ---------- ALERT', text, re.M | re.S)[1]
|
||||
self.assertNotRegex(styles, r'_color:', path.name)
|
||||
|
||||
def test_the_look_is_applied_at_boot_after_a_change_and_drawn_again(self):
|
||||
for path in PROFILES:
|
||||
text = path.read_text()
|
||||
boot = text.split('runtime_tiles::load_settings();', 1)[1].split('runtime_tiles::settings_changed', 1)[0]
|
||||
self.assertIn('theme::paints();\n theme::set_dark(settings_screen::dark_mode != 0);', boot,
|
||||
f'{path.name}: the paints filled, then the saved look, before the first frame')
|
||||
apply = text.split(' - id: apply_screen_settings\n', 1)[1].split('\n - id: ', 1)[0]
|
||||
self.assertIn('theme::set_dark(settings_screen::dark_mode != 0);', apply, f'{path.name}: a change of the setting')
|
||||
redraw = text.split('theme::redraw = []() {', 1)[1].split('};', 1)[0]
|
||||
for needle in ('runtime_tiles::restyle();', 'light_controls::restyle();', 'settings_screen::restyle();',
|
||||
'theme::surface(id(alert_card_color))', 'id(climate_card_refresh).execute();',
|
||||
'id(open_climate_mode_picker).execute();'):
|
||||
self.assertIn(needle, redraw, f'{path.name}: {needle}')
|
||||
self.assertIn('id(alert_card_color) = alert.color;', text)
|
||||
self.assertIn('lv_color_hex(theme::surface(alert.color))', text)
|
||||
|
||||
def test_the_firmware_draws_long_lived_parts_with_paints(self):
|
||||
tiles = (COMPONENT / 'runtime_tiles.h').read_text()
|
||||
for needle in ('lv_obj_add_style(w.slider,theme::style(theme::Paint::knob),LV_PART_KNOB);',
|
||||
'lv_obj_add_style(w.busy,theme::style(theme::Paint::veil),0);',
|
||||
'lv_obj_add_style(w.spinner,theme::style(theme::Paint::spinner),LV_PART_MAIN);',
|
||||
'lv_obj_add_style(part, theme::style(theme::Paint::slate), 0);',
|
||||
'inline void restyle() {'):
|
||||
self.assertIn(needle, tiles)
|
||||
# Dark mode is kept in a preference of its own, next to the others outside the frozen settings block.
|
||||
self.assertIn('make_preference<uint32_t>(0x44524B31)', tiles)
|
||||
self.assertIn('inline void restyle() {', (COMPONENT / 'settings_screen.h').read_text())
|
||||
self.assertIn('inline void restyle() {', (COMPONENT / 'light_controls.h').read_text())
|
||||
|
||||
|
||||
class RedrawnTheSame(unittest.TestCase):
|
||||
"""A change of look draws again what was drawn, and the renders compare a screen that switched with one that
|
||||
booted in that look. Two differences they found were older than Dark mode: what a page showed depended on the
|
||||
order it was drawn in."""
|
||||
|
||||
def test_a_switch_knob_follows_the_size_it_was_given(self):
|
||||
page = (COMPONENT / 'settings_screen.h').read_text()
|
||||
move = page.split('inline void move_knob(', 1)[1].split('\n}\n', 1)[0]
|
||||
# draw() ends in refresh() before LVGL has laid the new rows out, when coordinates still read 0.
|
||||
self.assertNotIn('lv_obj_get_width', move)
|
||||
self.assertNotIn('lv_obj_get_height', move)
|
||||
self.assertIn('knob_x(lv_obj_get_style_width(track, LV_PART_MAIN), lv_obj_get_style_height(track, LV_PART_MAIN), on)', move)
|
||||
pill = page.split('inline lv_obj_t *pill(', 1)[1].split('\n}\n', 1)[0]
|
||||
self.assertIn('plain(track, knob_x(w, h, on), inset, size, size)', pill)
|
||||
|
||||
def test_the_sun_path_keeps_its_own_fill_after_a_palette_change(self):
|
||||
tiles = (COMPONENT / 'runtime_tiles.h').read_text()
|
||||
self.assertIn('w.fill_color=lv_color_hex(theme::ha::SUNNY);', tiles)
|
||||
self.assertIn('if(w.extra_mode!="sunpath")w.fill_color=color;', tiles)
|
||||
self.assertEqual(len(re.findall(r'\bw\.fill_color=', tiles)), 2, 'the sun path and the palette are the only two')
|
||||
|
||||
|
||||
class Setting(unittest.TestCase):
|
||||
def test_dark_mode_is_a_setting_the_screen_owns(self):
|
||||
self.assertEqual(SETTING_RULES['dark_mode'], (False, None, None))
|
||||
self.assertIn('dark_mode', SETTINGS_BESIDE_BLOCK, 'never inside the eleven-key block older firmware insists on')
|
||||
self.assertEqual(SETTING_ENTITIES['dark_mode'], ('switch', 'Dark mode'))
|
||||
self.assertEqual(DARK_MODE_MIN_FIRMWARE, '0.2.54')
|
||||
self.assertLessEqual(tuple(map(int, DARK_MODE_MIN_FIRMWARE.split('.'))), tuple(map(int, FIRMWARE_VERSION.split('.'))))
|
||||
page = (COMPONENT / 'settings_screen.h').read_text()
|
||||
self.assertIn('toggle("Dark mode", []() -> int32_t { return dark_mode; },', page)
|
||||
self.assertIn('else if (key == "dark_mode") reported = dark_mode = flag(value);', page)
|
||||
editor = (ROOT / 'screen_manager/app/static/app.js').read_text()
|
||||
self.assertIn('{ key: "dark_mode", label: "Dark mode", kind: "toggle" },', editor)
|
||||
brightness = editor.split('{ title: "Brightness"', 1)[1].split('] },', 1)[0]
|
||||
self.assertLess(brightness.index('"brightness"'), brightness.index('"dark_mode"'), 'right under Brightness, as on the screen')
|
||||
self.assertLess(brightness.index('"dark_mode"'), brightness.index('"standby_enabled"'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
// c++ -std=c++17 -Wall -Wextra -pedantic tests/test_tile_controls.cpp -o /tmp/test_tile_controls && /tmp/test_tile_controls
|
||||
#define THEME_TEST
|
||||
#include "../components/smart_display/tile_controls.h"
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
#define THEME_TEST
|
||||
#include "components/smart_display/tile_palette.h"
|
||||
#include <cassert>
|
||||
int main() {
|
||||
assert(tile_palette::color("auto")==0);
|
||||
assert(tile_palette::color("")==0);
|
||||
assert(tile_palette::color("unknown-future-choice")==0);
|
||||
assert(tile_palette::color("red")!=0);
|
||||
assert(tile_palette::color("red")==0xFADADD);
|
||||
assert(tile_palette::color("green")!=tile_palette::color("red"));
|
||||
// "None" is not a colour: the card is hidden, and old firmware falls back to automatic.
|
||||
assert(tile_palette::color("none")==0);
|
||||
|
||||
@@ -12,8 +12,9 @@ def luminance(color):
|
||||
|
||||
class PaletteTests(unittest.IsolatedAsyncioTestCase):
|
||||
def test_palette_matches_firmware_and_has_readable_text(self):
|
||||
header=(Path(__file__).resolve().parents[1]/'components/smart_display/tile_palette.h').read_text()
|
||||
native=dict(re.findall(r'name=="(\w+)"\)return 0x([A-F0-9]+)',header))
|
||||
# The named card colours live in theme.h (firmware 0.2.54+): name, light value, dark value.
|
||||
header=(Path(__file__).resolve().parents[1]/'components/smart_display/theme.h').read_text()
|
||||
native={name:light for name,light,_ in re.findall(r'\{"(\w+)", 0x([A-F0-9]{6}), 0x([A-F0-9]{6})\}',header)}
|
||||
expected={k:v['color'][1:] for k,v in TILE_BACKGROUNDS.items() if v['color']}
|
||||
self.assertEqual(native,expected)
|
||||
for color in expected.values():
|
||||
|
||||
Reference in New Issue
Block a user