/** * **************** Roborock Sequence Scheduler **************** * * Usage: * Schedule multiple Roborock Vacuums to perform room sequence cleanings. * Choose the rooms cleaned and the room cleaning order for the sequence, as well as mop settings for each room. * Each robot can run their sequences concurrently, if desired, and the app will keep track of the sequence states independently. * Optional: a blocking device can be chosen to stop sequences from starting until the blocking device attribute clears * Optional: multiple blocking devices can be added to stop individual rooms from starting during the sequence, until the room blocking device attribute clears. Option for = and != value. * Optional: speaker device for each room to announce a room cleaning is about to start * Optional: use a chosen speaker device to annouce robot and dock errors when they happen. * Optional: auto empty for self-emptying vacs: Enter a Sq foot cleaned limit for each vac since last empty, to cause the vac to empty between rooms if it goes over limit. * Optional: signal light using an RGB bulb device for status. Green=Cleaning, Yellow=Blocked/waiting, Blue=Water Erros, Red=Other Robot Error, also includes brightness and hue settings * Optional: create a child pushable button device to create html attributes and room clean buttons for dashboards, with Sequence Schedules, room clean button codes, and status. * Child device also contains a button attribute, to pull up the app settings page in an iframe, to modify settings from a dashboard attribute tile or the device page. * * Version History: * v. 1.0a- 04/17/26 - Initial Code Structure, UI settings page - No AI used * v. 1.0 - 08/01/26 - Gemini AI code refactor and finish DeepSeek AI Version History: * v. 1.1 - 08/14/26 - Stability fixes (stable room IDs, pause flag, concurrent sequence guard, dynamic buttons) * v. 1.2 - 08/15/26 - Fixed runIn targetStep unwrapping bug, added debug logging * v. 1.3 - 08/28/26 - Fixed delay-resume step tracking, added duplicate-room detection * v. 1.4 - 09/05/26 - Per-room delay devices (global pool, per-room subset) * v. 1.5 - 09/12/26 - Per-room attribute + trigger value; general settings reduced * v. 1.6 - 09/18/26 - Simplified delay: one device per room; global delay list removed * v. 1.7 - 09/25/26 - Per-room speakers (sequences + instant clean); announce room on start only * v. 1.8 - 10/02/26 - Vacuum error alerts: subscribe to 'error' and 'dockError', announce via global speaker * v. 1.9 - 10/10/26 - UI Overhaul: visual grouping, 12-column alignment * v. 2.0 - 10/15/26 - Fixed cron scheduling overwrite bug (unique handlers), UI alignment fix * v. 2.1 - 10/20/26 - Added Room Order feature (dropdown sorting) * v. 2.2 - 10/23/26 - Added Sequence-level start delay feature * v. 2.3 - 10/26/26 - Implemented Auto-Empty (SqFt Limit) feature * v. 2.4 - 10/28/26 - Added timeout for block devices; Button 0 aborts waiting sequences * v. 2.5 - 10/30/26 - Fixed speech command handling, added safe fallbacks for room names * v. 2.6 - 10/30/26 - Conditionally hide SqFt Limit if Auto-Empty is false; updated label * v. 2.7 - 10/30/26 - Split sequenceList into separate attributes per vacuum to avoid string length limits * v. 2.8 - 10/31/26 - Added vacuum name to sequence lists; removed mop and speaker settings from lists * v. 2.9 - 10/31/26 - Overhauled engine to support concurrent sequences running on multiple vacuums at once * v. 2.10 - 10/31/26 - Fixed null pointer exception in delay device and vacuum state handlers * v. 2.11 - 10/31/26 - Include vacuum name in room cleaning speech announcements * v. 2.12 - 10/31/26 - Use sequence name instead of number in schedulerStatus messages * v. 2.13 - 10/31/26 - Added detailed debug logging for block states; updated tile status for block waits * v. 2.14 - 10/31/26 - Added exhaustive skip-condition logging in vacuumStateHandler to diagnose stuck sequences * v. 2.15 - 10/31/26 - Fixed state serialization bug (String vs Integer keys) causing sequences to fail to resume * v. 2.16 - 10/31/26 - Added sequence enable/disable switches; removed unnecessary debug log in delay handler * v. 2.17 - 10/31/26 - Removed hard-coded 10 sequence limit; use overwrite: false and data map * v. 2.18 - 10/31/26 - Added multiple blocking devices per room, with Add/Remove buttons and = / != operators * v. 2.19 - 10/31/26 - Adjusted layout of room blocking UI fields and updated labels * v. 2.20 - 10/31/26 - Matched room header font size to sequence header; kept bold * v. 2.21 - 10/31/26 - Added iframe Settings button to child driver; app triggers frame refresh on update * v. 2.22 - 10/31/26 - Styled iframe Settings button with outline, grey background, and 3D effect * v. 2.23 - 10/31/26 - Minified iframe Settings button HTML/CSS to prevent exceeding 1024 char dashboard limit * v. 2.24 - 10/31/26 - Reset SqFt counter when vacuum enters 'emptying' state (manual empty detection) * v. 2.25 - 10/31/26 - Calculate and send bin percent full to binPercent1...10 attributes on display tile * v. 2.30 - 11/01/26 - Added per-vac color light for running state and error alerts * v. 2.31 - 11/01/26 - Fixed Map generic syntax error in updateVisualLights() * v. 2.32 - 11/01/26 - Added vac block separators/headers in UI; clarified light is optional * v. 2.33 - 11/02/26 - Added light dim level setting; Added yellow color for delay waiting states * v. 2.34 - 11/02/26 - Added custom hue inputs for each color signal state * v. 2.35 - 11/03/26 - Split block timeouts: 30min default for room blocks, 12hr default for seq blocks * v. 2.36 - 11/05/26 - Check vacuum error attributes at sequence completion to ensure error lights * v. 2.37 - 11/05/26 - Robust error subscriptions, periodic safety refresh, refresh on state change * v. 2.38 - 11/05/26 - Fixed silent hue parse failures; reliable vac ID matching; belt-and-suspenders off * v. 2.39 - 11/05/26 - Removed 1-minute polling workaround; relying on fixed subscriptions * v. 2.40 - 11/05/26 - Detect authorization errors; preserve room config; purple light; recover on healthStatus=online * v. 2.41 - 11/08/26 - Room history tracking (started/completed/canceled) sent to display tile * v. 2.42 - 11/11/26 - Fix light staying blue after clear: reliable off() + delayed error reconciliation * v. 2.43 - 11/15/26 - Exclude transient errors (wifi offline etc.); fix state map remove persistence Claude AI Version History: * v. 3.0 - 11/15/26 - Efficiency / stability refactor: * - runIn jobs for sequences now use overwrite:false plus a per-run token, so concurrent sequences no longer cancel each other * and stale jobs from an aborted/finished run are ignored * - Periodic "every X days" now counts days since last run (no longer resets at month boundaries) * - All state maps use String keys and copy->modify->reassign; sequence state saved through helpers * - Room matrix no longer rebuilt on every page render (only when vac selection changes, on init, on 'rooms' change, on auth recovery) * - Light commands cached (only sent when the desired color/level changes) * - Vac lookup by device id map; error refresh limited to the vac that fired * - Lazy (closure) debug logging; debug defaults to off and auto-disables after 30 min * - Tile events only sent when value changed; smaller status HTML * - Attribute metadata cached; duplicate block-evaluation, room-sort and setting-cleanup code consolidated * - Early dock/charging events within 60s of a room start are ignored (with a recheck watchdog) * v. 3.2 - 11/16/26 - Fix MissingPropertyException: Hubitat events have no 'oldValue'. This aborted vacuumErrorHandler * and healthStatusHandler before the error map/light were updated. Previous error value now comes from stored state. * v. 3.1 - 11/16/26 - Fix light staying blue after error cleared: light cache no longer trusted over the bulb's * reported switch state; a one-shot verify pass 20s after any light command resends if it didn't take **/ import java.text.SimpleDateFormat import groovy.json.JsonSlurper import groovy.transform.Field // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- @Field static final List NUMERIC_TYPES = ["NUMBER", "INTEGER", "FLOAT", "DOUBLE", "BIGDECIMAL", "LONG"] @Field static final List DOCK_STATES = ["charging", "docked", "charging_complete"] @Field static final List MOP_LEVELS = ["DEFAULT", "AUTO", "CUSTOM", "OFF", "LOW", "MEDIUM", "HIGH"] @Field static final List CLEAR_ERROR_VALUES = ["", "0", "none", "no error", "no_error", "clear", "cleared", "ok", "normal", "false"] @Field static final List TRANSIENT_ERROR_TEXT = [ "wifi offline", "wifi is offline", "wifi disconnected", "offline", "network offline", "network error", "connection lost", "connection error", "not connected", "disconnected", "no connection" ] @Field static final Map LIGHT_PRIORITY = [off: 0, green: 1, yellow: 2, red: 3, blue: 4, purple: 5] @Field static final long ROOM_START_GRACE_MS = 60000L // Per-room blocking-device setting fields and their input types @Field static final Map DELAY_FIELD_TYPES = [ delayDevice : "capability.*", delayEq : "enum", delayAttr : "enum", delayValueEnum : "enum", delayValueNumber : "number", delayValueString : "string", delayNumOp : "enum" ] @Field static final List VAC_SETTING_SUFFIXES = [ "", "AutoEmpty", "BinSqrFeet", "Light", "LightLevel", "LightHueGreen", "LightHueYellow", "LightHueRed", "LightHueBlue", "LightHuePurple" ] @Field static final List SEQ_SETTING_PREFIXES = [ "seqEnabled", "seqName", "seqTime", "seqUsePeriodic", "seqPeriodicDays", "seqDays", "seqRooms", "seqDelayAfter" ] definition ( name: "Roborock Sequence Scheduler", namespace: "Hubitat", author: "Chris Burgess", description: "Multi-Vac Room Scheduler", category: "My Apps", iconUrl: "", iconX2Url: "" ) preferences { page(name: "mainPage") } // --------------------------------------------------------------------------- // Logging & Helpers // --------------------------------------------------------------------------- // Lazy logging: the message closure is only evaluated when debug logging is on. // Usage: logDebug { "text ${var}" } void logDebug(Closure msg) { if (settings?.logEnable) { log.debug "RR-Scheduler: ${msg()}" } } void logsOff() { log.info "RR-Scheduler: debug logging disabled automatically" app.updateSetting("logEnable", [type: "bool", value: false]) } String getSeqName(int seqIdx) { def val = settings["seqName_${seqIdx}"]?.toString()?.trim() if (val == null || val == "") return "Sequence ${seqIdx}" return val } String getSeqBlockDeviceName(int seqIdx) { def dev = firstOrNull(settings["seq_${seqIdx}_seqDelayDevice"]) return dev ? dev.displayName : "Unknown Device" } List normalizeToList(val) { if (val == null) return [] if (val instanceof List) return val return [val] } def firstOrNull(val) { if (val == null) return null if (val instanceof List) return val ? val[0] : null return val } Date parseTimeInput(timeInput) { if (timeInput == null) return null if (timeInput instanceof Date) return timeInput String s = timeInput.toString() def formats = [ "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm", "HH:mm" ] for (String fmt in formats) { try { return new SimpleDateFormat(fmt).parse(s) } catch (Exception ignored) { } } def matcher = (s =~ /(\d{1,2}):(\d{2})/) if (matcher.find()) { Calendar cal = Calendar.getInstance() cal.set(Calendar.HOUR_OF_DAY, matcher.group(1).toInteger()) cal.set(Calendar.MINUTE, matcher.group(2).toInteger()) cal.set(Calendar.SECOND, 0) cal.set(Calendar.MILLISECOND, 0) return cal.getTime() } return null } boolean isClearErrorValue(String val) { if (val == null) return true return CLEAR_ERROR_VALUES.contains(val.trim().toLowerCase()) } boolean isAuthErrorValue(String val) { if (val == null) return false String lower = val.trim().toLowerCase() if (lower == "") return false return lower.contains("authoriz") || (lower.contains("auth") && lower.contains("error")) } boolean isTransientError(String val) { if (val == null) return false String lower = val.trim().toLowerCase() if (lower == "") return false return TRANSIENT_ERROR_TEXT.any { lower.contains(it) } } boolean isWaterError(String val) { if (!val) return false String lower = val.toLowerCase() return lower.contains("water") && (lower.contains("empty") || lower.contains("full") || lower.contains("shortage")) } int getHueSafe(String key, int defaultHue) { def v = settings[key] if (v == null) return defaultHue try { return v.toString().toBigDecimal().intValue() } catch (Exception e) { log.warn "RR-Scheduler: Invalid hue for ${key}: '${v}' - using default ${defaultHue}" return defaultHue } } // Whole days since epoch in the hub's local time zone long localEpochDay() { long nowMs = now() long offset = location.timeZone.getOffset(nowMs) return (nowMs + offset).intdiv(86400000L) } // ---- state helpers (copy -> modify -> reassign so changes always persist) ---- Map getRoomMatrix() { return (state.globalRoomMatrix ?: [:]) as Map } Map getActiveSequences() { return (state.activeSequences ?: [:]) as Map } void putActiveSequence(String seqKey, Map seqState) { Map m = new HashMap(getActiveSequences()) m[seqKey] = seqState state.activeSequences = m } void removeActiveSequence(String seqKey) { Map m = new HashMap(getActiveSequences()) m.remove(seqKey) state.activeSequences = m } // Room data for the step a running sequence is currently on (null if none) Map getCurrentRoomData(Map seqState) { if (!seqState?.running) return null int step = (seqState.step ?: 0) as int List rooms = (seqState.rooms ?: []) as List if (step < 1 || step > rooms.size()) return null return getRoomMatrix()[rooms[step - 1].toString()] as Map } def getTile() { return getChildDevice("rr_scheduler_child_" + app.id) } void buildVacIdxMap() { Map idxById = [:] int numVacs = (settings["numVacs"] ?: 0) as int for (int i = 1; i <= numVacs; i++) { def v = settings?."vac${i}" if (v) idxById[v.id.toString()] = i } state.vacIdxById = idxById } // Vac index (1..n) for an event's device, or -1 int getVacIdx(evt) { String id = (evt.deviceId ?: evt.getDevice()?.getId())?.toString() if (!id) return -1 if (!state.vacIdxById) buildVacIdxMap() def idx = (state.vacIdxById as Map)[id] return (idx != null) ? (idx as int) : -1 } List getSortedRooms(int s) { List rooms = normalizeToList(settings["seqRooms_${s}"]) List objs = [] rooms.eachWithIndex { code, idx -> int orderNum = idx + 1 def orderVal = settings["seq_${s}_order_${code}"] if (orderVal != null) { try { orderNum = orderVal.toString().toInteger() } catch (Exception e) { } } objs << [code: code.toString(), order: orderNum, origIdx: idx] } objs.sort { a, b -> (a.order == b.order) ? (a.origIdx <=> b.origIdx) : (a.order <=> b.order) } return objs.collect { it.code as String } } String roomDelaySettingName(int s, String roomCode, String field, int i) { String suffix = (i == 1) ? "" : "_${i}" return "seq_${s}_${field}${suffix}_${roomCode}".toString() } // Cached attribute metadata (numeric? enum?) so evaluations don't re-query the device Map getAttrMeta(dev, String attr) { String ck = "${dev.id}:${attr}".toString() Map cache = (state.attrMetaCache ?: [:]) as Map Map hit = cache[ck] as Map if (hit) return hit def meta = dev.getSupportedAttributes()?.find { it.getName() == attr } if (!meta) return null def vals = meta.getValues() String dt = meta.dataType?.toString()?.toUpperCase() ?: "STRING" Map out = [hasEnum: (vals && vals.size() > 0), numeric: NUMERIC_TYPES.contains(dt)] Map nc = new HashMap(cache) nc[ck] = out state.attrMetaCache = nc return out } // One getSupportedAttributes() call per device per page render Map getAttrInfo(dev, String selectedAttr) { def supported = dev.getSupportedAttributes() ?: [] List names = supported.collect { it.getName() as String }.unique().sort() Map info = [names: names, hasEnum: false, enumVals: [], numeric: false] if (selectedAttr && names.contains(selectedAttr)) { def meta = supported.find { it.getName() == selectedAttr } if (meta) { def vals = meta.getValues() String dt = meta.dataType?.toString()?.toUpperCase() ?: "STRING" if (vals && vals.size() > 0) { info.hasEnum = true info.enumVals = vals.collect { it.toString() }.sort() } else if (NUMERIC_TYPES.contains(dt)) { info.numeric = true } } } return info } void announce(spk, String msg) { String command = (settings.echoCommand ?: "speak").toString().trim().toLowerCase() logDebug { "SPEECH: Announcing to ${spk.displayName}: '${msg}' (command: ${command})" } try { if (command == "speakmessage") spk.speakMessage(msg) else spk.speak(msg) } catch (Exception e) { log.error "Speech failed on ${spk.displayName}: ${e.message}" } } // --------------------------------------------------------------------------- // UI Sections // --------------------------------------------------------------------------- def mainPage() { int numVacs = (settings["numVacs"] ?: 0) as int if (settings["numVacs"] == null) { app.updateSetting("numVacs", [type: "number", value: 0]) } // Cheap: only rebuilds when the vac selection changed ensureRoomMatrix(numVacs) dynamicPage( name: "mainPage", title: "Setup Panel", install: true, uninstall: true ) { section("App Name") { label title: "Assign Name", required: false } section("Diagnostics") { input (name: "logEnable", type: "bool", title: "Enable debug logging (auto-disables after 30 minutes)", defaultValue: false, submitOnChange: true) } buildVacuumSetupSection(numVacs) buildSpeechSetupSection() buildErrorAlertSection() buildDelayEngineSection() buildSequenceConfigSection() buildInstantMopOverrideSection() buildDashboardTileSection() } } void buildVacuumSetupSection(int numVacs) { section("Choose Vacuum Devices") { if (numVacs <= 0) { return } for (int i = 1; i <= numVacs; i++) { if (i > 1) { paragraph "
" } paragraph "
Vacuum #${i}
" input (name: "vac${i}", type: "capability.actuator", title: "Select Vacuum Device", required: false, submitOnChange: true) input (name: "vac${i}AutoEmpty", type: "bool", title: "Has Auto-Empty", defaultValue: true, submitOnChange: true) if (settings["vac${i}AutoEmpty"] != false) { input (name: "vac${i}BinSqrFeet", type: "number", title: "SqFt Cleaned to cause Auto-Empty", defaultValue: 50, submitOnChange: true) } input (name: "vac${i}Light", type: "capability.colorControl", title: "Visual State Light (optional)", required: false, submitOnChange: true, width: 8) input (name: "vac${i}LightLevel", type: "number", title: "Level (1-100)", defaultValue: 100, range: "1..100", required: false, submitOnChange: true, width: 4) input (name: "vac${i}LightHueGreen", type: "number", title: "Green Hue", defaultValue: 33, range: "0..100", required: false, submitOnChange: true, width: 2) input (name: "vac${i}LightHueYellow", type: "number", title: "Yellow Hue", defaultValue: 16, range: "0..100", required: false, submitOnChange: true, width: 2) input (name: "vac${i}LightHueRed", type: "number", title: "Red Hue", defaultValue: 0, range: "0..100", required: false, submitOnChange: true, width: 2) input (name: "vac${i}LightHueBlue", type: "number", title: "Blue Hue", defaultValue: 66, range: "0..100", required: false, submitOnChange: true, width: 2) input (name: "vac${i}LightHuePurple", type: "number", title: "Purple Hue", defaultValue: 75, range: "0..100", required: false, submitOnChange: true, width: 2) paragraph "Leave light blank to disable visual state signals for this vacuum. If set, light turns green while this vac is running a sequence, yellow when waiting on a delay, red on error, blue for water tank issues, purple for authorization errors, and off when idle or cleared." } } section("") { input (name: "addVac", type: "button", title: "Add Vac", width: 1, submitOnChange: true) input (name: "RemoveVac", type: "button", title: "Remove Vac", width: 2, submitOnChange: true) } } // Called from mainPage: rebuild only if the set of selected vacuums changed (or matrix is empty) void ensureRoomMatrix(int numVacs) { String sig = "${numVacs}:" for (int i = 1; i <= numVacs; i++) { sig += "${settings?."vac${i}"?.id ?: '-'}," } if (state.matrixSig != sig || !state.globalRoomMatrix) { buildGlobalMatrixEngine(numVacs) } } void buildGlobalMatrixEngine(int numVacs) { String sig = "${numVacs}:" int numChosen = 0 for (int i = 1; i <= numVacs; i++) { def v = settings?."vac${i}" sig += "${v?.id ?: '-'}," if (v) numChosen++ } state.matrixSig = sig if (numVacs <= 0 || numChosen != numVacs) { state.globalRoomMatrix = [:] state.maxButtonCode = 0 return } Map authErrs = (state.authErrored ?: [:]) as Map Map oldMatrix = getRoomMatrix() Map tempMatrix = [:] StringBuilder keyString = new StringBuilder() int maxButton = 0 for (int i = 1; i <= numVacs; i++) { def vac = settings?."vac${i}" if (!vac) continue String vacLabel = vac.getLabel() ?: "Vac ${i}" boolean authError = (authErrs["${i}"] == true) if (authError) { int preserved = 0 oldMatrix.each { key, data -> if (data?.vacuumIndex == i) { tempMatrix[key] = data int bc = (data.buttonCode ?: 0) as int if (bc > maxButton) maxButton = bc keyString.append("${bc}: ${data.roomName} (${data.vacLabel})
") preserved++ } } logDebug { "buildGlobalMatrixEngine: preserved ${preserved} rooms for auth-errored vac ${i}" } continue } def roomsRaw = vac.currentValue("rooms") if (!roomsRaw) { logDebug { "Vac${i} has no 'rooms' attribute (not auth-errored; will skip)" } continue } Map numKeyMap = null try { if (roomsRaw instanceof Map) { numKeyMap = roomsRaw } else { numKeyMap = new JsonSlurper().parseText(roomsRaw.toString()) as Map } } catch (Exception e) { log.error "Failed to parse rooms attribute for vac${i}: ${e.message}" continue } if (!numKeyMap) continue numKeyMap.each { nativeKey, roomName -> int nativeKeyInt try { nativeKeyInt = nativeKey.toString().toInteger() } catch (Exception e) { return } int buttonCode = (i * 100) + nativeKeyInt if (buttonCode > maxButton) { maxButton = buttonCode } tempMatrix[buttonCode.toString()] = [ buttonCode : buttonCode, vacuumIndex : i, roomName : roomName, nativeRoomId : nativeKey.toString(), vacLabel : vacLabel ] keyString.append("${buttonCode}: ${roomName} (${vacLabel})
") } } state.globalRoomMatrix = tempMatrix state.maxButtonCode = maxButton // Only talk to the tile if the key text actually changed String keyText = keyString.toString() if (state.lastRoomKey != keyText) { def tile = getTile() if (tile) { tile.sendEvent(name: "roomKey", value: keyText) if (maxButton > 0) { tile.sendEvent(name: "numberOfButtons", value: maxButton + 10) } state.lastRoomKey = keyText } } } // Debounced rebuild when a vac's 'rooms' attribute changes void roomsChangedHandler(evt) { logDebug { "ROOMS-EVT: rooms attribute changed on ${evt.displayName}; rebuilding matrix shortly" } runIn(5, "rebuildMatrixAndLists") } void rebuildMatrixAndLists() { buildGlobalMatrixEngine((settings["numVacs"] ?: 0) as int) compileAndPublishSequenceList() } void buildSpeechSetupSection() { section("Speech") { input (name: "echoCommand", type: "string", title: "Speech command method (usually 'speak' or 'speakMessage')", defaultValue: "speak", width: 6) paragraph "Speakers are chosen per-room in each sequence below, and per-room for instant-clean buttons. Leave a room's speaker blank to keep that room silent." } } void buildErrorAlertSection() { section("Vacuum Error Alerts") { paragraph "Announces changes to 'error' or 'dockError' on any selected vacuum. Clear values (empty, 'none', '0', 'false', etc.) are not announced unless recovering from an active error." input (name: "errorAlertSpeaker", type: "capability.speechSynthesis", title: "Speaker for vacuum error alerts (empty = silent)", width: 6, submitOnChange: true) } } void buildDelayEngineSection() { if (getRoomMatrix().size() <= 0) { return } section("Delay Engine") { paragraph "Delay devices, attributes, and trigger values are configured per-room and per-sequence below." input (name: "delayCheckInterval", type: "number", title: "Retry check interval while paused (minutes)", defaultValue: 5, range: "1..30", required: true, width: 12) input (name: "maxBlockWaitHours", type: "number", title: "Max hours to wait for a blocked sequence to start before dropping it", defaultValue: 12, range: "1..48", required: true, width: 12) input (name: "maxRoomBlockWaitMinutes", type: "number", title: "Max minutes to wait for a blocked room before skipping to the next room", defaultValue: 30, range: "1..180", required: true, width: 12) } } void buildSequenceConfigSection() { Map matrix = getRoomMatrix() if (matrix.size() <= 0) { return } section("Sequences Configuration") { int numSequences = (settings["numSequences"] ?: 1) as int if (settings["numSequences"] == null) { app.updateSetting("numSequences", [type: "number", value: 1]) } Map roomOptions = [:] matrix.each { codeKey, data -> roomOptions[codeKey] = "${data.roomName} (${data.vacLabel})" } for (int s = 1; s <= numSequences; s++) { String customName = settings["seqName_${s}"]?.toString()?.trim() String headerText = "Sequence #${s}" if (customName && customName != "Sequence ${s}") { headerText += " - ${customName}" } paragraph "
" paragraph "
${headerText}
" input(name: "seqEnabled_${s}", type: "bool", title: "Enable Sequence ${s}", defaultValue: true, width: 12, submitOnChange: true) if (settings["seqEnabled_${s}"] != false) { input (name: "seqName_${s}", type: "string", title: "Name", defaultValue: "Sequence ${s}", width: 4) input (name: "seqTime_${s}", type: "time", title: "Time", width: 4) input (name: "seqUsePeriodic_${s}", type: "bool", title: "Use Periodic Days", defaultValue: false, width: 4, submitOnChange: true) if (settings["seqUsePeriodic_${s}"] == true) { input (name: "seqPeriodicDays_${s}", type: "enum", title: "Run every X days", options: ["2", "3", "4", "5", "6"], defaultValue: "2", width: 12, submitOnChange: true) } else { input (name: "seqDays_${s}", type: "enum", title: "Days of Week", options: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], multiple: true, width: 12) } input (name: "seqRooms_${s}", type: "enum", title: "Select Rooms for Sequence", options: roomOptions, multiple: true, submitOnChange: true, width: 12) List selectedRooms = normalizeToList(settings["seqRooms_${s}"]) int numSelected = selectedRooms.size() Map orderOptions = [:] for (int i = 1; i <= numSelected; i++) { orderOptions[i.toString()] = i.toString() } selectedRooms.eachWithIndex { roomCode, idx -> Map roomMeta = matrix[roomCode.toString()] as Map if (roomMeta) { paragraph "
Room: ${roomMeta.roomName} (${roomMeta.vacLabel})
" input(name: "seq_${s}_order_${roomCode}", type: "enum", title: "Clean Order", options: orderOptions, defaultValue: "${idx + 1}", width: 2) input (name: "seq_${s}_mop_${roomCode}", type: "enum", title: "Mop Level", options: MOP_LEVELS, defaultValue: "DEFAULT", width: 3) input (name: "seq_${s}_speechDevice_${roomCode}", type: "capability.speechSynthesis", title: "Speaker (empty = silent)", width: 7) buildRoomDelayInputs(s, roomCode.toString(), roomMeta) } } paragraph "
" input (name: "seqDelayAfter_${s}", type: "number", title: "Delay Buffer (mins) after sequence finishes", defaultValue: 2, required: true, width: 12) paragraph "
Block Sequence Start
" input(name: "seq_${s}_seqDelayEnable", type: "bool", title: "Delay entire sequence from starting?", defaultValue: false, width: 12, submitOnChange: true) if (settings["seq_${s}_seqDelayEnable"]) { input(name: "seq_${s}_seqDelayDevice", type: "capability.*", title: "Delay Device", width: 7, submitOnChange: true) input(name: "seq_${s}_seqDelayEq", type: "enum", title: "Delay cleaning if", options: ["=", "!="], defaultValue: "=", width: 2, submitOnChange: true) def seqDelayDev = firstOrNull(settings["seq_${s}_seqDelayDevice"]) if (seqDelayDev) { String currentSeqAttr = settings["seq_${s}_seqDelayAttr"]?.toString() Map info = getAttrInfo(seqDelayDev, currentSeqAttr) List seqAttrs = info.names as List if (seqAttrs.size() > 0) { input(name: "seq_${s}_seqDelayAttr", type: "enum", title: "Attribute to Monitor", options: seqAttrs, width: 6, submitOnChange: true) if (currentSeqAttr && seqAttrs.contains(currentSeqAttr)) { if (info.hasEnum) { input(name: "seq_${s}_seqDelayValueEnum", type: "enum", title: "Attribute Value", options: info.enumVals, width: 6, submitOnChange: true) } else if (info.numeric) { input(name: "seq_${s}_seqDelayNumOp", type: "enum", title: "Operator", options: ["=", ">", "<", "<=", ">="], defaultValue: "=", width: 2, submitOnChange: true) input(name: "seq_${s}_seqDelayValueNumber", type: "number", title: "Value", width: 4, submitOnChange: true) } else { input(name: "seq_${s}_seqDelayValueString", type: "string", title: "Attribute Value", width: 6, submitOnChange: true) } } } else { paragraph "⚠ Device has no supported attributes." } } } } else { paragraph "Sequence disabled. Enable it above to configure." } } } section("") { input (name: "addSeq", type: "button", title: "Add Sequence", width: 2, submitOnChange: true) input (name: "removeSeq", type: "button", title: "Remove Sequence", width: 2, submitOnChange: true) } } void buildRoomDelayInputs(int s, String roomCode, Map roomMeta) { String enableName = "seq_${s}_delayEnable_${roomCode}" input (name: enableName, type: "bool", title: "Delay this room?", defaultValue: false, width: 12, submitOnChange: true) if (!settings[enableName]) { return } int count = (settings["seq_${s}_delayCount_${roomCode}"] ?: 1) as int for (int i = 1; i <= count; i++) { String devName = roomDelaySettingName(s, roomCode, "delayDevice", i) String eqName = roomDelaySettingName(s, roomCode, "delayEq", i) String attrName = roomDelaySettingName(s, roomCode, "delayAttr", i) String enumName = roomDelaySettingName(s, roomCode, "delayValueEnum", i) String numName = roomDelaySettingName(s, roomCode, "delayValueNumber", i) String strName = roomDelaySettingName(s, roomCode, "delayValueString", i) String opName = roomDelaySettingName(s, roomCode, "delayNumOp", i) if (!settings[eqName]) app.updateSetting(eqName, [type: "enum", value: "="]) paragraph "
" if (i > 1) { input (name: devName, type: "capability.*", title: "Blocking Device ${i}", width: 9, submitOnChange: true) input(name: "removeRoomDelay_${s}_${roomCode}_${i}", type: "button", title: "Remove", width: 3, submitOnChange: true) } else { input (name: devName, type: "capability.*", title: "Blocking Device ${i}", width: 12, submitOnChange: true) } def delayDev = firstOrNull(settings[devName]) if (delayDev) { String savedAttr = settings[attrName]?.toString() Map info = getAttrInfo(delayDev, savedAttr) List attrs = info.names as List if (attrs.size() == 0) { paragraph "⚠ ${delayDev.displayName} has no supported attributes." continue } if (savedAttr && !attrs.contains(savedAttr)) { paragraph "⚠ Previously selected attribute '${savedAttr}' is not on ${delayDev.displayName}. Please re-select." } input (name: attrName, type: "enum", title: "Attribute to Monitor", options: attrs, width: 4, submitOnChange: true) input (name: eqName, type: "enum", title: "Delay cleaning if", options: ["=", "!="], defaultValue: "=", width: 3, submitOnChange: true) if (!savedAttr || !attrs.contains(savedAttr)) { continue } if (info.hasEnum) { input (name: enumName, type: "enum", title: "Attribute Value", options: info.enumVals, width: 5, submitOnChange: true) } else if (info.numeric) { input (name: opName, type: "enum", title: "Operator", options: ["=", ">", "<", "<=", ">="], defaultValue: "=", width: 2, submitOnChange: true) input (name: numName, type: "number", title: "Value", width: 3, submitOnChange: true) } else { input (name: strName, type: "string", title: "Attribute Value", width: 5, submitOnChange: true) } } } if (count < 5) { input(name: "addRoomDelay_${s}_${roomCode}", type: "button", title: "Add Blocking Device", width: 12, submitOnChange: true) } } void buildInstantMopOverrideSection() { Map matrix = getRoomMatrix() if (matrix.size() <= 0) { return } section("Instant Clean - Mop & Speaker Overrides") { paragraph "Per-room mop level and speaker for instant-push dashboard buttons. Leave speaker blank for silent." matrix.each { codeKey, data -> input (name: "instantMop_${data.buttonCode}", type: "enum", title: "Mop Level [Code ${data.buttonCode}: ${data.roomName}]", options: MOP_LEVELS, defaultValue: "DEFAULT", width: 6) input (name: "instantSpeech_${data.buttonCode}", type: "capability.speechSynthesis", title: "Speaker [Code ${data.buttonCode}: ${data.roomName}]", width: 6) } } } void buildDashboardTileSection() { if (getRoomMatrix().size() <= 0) { return } section("Dashboard Tile") { input (name: "createChildDevice", type: "bool", title: "Create Status Tile?", defaultValue: false, submitOnChange: true) } } // --------------------------------------------------------------------------- // Button handler / Lifecycle // --------------------------------------------------------------------------- // Copy one room-delay setting to another slot (used when removing a blocking device) void copySetting(String src, String dst, String type) { def v = settings[src] if (v == null) { app.removeSetting(dst) } else { app.updateSetting(dst, [type: type, value: v]) } } void removeSequenceSettings(int s) { List exact = SEQ_SETTING_PREFIXES.collect { "${it}_${s}".toString() } String prefix = "seq_${s}_" settings.keySet().toList().findAll { String k -> k.startsWith(prefix) || exact.contains(k) }.each { String k -> app.removeSetting(k) } } def appButtonHandler(String buttonName) { logDebug { "APP BUTTON PUSHED: ${buttonName}" } if (buttonName.startsWith("addRoomDelay_")) { def parts = buttonName.split("_") int s = parts[1].toInteger() String roomCode = parts[2] String countKey = "seq_${s}_delayCount_${roomCode}" int count = (settings[countKey] ?: 1) as int app.updateSetting(countKey, [type: "number", value: count + 1]) return } if (buttonName.startsWith("removeRoomDelay_")) { def parts = buttonName.split("_") int s = parts[1].toInteger() String roomCode = parts[2] int idx = parts[3].toInteger() String countKey = "seq_${s}_delayCount_${roomCode}" int count = (settings[countKey] ?: 1) as int // Shift everything above the removed slot down by one for (int j = idx; j < count; j++) { DELAY_FIELD_TYPES.each { String field, String type -> copySetting(roomDelaySettingName(s, roomCode, field, j + 1), roomDelaySettingName(s, roomCode, field, j), type) } } // Clear the now-unused last slot DELAY_FIELD_TYPES.keySet().each { String field -> app.removeSetting(roomDelaySettingName(s, roomCode, field, count)) } app.updateSetting(countKey, [type: "number", value: count - 1]) return } switch(buttonName) { case "addVac": app.updateSetting("numVacs", [type: "number", value: ((settings["numVacs"] ?: 0) as int) + 1]) break case "RemoveVac": int vCur = (settings["numVacs"] ?: 0) as int if (vCur > 0) { VAC_SETTING_SUFFIXES.each { String suffix -> app.removeSetting("vac${vCur}${suffix}") } app.updateSetting("numVacs", [type: "number", value: vCur - 1]) } break case "addSeq": app.updateSetting("numSequences", [type: "number", value: ((settings["numSequences"] ?: 1) as int) + 1]) break case "removeSeq": int sCur = (settings["numSequences"] ?: 1) as int if (sCur > 1) { removeSequenceSettings(sCur) app.updateSetting("numSequences", [type: "number", value: sCur - 1]) } break } } def installed() { initialize() } def updated() { initialize() // Must be scheduled after initialize(), which calls unschedule() if (settings.logEnable) runIn(1800, "logsOff") } def initialize() { logDebug { "Initializing app..." } unschedule() unsubscribe() state.activeSequences = [:] state.attrMetaCache = [:] state.lastLight = [:] state.lastStatusMsg = null if (state.lastErrorAnnounce == null) state.lastErrorAnnounce = [:] if (state.sentVacLists == null) state.sentVacLists = [:] if (state.sentBinPercents == null) state.sentBinPercents = [:] if (state.authErrored == null) state.authErrored = [:] if (state.lastPeriodicRun == null) state.lastPeriodicRun = [:] Map authErrs = new HashMap((state.authErrored ?: [:]) as Map) Map idxById = [:] int numVacs = (settings["numVacs"] ?: 0) as int for (int i = 1; i <= numVacs; i++) { if (state."vac${i}TotalSqFt" == null) state."vac${i}TotalSqFt" = 0 if (state."vac${i}Errors" == null) state."vac${i}Errors" = [:] def vacDevice = settings?."vac${i}" if (!vacDevice) continue idxById[vacDevice.id.toString()] = i subscribe(vacDevice, "state", "vacuumStateHandler") subscribe(vacDevice, "error", "vacuumErrorHandler") subscribe(vacDevice, "dockError", "vacuumErrorHandler") subscribe(vacDevice, "healthStatus", "healthStatusHandler") subscribe(vacDevice, "rooms", "roomsChangedHandler") def currentState = vacDevice.currentValue("state")?.toString() ?: "" if (isAuthErrorValue(currentState)) { authErrs["${i}"] = true logDebug { "initialize: vac${i} ${vacDevice.displayName} currently in authorization-error state" } } } state.vacIdxById = idxById state.authErrored = authErrs // Subscribe once per (attribute, device) for all blocking devices Map subsByAttr = [:] int numSeqs = (settings["numSequences"] ?: 1) as int for (int s = 1; s <= numSeqs; s++) { if (settings["seqEnabled_${s}"] == false) continue if (settings["seq_${s}_seqDelayEnable"]) { def dev = firstOrNull(settings["seq_${s}_seqDelayDevice"]) String attr = settings["seq_${s}_seqDelayAttr"]?.toString() if (dev && attr) { if (!subsByAttr[attr]) subsByAttr[attr] = [:] subsByAttr[attr][dev.id.toString()] = dev } } normalizeToList(settings["seqRooms_${s}"]).each { code -> if (!(settings["seq_${s}_delayEnable_${code}"] as Boolean)) return int count = (settings["seq_${s}_delayCount_${code}"] ?: 1) as int for (int i = 1; i <= count; i++) { def dev = firstOrNull(settings[roomDelaySettingName(s, code.toString(), "delayDevice", i)]) String attr = settings[roomDelaySettingName(s, code.toString(), "delayAttr", i)]?.toString() if (dev && attr) { if (!subsByAttr[attr]) subsByAttr[attr] = [:] subsByAttr[attr][dev.id.toString()] = dev } } } } subsByAttr.each { attr, devMap -> subscribe(devMap.values() as List, attr, "delayDeviceChangeHandler") } manageChildDevice() buildGlobalMatrixEngine(numVacs) buildAutomatedCronSchedules() compileAndPublishSequenceList() updateBinPercentages() refreshVacuumErrors() updateVisualLights() logDebug { "initialize() complete. Rooms in matrix: ${getRoomMatrix().size()}" } } void manageChildDevice() { String childNetworkId = "rr_scheduler_child_" + app.id def childDevice = getChildDevice(childNetworkId) boolean wantDevice = settings.createChildDevice ?: false if (wantDevice && childDevice) { childDevice.setAppFrame() return } if (!wantDevice && !childDevice) { return } // Tile is being created or deleted: forget what we last sent to it state.lastRoomKey = null state.lastStatusMsg = null state.sentVacLists = [:] state.sentBinPercents = [:] if (!wantDevice) { logDebug { "Deleting child device" } deleteChildDevice(childNetworkId) return } Map childProperties = [:] childProperties.label = "Roborock Scheduler Tile" childProperties.isComponent = true logDebug { "Creating child device ${childNetworkId}" } def newDevice = addChildDevice("Hubitat", "Roborock Scheduler Display Tile", childNetworkId, null, childProperties) if (newDevice) newDevice.setAppFrame() updateDashboardHtml("Ready.") } // --------------------------------------------------------------------------- // Visual State Light Engine & History // --------------------------------------------------------------------------- void addChildHistory(String roomName, String status) { def childDevice = getTile() if (!childDevice) return try { childDevice.addHistoryEvent(roomName, status) } catch (Exception e) { log.warn "addChildHistory failed: ${e.message}" } } // Re-read error attributes from the driver. Pass a vac index to refresh only that vac. void refreshVacuumErrors(int onlyIdx = 0) { int numVacs = (settings["numVacs"] ?: 0) as int Map authErrs = (state.authErrored ?: [:]) as Map int from = (onlyIdx > 0) ? onlyIdx : 1 int to = (onlyIdx > 0) ? Math.min(onlyIdx, numVacs) : numVacs for (int i = from; i <= to; i++) { if (authErrs["${i}"] == true) { logDebug { "refreshVacuumErrors: skipping auth-errored vac${i}" } continue } def vac = settings?."vac${i}" if (!vac) continue String errVal = vac.currentValue("error")?.toString()?.trim() ?: "" String dockErrVal = vac.currentValue("dockError")?.toString()?.trim() ?: "" logDebug { "refreshVacuumErrors: vac${i} (${vac.displayName}) error='${errVal}' dockError='${dockErrVal}'" } Map oldMap = (state."vac${i}Errors" ?: [:]) as Map Map m = [:] if (!isClearErrorValue(errVal) && !isTransientError(errVal)) m["error"] = errVal if (!isClearErrorValue(dockErrVal) && !isTransientError(dockErrVal)) m["dockError"] = dockErrVal if (m != oldMap) { state."vac${i}Errors" = m } } } boolean anyVacErrors() { int numVacs = (settings["numVacs"] ?: 0) as int for (int i = 1; i <= numVacs; i++) { if (((state."vac${i}Errors" ?: [:]) as Map).size() > 0) return true } return false } // Chained 5-minute reconciler while any error is present: catches a stuck error state // that no further events will fix. Also clears the light cache so the bulb self-heals. void safetyErrorReconcile() { logDebug { "safetyErrorReconcile: re-reading driver errors" } state.lastLight = [:] refreshVacuumErrors() updateVisualLights() if (anyVacErrors()) { logDebug { "safetyErrorReconcile: errors still present, next pass in 5 min" } runIn(300, "safetyErrorReconcile") } else { logDebug { "safetyErrorReconcile: all errors cleared, stopping" } } } void setDesired(Map desired, String lid, String st) { int cur = LIGHT_PRIORITY[(desired[lid] ?: "off") as String] if (LIGHT_PRIORITY[st] > cur) desired[lid] = st } boolean turnLightOff(light) { // Standard off() first. Some drivers reject setLevel(0), so never call it first. try { light.off() return true } catch (Exception e) { log.error "Light off() failed on ${light.displayName}: ${e.message}" } try { light.setColor([hue: 0, saturation: 0, level: 0]) light.setLevel(0) return true } catch (Exception e2) { log.error "Light fallback off failed on ${light.displayName}: ${e2.message}" } return false } // One-shot follow-up after a light command: re-checks the bulb and resends if it didn't take void verifyLights() { updateVisualLights(true) } void updateVisualLights(boolean verifyPass = false) { int numVacs = (settings["numVacs"] ?: 0) as int if (numVacs <= 0) return boolean anyLight = false for (int i = 1; i <= numVacs; i++) { if (settings["vac${i}Light"]) { anyLight = true; break } } if (!anyLight) return Map authErrs = (state.authErrored ?: [:]) as Map Map matrix = getRoomMatrix() // One pass over active sequences: which vacs are waiting / running? Set waitingVacs = new HashSet() Set runningVacs = new HashSet() getActiveSequences().each { seqKey, seqState -> if (!seqState) return if (seqState.waitingForStart) { normalizeToList(settings["seqRooms_${seqKey}"]).each { rc -> def rd = matrix[rc.toString()] if (rd) waitingVacs.add(rd.vacuumIndex as Integer) } } else if (seqState.running) { Map rd = getCurrentRoomData(seqState as Map) if (rd) { if (seqState.pausedForDelay) { waitingVacs.add(rd.vacuumIndex as Integer) } else { runningVacs.add(rd.vacuumIndex as Integer) } } } } // Decide each vac's color, merge by priority when vacs share a light Map desired = [:] for (int i = 1; i <= numVacs; i++) { def light = settings["vac${i}Light"] if (!light) continue String color = "off" if (authErrs["${i}"] == true) { color = "purple" } else { Map errs = (state."vac${i}Errors" ?: [:]) as Map boolean hasBlue = false boolean hasRed = false errs.values().each { v -> if (v) { if (isWaterError(v.toString())) { hasBlue = true } else { hasRed = true } } } if (hasBlue) color = "blue" else if (hasRed) color = "red" else if (waitingVacs.contains(i)) color = "yellow" else if (runningVacs.contains(i)) color = "green" } setDesired(desired, light.id.toString(), color) } // Apply, but only when something actually changed Map last = new HashMap((state.lastLight ?: [:]) as Map) boolean cacheChanged = false boolean sentCmd = false Set done = new HashSet() for (int i = 1; i <= numVacs; i++) { def light = settings["vac${i}Light"] if (!light) continue String lid = light.id.toString() if (!done.add(lid)) continue String st = (desired[lid] ?: "off") as String int level = (settings["vac${i}LightLevel"] ?: 100) as int if (level <= 0 || level > 100) level = 100 int hue = 0 switch (st) { case "green": hue = getHueSafe("vac${i}LightHueGreen", 33); break case "yellow": hue = getHueSafe("vac${i}LightHueYellow", 16); break case "red": hue = getHueSafe("vac${i}LightHueRed", 0); break case "blue": hue = getHueSafe("vac${i}LightHueBlue", 66); break case "purple": hue = getHueSafe("vac${i}LightHuePurple", 75); break } String sig = (st == "off") ? "off" : "${st}:${hue}:${level}".toString() // Trust the bulb's reported switch state over our cache, so a dropped command gets retried. // (Reading the attribute is a local hub read; no radio traffic.) String sw = light.currentValue("switch")?.toString() boolean looksApplied if (st == "off") { looksApplied = (sw == "off") || (sw == null && last[lid] == sig) } else { looksApplied = (last[lid] == sig) && (sw != "off") } if (looksApplied) continue boolean ok = false try { if (st == "off") { ok = turnLightOff(light) } else { light.setColor([hue: hue, saturation: 100, level: level]) ok = true } } catch (Exception e) { log.error "Light update failed on ${light.displayName}: ${e.message}" } if (ok) { last[lid] = sig cacheChanged = true sentCmd = true logDebug { "LIGHT: ${light.displayName} -> ${sig} (switch was '${sw}')" } } } if (cacheChanged) state.lastLight = last // Re-verify once, 20s later. The verify pass never schedules another, so this can't loop. if (sentCmd && !verifyPass) runIn(20, "verifyLights") if (verifyPass && sentCmd) log.warn "RR-Scheduler: a light did not match its desired state after the first command; resent" } // --------------------------------------------------------------------------- // Health Status Handler (auth recovery) // --------------------------------------------------------------------------- void healthStatusHandler(evt) { String newStatus = evt.value?.toString()?.trim()?.toLowerCase() ?: "" int vacIdx = getVacIdx(evt) def vac = (vacIdx > 0) ? settings["vac${vacIdx}"] : null logDebug { "HEALTH-EVT: ${vac?.displayName ?: evt.deviceId} healthStatus -> '${newStatus}' (vac idx ${vacIdx})" } if (vacIdx == -1) return Map authErrs = new HashMap((state.authErrored ?: [:]) as Map) boolean wasAuthErrored = (authErrs["${vacIdx}"] == true) if (newStatus == "online") { if (wasAuthErrored) { log.warn "HEALTH-EVT: Vac${vacIdx} ${vac?.displayName} back ONLINE (was auth-errored). Re-initializing rooms and schedule list." authErrs.remove("${vacIdx}") state.authErrored = authErrs refreshVacuumErrors(vacIdx) updateVisualLights() buildGlobalMatrixEngine((settings["numVacs"] ?: 0) as int) compileAndPublishSequenceList() } else { logDebug { "HEALTH-EVT: Vac${vacIdx} is online (no auth-error flag set)." } } } else { logDebug { "HEALTH-EVT: Vac${vacIdx} healthStatus not online: '${newStatus}' (not touching auth flag)" } } } // --------------------------------------------------------------------------- // Scheduling // --------------------------------------------------------------------------- void buildAutomatedCronSchedules() { int totalSeqs = (settings["numSequences"] ?: 1) as int for (int s = 1; s <= totalSeqs; s++) { if (settings["seqEnabled_${s}"] == false) { logDebug { "Sequence ${s} is disabled. Skipping schedule." } continue } def timeInput = settings["seqTime_${s}"] if (!timeInput) continue try { Date parsedTime = parseTimeInput(timeInput) if (!parsedTime) continue Calendar cal = Calendar.getInstance() cal.setTime(parsedTime) String cronExpression = "" if (settings["seqUsePeriodic_${s}"] == true) { // Fire daily; automatedSequenceTrigger decides whether enough days have passed. // (A cron day-of-month "1/N" would restart the cycle every month.) cronExpression = "0 ${cal.get(Calendar.MINUTE)} ${cal.get(Calendar.HOUR_OF_DAY)} * * ?" logDebug { "Scheduled sequence ${s} PERIODICALLY (every ${settings["seqPeriodicDays_${s}"] ?: 2} days) with daily cron '${cronExpression}'" } } else { List daysInput = normalizeToList(settings["seqDays_${s}"]) if (daysInput.size() == 0) continue String daysString = daysInput.collect { it.toString().substring(0,3).toUpperCase() }.join(',') cronExpression = "0 ${cal.get(Calendar.MINUTE)} ${cal.get(Calendar.HOUR_OF_DAY)} ? * ${daysString}" logDebug { "Scheduled sequence ${s} WEEKLY with cron '${cronExpression}'" } } Map data = [seqIdx: s] schedule(cronExpression, "automatedSequenceTrigger", [data: data, overwrite: false]) } catch (Exception e) { log.error "Failed to schedule sequence ${s}: ${e.message}" } } } void automatedSequenceTrigger(Map data) { Integer seqIdx = data?.seqIdx as Integer if (seqIdx == null) return if (settings["seqUsePeriodic_${seqIdx}"] == true) { int interval = (settings["seqPeriodicDays_${seqIdx}"] ?: 2) as int long today = localEpochDay() Map last = (state.lastPeriodicRun ?: [:]) as Map def lastDay = last["${seqIdx}"] if (lastDay != null && (today - (lastDay as long)) < interval) { logDebug { "Cron trigger for sequence ${seqIdx}: only ${today - (lastDay as long)} day(s) since last run (interval ${interval}). Skipping." } return } Map nl = new HashMap(last) nl["${seqIdx}"] = today state.lastPeriodicRun = nl } logDebug { "Cron trigger fired for sequence ${seqIdx}" } startSequenceExecution(seqIdx) } // --------------------------------------------------------------------------- // Sequence engine // --------------------------------------------------------------------------- // runIn with overwrite:false so concurrent sequences never cancel each other's jobs. // runId lets a job detect that it belongs to an older (finished/aborted) run and bail out. void scheduleEngine(int seqIdx, int targetStep, int secs, String runId) { runIn(secs, "executeSequenceEngine", [data: [seqIdx: seqIdx, targetStep: targetStep, runId: runId], overwrite: false]) } void startSequenceExecution(int seqIndex) { logDebug { "STARTSEQUENCEEXECUTION: Checking Seq ${seqIndex}" } if (settings["seqEnabled_${seqIndex}"] == false) { logDebug { "Sequence ${seqIndex} is disabled. Ignoring trigger." } return } String seqKey = seqIndex.toString() if (getActiveSequences().containsKey(seqKey)) { log.warn "Sequence ${seqIndex} skipped: already running or waiting to start." return } if (isSequenceDelayedForSequence(seqIndex)) { String runId = now().toString() putActiveSequence(seqKey, [ running: false, waitingForStart: true, seqBlockedSince: now(), runId: runId ]) String blockDev = getSeqBlockDeviceName(seqIndex) int interval = (settings.delayCheckInterval ?: 5) as int updateDashboardHtml("${getSeqName(seqIndex)} is waiting for ${blockDev}") logDebug { "Seq ${seqIndex} BLOCKED by ${blockDev}. Waiting to start. Retry in ${interval} min." } updateVisualLights() runIn(interval * 60, "retrySequenceStart", [data: [seqIdx: seqIndex, runId: runId], overwrite: false]) return } launchSequence(seqIndex) } void launchSequence(int seqIndex) { String seqKey = seqIndex.toString() Map existing = getActiveSequences()[seqKey] as Map if (existing?.running) return List sortedRooms = getSortedRooms(seqIndex) if (!sortedRooms) return String runId = now().toString() putActiveSequence(seqKey, [ running: true, waitingForStart: false, step: 1, rooms: sortedRooms, intermissionDelayActive: false, pausedForDelay: false, roomBlockedSince: null, lastStartedStep: null, lastStartedAt: 0, startedRoomCode: null, dockRecheckStep: null, runId: runId ]) logDebug { "LAUNCHSEQUENCE: START seq ${seqIndex}: ${sortedRooms.size()} room(s) -> ${sortedRooms}" } updateVisualLights() executeSequenceEngine([seqIdx: seqIndex, targetStep: 1, runId: runId]) } void retrySequenceStart(Map data) { Integer seqIdx = data?.seqIdx as Integer if (seqIdx == null) return String seqKey = seqIdx.toString() Map seqState = getActiveSequences()[seqKey] as Map if (!seqState || !seqState.waitingForStart) return if (data.runId != null && seqState.runId?.toString() != data.runId.toString()) return if (isSequenceDelayedForSequence(seqIdx)) { long maxMs = ((settings.maxBlockWaitHours ?: 12) as long) * 3600000L long blockedSince = (seqState.seqBlockedSince ?: now()) as long if (now() - blockedSince > maxMs) { log.warn "Sequence ${seqIdx} TIMED OUT waiting for start block to clear. Dropping this run." updateDashboardHtml("${getSeqName(seqIdx)} timed out waiting to start.") removeActiveSequence(seqKey) updateVisualLights() return } int interval = (settings.delayCheckInterval ?: 5) as int logDebug { "RETRYSEQSTART: Seq ${seqIdx} still BLOCKED by ${getSeqBlockDeviceName(seqIdx)}. Retrying in ${interval} min." } runIn(interval * 60, "retrySequenceStart", [data: [seqIdx: seqIdx, runId: data.runId], overwrite: false]) } else { logDebug { "RETRYSEQSTART: Seq ${seqIdx} start block CLEARED. Launching." } launchSequence(seqIdx) } } void executeSequenceEngine(Map data) { Integer seqIdx = data?.seqIdx as Integer if (seqIdx == null) return int targetStep = (data?.targetStep ?: 1) as int String seqKey = seqIdx.toString() Map seqState = getActiveSequences()[seqKey] as Map if (!seqState || !seqState.running) return // Ignore stale jobs from an older run, or for a step that is already done if (data.runId != null && seqState.runId?.toString() != data.runId.toString()) { logDebug { "EXECENGINE: Seq ${seqIdx} ignoring stale job (run ${data.runId})" } return } if (targetStep < ((seqState.step ?: 1) as int)) return if (seqState.lastStartedStep != null && (seqState.lastStartedStep as int) >= targetStep) return String runId = seqState.runId?.toString() List rooms = seqState.rooms as List seqState.intermissionDelayActive = false seqState.step = targetStep if (targetStep > rooms.size()) { terminateSequence(seqIdx, true) return } Map matrix = getRoomMatrix() String currentRoomCode = rooms[targetStep - 1].toString() Map roomData = matrix[currentRoomCode] as Map String roomLabel = roomData?.roomName ?: currentRoomCode String vacLabel = roomData?.vacLabel ?: "Vacuum" String blockingDevice = getRoomDelayBlockingDevice(seqIdx, currentRoomCode) if (blockingDevice != null) { int maxMin = (settings.maxRoomBlockWaitMinutes ?: 30) as int long maxMs = (maxMin as long) * 60000L long blockedSince = (seqState.roomBlockedSince ?: now()) as long if (now() - blockedSince > maxMs) { log.warn "Room ${roomLabel} TIMED OUT waiting for block to clear (${maxMin} min). Skipping to next room." updateDashboardHtml("${getSeqName(seqIdx)}: Skipped room '${roomLabel}' (blocked by ${blockingDevice} for ${maxMin}+ min)") seqState.roomBlockedSince = null seqState.pausedForDelay = false putActiveSequence(seqKey, seqState) executeSequenceEngine([seqIdx: seqIdx, targetStep: targetStep + 1, runId: runId]) return } boolean firstBlock = !seqState.pausedForDelay if (firstBlock) { seqState.pausedForDelay = true if (seqState.roomBlockedSince == null) seqState.roomBlockedSince = now() } putActiveSequence(seqKey, seqState) if (firstBlock) { updateDashboardHtml("${vacLabel} is waiting for ${blockingDevice}") logDebug { "EXECENGINE: Step ${targetStep} (${roomLabel}) BLOCKED by ${blockingDevice}. Waiting..." } updateVisualLights() } scheduleEngine(seqIdx, targetStep, ((settings.delayCheckInterval ?: 5) as int) * 60, runId) return } seqState.pausedForDelay = false seqState.roomBlockedSince = null seqState.lastStartedStep = targetStep putActiveSequence(seqKey, seqState) if (!roomData) { logDebug { "EXECENGINE: Room data missing for ${currentRoomCode}, skipping." } executeSequenceEngine([seqIdx: seqIdx, targetStep: targetStep + 1, runId: runId]) return } def targetVacDevice = settings?."vac${roomData.vacuumIndex}" if (!targetVacDevice) { logDebug { "EXECENGINE: Vac ${roomData.vacuumIndex} not configured, skipping." } executeSequenceEngine([seqIdx: seqIdx, targetStep: targetStep + 1, runId: runId]) return } logDebug { "EXECENGINE: Seq ${seqIdx} Step ${targetStep} CLEAR. Starting ${roomLabel} on ${vacLabel}." } updateDashboardHtml("${getSeqName(seqIdx)} Active: Cleaning ${roomLabel}") updateVisualLights() executeStepAnnouncement(seqIdx, currentRoomCode, roomData.roomName as String, roomData.vacLabel as String) String mopConfig = settings["seq_${seqIdx}_mop_${currentRoomCode}"] ?: "DEFAULT" try { targetVacDevice.appRoomClean(roomData.nativeRoomId.toString(), mopConfig) addChildHistory(roomData.roomName as String, "started") seqState.startedRoomCode = currentRoomCode seqState.lastStartedAt = now() putActiveSequence(seqKey, seqState) } catch (Exception e) { log.error "appRoomClean failed for room ${roomData.roomName}: ${e.message}" scheduleEngine(seqIdx, targetStep + 1, 5, runId) } } // A room is done: update bin counters, history, then wait the buffer and start the next room void roomFinished(int seqIdx, Map seqState, Map roomData, vac) { String seqKey = seqIdx.toString() int vIdx = roomData.vacuumIndex as int int currentStep = seqState.step as int logDebug { "VAC-STATE: ${vac?.displayName} finished cleaning ${roomData.roomName}." } boolean autoEmpty = settings["vac${vIdx}AutoEmpty"] ?: false if (autoEmpty && vac) { def areaStr = vac.currentValue("cleanArea") if (areaStr != null) { BigDecimal area = 0 try { area = areaStr.toString() as BigDecimal } catch (Exception e) { } BigDecimal currentTotal = (state."vac${vIdx}TotalSqFt" ?: 0) as BigDecimal currentTotal += area BigDecimal limit = (settings["vac${vIdx}BinSqrFeet"] ?: 50) as BigDecimal if (currentTotal >= limit) { logDebug { "VAC-STATE: Auto-empty threshold reached (${currentTotal} >= ${limit}). Triggering dust collection." } try { vac.execute("app_start_collect_dust") } catch (Exception e) { } currentTotal = 0 } state."vac${vIdx}TotalSqFt" = currentTotal logDebug { "VAC-STATE: Area total is now ${currentTotal} / ${limit}" } updateBinPercentages() } } if (seqState.startedRoomCode) { addChildHistory(roomData.roomName as String, "completed") seqState.startedRoomCode = null } int bufferMinutes = (settings["seqDelayAfter_${seqIdx}"] ?: 2) as int seqState.intermissionDelayActive = true putActiveSequence(seqKey, seqState) String runId = seqState.runId?.toString() logDebug { "VAC-STATE: Seq ${seqIdx} waiting ${bufferMinutes} min before next room." } if (bufferMinutes > 0) { scheduleEngine(seqIdx, currentStep + 1, bufferMinutes * 60, runId) } else { executeSequenceEngine([seqIdx: seqIdx, targetStep: currentStep + 1, runId: runId]) } } void vacuumStateHandler(evt) { String newState = evt.value?.toString()?.trim()?.toLowerCase() ?: "" int vacIdx = getVacIdx(evt) def vac = (vacIdx > 0) ? settings["vac${vacIdx}"] : null logDebug { "VAC-STATE: ${vac?.displayName ?: evt.deviceId} -> '${newState}'" } if (!vac) return if (isAuthErrorValue(newState)) { Map authErrs = new HashMap((state.authErrored ?: [:]) as Map) if (authErrs["${vacIdx}"] != true) { log.warn "AUTH-EVT: Vac${vacIdx} (${vac.displayName}) reports authorization error" authErrs["${vacIdx}"] = true state.authErrored = authErrs updateVisualLights() } return } if (newState.contains("emptying") || newState == "empty_bin") { boolean autoEmpty = settings["vac${vacIdx}AutoEmpty"] ?: false if (autoEmpty) { BigDecimal prev = (state."vac${vacIdx}TotalSqFt" ?: 0) as BigDecimal state."vac${vacIdx}TotalSqFt" = 0 logDebug { "VAC-STATE: ${vac.displayName} is emptying bin. Reset SqFt counter (was ${prev})." } updateDashboardHtml("${vac.displayName} emptied bin. SqFt counter reset.") updateBinPercentages() } return } if (!DOCK_STATES.contains(newState)) return // Docked: refresh only this vac's errors and the light refreshVacuumErrors(vacIdx) updateVisualLights() Map active = getActiveSequences() if (!active) return Map matrix = getRoomMatrix() for (String seqKey in active.keySet().toList()) { Map seqState = active[seqKey] as Map int seqIdx = seqKey.toInteger() // One summary line instead of a log per skip condition String skip = null Map roomData = null if (!seqState) { skip = "state is null" } else if (!seqState.running) { skip = "not running" } else if (seqState.intermissionDelayActive) { skip = "in intermission delay" } else if (seqState.pausedForDelay) { skip = "paused for delay" } else { int step = (seqState.step ?: 0) as int List roomsList = (seqState.rooms ?: []) as List if (step < 1 || step > roomsList.size()) { skip = "step ${step} out of bounds" } else { roomData = matrix[roomsList[step - 1].toString()] as Map if (!roomData) { skip = "no room data for ${roomsList[step - 1]}" } else if ((roomData.vacuumIndex as int) != vacIdx) { skip = "current room belongs to vac${roomData.vacuumIndex}, event was vac${vacIdx}" } } } if (skip) { logDebug { "VAC-STATE: Seq ${seqIdx} skipped: ${skip}." } continue } // A dock/charging event right after a room start is almost certainly the vac // still leaving the dock. Ignore it, but leave a watchdog in case it never leaves. long startedAt = (seqState.lastStartedAt ?: 0) as long long sinceStart = now() - startedAt if (startedAt > 0 && sinceStart < ROOM_START_GRACE_MS) { int step = seqState.step as int logDebug { "VAC-STATE: Seq ${seqIdx} ignoring early '${newState}' (${(sinceStart / 1000) as int}s after room start)." } if (seqState.dockRecheckStep == null || (seqState.dockRecheckStep as int) != step) { seqState.dockRecheckStep = step putActiveSequence(seqKey, seqState) int secs = (((ROOM_START_GRACE_MS - sinceStart) / 1000) as int) + 5 runIn(secs, "earlyDockRecheck", [data: [seqIdx: seqIdx, step: step, runId: seqState.runId?.toString()], overwrite: false]) } continue } roomFinished(seqIdx, seqState, roomData, vac) } } // Watchdog: if the vac is still docked after the start grace period, the room never really ran void earlyDockRecheck(Map data) { Integer seqIdx = data?.seqIdx as Integer if (seqIdx == null) return Map seqState = getActiveSequences()[seqIdx.toString()] as Map if (!seqState || !seqState.running) return if (seqState.runId?.toString() != data.runId?.toString()) return if ((seqState.step as int) != (data.step as int)) return if (seqState.intermissionDelayActive || seqState.pausedForDelay) return Map roomData = getCurrentRoomData(seqState) if (!roomData) return def vac = settings["vac${roomData.vacuumIndex}"] String cur = vac?.currentValue("state")?.toString()?.trim()?.toLowerCase() if (cur && DOCK_STATES.contains(cur)) { logDebug { "DOCK-RECHECK: Seq ${seqIdx} vac still '${cur}' after start grace period; treating room as finished." } roomFinished(seqIdx, seqState, roomData, vac) } } void delayDeviceChangeHandler(evt) { Map active = getActiveSequences() if (!active) return for (String seqKey in active.keySet().toList()) { Map seqState = active[seqKey] as Map if (!seqState) continue int seqIdx = seqKey.toInteger() if (seqState.waitingForStart) { if (!isSequenceDelayedForSequence(seqIdx)) { logDebug { "DELAY-EVT: Seq ${seqIdx} start block CLEARED. Launching." } launchSequence(seqIdx) } } else if (seqState.running && seqState.pausedForDelay && !seqState.intermissionDelayActive) { int currentStep = seqState.step as int List roomsList = seqState.rooms as List if (currentStep > 0 && currentStep <= roomsList.size()) { String currentRoomCode = roomsList[currentStep - 1].toString() if (getRoomDelayBlockingDevice(seqIdx, currentRoomCode) == null) { logDebug { "DELAY-EVT: Seq ${seqIdx} room ${currentRoomCode} block CLEARED. Resuming." } executeSequenceEngine([seqIdx: seqIdx, targetStep: currentStep, runId: seqState.runId?.toString()]) } } } } } void vacuumErrorHandler(evt) { String attr = evt.name?.toString() ?: "?" String newVal = evt.value?.toString()?.trim() ?: "" // Hubitat events have no oldValue property; the previous value is whatever we had stored for this attribute String oldVal = "" int vacIdx = getVacIdx(evt) def vac = (vacIdx > 0) ? settings["vac${vacIdx}"] : null String deviceName = vac?.displayName ?: evt.displayName ?: "Vacuum" if (vacIdx != -1) { // copy -> modify -> reassign: in-place mutation of a state map does not reliably persist Map m = new HashMap((state."vac${vacIdx}Errors" ?: [:]) as Map) oldVal = m[attr]?.toString() ?: "" if (isClearErrorValue(newVal)) { m.remove(attr) logDebug { "ERROR-EVT: Clear received for '${attr}' on vac${vacIdx}. Map now: ${m}" } } else if (isTransientError(newVal)) { // Transient network errors must not light the bulb m.remove(attr) logDebug { "ERROR-EVT: Ignoring transient '${attr}'='${newVal}' on vac${vacIdx}. Map now: ${m}" } } else { m[attr] = newVal logDebug { "ERROR-EVT: Set '${attr}'='${newVal}' on vac${vacIdx}. Map now: ${m}" } } state."vac${vacIdx}Errors" = m updateVisualLights() // If errors are still present, chain a reconciliation every 5 min if (m.size() > 0) { runIn(300, "safetyErrorReconcile") } } else { logDebug { "ERROR-EVT: Could not match device ${deviceName} (id=${evt.deviceId}) to a configured vac" } } logDebug { "ERROR-EVT: ${deviceName} ${attr} changed from '${oldVal}' to '${newVal}'" } boolean newClear = isClearErrorValue(newVal) boolean oldClear = isClearErrorValue(oldVal) // Announcement logic: skip transient errors and clear-of-clear if (isTransientError(newVal)) return if (newClear && oldClear) return def spk = settings.errorAlertSpeaker if (!spk) return String msg = null if (!newClear) { msg = "${deviceName} reports ${attr}: ${newVal}" } else if (!oldClear) { msg = "${deviceName} ${attr} cleared" } else { return } String dedupKey = "${evt.deviceId ?: '?'}:${attr}:${newVal}".toString() long nowMs = now() // Copy, prune entries older than 1 hour, then dedupe Map lastAnnounce = [:] ((state.lastErrorAnnounce ?: [:]) as Map).each { k, v -> if ((nowMs - (v as long)) < 3600000L) lastAnnounce[k] = v } long lastMs = (lastAnnounce[dedupKey] ?: 0) as long if ((nowMs - lastMs) < 60000) { logDebug { "ERROR-EVT: Suppressed duplicate announcement." } state.lastErrorAnnounce = lastAnnounce return } lastAnnounce[dedupKey] = nowMs state.lastErrorAnnounce = lastAnnounce announce(spk, msg) } void updateBinPercentages() { def childDevice = getTile() if (!childDevice) return Map sent = new HashMap((state.sentBinPercents ?: [:]) as Map) int numVacs = (settings["numVacs"] ?: 0) as int // Only walk as far as we have vacs or previously-sent attributes (tile supports up to 10) int maxSentIdx = 0 sent.keySet().each { k -> try { maxSentIdx = Math.max(maxSentIdx, k.toString().toInteger()) } catch (Exception e) { } } int maxIdx = Math.min(10, Math.max(numVacs, maxSentIdx)) boolean changed = false for (int i = 1; i <= maxIdx; i++) { String key = i.toString() String val = "" if (i <= numVacs) { def vac = settings?."vac${i}" boolean autoEmpty = settings["vac${i}AutoEmpty"] ?: false if (vac && autoEmpty) { BigDecimal total = (state."vac${i}TotalSqFt" ?: 0) as BigDecimal BigDecimal limit = (settings["vac${i}BinSqrFeet"] ?: 50) as BigDecimal if (limit <= 0) limit = 50 int percent = Math.min(100, (int) Math.round(((total / limit) * 100) as double)) val = "${percent}%".toString() } } def prev = sent[key] if (prev != val) { // Don't send a clear for something we never sent if (!(prev == null && val == "")) { childDevice.sendEvent(name: "binPercent${i}", value: val) } sent[key] = val changed = true } } if (changed) state.sentBinPercents = sent } // Returns the display name of the first blocking device for this room, or null if clear String getRoomDelayBlockingDevice(int seqIdx, String roomCode) { if (!(settings["seq_${seqIdx}_delayEnable_${roomCode}"] as Boolean)) return null int count = (settings["seq_${seqIdx}_delayCount_${roomCode}"] ?: 1) as int for (int i = 1; i <= count; i++) { String blocker = checkBlock( roomDelaySettingName(seqIdx, roomCode, "delayDevice", i), roomDelaySettingName(seqIdx, roomCode, "delayEq", i), roomDelaySettingName(seqIdx, roomCode, "delayAttr", i), roomDelaySettingName(seqIdx, roomCode, "delayValueEnum", i), roomDelaySettingName(seqIdx, roomCode, "delayValueNumber", i), roomDelaySettingName(seqIdx, roomCode, "delayValueString", i), roomDelaySettingName(seqIdx, roomCode, "delayNumOp", i)) if (blocker) return blocker } return null } Boolean isSequenceDelayedForSequence(int seqIdx) { if (!(settings["seq_${seqIdx}_seqDelayEnable"] as Boolean)) return false return checkBlock( "seq_${seqIdx}_seqDelayDevice".toString(), "seq_${seqIdx}_seqDelayEq".toString(), "seq_${seqIdx}_seqDelayAttr".toString(), "seq_${seqIdx}_seqDelayValueEnum".toString(), "seq_${seqIdx}_seqDelayValueNumber".toString(), "seq_${seqIdx}_seqDelayValueString".toString(), "seq_${seqIdx}_seqDelayNumOp".toString()) != null } // Single implementation of the "is this blocking device currently blocking?" test. // Takes the names of the settings that hold the device config; returns the device's // display name if it is blocking, otherwise null. String checkBlock(String devName, String eqName, String attrName, String enumName, String numName, String strName, String opName) { def dev = firstOrNull(settings[devName]) if (!dev) return null String attr = settings[attrName]?.toString() if (!attr) return null Map meta = getAttrMeta(dev, attr) if (!meta) return null String eq = settings[eqName]?.toString() ?: "=" boolean match = false String desc if (meta.numeric && !meta.hasEnum) { def rawNum = settings[numName] if (rawNum == null) return null BigDecimal target try { target = rawNum.toString() as BigDecimal } catch (Exception e) { return null } def cv = dev.currentValue(attr) if (cv == null) return null BigDecimal cur try { cur = cv.toString() as BigDecimal } catch (Exception e) { return null } String op = settings[opName]?.toString() ?: "=" switch (op) { case "=": match = (cur == target); break case ">": match = (cur > target); break case "<": match = (cur < target); break case "<=": match = (cur <= target); break case ">=": match = (cur >= target); break } desc = "${cur} ${op} ${target}" } else { String target = (meta.hasEnum ? settings[enumName] : settings[strName])?.toString()?.trim() if (!target) return null String cur = dev.currentValue(attr)?.toString()?.trim() match = (cur == target) desc = "'${cur}' == '${target}'" } if (eq == "!=") match = !match logDebug { "BlockEval: ${devName}, ${dev.displayName}, ${attr}: ${desc} (Eq: ${eq}) ? ${match}" } return match ? dev.displayName.toString() : null } void childDeviceButtonHandler(Integer buttonNumber) { logDebug { "BUTTON PUSHED: ${buttonNumber}" } Map active = getActiveSequences() if (buttonNumber == 0) { if (active.size() > 0) { log.warn "Emergency Abort triggered for all active sequences." for (String seqKey in active.keySet().toList()) { Map seqState = active[seqKey] as Map Map rData = getCurrentRoomData(seqState) if (rData) { try { settings?."vac${rData.vacuumIndex}"?.appDock() } catch (Exception e) { log.error "appDock failed: ${e.message}" } } terminateSequence(seqKey.toInteger(), false) } } return } if (buttonNumber < 100) return Map targetRoomData = getRoomMatrix()[buttonNumber.toString()] as Map if (!targetRoomData) return boolean vacBusy = false for (String seqKey in active.keySet().toList()) { Map rData = getCurrentRoomData(active[seqKey] as Map) if (rData && rData.vacuumIndex == targetRoomData.vacuumIndex) { vacBusy = true break } } if (vacBusy) { log.warn "Command blocked: Vacuum ${targetRoomData.vacLabel} is currently running a sequence." return } def targetVacDevice = settings?."vac${targetRoomData.vacuumIndex}" if (!targetVacDevice) return String chosenMopLevel = settings["instantMop_${buttonNumber}"] ?: "DEFAULT" logDebug { "BUTTON: Instant Clean ${targetRoomData.roomName} on ${targetRoomData.vacLabel}" } updateDashboardHtml("Instant Clean: ${targetRoomData.roomName} (Mop: ${chosenMopLevel})") executeInstantAnnouncement(buttonNumber, targetRoomData.roomName as String, targetRoomData.vacLabel as String) try { targetVacDevice.appRoomClean(targetRoomData.nativeRoomId.toString(), chosenMopLevel) } catch (Exception e) { log.error "Instant clean failed for ${targetRoomData.roomName}: ${e.message}" } } void executeStepAnnouncement(int seqIdx, String roomCode, String roomName, String vacName) { def spk = firstOrNull(settings["seq_${seqIdx}_speechDevice_${roomCode}"]) if (!spk) { logDebug { "SPEECH: No speaker configured for sequence ${seqIdx}, room ${roomCode}." } return } String safeRoomName = roomName ? roomName.toString() : "the room" String safeVacName = vacName ? vacName.toString() : "The vacuum" announce(spk, "${safeVacName} is cleaning the ${safeRoomName}".toString()) } void executeInstantAnnouncement(Integer buttonNumber, String roomName, String vacName) { def spk = firstOrNull(settings["instantSpeech_${buttonNumber}"]) if (!spk) { logDebug { "SPEECH: No instant-clean speaker configured for button ${buttonNumber}." } return } String safeRoomName = roomName ? roomName.toString() : "the room" String safeVacName = vacName ? vacName.toString() : "The vacuum" announce(spk, "${safeVacName} is cleaning the ${safeRoomName}".toString()) } void updateDashboardHtml(String statusMessage) { def childDevice = getTile() if (!childDevice) return if (state.lastStatusMsg == statusMessage) return state.lastStatusMsg = statusMessage // Compact markup keeps the attribute well under the 1024-char dashboard limit String formattedHtml = "
Status:
${statusMessage}
" childDevice.sendEvent(name: "schedulerStatus", value: formattedHtml) logDebug { "DASHBOARD STATUS UPDATE: ${statusMessage}" } } void terminateSequence(Integer seqIdx, Boolean regularCompletion = true) { logDebug { "TERMINATE: seq=${seqIdx}, regular=${regularCompletion}" } String seqKey = seqIdx.toString() Map seqState = getActiveSequences()[seqKey] as Map if (seqState?.startedRoomCode) { String rCode = seqState.startedRoomCode.toString() Map rData = getRoomMatrix()[rCode] as Map addChildHistory((rData?.roomName ?: rCode) as String, "canceled") } removeActiveSequence(seqKey) refreshVacuumErrors() updateVisualLights() if (regularCompletion) { updateDashboardHtml("${getSeqName(seqIdx)} completed.") } else { updateDashboardHtml("${getSeqName(seqIdx)} aborted.") } } void compileAndPublishSequenceList() { def childDevice = getTile() if (!childDevice) return Map matrix = getRoomMatrix() int totalSeqs = (settings["numSequences"] ?: 1) as int Map vacLists = [1:[], 2:[], 3:[], 4:[], 5:[]] for (int s = 1; s <= totalSeqs; s++) { if (settings["seqEnabled_${s}"] == false) continue String seqName = getSeqName(s) List sortedRoomCodes = getSortedRooms(s) def rawTime = settings["seqTime_${s}"] List daysList = normalizeToList(settings["seqDays_${s}"]) String scheduleText = "Not Scheduled" if (rawTime) { String cleanTime = "??:??" Date t = parseTimeInput(rawTime) if (t) cleanTime = new SimpleDateFormat("HH:mm").format(t) if (settings["seqUsePeriodic_${s}"] == true) { int interval = (settings["seqPeriodicDays_${s}"] ?: 2) as int scheduleText = "Every ${interval} days @ ${cleanTime}" } else if (daysList.size() > 0) { String daysJoined = daysList.collect { it.toString().substring(0, 3) }.join(", ") scheduleText = daysJoined + " @ " + cleanTime } } Map vacRooms = [:] sortedRoomCodes.each { roomCode -> Map roomMeta = matrix[roomCode] as Map if (roomMeta) { int vIdx = roomMeta.vacuumIndex as int if (vIdx > 5) vIdx = 5 if (!vacRooms[vIdx]) vacRooms[vIdx] = [] vacRooms[vIdx] << roomCode } } vacRooms.each { vIdx, rooms -> String vacLabel = matrix[rooms[0].toString()]?.vacLabel ?: "Vac ${vIdx}" StringBuilder block = new StringBuilder("${seqName} (${vacLabel})
Scheduled: ${scheduleText}
") rooms.each { roomCode -> Map roomMeta = matrix[roomCode.toString()] as Map String delayStr = "" if (settings["seq_${s}_delayEnable_${roomCode}"] as Boolean) { int count = (settings["seq_${s}_delayCount_${roomCode}"] ?: 1) as int List devNames = [] for (int i = 1; i <= count; i++) { def dev = firstOrNull(settings[roomDelaySettingName(s, roomCode.toString(), "delayDevice", i)]) if (dev) devNames << dev.displayName.toString() } if (devNames.size() > 0) { delayStr = " [delay: ${devNames.join(', ')}]" } } block.append("- ${roomMeta.roomName}${delayStr}
") } block.append("
") vacLists[vIdx] << block.toString() } } // Only send events when content changed (hash compare) Map sent = new HashMap((state.sentVacLists ?: [:]) as Map) boolean changed = false for (int i = 1; i <= 5; i++) { String key = i.toString() String content = (vacLists[i] as List).join("") if (content) { String h = content.hashCode().toString() if (sent[key] != h) { childDevice.sendEvent(name: "sequenceListVac${i}", value: content) sent[key] = h changed = true } } else if (sent[key]) { childDevice.sendEvent(name: "sequenceListVac${i}", value: "") sent[key] = "" changed = true } } if (changed) state.sentVacLists = sent }