#pragma once #include "runtime_model.h" #include "header_bar.h" #include "tile_palette.h" #include "tile_icon.h" #include "screen_settings.h" #include "settings_screen.h" #include "esphome/core/preferences.h" #include "cyd_ui.h" #include "light_controls.h" #include "tile_controls.h" #include "swipe_profile.h" #include "esphome/components/json/json_util.h" #include "esphome/components/api/api_server.h" #include "esphome/core/hal.h" #include "esphome/core/util.h" #include "esphome/core/time.h" #include "lvgl.h" #include #include namespace runtime_tiles { inline bool enabled = false; // Swiping, rotation and going back to page 1 live in settings_screen, next to the other settings the // screen can change itself; these names stay as the way the rest of the firmware reaches them. using settings_screen::swipe_pages; using settings_screen::rotation; using settings_screen::rotation_supported; using settings_screen::auto_home; using settings_screen::auto_home_seconds; inline esphome::ESPPreferenceObject rotation_preference; inline esphome::ESPPreferenceObject swipe_preference; inline esphome::ESPPreferenceObject home_preference; inline Model model; inline std::string inbox; inline const lv_font_t *watch_font = nullptr; inline const lv_font_t *mini_icon_font = nullptr; inline const lv_font_t *watch_value_font = nullptr, *watch_icon_font = nullptr; // Big digits for the clock card; the board profile sets it with the local time source. inline const lv_font_t *clock_font = nullptr; // Text in the -/+ pill and the run key of direct controls; the board profile sets it. inline const lv_font_t *control_font = nullptr; inline lv_obj_t *room_label = nullptr; // remembered by render() so page switches can render synchronously // Top bar (0.2.32+): the profile's clock label only lends its place and margin; values use the // profile's text font, icons its small icon font. Set by the board profile at boot. inline header_bar::Bar header; inline lv_obj_t *time_label = nullptr; inline const lv_font_t *header_text_font = nullptr, *header_icon_font = nullptr; inline void render_header(); inline std::function now_time; // True while the screen is in use: the profile reports standby (also the night level) as not awake. // The analog clock's second hand runs only then; a standby screen stays on its minute redraws. inline std::function screen_awake; inline bool awake() { return !screen_awake || screen_awake(); } inline uint32_t now_epoch() { if (!now_time) return 0; auto t = now_time(); return t.is_valid() ? static_cast(t.timestamp) : 0; } inline void tick(); inline void refresh_tile(size_t index); #ifdef SWIPE_PROFILE inline void swipe_test(unsigned count, unsigned interval_ms, unsigned back_ms, JsonObject tuning); #endif inline void refresh_header_only(); inline void refresh_all(); inline void refresh_detail(unsigned index); inline const char *weather_icon(const std::string &condition); inline const char *weather_text(const std::string &condition); inline std::string timer_text(const Tile &t); inline std::string last_run_text(uint32_t epoch); inline int active_index = -1; inline uint32_t last_received = 0; // Seconds between the manager's full repeats; every layout message declares it (app // 0.2.26+). Older managers get the 120 s that app 0.2.20 introduced. inline uint32_t keepalive_seconds = 120; // Revision of the layout the manager sent last (app 0.2.39+). A keepalive ping carries the // manager's revision; a mismatch (a restart, a demo layout) asks for the whole layout again. inline std::string layout_rev; inline std::function layout_changed, refresh, dismiss, settings_changed; inline esphome::ESPPreferenceObject settings_preference; // The two extra values of 0.2.44+ in one record: going back to page 1 by itself, and after how long. struct HomeTimeout { uint32_t enabled = 1, seconds = 120; }; inline void load_settings() { settings_preference = esphome::global_preferences->make_preference(0x53435231); swipe_preference = esphome::global_preferences->make_preference(0x53575031); home_preference = esphome::global_preferences->make_preference(0x484F4D31); uint32_t swipe_saved=0; if(swipe_preference.load(&swipe_saved))swipe_pages=swipe_saved==1; HomeTimeout home; if(home_preference.load(&home) && home.seconds>=30 && home.seconds<=3600){ auto_home=home.enabled?1:0;auto_home_seconds=(int32_t)home.seconds; } if(rotation_supported){ rotation_preference=esphome::global_preferences->make_preference(0x524F5431); uint32_t saved=0; if(rotation_preference.load(&saved) && saved<=270 && saved%90==0)rotation=(int32_t)saved; } screen_settings::Settings saved; if (settings_preference.load(&saved) && saved.valid()) screen_settings::current = saved; } // Everything the screen remembers, written in one go. ESPHome batches the flash writes, so a row of // taps on -/+ costs one write, and a value that did not change costs nothing. inline void persist_settings() { if (screen_settings::current.valid()) settings_preference.save(&screen_settings::current); uint32_t swipe = swipe_pages ? 1 : 0; swipe_preference.save(&swipe); HomeTimeout home{(uint32_t) (auto_home ? 1 : 0), (uint32_t) std::clamp(auto_home_seconds, 30, 3600)}; home_preference.save(&home); if (rotation_supported) { uint32_t turned = (uint32_t) rotation; rotation_preference.save(&turned); } } inline bool parse_settings(JsonObject obj, screen_settings::Settings &s) { // Require the complete known schema; validate before touching any runtime state. if (obj.size() != 11) return false; const char *flags[] = {"standby_enabled", "night_enabled", "show_clock", "clock_24h", "home_on_standby"}; int32_t *flag_values[] = {&s.standby_enabled, &s.night_enabled, &s.show_clock, &s.clock_24h, &s.home_on_standby}; for (int i = 0; i < 5; ++i) { if (!obj[flags[i]].is()) return false; *flag_values[i] = obj[flags[i]].as(); } const char *numbers[] = {"standby_seconds", "brightness", "standby_brightness", "night_start", "night_end", "night_brightness"}; int32_t *values[] = {&s.standby_seconds, &s.brightness, &s.standby_brightness, &s.night_start, &s.night_end, &s.night_brightness}; for (int i = 0; i < 6; ++i) { if (!obj[numbers[i]].is() || obj[numbers[i]].is()) return false; *values[i] = obj[numbers[i]].as(); } return s.valid(); } inline std::function detail, detail_update; struct Widgets { lv_obj_t *tile{}, *title{}, *value{}, *circle{}, *icon{}; size_t index{}; int cached_active = -1; lv_obj_t *slider{}, *progress{}, *unit{}; int title_x=0,title_y=0,value_x=0,value_y=0; const lv_font_t *value_font{}, *icon_font{}; // Wide cards span both columns; custom cards (clock, forecast, graph) draw into `extra`. bool wide=false; int base_width=0; lv_obj_t *extra{}; std::string extra_mode; std::array parts{}; lv_point_precise_t *points{}; // Analog clock: centre and radius of the dial, so the second hand can move without a card redraw. int hand_cx=0, hand_cy=0, hand_r=0, hand_width=1; // Soft area under a polyline (graph, sun path), painted by the extra container's draw event. const lv_point_precise_t *fill_points{}; unsigned fill_count=0; int fill_x=0, fill_y=0, fill_base=0; lv_color_t fill_color{}; lv_opa_t fill_opa=0; // Direct controls on a wide card: a panel at the right with pill keys, a -/+ pill, // a slider or a toggle. Objects are rebuilt only when the control set changes. lv_obj_t *panel{}; std::string panel_mode; bool panel_dirty=false; int panel_w=0; std::array keys{}, key_icons{}; std::array key_commands{}; std::array key_args; std::array key_checked{}; lv_obj_t *pill{}, *pill_value{}, *knob{}, *control_slider{}; int knob_on=-1; lv_color_t panel_accent{}, panel_text{}; // Busy sheet: a translucent white cover with a small spinner while a command is under way. lv_obj_t *busy{}, *spinner{}; // Page fill skeleton: a sheet in the card's colour over its contents until the card is drawn. lv_obj_t *veil{}; }; constexpr unsigned POINT_BUFFER = 128; inline std::array widgets; // All icon fonts carry the same generated glyph set, so the first bound one answers for all. inline bool has_icon_glyph(uint32_t codepoint) { for (auto &w : widgets) if (w.icon_font) { lv_font_glyph_dsc_t dsc; return lv_font_get_glyph_dsc(w.icon_font, &dsc, codepoint, 0); } return false; } // Home Assistant's API link as ESPHome itself tracks it: gone the moment the socket drops, // back the moment HA reconnects, no guessing from message age. inline bool ha_connected() { return esphome::api_is_connected(); } // The manager repeats the whole layout every keepalive; one missed round plus its 20 s // loop slack and the sending itself are tolerated before the feed counts as gone. inline bool feed_alive() { return esphome::millis() - last_received < keepalive_seconds * 2000 + 60000; } inline bool fresh() { return model.ready() && ha_connected() && feed_alive(); } // A dropped tap is logged with its reason, so a missed touch can be read from the ESPHome log // instead of guessed: moved too far, too short, already used by this contact, or bounce. inline bool allowed(uint32_t now, int tile, const std::string &what) { if (cyd::touch_guard.accept(now, tile)) return true; ESP_LOGI("touch", "tap on %s ignored: %s", what.c_str(), cyd::touch_guard.reason().c_str()); return false; } inline float number(JsonVariant value, float fallback = NAN) { if (!value.is() && !value.is()) return fallback; float n = value.as(); return std::isfinite(n) ? n : fallback; } inline std::string string(JsonVariant value, size_t maximum = 160) { if (!value.is()) return {}; std::string s = value.as(); if (s.size() > maximum) { while (maximum > 0 && (static_cast(s[maximum]) & 0xC0) == 0x80) --maximum; s.resize(maximum); } return s; } inline std::string list(JsonVariant value) { if (!value.is()) return {}; std::string out; serializeJson(value, out); return out.size() <= 512 ? out : ""; } inline std::string receive(const std::string &payload) { if (!enabled) return "Use the Easy Setup profile"; if (payload.size() > 4096) return "Error: message too large"; std::string result = "Error: invalid message"; esphome::json::parse_json(payload, [&](JsonObject root) -> bool { if (root["v"].as() != 1) { result = "Error: protocol version"; return false; } auto op = string(root["op"]); if (op == "layout") { if (!root["entities"].is() || !root["title"].is()) return false; auto settings = screen_settings::current; if (!root["settings"].isNull() && (!root["settings"].is() || !parse_settings(root["settings"].as(), settings))) { result = "Error: screen settings"; return false; } std::vector entities; for (JsonVariant entity : root["entities"].as()) { if (!entity.is() || entities.size() == MAX_TILES) return false; entities.push_back(entity.as()); } if(!root["swipe_pages"].isNull() && !root["swipe_pages"].is())return false; if(!root["auto_home"].isNull() && !root["auto_home"].is())return false; if(!root["auto_home_seconds"].isNull() && (!root["auto_home_seconds"].is() || root["auto_home_seconds"].as()<30 || root["auto_home_seconds"].as()>3600))return false; if(!root["rotation"].isNull() && (!root["rotation"].is() || root["rotation"].as()>270 || root["rotation"].as()%90!=0))return false; if(!root["keepalive"].isNull() && (!root["keepalive"].is() || root["keepalive"].as()<5 || root["keepalive"].as()>3600))return false; // Explicit grid positions (0.2.26+), one absolute slot per entity; absent on older managers. std::vector positions; if (!root["slots"].isNull()) { if (!root["slots"].is()) return false; for (JsonVariant slot : root["slots"].as()) { if (!slot.is() || slot.as() >= MAX_SLOTS || positions.size() == MAX_TILES) return false; positions.push_back(static_cast(slot.as())); } } inbox = string(root["inbox"], 160); bool changed = false, moved = false, was_configured = model.configured; const std::string previous_title = model.title; const uint8_t previous_pages = model.pages; if (!model.set_layout(entities, string(root["title"], 96), changed, positions, moved)) return false; // Empty pages the user keeps on purpose; absent on older managers. model.pages = root["pages"].is() ? static_cast(std::clamp(root["pages"].as(), 1, MAX_PAGES)) : 1; if(root["swipe_pages"].is() && swipe_pages!=root["swipe_pages"].as()){ swipe_pages=root["swipe_pages"].as();uint32_t saved=swipe_pages?1:0;swipe_preference.save(&saved); } if((root["auto_home"].is() && auto_home!=root["auto_home"].as()) || (root["auto_home_seconds"].is() && auto_home_seconds!=(int32_t)root["auto_home_seconds"].as())){ if(root["auto_home"].is())auto_home=root["auto_home"].as(); if(root["auto_home_seconds"].is())auto_home_seconds=(int32_t)root["auto_home_seconds"].as(); HomeTimeout home{(uint32_t)(auto_home?1:0),(uint32_t)auto_home_seconds};home_preference.save(&home); } bool rotation_changed=false; if(rotation_supported && root["rotation"].is() && rotation!=root["rotation"].as()){ rotation=root["rotation"].as();rotation_preference.save(&rotation);rotation_changed=true; } if (!(settings == screen_settings::current)) { screen_settings::current = settings; settings_preference.save(&settings); // ESPHome batches flash writes; no write on keepalive. rotation_changed=true; } if(rotation_changed && settings_changed)settings_changed(); if (changed) { active_index = -1; for (auto &w : widgets) w.cached_active = -1; if (dismiss) dismiss(); } if (moved) ESP_LOGI("runtime", "tiles moved: pages rearranged"); if (root["keepalive"].is()) keepalive_seconds = root["keepalive"].as(); layout_rev = string(root["rev"], 16); last_received = esphome::millis(); // A repeat of the layout on screen (the hourly repeat, a save that changed nothing here) only // refreshes the feed: drawing the whole page again stalls touch input for a few hundred ms, // long enough to spoil a slider drag. The tile states that follow redraw their own tiles. if (changed || moved || !was_configured || rotation_changed || model.pages != previous_pages || model.title != previous_title) { if (layout_changed) layout_changed(); refresh_all(); } // A repeat of the same layout keeps the inbox state as it is: no new recorder row. result = changed || moved || !was_configured ? "Layout received" : model.ready() ? "Synced" : "Loading tiles"; return true; } if (op == "ping") { // Keepalive without content (app 0.2.39+): only the revision of the layout the manager holds. if (!root["rev"].is()) return false; if(!root["keepalive"].isNull() && (!root["keepalive"].is() || root["keepalive"].as()<5 || root["keepalive"].as()>3600))return false; if (root["keepalive"].is()) keepalive_seconds = root["keepalive"].as(); last_received = esphome::millis(); if (!model.configured || layout_rev != string(root["rev"], 16)) { result = "Resend needed"; return true; } result = model.ready() ? "Synced" : "Loading tiles"; return true; } if (op == "header") { // Validate every item before replacing the bar; an icon these fonts lack is left out. if (!root["items"].is()) return false; header_bar::Bar next; for (JsonVariant value : root["items"].as()) { if (next.count == header_bar::MAX_ITEMS || !value.is()) return false; header_bar::Item item; item.kind = header_bar::kind(string(value["k"], 8)); if (item.kind == header_bar::Kind::none) return false; uint32_t icon = tile_icon::codepoint(string(value["i"], 8)); item.icon = icon && has_icon_glyph(icon) ? icon : 0; item.text = string(value["t"], header_bar::TEXT_BYTES); item.epoch = value["e"].is() ? value["e"].as() : 0; item.has_color = header_bar::color(string(value["c"], 8), item.color); if (item.kind == header_bar::Kind::ago && item.epoch <= 0) return false; next.items[next.count++] = item; } next.received = true; bool same = header.received && header.count == next.count; for (size_t i = 0; same && i < next.count; ++i) same = header.items[i] == next.items[i]; header = next; last_received = esphome::millis(); if (!same) refresh_header_only(); // The same status as a tile state, so a changing value never flips the inbox entity. result = model.ready() ? "Synced" : "Loading tiles"; return true; } #ifdef SWIPE_PROFILE if (op == "swipe_test") { // Diagnostic builds only: page switches without a finger, `n` of them `ms` apart; `back` // (ms) swipes straight back after each one, like a quick second swipe. swipe_test(root["n"] | 20u, root["ms"] | 1200u, root["back"] | 0u, root); result = "Swipe test started"; return true; } #endif if (op != "state" || !root["i"].is() || !root["a"].is()) return false; unsigned index = root["i"].as(); std::string entity = string(root["entity"], 120); if (!model.accepts(index, entity)) { result = "Error: outdated tile"; return false; } Tile &tile = model.tiles[index]; auto a = root["a"].as(); // The fingerprint of state, attributes and extras (a vacuum's mode or water select changes only // there), hashed while serializing so no copy of the message stays behind. Fingerprint revision; revision.add(string(root["state"])); revision.write('\n'); serializeJson(a, revision); if (!root["x"].isNull()) serializeJson(root["x"], revision); bool was_confirmed=tile.confirmed; tile.observe(revision.value); if(tile.pending && !tile.local_feedback && !was_confirmed && tile.confirmed) ESP_LOGI("runtime_action","HA state received entity=%s elapsed=%u ms",entity.c_str(),(unsigned)(esphome::millis()-tile.pending_since)); auto options = root["o"]; std::string background=string(options["background"],16); tile.background = tile_palette::color(background); tile.transparent = tile_palette::transparent(background); // An icon these fonts lack (a newer set than this firmware) keeps the domain icon. uint32_t icon = tile_icon::codepoint(string(options["icon"], 8)); tile.icon = icon && has_icon_glyph(icon) ? tile_icon::utf8(icon) : ""; tile.tap = string(options["tap"]); if (tile.tap.empty()) tile.tap="auto"; tile.display = string(options["display"]); if (tile.display.empty()) tile.display="standard"; tile.inline_control = string(options["inline"]); if (tile.inline_control.empty()) tile.inline_control="none"; // Direct controls (0.2.19+): the manager sends only the set a wide card really shows. tile.controls = string(options["controls"], 16); // Width arrives with the state, after the layout: re-pack the pages when it changes. bool was_wide = tile.wide; tile.wide = string(options["size"]) == "wide"; bool repack = was_wide != tile.wide; // Pre-computed extras: the manager converts time zones and fetches forecasts. What only some tiles // carry is collected in `next` and replaces the tile's Extra at the end (see Tile::set_extra). auto extra = root["x"]; Extra next; if (extra["days"].is()) for (JsonVariant day : extra["days"].as()) { if (next.forecast.size() == 5) break; next.forecast.emplace_back(); auto &f = next.forecast.back(); f.day = string(day["d"], 3); f.condition = string(day["c"], 20); f.high = number(day["h"]); f.low = number(day["l"]); f.rain = number(day["p"]); f.mm = number(day["r"]); } if (extra["hours"].is()) for (JsonVariant hour : extra["hours"].as()) { if (next.hours.size() == 8) break; next.hours.emplace_back(); auto &h = next.hours.back(); h.time = string(hour["t"], 5); h.condition = string(hour["c"], 20); h.temp = number(hour["h"]); h.rain = number(hour["p"]); h.mm = number(hour["r"]); } tile.last_run = extra["last"].is() ? extra["last"].as() : 0; next.sunrise = string(extra["rise"], 5); next.sunset = string(extra["set"], 5); next.timer_end = extra["end"].is() ? extra["end"].as() : 0; next.duration = string(extra["dur"], 16); next.remaining = string(extra["rem"], 16); tile.has_history=false; if (root["history"]["values"].is()) { tile.history.assign(24,NAN);unsigned j=0; for (JsonVariant value:root["history"]["values"].as()) { if(j==24) break; tile.history[j++]=number(value); } tile.has_history=j>0;tile.history_hours=std::clamp(root["history"]["hours"].as(),1u,24u); } else if (!tile.history.empty()) { tile.history.clear(); tile.history.shrink_to_fit(); } if (a["options"].is()) for(JsonVariant option:a["options"].as()) { if(next.options.size()==8)break;next.options.push_back(string(option,48)); } tile.battery=number(a["battery_level"]);tile.volume=number(a["volume_level"]); tile.muted=a["is_volume_muted"].is() && a["is_volume_muted"].as(); tile.device_class=string(a["device_class"],24);next.hvac_action=string(a["hvac_action"],24); next.media_title=string(a["media_title"],80);tile.supported=a["supported_features"].as(); tile.name = string(root["name"], 80); tile.state = string(root["state"], 160); tile.unit = string(a["unit_of_measurement"], 20); tile.brightness = number(a["brightness"]); tile.percentage = number(a["percentage"]); tile.position = number(a["current_position"]); tile.current = number(a["current_temperature"]); tile.target = number(a["temperature"]); tile.humidity = number(a["current_humidity"]); tile.minimum = number(a["min_temp"], 7); tile.maximum = number(a["max_temp"], 35); tile.step = number(a["target_temp_step"], 0.5f); if(tile.domain()=="number" || tile.domain()=="input_number") { tile.minimum=number(a["min"],0);tile.maximum=number(a["max"],100);tile.step=number(a["step"],1); } if(tile.domain()=="weather") { tile.current=number(a["temperature"]);tile.unit=string(a["temperature_unit"],12); tile.humidity=number(a["humidity"]);next.wind=number(a["wind_speed"]);next.wind_unit=string(a["wind_speed_unit"],8);next.feels=number(a["apparent_temperature"]); } tile.modes = list(a["supported_color_modes"]); next.hvac_modes = list(a["hvac_modes"]); next.fan_modes = list(a["fan_modes"]); next.swing_modes = list(a["swing_modes"]); next.fan_mode = string(a["fan_mode"], 48); next.swing_mode = string(a["swing_mode"], 48); float hue = number(a["hs_color"][0]); float saturation = number(a["hs_color"][1]); tile.has_hs_color = std::isfinite(hue) && std::isfinite(saturation); tile.saturation = tile.has_hs_color ? std::lround(std::clamp(saturation, 0.0f, 100.0f)) : 0; if (std::isfinite(hue)) tile.hue = std::lround(std::clamp(hue, 0.0f, 360.0f)); float kelvin = number(a["color_temp_kelvin"]); if (std::isfinite(kelvin)) tile.kelvin = std::lround(std::clamp(kelvin, 1000.0f, 15000.0f)); tile.min_kelvin = std::clamp(number(a["min_color_temp_kelvin"], 0), 0.0f, 15000.0f); tile.max_kelvin = std::clamp(number(a["max_color_temp_kelvin"], 0), 0.0f, 15000.0f); next.fan_speed = string(a["fan_speed"], 48); if (a["fan_speed_list"].is()) for (JsonVariant speed : a["fan_speed_list"].as()) { if (next.fan_speeds.size() == 4) break; next.fan_speeds.push_back(string(speed, 48)); } // Vacuum rows (app 0.2.46+): the cleaning mode and water selects of the robot's device and the // suction speeds to offer, each at most six; the battery sensor when the vacuum has no attribute. // A chip just tapped keeps its choice while Home Assistant is still busy with it, so another update // of the robot (its battery, say) does not flip the row back for a moment. std::vector> tapped; if (tile.loading(esphome::millis())) for (auto &c : tile.extra().choices) if (!c.sent.empty()) tapped.emplace_back(c.kind, c.sent); auto choice = [&](const char *key, char kind) { auto c = extra[key]; if (!c["o"].is()) return; Choice row; row.kind = kind; row.entity = string(c["e"], 120); row.current = string(c["s"], 48); row.roles = string(c["r"], 6); if (kind != 's' && !valid_entity(row.entity)) return; for (JsonVariant value : c["o"].as()) { if (row.values.size() == 6) break; row.values.push_back(string(value, 48)); } if (c["l"].is()) for (JsonVariant label : c["l"].as()) { if (row.labels.size() == row.values.size()) break; row.labels.push_back(string(label, 24)); } while (row.labels.size() < row.values.size()) row.labels.push_back(row.values[row.labels.size()]); if (!row.values.empty()) next.choices.push_back(std::move(row)); }; if (tile.domain() == "vacuum") { choice("mode", 'm'); choice("water", 'w'); choice("fan", 's'); tile_controls::settle_suction(next); } for (auto &[kind, value] : tapped) if (auto *c = next.choice(kind)) if (c->current != value) c->sent = value; if (!std::isfinite(tile.battery)) tile.battery = number(extra["bat"]); next.charging = extra["chg"].is() && extra["chg"].as() == 1; next.room = string(extra["room"], 32); tile.set_extra(std::move(next)); // Home Assistant reports the edited value: the -/+ pill follows its state again. if(std::isfinite(tile.edit_value) && tile.edit_sent && std::fabs(tile_controls::edit_target(tile)-tile.edit_value)<0.051f)tile.edit_value=NAN; tile.received = true; for(auto &w:widgets)if(w.index==index)w.cached_active=-1; last_received = esphome::millis(); if (repack && layout_changed) layout_changed(); refresh_tile(index); if (active_index == static_cast(index) && detail_update) detail_update(tile); refresh_detail(index); result = model.ready() ? "Synced" : "Loading tiles"; return true; }); return result; } inline void action(const std::string &service, const std::string &entity, const std::string &key="", const std::string &value="") { if (!fresh() || !valid_entity(entity)) return; esphome::api::HomeassistantActionRequest request; request.service = esphome::StringRef(service); request.data.init(key.empty() ? 1 : 2); esphome::api::HomeassistantServiceMap entry; entry.key = esphome::StringRef("entity_id"); entry.value = esphome::StringRef(entity); request.data.push_back(entry); if(!key.empty()) {esphome::api::HomeassistantServiceMap param;param.key=esphome::StringRef(key);param.value=esphome::StringRef(value);request.data.push_back(param);} for(size_t i=0;isend_homeassistant_action(request); ESP_LOGI("runtime_action","Sent service=%s entity=%s",service.c_str(),entity.c_str()); } inline void setting_event(const std::string &key, int value) { if(inbox.empty())return; esphome::api::HomeassistantActionRequest request;request.service=esphome::StringRef("esphome.screen_setting");request.is_event=true; std::string number=std::to_string(value);request.data.init(3); const std::string keys[]={"inbox","key","value"},values[]={inbox,key,number}; for(int i=0;i<3;++i){esphome::api::HomeassistantServiceMap entry;entry.key=esphome::StringRef(keys[i]);entry.value=esphome::StringRef(values[i]);request.data.push_back(entry);} esphome::api::global_api_server->send_homeassistant_action(request); } } // namespace runtime_tiles // Small shared native-LVGL detail cards. No images, canvas buffers or free scrolling. namespace runtime_tiles { inline lv_obj_t *detail_root=nullptr; inline unsigned detail_index=0; inline const lv_font_t *detail_font=nullptr; inline lv_obj_t *detail_actions[32]{}; inline unsigned detail_action_count=0; inline lv_obj_t *detail_status=nullptr; inline lv_obj_t *detail_badge_status=nullptr; inline lv_obj_t *detail_switch=nullptr; inline lv_obj_t *detail_label(lv_obj_t *parent,const std::string &text,int x,int y,int width) { auto *label=lv_label_create(parent);lv_label_set_text(label,text.c_str());lv_obj_set_pos(label,x,y);lv_obj_set_width(label,width); lv_obj_set_style_text_font(label,detail_font,0);lv_obj_set_style_text_color(label,lv_color_hex(0x202020),0); lv_label_set_long_mode(label,LV_LABEL_LONG_DOT);lv_obj_set_height(label,lv_font_get_line_height(detail_font));return label; } inline std::string detail_state(const Tile &t){ if(t.domain()=="person")return t.state=="home"?"Home":t.state=="not_home"?"Away":t.state; if(t.domain()=="sun")return t.state=="above_horizon"?"Above the horizon":"Below the horizon"; if(t.domain()=="timer")return timer_text(t); if(t.domain()=="script"||t.domain()=="scene"||t.domain()=="button"||t.domain()=="input_button")return t.state=="on"?"Running...":last_run_text(t.last_run); if(t.state=="on")return "On"; if(t.state=="off")return "Off"; if(t.state=="docked")return "Docked"; if(t.state=="cleaning")return "Cleaning"; if(t.state=="paused")return "Paused"; if(t.state=="returning")return "Returning to dock"; if(t.state=="idle")return "Idle"; if(t.state=="error")return "Check the robot in HA"; if(!t.available())return "Unavailable"; return t.state; } inline void hide_detail(){if(detail_root)lv_obj_add_flag(detail_root,LV_OBJ_FLAG_HIDDEN);} inline int slider_value(const Tile &t){ auto d=t.domain();float value=0; if(d=="light")value=std::isfinite(t.brightness)?t.brightness/255:0; if(d=="fan")value=std::isfinite(t.percentage)?t.percentage/100:0; if(d=="cover")value=std::isfinite(t.position)?t.position/100:0; if(d=="media_player")value=std::isfinite(t.volume)?t.volume:0; if(d=="number"||d=="input_number") {char *end;float state=strtof(t.state.c_str(),&end);if(end!=t.state.c_str() && t.maximum>t.minimum)value=(state-t.minimum)/(t.maximum-t.minimum);} return std::clamp((int)std::lround(value*1000),0,1000); } inline lv_obj_t *captured_slider=nullptr; inline bool slider_changed=false; inline int slider_held=0; inline void slider_event(lv_event_t *e); inline void commit_slider(unsigned i,int raw){ if(i>=model.count || !fresh())return;auto &t=model.tiles[i];if(!t.available() || t.loading(esphome::millis()))return; float value=std::clamp(raw,0,1000)/1000.0f;auto d=t.domain(); // A light's slider stops at 1 %, as in Home Assistant; tapping the card turns it off. if(d=="light")action("light.turn_on",t.entity,"brightness",std::to_string(std::max(3,(int)std::lround(value*255)))); if(d=="fan")action("fan.set_percentage",t.entity,"percentage",std::to_string((int)std::lround(value*100))); if(d=="cover")action("cover.set_cover_position",t.entity,"position",std::to_string((int)std::lround(value*100))); if(d=="media_player")action("media_player.volume_set",t.entity,"volume_level",std::to_string(value)); if(d=="number"||d=="input_number") { if(!std::isfinite(t.minimum)||!std::isfinite(t.maximum)||t.maximum<=t.minimum||t.step<=0)return; value=std::clamp(t.minimum+std::round(value*(t.maximum-t.minimum)/t.step)*t.step,t.minimum,t.maximum); action(d+".set_value",t.entity,"value",std::to_string(value)); } } inline void slider_event(lv_event_t *e){ auto *slider=lv_event_get_target_obj(e);auto code=lv_event_get_code(e); if(code==LV_EVENT_PRESSED){captured_slider=slider;slider_changed=false;} // On release LVGL sets the value once more from the last touch point: log it when that throws a // dragged slider to one of its ends, so a stray touch sample shows up (cyd::release_jump). if(code==LV_EVENT_VALUE_CHANGED && captured_slider==slider){ auto *indev=lv_indev_active();int raw=lv_slider_get_value(slider); if(!indev || lv_indev_get_state(indev)!=LV_INDEV_STATE_RELEASED)slider_held=raw; else if(slider_changed && cyd::release_jump(slider_held,raw,lv_slider_get_min_value(slider),lv_slider_get_max_value(slider))){ lv_point_t point;lv_indev_get_point(indev,&point); ESP_LOGW("slider","Tile slider jumped on release: %d -> %d (touch x=%d y=%d)",slider_held,raw,(int)point.x,(int)point.y); } } // The range reaches below zero only to draw the round end at 0 (slider_handle). if(code==LV_EVENT_VALUE_CHANGED && lv_slider_get_value(slider)<0)lv_slider_set_value(slider,0,LV_ANIM_OFF); if(code==LV_EVENT_VALUE_CHANGED && captured_slider==slider)slider_changed=true; if(code==LV_EVENT_PRESS_LOST && captured_slider==slider){captured_slider=nullptr;slider_changed=false;} if(code==LV_EVENT_RELEASED && captured_slider==slider){ unsigned index=(uintptr_t)lv_event_get_user_data(e); for(auto &w:widgets)if(w.slider==slider || w.control_slider==slider){index=w.index;break;} bool changed=slider_changed;captured_slider=nullptr;slider_changed=false; if(changed && cyd::touch_guard.accept_slider(esphome::millis(),200+index))commit_slider(index,lv_slider_get_value(slider)); } } inline void show_detail(unsigned index); // A chip on the vacuum card: the service call goes out, the chip shows the choice at once, and the card // waits for Home Assistant like after its other buttons. The card is drawn again once this tap's event // has finished, because a chosen mode can add or remove the suction and water rows. inline void choose(Tile &t,Choice &row,const std::string &value){ if(value==row.current)return; auto a=tile_controls::choice_action(t,row.kind,value);if(!a.valid())return; action(a.service,row.kind=='s'?t.entity:row.entity,a.key,a.value); row.sent=value;t.begin(esphome::millis()); lv_async_call([](void *){if(detail_root && !lv_obj_has_flag(detail_root,LV_OBJ_FLAG_HIDDEN))show_detail(detail_index);},nullptr); } inline lv_obj_t *detail_button(const char *text,int x,int y,int width,int height,int command){ auto *button=lv_obj_create(detail_root);lv_obj_remove_style_all(button);lv_obj_set_pos(button,x,y);lv_obj_set_size(button,width,height); lv_obj_set_style_bg_color(button,lv_color_hex(command==0?0x009FE3:0xD9E6F0),0);lv_obj_set_style_bg_opa(button,LV_OPA_COVER,0);lv_obj_set_style_radius(button,12,0);lv_obj_add_flag(button,LV_OBJ_FLAG_CLICKABLE); auto *label=detail_label(button,text,6,0,width-12);lv_obj_center(label);lv_obj_set_style_text_align(label,LV_TEXT_ALIGN_CENTER,0);if(command==0)lv_obj_set_style_text_color(label,lv_color_hex(0xFFFFFF),0);lv_obj_remove_flag(label,LV_OBJ_FLAG_CLICKABLE); lv_obj_add_event_cb(button,[](lv_event_t *e){ int cmd=(intptr_t)lv_event_get_user_data(e);if(cmd==-1){hide_detail();return;} if(!fresh()||detail_index>=model.count || !allowed(esphome::millis(),300+cmd,"card button "+model.tiles[detail_index].entity))return; auto &t=model.tiles[detail_index];if(!t.available()||t.loading(esphome::millis()))return; if(cmd<4){const char *services[]={"vacuum.start","vacuum.pause","vacuum.return_to_base","vacuum.locate"};action(services[cmd],t.entity);} // Vacuum rows: 10-15 suction, 50-55 cleaning mode, 60-65 water. static const std::pair rows[]={{10,'s'},{50,'m'},{60,'w'}}; for(const auto &[first,kind]:rows) if(cmd>=first && cmdvalues.size())choose(t,*row,row->values[cmd-first]);} if(cmd==20)action("media_player.media_play_pause",t.entity); if(cmd==21)action("media_player.media_previous_track",t.entity); if(cmd==22)action("media_player.media_next_track",t.entity); if(cmd>=30 && cmd<38 && cmd-30<(int)t.extra().options.size())action(t.domain()+".select_option",t.entity,"option",t.extra().options[cmd-30]); if(cmd==40)action(t.state=="active"?"timer.pause":"timer.start",t.entity); if(cmd==41)action("timer.cancel",t.entity); },LV_EVENT_SHORT_CLICKED,(void*)(intptr_t)command); lv_obj_set_style_bg_color(button,lv_color_hex(0x0075B0),LV_STATE_PRESSED); lv_obj_set_style_transform_width(button,-2,LV_STATE_PRESSED);lv_obj_set_style_transform_height(button,-2,LV_STATE_PRESSED); lv_obj_set_style_opa(button,LV_OPA_50,LV_STATE_DISABLED); if(command>=0 && detail_action_count<32)detail_actions[detail_action_count++]=button; return button; } // ---- Weather card: now, the next hours and the coming days, with rain ---- inline uint32_t weather_accent(const std::string &c) { if(c=="sunny")return 0xFFB300; if(c=="clear-night")return 0x6E41AB; if(c=="rainy"||c=="pouring"||c=="lightning-rainy"||c=="snowy-rainy")return 0x1E88E5; if(c=="snowy"||c=="hail")return 0x4FC3F7; if(c=="lightning")return 0xFFA000; if(c=="partlycloudy")return 0x7E9BB5; return 0x78909C; } inline lv_obj_t *detail_text(lv_obj_t *parent,const std::string &text,int x,int y,int width,const lv_font_t *font,lv_text_align_t align,uint32_t color){ auto *l=detail_label(parent,text,x,y,std::max(1,width));lv_obj_set_style_text_font(l,font,0);lv_obj_set_height(l,lv_font_get_line_height(font)); lv_obj_set_style_text_align(l,align,0);lv_obj_set_style_text_color(l,lv_color_hex(color),0);return l; } // "30%", "30% · 1.7 mm" or "1.7 mm": whatever the provider reports; empty when dry. inline std::string rain_text(float chance,float mm,bool with_mm){ char b[32]; if(std::isfinite(chance) && chance>=0){ if(with_mm && std::isfinite(mm) && mm>=0.05f){snprintf(b,sizeof(b),"%d%% · %.1f mm",(int)std::lround(chance),mm);return b;} snprintf(b,sizeof(b),"%d%%",(int)std::lround(chance));return b; } if(std::isfinite(mm) && mm>=0.05f){snprintf(b,sizeof(b),mm<10?"%.1f mm":"%.0f mm",mm);return b;} return ""; } inline std::string degrees(float value){ if(!std::isfinite(value))return "--"; char b[16];snprintf(b,sizeof(b),"%.0f°",value);return b; } inline lv_obj_t *detail_card(int x,int y,int w,int h){ auto *card=lv_obj_create(detail_root);lv_obj_remove_style_all(card);lv_obj_remove_flag(card,LV_OBJ_FLAG_SCROLLABLE);lv_obj_remove_flag(card,LV_OBJ_FLAG_CLICKABLE); lv_obj_set_pos(card,x,y);lv_obj_set_size(card,w,h); lv_obj_set_style_bg_color(card,lv_color_hex(0xFFFFFF),0);lv_obj_set_style_bg_opa(card,LV_OPA_COVER,0); lv_obj_set_style_radius(card,lv_obj_get_style_radius(widgets[0].tile,LV_PART_MAIN),0); lv_obj_set_style_border_width(card,1,0);lv_obj_set_style_border_color(card,lv_color_hex(0xDDDDDD),0); return card; } // Two cards: "now" with the next hours, and the coming days. Bold highs, muted lows, // rain in blue with a drop, so the eye finds temperature first and rain second. inline void render_weather_detail(const Tile &t,bool large,int width,int height,int pad){ const Extra &weather=t.extra(); if(detail_status){lv_obj_add_flag(detail_status,LV_OBJ_FLAG_HIDDEN);detail_status=nullptr;} const lv_font_t *big=watch_value_font?watch_value_font:detail_font; const lv_font_t *icon_font=widgets[0].icon_font?widgets[0].icon_font:detail_font; const lv_font_t *mini=mini_icon_font?mini_icon_font:icon_font; const lv_font_t *tiny=watch_icon_font?watch_icon_font:mini; const lv_font_t *small=widgets[0].value?lv_obj_get_style_text_font(widgets[0].value,LV_PART_MAIN):detail_font; uint32_t ink=0x202020,muted=0x6B6B6B,rain=0x1E88E5; int text_h=lv_font_get_line_height(detail_font),small_h=lv_font_get_line_height(small),mini_h=lv_font_get_line_height(mini),tiny_h=lv_font_get_line_height(tiny); int icon_h=lv_font_get_line_height(icon_font),big_h=lv_font_get_line_height(big),hero=std::max(icon_h,big_h); int card_pad=large?14:7,inner=width-2*pad-2*card_pad; unsigned columns=std::min(weather.hours.size(),6); int hours_h=columns?small_h+mini_h+text_h+small_h+(large?16:6):0; int card_a_h=card_pad+hero+(columns?(large?14:8)+hours_h:0)+card_pad; int y=large?62:38; auto *now=detail_card(pad,y,width-2*pad,card_a_h); // Now: icon, temperature, condition, then feels-like / humidity / wind in one muted line. int cy=card_pad;char b[48]; detail_text(now,t.available()?weather_icon(t.state):"\U000F0595",card_pad,cy+(hero-icon_h)/2,icon_h+8,icon_font,LV_TEXT_ALIGN_LEFT,weather_accent(t.state)); int temp_x=card_pad+icon_h+(large?14:6),temp_w=large?92:50; detail_text(now,degrees(t.current),temp_x,cy+(hero-big_h)/2,temp_w,big,LV_TEXT_ALIGN_LEFT,ink); int text_x=temp_x+temp_w+(large?4:2),text_w=width-2*pad-card_pad-text_x; int lines_h=text_h+small_h+(large?2:0); detail_text(now,t.available()?weather_text(t.state):"Unavailable",text_x,cy+(hero-lines_h)/2,text_w,detail_font,LV_TEXT_ALIGN_LEFT,ink); std::string details; if(std::isfinite(weather.feels)){snprintf(b,sizeof(b),"Feels like %.0f°",weather.feels);details=b;} if(std::isfinite(t.humidity)){snprintf(b,sizeof(b),"%d%%",(int)std::lround(t.humidity));details+=(details.empty()?"":" · ")+std::string(b);} if(std::isfinite(weather.wind)){snprintf(b,sizeof(b),"%.0f %s",weather.wind,weather.wind_unit.empty()?"km/h":weather.wind_unit.c_str());details+=(details.empty()?"":" · ")+std::string(b);} detail_text(now,details,text_x,cy+(hero-lines_h)/2+text_h+(large?2:0),text_w,small,LV_TEXT_ALIGN_LEFT,muted); // Next hours inside the same card: time, icon, temperature, rain per column. if(columns){ int hy=cy+hero+(large?14:8),col=inner/(int)columns; for(unsigned i=0;i((int)row.values.size(),6);if(!n)return; auto *bar=detail_shape(detail_root,x,y,w,h,track,h/2); if(border){lv_obj_set_style_border_width(bar,1,0);lv_obj_set_style_border_color(bar,lv_color_hex(0xDDDDDD),0);} int inset=std::max(3,h/12),room=w-2*inset,words=0;int widths[6]; for(int i=0;i24) detail_text(detail_root," · "+t.extra().room,pad+dot+10+state_w,y,words-state_w,text,LV_TEXT_ALIGN_LEFT,0x5F6368); if(battery)vacuum_power(detail_root,t,pad+inner-power_w,y,text,false); y+=line+(gap+4); } // Start (or pause, or resume) as the one blue button, dock beside it. int action_h=large?54:(small_hero?40:36),start_w=large?(inner-gap)*2/3:(inner-gap)/2; vacuum_command(cleaning?"\U000F03E4":"\U000F040A",cleaning?(large?"Pause cleaning":"Pause"):paused?"Resume":(large?"Start cleaning":"Clean"), pad,y,start_w,action_h,cleaning?1:0,true,text,icons,large?radius:action_h/2); vacuum_command("\U000F05F8","Dock",pad+start_w+gap,y,inner-start_w-gap,action_h,2,false,text,icons,large?radius:action_h/2); y+=action_h+gap; if(!mode && !suction && !water){ auto *note=detail_text(detail_root,"Automatic suction power",pad,y+gap,inner,text,LV_TEXT_ALIGN_CENTER,0x6B6B6B);(void)note; return; } // How it cleans. The Guition groups the rows on one white card; the small screen has no room for a card. int mode_h=large?48:34,row_h=large?44:32,step=large?10:6,edge=large?14:0,icon_w=large?40:26; int note_h=lv_font_get_line_height(text); int block=(mode?mode_h:0)+(suction?(mode?step:0)+row_h:0)+(water?((mode||suction)?step:0)+row_h:0)+(automatic?step+note_h+step:0); uint32_t track=large?0xF1F1F1:0xFFFFFF; if(large)detail_card(pad,y,inner,block+2*edge); int x=pad+edge,w=inner-2*edge; y+=edge; if(mode){vacuum_segments(t,*mode,50,x,y,w,mode_h,track,!large,text);y+=mode_h+step;} auto level=[&](const Choice &row,int first,const char *icon){ detail_text(detail_root,icon,x,y+(row_h-lv_font_get_line_height(icons))/2,icon_w,icons,LV_TEXT_ALIGN_LEFT,0x6B6B6B); vacuum_segments(t,row,first,x+icon_w,y,w-icon_w,row_h,track,!large,text); y+=row_h+step; }; if(suction)level(*suction,10,"\U000F0210"); if(water)level(*water,60,"\U000F058C"); if(automatic){ bool smart=tile_controls::shown_value(t,*mode,now).find("smart")!=std::string::npos; detail_text(detail_root,smart?"The robot chooses suction and water":"Suction and water as set per room",x,y,w,text,LV_TEXT_ALIGN_CENTER,0x6B6B6B); } } inline void show_detail(unsigned index){ if(index>=model.count)return;detail_index=index;auto &t=model.tiles[index]; if(!detail_font)detail_font=lv_obj_get_style_text_font(widgets[0].title,LV_PART_MAIN); if(!detail_root){detail_root=lv_obj_create(lv_screen_active());lv_obj_remove_style_all(detail_root);lv_obj_set_size(detail_root,lv_pct(100),lv_pct(100));lv_obj_remove_flag(detail_root,LV_OBJ_FLAG_SCROLLABLE);} detail_action_count=0;detail_status=nullptr;detail_badge_status=nullptr;detail_switch=nullptr;lv_obj_clean(detail_root);lv_obj_remove_flag(detail_root,LV_OBJ_FLAG_HIDDEN);lv_obj_move_foreground(detail_root); lv_obj_set_style_bg_color(detail_root,lv_color_hex(0xE7E7E7),0);lv_obj_set_style_bg_opa(detail_root,LV_OPA_COVER,0); int width=lv_display_get_horizontal_resolution(lv_display_get_default()), height=lv_display_get_vertical_resolution(lv_display_get_default()); bool large=width>=480;int pad=large?20:10, top=large?100:62, gap=large?12:6,bh=large?58:34,cw=(width-pad*2-gap)/2; // The same top bar as the board's own cards: a round back arrow at the left, the name centred. int bar=large?60:40,bar_x=large?16:10,bar_y=large?16:8; auto *back=detail_button("",bar_x,bar_y,bar,bar,-1);lv_obj_set_style_radius(back,LV_RADIUS_CIRCLE,0);lv_obj_set_style_bg_color(back,lv_color_hex(0xEEEEEE),0); auto *arrow=lv_obj_get_child(back,0);if(mini_icon_font)lv_obj_set_style_text_font(arrow,mini_icon_font,0);lv_label_set_text(arrow,"\U000F004D");lv_obj_set_size(arrow,LV_SIZE_CONTENT,LV_SIZE_CONTENT);lv_obj_center(arrow); const lv_font_t *title_font=watch_font?watch_font:detail_font; auto *heading=detail_label(detail_root,t.name,bar_x+bar+8,bar_y+(bar-lv_font_get_line_height(title_font))/2,width-2*(bar_x+bar+8)); lv_obj_set_style_text_font(heading,title_font,0);lv_obj_set_height(heading,lv_font_get_line_height(title_font));lv_obj_set_style_text_align(heading,LV_TEXT_ALIGN_CENTER,0); std::string state=detail_state(t); auto d=t.domain(); // The vacuum card draws its own state (hero or status row) with the battery beside it. if(d!="vacuum"){detail_status=detail_label(detail_root,state+(t.unit.empty()?"":" "+t.unit),pad,large?80:50,width-2*pad);lv_obj_set_style_text_align(detail_status,LV_TEXT_ALIGN_CENTER,0);lv_obj_set_style_text_color(detail_status,lv_color_hex(0x616161),0);} if(t.is_switch()){ detail_label(detail_root,"Tap to toggle",pad,top,width-2*pad); detail_switch=lv_switch_create(detail_root); lv_obj_set_size(detail_switch,large?240:140,large?112:64); lv_obj_set_pos(detail_switch,(width-(large?240:140))/2,top+(large?65:30)); lv_obj_set_style_bg_color(detail_switch,lv_color_hex(0xB0B0B0),LV_PART_MAIN); lv_obj_set_style_bg_color(detail_switch,lv_color_hex(0xFFB900),LV_PART_INDICATOR|LV_STATE_CHECKED); lv_obj_set_style_bg_color(detail_switch,lv_color_hex(0xFFFFFF),LV_PART_KNOB); lv_obj_set_style_opa(detail_switch,LV_OPA_50,LV_STATE_DISABLED); if(t.state=="on")lv_obj_add_state(detail_switch,LV_STATE_CHECKED); lv_obj_add_event_cb(detail_switch,[](lv_event_t *e){ if(detail_index>=model.count)return; auto &tile=model.tiles[detail_index];auto *control=lv_event_get_target_obj(e); bool allowed=fresh() && tile.available() && !tile.awaiting_action(esphome::millis()) && cyd::touch_guard.accept(esphome::millis(),350); bool requested_on=lv_obj_has_state(control,LV_STATE_CHECKED); // Only HA's reported state is authoritative, including a refused/failed command. if(tile.state=="on")lv_obj_add_state(control,LV_STATE_CHECKED);else lv_obj_remove_state(control,LV_STATE_CHECKED); if(allowed)action(tile.domain()+(requested_on?".turn_on":".turn_off"),tile.entity); },LV_EVENT_VALUE_CHANGED,nullptr); detail_actions[detail_action_count++]=detail_switch; }else if(d=="vacuum"){ render_vacuum_detail(t,large,width,height,pad); }else if(d=="sensor"){ float minimum=INFINITY,maximum=-INFINITY;for(float value:t.history)if(t.has_history&&std::isfinite(value)){minimum=std::min(minimum,value);maximum=std::max(maximum,value);} if(!std::isfinite(minimum)){detail_label(detail_root,"No numeric HA history",pad,top,width-2*pad);return;} char text[100];snprintf(text,sizeof(text),"%u hours / %.2f - %.2f %s",t.history_hours,minimum,maximum,t.unit.c_str());detail_label(detail_root,text,pad,top,width-2*pad); int chart_y=top+(large?46:28),chart_h=height-chart_y-30,bar_w=(width-pad*2)/24; for(unsigned i=0;iminimum?8+(chart_h-8)*(t.history[i]-minimum)/(maximum-minimum):chart_h/2; auto *bar=lv_obj_create(detail_root);lv_obj_remove_style_all(bar);lv_obj_set_pos(bar,pad+i*bar_w,chart_y+chart_h-h);lv_obj_set_size(bar,std::max(2,bar_w-2),h);lv_obj_set_style_bg_color(bar,lv_color_hex(0x16A5E6),0);lv_obj_set_style_bg_opa(bar,LV_OPA_COVER,0);} detail_label(detail_root,std::to_string(t.history_hours)+" hours ago",pad,height-24,(width-2*pad)/2); auto *now=detail_label(detail_root,"Now",width/2,height-24,width/2-pad);lv_obj_set_style_text_align(now,LV_TEXT_ALIGN_RIGHT,0); }else if(d=="select"||d=="input_select"){ const auto &options=t.extra().options; for(unsigned i=0;i= 3600) snprintf(b, sizeof(b), "%u:%02u:%02u", seconds / 3600, seconds / 60 % 60, seconds % 60); else snprintf(b, sizeof(b), "%u:%02u", seconds / 60, seconds % 60); return b; } // "Last 14:32" today, "Yesterday 14:32", else "Last 13 Sep"; scripts and scenes have no useful on/off. inline std::string month_short(const esphome::ESPTime &now); inline std::string last_run_text(uint32_t epoch) { if (!epoch) return "Never run"; auto when = esphome::ESPTime::from_epoch_local(epoch); auto now = now_time ? now_time() : esphome::ESPTime{}; if (!when.is_valid()) return "Never run"; char clock[8]; snprintf(clock, sizeof(clock), "%02d:%02d", when.hour, when.minute); if (now.is_valid() && now.year == when.year && now.day_of_year == when.day_of_year) return std::string("Last ") + clock; if (now.is_valid() && now.year == when.year && now.day_of_year == when.day_of_year + 1) return std::string("Yesterday ") + clock; return "Last " + std::to_string(when.day_of_month) + " " + month_short(when); } inline std::string timer_text(const Tile &t) { const Extra &x = t.extra(); if (t.state == "active") { uint32_t now = now_epoch(); return countdown(x.timer_end > now && now ? x.timer_end - now : 0); } if (t.state == "paused") return "Paused " + countdown(duration_seconds(x.remaining)); return x.duration.empty() ? "Off" : countdown(duration_seconds(x.duration)); } inline std::string weekday_text(const esphome::ESPTime &now) { static const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; return now.is_valid() && now.day_of_week >= 1 && now.day_of_week <= 7 ? days[now.day_of_week - 1] : ""; } inline std::string month_short(const esphome::ESPTime &now) { static const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; return now.is_valid() && now.month >= 1 && now.month <= 12 ? months[now.month - 1] : ""; } inline std::string date_text(const esphome::ESPTime &now) { static const char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; if (!now.is_valid() || now.day_of_week < 1 || now.day_of_week > 7 || now.month < 1 || now.month > 12) return ""; return weekday_text(now) + " " + std::to_string(now.day_of_month) + " " + months[now.month - 1]; } inline void event(lv_event_t *event) { auto &w = *static_cast(lv_event_get_user_data(event)); if (!enabled || w.index >= model.count) return; auto code = lv_event_get_code(event); if (code != LV_EVENT_SHORT_CLICKED && code != LV_EVENT_LONG_PRESSED) return; // The built-in cards need nothing from Home Assistant: the settings card opens the screen's own page with // the link down too, as its card says (firmware 0.2.49+), and the clock card does nothing under a finger. if (model.tiles[w.index].builtin()) { auto &card = model.tiles[w.index]; if (!card.is_settings() || card.tap == "none" || (settings_screen::may_open && !settings_screen::may_open())) return; if (allowed(esphome::millis(), 100 + w.index, card.entity)) settings_screen::open(); return; } if (!fresh()) return; if (!allowed(esphome::millis(), 100 + w.index, model.tiles[w.index].entity)) return; auto &tile = model.tiles[w.index]; auto d = tile.domain(); // Scenes/scripts often have timestamps or 'off'; unavailable devices never act. if (!tile.available() || tile.loading(esphome::millis()) || tile.tap=="none") return; bool open = code == LV_EVENT_LONG_PRESSED || d == "climate" || d == "vacuum" || d == "cover"; if(code==LV_EVENT_SHORT_CLICKED && tile.tap=="detail")open=true; if(code==LV_EVENT_SHORT_CLICKED && tile.tap=="toggle")open=false; if(d=="media_player" && tile.tap=="toggle" && code==LV_EVENT_SHORT_CLICKED){action("media_player.toggle",tile.entity);return;} if(d=="climate" && tile.tap=="toggle" && code==LV_EVENT_SHORT_CLICKED){action("climate.toggle",tile.entity);return;} // A short tap runs or pauses the timer; holding opens the card with a cancel button. if(d=="timer" && !open){action(tile.state=="active"?"timer.pause":"timer.start",tile.entity);return;} if(d=="sensor" || d=="binary_sensor" || d=="weather" || d=="number" || d=="input_number" || d=="select" || d=="input_select" || d=="media_player" || d=="vacuum" || d=="sun" || d=="person" || d=="timer") { tile.begin(esphome::millis(),true); active_index=w.index; show_detail(w.index); return; } if (open) { if (d == "light" || d == "climate" || d == "vacuum" || d == "fan" || d == "cover") { active_index = w.index; tile.begin(esphome::millis(),true); if (detail) detail(tile); } else { active_index=w.index;show_detail(w.index); } return; } if (d == "light" || d == "switch" || d == "input_boolean" || d == "fan") action(d + ".toggle", tile.entity); if (d == "scene" || d == "script") action(d + ".turn_on", tile.entity); if (d == "button" || d == "input_button") action(d + ".press", tile.entity); } // The same guard for any local style: a page switch mostly hands a slot the colours it already has, // and each real set refreshes the style and invalidates the object (about 0.3 ms on the Guition). inline void set_color(lv_obj_t *obj, lv_style_prop_t prop, lv_color_t color, lv_style_selector_t selector = 0) { lv_style_value_t current; if (lv_obj_get_local_style_prop(obj, prop, ¤t, selector) == LV_STYLE_RES_FOUND && lv_color_eq(current.color, color)) return; lv_style_value_t value{}; value.color = color; lv_obj_set_local_style_prop(obj, prop, value, selector); } inline void set_number(lv_obj_t *obj, lv_style_prop_t prop, int32_t number, lv_style_selector_t selector = 0) { lv_style_value_t current; if (lv_obj_get_local_style_prop(obj, prop, ¤t, selector) == LV_STYLE_RES_FOUND && current.num == number) return; lv_style_value_t value{}; value.num = number; lv_obj_set_local_style_prop(obj, prop, value, selector); } // Card sliders follow Home Assistant's control slider (a 42 px track there): corners of 12 and // 8 px on track and fill, a white handle 4 px wide and half the height, an eighth of the height in // from the end of the fill, and a fill that never gets shorter than a third of the height. LVGL // centres the knob on the end of the fill, so the knob is narrowed and moved back; the range starts // below zero, so at 0 the fill is still that short stub holding the handle. Values below zero never // leave the slider (see slider_event). Small strips keep round ends: the corners would not show. inline int slider_handle_width(int height) { return height > 20 ? 4 : 2; } inline int slider_stub(int height) { return std::max(height / 3, 2 * std::max(1, height / 8) + slider_handle_width(height)); } inline void slider_handle(lv_obj_t *slider, int width, int height) { int handle = slider_handle_width(height), inset = std::max(1, height / 8) + handle / 2, half = height >> 1; // Track and fill share one radius: a fill rounded less than its track makes LVGL draw the fill into // a buffer of its own size on every redraw (15 KB on a CYD card), which the CYD's heap can't spare. int corner = height > 20 ? height * 12 / 42 : LV_RADIUS_CIRCLE; set_number(slider, LV_STYLE_RADIUS, corner, LV_PART_MAIN); set_number(slider, LV_STYLE_RADIUS, corner, LV_PART_INDICATOR); set_number(slider, LV_STYLE_PAD_LEFT, inset + handle / 2 - half, LV_PART_KNOB); set_number(slider, LV_STYLE_PAD_RIGHT, handle / 2 - inset - (height - half), LV_PART_KNOB); set_number(slider, LV_STYLE_PAD_TOP, -(height / 4), LV_PART_KNOB); set_number(slider, LV_STYLE_PAD_BOTTOM, -(height / 4), LV_PART_KNOB); int stub = slider_stub(height), below = width > stub ? 1000 * stub / (width - stub) : 0; if (lv_slider_get_min_value(slider) != -below || lv_slider_get_max_value(slider) != 1000) lv_slider_set_range(slider, -below, 1000); } // An off light or fan shows only the grey track, as in Home Assistant: no fill, no handle. inline void slider_bar(lv_obj_t *slider, bool shown) { set_number(slider, LV_STYLE_BG_OPA, shown ? LV_OPA_COVER : LV_OPA_TRANSP, LV_PART_INDICATOR); set_number(slider, LV_STYLE_BG_OPA, shown ? LV_OPA_COVER : LV_OPA_TRANSP, LV_PART_KNOB); } inline bool slider_bar_shown(const Tile &t, bool on) { auto d = t.domain(); return on || (d != "light" && d != "fan"); } inline void set_hidden(lv_obj_t *obj, bool hidden) { if (hidden) lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN); else lv_obj_remove_flag(obj, LV_OBJ_FLAG_HIDDEN); } // A card's size as its styles request it. LVGL's own getters only follow after a layout pass, and // that pass walks every object on the screen, so the cards are laid out without asking for one. inline int tile_width(const Widgets &w) { int32_t width = lv_obj_get_style_width(w.tile, LV_PART_MAIN); return LV_COORD_IS_PX(width) ? width : lv_obj_get_width(w.tile); } inline int content_width(const Widgets &w) { return tile_width(w) - lv_obj_get_style_space_left(w.tile, LV_PART_MAIN) - lv_obj_get_style_space_right(w.tile, LV_PART_MAIN); } inline int content_height(const Widgets &w) { return lv_obj_get_height(w.tile) - lv_obj_get_style_space_top(w.tile, LV_PART_MAIN) - lv_obj_get_style_space_bottom(w.tile, LV_PART_MAIN); } inline void bind(size_t index, lv_obj_t *tile, lv_obj_t *title, lv_obj_t *value, lv_obj_t *circle, lv_obj_t *icon) { lv_obj_update_layout(tile); // Compact cards need room for two text lines and a separate dimmer track. if(lv_obj_get_height(tile)<=80){lv_obj_set_style_pad_top(tile,4,0);lv_obj_set_style_pad_bottom(tile,4,0);} lv_obj_set_style_border_width(tile,1,0); lv_obj_update_layout(tile); widgets[index] = {tile, title, value, circle, icon, index}; auto &w=widgets[index]; w.title_x=lv_obj_get_x(title);w.title_y=lv_obj_get_y(title);w.value_x=lv_obj_get_x(value);w.value_y=lv_obj_get_y(value);w.value_font=lv_obj_get_style_text_font(value,LV_PART_MAIN); w.base_width=lv_obj_get_width(tile); w.icon_font=lv_obj_get_style_text_font(icon,LV_PART_MAIN); w.unit=lv_label_create(tile);lv_obj_set_style_text_font(w.unit,w.value_font,0);lv_obj_remove_flag(w.unit,LV_OBJ_FLAG_CLICKABLE);lv_obj_add_flag(w.unit,LV_OBJ_FLAG_HIDDEN); // Fixed one-line boxes prevent wrapped names from overlapping the state on both boards. lv_obj_set_height(title,lv_font_get_line_height(lv_obj_get_style_text_font(title,LV_PART_MAIN))); lv_obj_set_height(value,lv_font_get_line_height(w.value_font)); lv_label_set_long_mode(title,LV_LABEL_LONG_DOT);lv_label_set_long_mode(value,LV_LABEL_LONG_DOT); w.progress=lv_obj_create(tile);lv_obj_remove_style_all(w.progress);lv_obj_set_size(w.progress,0,3);lv_obj_align(w.progress,LV_ALIGN_BOTTOM_LEFT,0,0);lv_obj_add_flag(w.progress,LV_OBJ_FLAG_HIDDEN); w.slider=lv_slider_create(tile);lv_obj_set_size(w.slider,lv_obj_get_width(tile)-24,lv_obj_get_height(tile)>80?28:10);lv_obj_align(w.slider,LV_ALIGN_BOTTOM_MID,0,0);lv_slider_set_range(w.slider,0,1000); // A short white bar inside the fill as handle, like the control sliders (invisible before 0.2.20). int strip=lv_obj_get_height(tile)>80?28:10; lv_obj_set_style_bg_color(w.slider,lv_color_hex(0xFFFFFF),LV_PART_KNOB);lv_obj_set_style_bg_opa(w.slider,LV_OPA_COVER,LV_PART_KNOB); slider_handle(w.slider,lv_obj_get_width(tile)-24,strip); lv_obj_set_style_border_width(w.slider,0,LV_PART_KNOB);lv_obj_set_style_shadow_width(w.slider,0,LV_PART_KNOB); lv_obj_set_style_radius(w.slider,2,LV_PART_KNOB);lv_obj_set_style_bg_color(w.slider,lv_color_hex(0xFCE5B4),LV_PART_MAIN);lv_obj_set_style_bg_color(w.slider,lv_color_hex(0xFFB900),LV_PART_INDICATOR); lv_obj_add_flag(w.slider,LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(w.slider,LV_OBJ_FLAG_GESTURE_BUBBLE); lv_obj_add_event_cb(w.slider,slider_event,LV_EVENT_ALL,(void*)(uintptr_t)index); lv_obj_add_event_cb(tile, event, LV_EVENT_SHORT_CLICKED, &widgets[index]); lv_obj_add_event_cb(tile, event, LV_EVENT_LONG_PRESSED, &widgets[index]); } inline void label(lv_obj_t *obj, const std::string &text) { if (text != lv_label_get_text(obj)) lv_label_set_text(obj, text.c_str()); } // lv_obj_set_style_* always invalidates the object; these only do so on a real change, // which keeps a one-second clock tick or a busy spinner from redrawing whole cards. inline void set_font(lv_obj_t *obj, const lv_font_t *value) { if (lv_obj_get_style_text_font(obj, LV_PART_MAIN) != value) lv_obj_set_style_text_font(obj, value, 0); } inline void set_text_align(lv_obj_t *obj, lv_text_align_t value) { if (lv_obj_get_style_text_align(obj, LV_PART_MAIN) != value) lv_obj_set_style_text_align(obj, value, 0); } inline void pad_vertical(lv_obj_t *obj, int value) { if (lv_obj_get_style_pad_top(obj, LV_PART_MAIN) != value) lv_obj_set_style_pad_top(obj, value, 0); if (lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN) != value) lv_obj_set_style_pad_bottom(obj, value, 0); } inline void set_line_width(lv_obj_t *obj, int value) { if (lv_obj_get_style_line_width(obj, LV_PART_MAIN) != value) lv_obj_set_style_line_width(obj, value, 0); } // HA's default domain/state palette. Pastel circles also identify inactive domains. // Custom Lovelace card/theme CSS is not an entity attribute and is not imported. inline uint32_t domain_accent(const Tile &t) { auto d=t.domain(); if(d=="light" || d=="switch" || d=="input_boolean" || d=="binary_sensor")return 0xFFC107; // A climate card that is off or in an unknown mode keeps HA's orange climate circle. if(d=="climate"){uint32_t c=tile_controls::mode_color(t.state);return c==0x9E9E9E?0xFF9800:c;} if(d=="vacuum")return t.state=="error"?0xF44336:0x009688; if(d=="fan")return 0x00BCD4; if(d=="cover")return 0x926BC7; if(d=="media_player")return 0x03A9F4; if(d=="scene" || d=="script")return 0x926BC7; if(d=="select" || d=="input_select")return 0x3F51B5; if(d=="number" || d=="input_number")return 0x009688; if(d=="weather")return t.state=="sunny"?0xFFC107:t.state=="clear-night"?0x6E41AB:0x03A9F4; if(d=="sun")return t.state=="above_horizon"?0xFF9800:0x6E41AB; if(d=="timer")return t.state=="active"?0x009688:t.state=="paused"?0xFF9800:0x9E9E9E; if(d=="person")return t.state=="home"?0x4CAF50:0x9E9E9E; if(d=="screen")return 0x2196F3; if(d=="sensor"){ if(t.unit=="lx")return 0xFFC107; if(t.unit=="°C" || t.unit=="°F")return 0xFF6F22; if(t.unit=="kWh" || t.unit=="Wh")return 0x926BC7; if(t.unit=="%")return 0x009688; } return 0x2196F3; } // Custom cards draw into a transparent `extra` container; parts are rebuilt only // when a slot changes mode, so paging keeps RAM use flat on the CYD. // A slot whose next card draws no custom part only hides them: paging back to the clock or // graph in that slot reuses its objects instead of creating them again (tens of ms per card). inline void hide_extra(Widgets &w) { if(!w.extra)return; if(!lv_obj_has_flag(w.extra,LV_OBJ_FLAG_HIDDEN))lv_obj_add_flag(w.extra,LV_OBJ_FLAG_HIDDEN); w.fill_points=nullptr;w.fill_count=0; } inline void end_extra(Widgets &w) { if(!w.extra)return; hide_extra(w); if(!w.extra_mode.empty()){lv_obj_clean(w.extra);w.parts.fill(nullptr);w.extra_mode.clear();delete[] w.points;w.points=nullptr;} } // Two triangles per segment between the polyline and its baseline. No canvas // buffer is needed, so the CYD can afford it as well. inline void extra_draw(lv_event_t *e) { auto &w=*static_cast(lv_event_get_user_data(e)); if(!w.fill_points || w.fill_count<2 || !w.fill_opa)return; auto *layer=lv_event_get_layer(e);lv_area_t area;lv_obj_get_coords(w.extra,&area); lv_draw_triangle_dsc_t dsc;lv_draw_triangle_dsc_init(&dsc);dsc.color=w.fill_color;dsc.opa=w.fill_opa; const lv_value_precise_t ox=area.x1+w.fill_x, oy=area.y1+w.fill_y, base=oy+w.fill_base; for(unsigned i=0;i+1