diff --git a/CLAUDE.md b/CLAUDE.md index fd54464..343891c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -218,7 +218,7 @@ See README.md for the overview. page (the HA "Mode" dropdown). Schedule and rules are stored in NVS (`system/schedule_store.cpp`, bump `VERSION` when `PageSchedule` changes). Pages used by the schedule or rules can't be deleted. -- The ESP32 flash slot is about 90% full (web page and fonts are in flash). Check the size +- The ESP32 flash slot is about 95% full (web page and fonts are in flash). Check the size after adding features; the web page could be served gzipped if it gets tight. - Fonts use the "FDF1" format of `logic/font.h`; the web page writes the same format. `logic/builtin_fonts.cpp` is generated: change `tools/make_builtin_fonts.py` and rerun it. diff --git a/Pictures/web-ui/schedule.png b/Pictures/web-ui/schedule.png index 2c7202d..2220630 100644 Binary files a/Pictures/web-ui/schedule.png and b/Pictures/web-ui/schedule.png differ diff --git a/docs/web-ui.md b/docs/web-ui.md index 172bd9a..a1e055b 100644 --- a/docs/web-ui.md +++ b/docs/web-ui.md @@ -64,7 +64,9 @@ to 6 pages or bitmaps that rotate (each for its own time, 5 s to 1 hour), switch the refresh effect or instantly. Rules bring a page to the front from a Home Assistant state (an entity or attribute, `=`, -`is not`, `above`, `below`): they show it while the state is true, add it to the rotation +`is not`, `above`, `below`, `contains`, `does not contain`), optionally with a second +condition that must be true as well (e.g. print state `=` `paused` and display message +`does not contain` `soaking`; an unknown value is never true): they show it while the state is true, add it to the rotation while it is true, or show it for a while when it becomes true. Each rule is read at its own interval (2-600 s) and can be limited to some of the blocks. The first rule that shows a page wins. A rule can leave a page chosen by hand alone (untick "also over a page chosen by diff --git a/platformio.ini b/platformio.ini index 238e656..1432a31 100644 --- a/platformio.ini +++ b/platformio.ini @@ -55,7 +55,8 @@ upload_command = "$PYTHONEXE" "$PROJECT_DIR/tools/nano_net_upload.py" "$SOURCE" ; ESP32 - controller, talks to the Nano over serial ; --------------------------------------------------------------------------- [esp32_common] -platform = espressif32 +; Pinned: Arduino core 2.0.17 (ESP-IDF 4.4). The firmware doesn't build on core 3 (watchdog API) +platform = espressif32@6.10.0 board = esp32doit-devkit-v1 ; factory = recovery app, ota_0 / ota_1 = clock firmware (see partitions.csv) board_build.partitions = partitions.csv diff --git a/src/esp32/app.cpp b/src/esp32/app.cpp index f00e7d9..f71683f 100644 --- a/src/esp32/app.cpp +++ b/src/esp32/app.cpp @@ -274,7 +274,8 @@ void appPageLoop(bool time_valid, const LocalTime &time) for (int i = 0; i < page_schedule.rule_count; i++) { const TriggerRule &r = page_schedule.rules[i]; - selector.setRuleState(i, ruleMatches(r, haApiValue(r.entity, r.attribute)), now); + const char *and_value = r.and_entity[0] ? haApiValue(r.and_entity, r.and_attribute) : nullptr; + selector.setRuleState(i, ruleMatches(r, haApiValue(r.entity, r.attribute), and_value), now); } time_known = time_valid; if (!time_valid) diff --git a/src/esp32/config.h b/src/esp32/config.h index 73e50fd..854246f 100644 --- a/src/esp32/config.h +++ b/src/esp32/config.h @@ -118,7 +118,7 @@ const uint32_t SETUP_AP_DELAY = 20000; // open the AP when WiFi fails thi const uint32_t WIFI_CONNECT_TIMEOUT = 30000; const uint32_t WIFI_RESTART_TIME = 10UL * 60 * 1000; -#define FIRMWARE_VERSION "2.19.3" +#define FIRMWARE_VERSION "2.20.0" // Home Assistant device id (do not change: Home Assistant's entities are linked to it) const uint8_t HA_DEVICE_ID[] = {0x34, 0x86, 0x5d, 0x3a, 0x08, 0x28}; diff --git a/src/esp32/logic/page_schedule.cpp b/src/esp32/logic/page_schedule.cpp index edd8487..8624897 100644 --- a/src/esp32/logic/page_schedule.cpp +++ b/src/esp32/logic/page_schedule.cpp @@ -50,10 +50,16 @@ const char *validateSchedule(const PageSchedule &s) return "Rules need an entity id like sensor.printer_state"; if (!terminated(r.attribute, sizeof(r.attribute)) || !validAttribute(r.attribute)) return "Invalid attribute"; - if (r.compare >= Compare::Count || r.mode >= TriggerMode::Count) + if (r.compare >= Compare::Count || r.and_compare >= Compare::Count || r.mode >= TriggerMode::Count) return "Unknown rule setting"; if (!terminated(r.value, sizeof(r.value))) return "Rule value too long (32 characters)"; + if (!terminated(r.and_entity, sizeof(r.and_entity)) || (r.and_entity[0] && !validEntityId(r.and_entity))) + return "Rules need an entity id like sensor.printer_state"; + if (!terminated(r.and_attribute, sizeof(r.and_attribute)) || !validAttribute(r.and_attribute)) + return "Invalid attribute"; + if (!terminated(r.and_value, sizeof(r.and_value))) + return "Rule value too long (32 characters)"; if (!terminated(r.page, sizeof(r.page)) || !validBitmapName(r.page)) return "Choose a page for each rule"; if (r.mode != TriggerMode::WhileTrue && (r.seconds < 1 || r.seconds > ITEM_SECONDS_MAX)) @@ -74,6 +80,21 @@ static bool sameText(const char *a, const char *b) return *a == *b; } +// Whether `part` is somewhere in `text`, without case +static bool hasText(const char *text, const char *part) +{ + for (;; text++) + { + const char *a = text, *b = part; + while (*a && *b && tolower((unsigned char)*a) == tolower((unsigned char)*b)) + a++, b++; + if (!*b) + return true; + if (!*text) + return false; + } +} + static bool number(const char *text, double &value) { char *end; @@ -86,26 +107,36 @@ bool ruleInBlock(const TriggerRule &rule, int block) return rule.blocks == 0 || block < 0 || (rule.blocks >> block) & 1; } -bool ruleMatches(const TriggerRule &rule, const char *value) +static bool conditionTrue(Compare compare, const char *value, const char *wanted) { if (value == nullptr) return false; double a, b; - switch (rule.compare) + switch (compare) { case Compare::Equal: - return sameText(value, rule.value); + return sameText(value, wanted); case Compare::NotEqual: - return !sameText(value, rule.value); + return !sameText(value, wanted); case Compare::Above: - return number(value, a) && number(rule.value, b) && a > b; + return number(value, a) && number(wanted, b) && a > b; case Compare::Below: - return number(value, a) && number(rule.value, b) && a < b; + return number(value, a) && number(wanted, b) && a < b; + case Compare::Contains: + return hasText(value, wanted); + case Compare::NotContains: + return !hasText(value, wanted); default: return false; } } +bool ruleMatches(const TriggerRule &rule, const char *value, const char *and_value) +{ + return conditionTrue(rule.compare, value, rule.value) && + (!rule.and_entity[0] || conditionTrue(rule.and_compare, and_value, rule.and_value)); +} + bool scheduleUses(const PageSchedule &s, const char *name) { for (int i = 0; i < s.block_count; i++) diff --git a/src/esp32/logic/page_schedule.h b/src/esp32/logic/page_schedule.h index f39fe64..d3c5c80 100644 --- a/src/esp32/logic/page_schedule.h +++ b/src/esp32/logic/page_schedule.h @@ -43,6 +43,8 @@ enum class Compare : uint8_t NotEqual, Above, // numbers Below, + Contains, // text, without case + NotContains, Count, }; @@ -68,6 +70,11 @@ struct TriggerRule bool over_manual = true; // also over a page picked by hand (false: it waits until the pick ends) bool over_slow_mode = false; // while its page is shown the display works normally (slow mode waits) bool skip_slow_mode = false; // AddToRotation: left out of the rotation while slow mode is on + // Optional second condition, which must be true as well (empty entity: none) + char and_entity[ELEMENT_ENTITY_SIZE] = ""; + char and_attribute[ELEMENT_ATTRIBUTE_SIZE] = ""; // empty: the state + Compare and_compare = Compare::Equal; + char and_value[RULE_VALUE_SIZE] = ""; }; struct PageSchedule @@ -86,8 +93,9 @@ const char *validateSchedule(const PageSchedule &schedule); // Whether a rule acts during this block (-1: no schedule runs, then always) bool ruleInBlock(const TriggerRule &rule, int block); -// Whether a rule's condition is true for this value (nullptr: not known, never true) -bool ruleMatches(const TriggerRule &rule, const char *value); +// Whether a rule's conditions are true for these values (nullptr: not known, never true). +// and_value is only used when the rule has a second condition. +bool ruleMatches(const TriggerRule &rule, const char *value, const char *and_value = nullptr); // Whether the schedule or a rule shows this page or bitmap (compared without case) bool scheduleUses(const PageSchedule &schedule, const char *name); diff --git a/src/esp32/net/ha_api.cpp b/src/esp32/net/ha_api.cpp index a21db46..f8f163d 100644 --- a/src/esp32/net/ha_api.cpp +++ b/src/esp32/net/ha_api.cpp @@ -269,6 +269,19 @@ void haApiWatch(const DynamicPage *page) } } +static void watchRuleEntity(const char *rule_entity, const char *attribute, uint16_t interval) +{ + String entity; + if (!expand(rule_entity, entity)) + return; + Entry &e = add(entity, attribute); + if (!e.watched()) + e.next_poll = millis(); + uint32_t ms = interval * 1000UL; + if (!e.rule_interval || ms < e.rule_interval) + e.rule_interval = ms; +} + void haApiWatchRules(const PageSchedule *schedule) { for (Entry &e : entries) @@ -278,15 +291,9 @@ void haApiWatchRules(const PageSchedule *schedule) for (int i = 0; i < schedule->rule_count; i++) { const TriggerRule &rule = schedule->rules[i]; - String entity; - if (!expand(rule.entity, entity)) - continue; - Entry &e = add(entity, rule.attribute); - if (!e.watched()) - e.next_poll = millis(); - uint32_t ms = rule.interval * 1000UL; - if (!e.rule_interval || ms < e.rule_interval) - e.rule_interval = ms; + watchRuleEntity(rule.entity, rule.attribute, rule.interval); + if (rule.and_entity[0]) + watchRuleEntity(rule.and_entity, rule.and_attribute, rule.interval); } } diff --git a/src/esp32/system/schedule_store.cpp b/src/esp32/system/schedule_store.cpp index ee581eb..6453e2c 100644 --- a/src/esp32/system/schedule_store.cpp +++ b/src/esp32/system/schedule_store.cpp @@ -6,9 +6,10 @@ static const char *NAMESPACE = "flipdot"; static const char *KEY = "schedule"; // Increase when PageSchedule changes; records of other versions are ignored (an empty -// schedule). 2.18.0 stored the schedule again in version 5. To keep the schedule over a -// change, add a frozen copy of the old layout and convert it (see git history). -static const uint16_t VERSION = 5; +// schedule). 2.20.0 added the second rule condition (version 6). To keep the schedule over a +// change, add a frozen copy of the old layout and convert it (see git history), or save it +// again through the web API after flashing. +static const uint16_t VERSION = 6; struct StoredSchedule { diff --git a/src/esp32/web/schedule_json.cpp b/src/esp32/web/schedule_json.cpp index a137513..5d844b4 100644 --- a/src/esp32/web/schedule_json.cpp +++ b/src/esp32/web/schedule_json.cpp @@ -5,7 +5,7 @@ #include "logic/settings.h" -static const char *const COMPARES[] = {"eq", "ne", "gt", "lt"}; +static const char *const COMPARES[] = {"eq", "ne", "gt", "lt", "contains", "not_contains"}; static const char *const MODES[] = {"while", "rotate", "for"}; template static int indexOf(const char *const (&names)[N], const char *name) @@ -63,6 +63,10 @@ void scheduleToJson(const PageSchedule &s, JsonObject out) o["over_manual"] = r.over_manual; o["over_slow_mode"] = r.over_slow_mode; o["skip_slow_mode"] = r.skip_slow_mode; + o["and_entity"] = r.and_entity; + o["and_attribute"] = r.and_attribute; + o["and_compare"] = COMPARES[(int)r.and_compare]; + o["and_value"] = r.and_value; JsonArray in_blocks = o["blocks"].to(); for (int b = 0; b < s.block_count; b++) if ((r.blocks >> b) & 1) @@ -107,12 +111,17 @@ const char *scheduleFromJson(JsonVariantConst in, PageSchedule &s) { TriggerRule &r = s.rules[s.rule_count++]; int compare = indexOf(COMPARES, o["compare"] | "eq"), mode = indexOf(MODES, o["mode"] | "while"); - if (compare < 0 || mode < 0) + int and_compare = indexOf(COMPARES, o["and_compare"] | "eq"); + if (compare < 0 || and_compare < 0 || mode < 0) return "Unknown rule setting"; r.compare = (Compare)compare; + r.and_compare = (Compare)and_compare; r.mode = (TriggerMode)mode; if (!copyText(o["entity"], r.entity, sizeof(r.entity)) || !copyText(o["attribute"], r.attribute, sizeof(r.attribute)) || - !copyText(o["value"], r.value, sizeof(r.value)) || !copyText(o["page"], r.page, sizeof(r.page))) + !copyText(o["value"], r.value, sizeof(r.value)) || !copyText(o["page"], r.page, sizeof(r.page)) || + !copyText(o["and_entity"], r.and_entity, sizeof(r.and_entity)) || + !copyText(o["and_attribute"], r.and_attribute, sizeof(r.and_attribute)) || + !copyText(o["and_value"], r.and_value, sizeof(r.and_value))) return "Rule text too long"; r.seconds = constrain(o["seconds"] | 30, 0, 65535); r.interval = constrain(o["interval"] | 10, 0, 65535); diff --git a/src/esp32/web/web_page.h b/src/esp32/web/web_page.h index 6f906ee..4b3e5c2 100644 --- a/src/esp32/web/web_page.h +++ b/src/esp32/web/web_page.h @@ -336,7 +336,7 @@ async function swSetStart(){const v=$('swstart').value;if(!v){msg('Pick a date a async function live(bits){await post('/api/live',{data:toHex(bits)});msg('Shown on the display')} async function stopLive(){await post('/api/live/stop');msg('Back to normal')} // schedule and rules -const RCMP=[['eq','='],['ne','is not'],['gt','above'],['lt','below']]; +const RCMP=[['eq','='],['ne','is not'],['gt','above'],['lt','below'],['contains','contains'],['not_contains','does not contain']]; const RMODE=[['while','show it while true'],['rotate','add it to the rotation while true'],['for','show it for a while when it becomes true']]; function sinp(o,k,type,props){const i=mk('input',Object.assign({type:type||'text',value:o[k]},props||{}));i.oninput=()=>{o[k]=type=='number'?Math.round(+i.value||0):i.value;schedDirty=true};return i} function ssel(o,k,opts,after){const s=mk('select');opts.forEach(([v,t])=>s.append(mk('option',{value:v,textContent:t})));if(!opts.some(x=>x[0]==o[k]))s.append(mk('option',{value:o[k],textContent:o[k]+' (gone)'})); @@ -365,6 +365,9 @@ function schedBuild(){if(!sched)return;schedLink();$('sc_en').checked=sched.enab mk('div',{className:'row'},mk('b',{textContent:(i+1)+'. When'}),sinp(ru,'entity','text',{placeholder:'sensor.mainsailos_current_print_state',size:30,maxLength:64}), sinp(ru,'attribute','text',{placeholder:'(the state)',size:10,maxLength:32}),ssel(ru,'compare',RCMP),sinp(ru,'value','text',{size:12,maxLength:32,placeholder:'printing'}), btn('Test',async()=>{state.textContent='now: '+await haValue(ru.entity,ru.attribute)})), + mk('div',{className:'row'},'and',sinp(ru,'and_entity','text',{placeholder:'(optional) second entity',size:30,maxLength:64}), + sinp(ru,'and_attribute','text',{placeholder:'(the state)',size:10,maxLength:32}),ssel(ru,'and_compare',RCMP),sinp(ru,'and_value','text',{size:12,maxLength:32}), + btn('Test',async()=>{state.textContent='now: '+await haValue(ru.and_entity,ru.and_attribute)})), mk('div',{className:'row'},'then',ssel(ru,'page',opts),ssel(ru,'mode',RMODE,()=>{secs.style.display=ru.mode=='while'?'none':'';skip.style.display=ru.mode=='rotate'?'':'none'}),secs,skip, 'read every',sinp(ru,'interval','number',{style:'width:5em',min:2,max:600}),'s',state,btn('Remove',()=>{sched.rules.splice(i,1);schedDirty=true;schedBuild()},'d')), mk('div',{className:'row'},(()=>{const c=mk('input',{type:'checkbox',checked:ru.over_manual!==false});c.onchange=()=>{ru.over_manual=c.checked;schedDirty=true}; @@ -378,7 +381,7 @@ function schedBuild(){if(!sched)return;schedLink();$('sc_en').checked=sched.enab function scAddBlock(){if(sched.blocks.length>=8){msg('8 blocks at most',true);return} sched.blocks.push({start:'12:00',effect:true,items:[{page:settings.page,seconds:30}]});sched.blocks.sort(bySlot);schedDirty=true;schedBuild()} function scAddRule(){if(sched.rules.length>=8){msg('8 rules at most',true);return} - sched.rules.push({entity:'',attribute:'',compare:'eq',value:'',page:settings.page,mode:'while',seconds:30,interval:10,over_manual:true,over_slow_mode:false,skip_slow_mode:false});schedDirty=true;schedBuild()} + sched.rules.push({entity:'',attribute:'',compare:'eq',value:'',page:settings.page,mode:'while',seconds:30,interval:10,over_manual:true,over_slow_mode:false,skip_slow_mode:false,and_entity:'',and_attribute:'',and_compare:'eq',and_value:''});schedDirty=true;schedBuild()} async function scSave(){sched.blocks.sort(bySlot);sched=await post('/api/schedule',schedPayload());schedDirty=false;schedBuild();msg('Schedule saved');loadLists([])} async function backToSchedule(){await post('/api/schedule/back');msg('Back to the schedule');setTimeout(pollStatusOnce,500)} async function pollStatusOnce(){try{status=await api('/api/status');$('sc_now').textContent='Showing: '+status.shown+' ('+status.shown_status+')';$('shownnow').textContent=$('sc_now').textContent}catch(e){}} diff --git a/test/test_esp32/test_main.cpp b/test/test_esp32/test_main.cpp index 5854bbd..8d7a6cd 100644 --- a/test/test_esp32/test_main.cpp +++ b/test/test_esp32/test_main.cpp @@ -1976,6 +1976,64 @@ void test_rule_comparisons() TEST_ASSERT_TRUE(ruleMatches(r, "-3")); } +void test_rule_contains() +{ + const char *soaking = "Soaking -- temp: 51.3C / 46.0C -- 26.8m remaining"; + TriggerRule r = rule("x", TriggerMode::WhileTrue); + r.compare = Compare::Contains; + strcpy(r.value, "soaking"); + TEST_ASSERT_TRUE(ruleMatches(r, soaking)); // without case + TEST_ASSERT_FALSE(ruleMatches(r, "Heating")); + TEST_ASSERT_FALSE(ruleMatches(r, "")); + TEST_ASSERT_FALSE(ruleMatches(r, nullptr)); + strcpy(r.value, "remaining"); + TEST_ASSERT_TRUE(ruleMatches(r, soaking)); // at the very end + strcpy(r.value, "remaining!"); + TEST_ASSERT_FALSE(ruleMatches(r, soaking)); // longer than what is left of the text + strcpy(r.value, "soaking"); + r.compare = Compare::NotContains; + TEST_ASSERT_FALSE(ruleMatches(r, soaking)); + TEST_ASSERT_TRUE(ruleMatches(r, "Heating")); + TEST_ASSERT_TRUE(ruleMatches(r, "")); + TEST_ASSERT_FALSE(ruleMatches(r, nullptr)); // unknown is never true +} + +void test_rule_second_condition() +{ + TriggerRule r = rule("x", TriggerMode::WhileTrue); + strcpy(r.value, "paused"); + // Without a second entity its value doesn't matter + TEST_ASSERT_TRUE(ruleMatches(r, "paused")); + TEST_ASSERT_TRUE(ruleMatches(r, "paused", "Soaking")); + + strcpy(r.and_entity, "sensor.message"); + r.and_compare = Compare::NotContains; + strcpy(r.and_value, "soaking"); + TEST_ASSERT_TRUE(ruleMatches(r, "paused", "Filament runout")); + TEST_ASSERT_FALSE(ruleMatches(r, "paused", "Soaking -- temp: 51.3C")); + TEST_ASSERT_FALSE(ruleMatches(r, "printing", "Filament runout")); + TEST_ASSERT_FALSE(ruleMatches(r, nullptr, "Filament runout")); + TEST_ASSERT_FALSE(ruleMatches(r, "paused", nullptr)); // unknown is never true +} + +void test_schedule_checks_the_second_condition() +{ + PageSchedule s; + s.rule_count = 1; + s.rules[0] = rule("x", TriggerMode::WhileTrue); + TEST_ASSERT_NULL(validateSchedule(s)); // no second condition is fine + strcpy(s.rules[0].and_entity, "sensor.message"); + TEST_ASSERT_NULL(validateSchedule(s)); + strcpy(s.rules[0].and_entity, "not an entity"); + TEST_ASSERT_NOT_NULL(validateSchedule(s)); + strcpy(s.rules[0].and_entity, "sensor.message"); + strcpy(s.rules[0].and_attribute, "a b"); + TEST_ASSERT_NOT_NULL(validateSchedule(s)); + s.rules[0].and_attribute[0] = '\0'; + s.rules[0].and_compare = Compare::Count; + TEST_ASSERT_NOT_NULL(validateSchedule(s)); +} + void test_selector_without_schedule_shows_the_chosen_page() { PageSelector sel; @@ -3375,6 +3433,9 @@ int main() RUN_TEST(test_moving_page_is_redrawn_when_due); RUN_TEST(test_schedule_validation); RUN_TEST(test_rule_comparisons); + RUN_TEST(test_rule_contains); + RUN_TEST(test_rule_second_condition); + RUN_TEST(test_schedule_checks_the_second_condition); RUN_TEST(test_selector_without_schedule_shows_the_chosen_page); RUN_TEST(test_selector_rotates_the_block); RUN_TEST(test_selector_manual_pick_until_the_next_block);