/**
* Muse Bridge for Hubitat
*
* Copyright (c) 2026 Rayzurbock (Brian S. Lowrance)
* Licensed under the MIT License. See LICENSE file for details.
*
* Exposes selected devices, location modes, and a spoken alert-rule engine
* to Muse (or any REST client) through local and Hubitat-cloud endpoints.
*
* Features
* - REST API: list devices + live attributes, send any device command,
* read recent device events, list/set location modes, trigger speech.
* - Alert rules: watch a device attribute, alert when it stays in a state
* longer than (or clears sooner than) a duration you choose, with
* conditions on mode, thermostat operating state, time window, and days.
* - Spoken alerts via speechSynthesis, audioNotification, or musicPlayer
* devices, with optional repeat and clear announcements.
* - Rules can be managed from the Hubitat UI or through the REST API,
* so an assistant (or anything else) can create them on demand.
*/
import groovy.json.JsonOutput
definition(
name: "Muse Bridge",
namespace: "musebridge",
author: "Rayzurbock",
description: "REST API plus spoken alert-rule engine for Muse and other integrations.",
category: "Integrations",
iconUrl: "",
iconX2Url: "",
singleInstance: true
)
preferences {
page(name: "mainPage", title: "Muse Bridge", install: true, uninstall: true)
page(name: "devicesPage", title: "Devices")
page(name: "rulesPage", title: "Alert Rules")
page(name: "rulePage", title: "Alert Rule")
page(name: "apiPage", title: "API Access")
page(name: "linkPage", title: "Link with Muse")
page(name: "exposePage", title: "Choose Exposed Devices")
page(name: "healthPage", title: "Device Health")
page(name: "speakerPage", title: "Choose Speakers")
page(name: "museActionsPage", title: "Muse Automations")
}
mappings {
path("/health") {
action: [GET: "apiHealth"]
}
path("/devices") {
action: [GET: "apiListDevices"]
}
path("/devices/:id") {
action: [GET: "apiGetDevice"]
}
path("/devices/:id/command") {
action: [POST: "apiDeviceCommand"]
}
path("/devices/:id/events") {
action: [GET: "apiDeviceEvents"]
}
path("/modes") {
action: [GET: "apiListModes"]
}
path("/mode") {
action: [GET: "apiGetMode", POST: "apiSetMode"]
}
path("/hsm") {
action: [GET: "apiGetHsm", POST: "apiSetHsm"]
}
path("/speak") {
action: [POST: "apiSpeak"]
}
path("/notify") {
action: [POST: "apiNotify"]
}
path("/rules") {
action: [GET: "apiListRules", POST: "apiCreateRule"]
}
path("/rules/:id") {
action: [GET: "apiGetRule", PUT: "apiUpdateRule", DELETE: "apiDeleteRule"]
}
path("/rules/:id/enable") {
action: [POST: "apiEnableRule"]
}
path("/rules/:id/disable") {
action: [POST: "apiDisableRule"]
}
path("/rules/:id/test") {
action: [POST: "apiTestRule"]
}
path("/muse-side-actions") {
action: [GET: "apiListSideActions", POST: "apiSetSideActions"]
}
}
// ============================================================================
// Pages
// ============================================================================
def mainPage() {
ensureToken()
def devCount = allExposedDevices().size()
def rules = getRules()
def breached = rules.count { ruleStateFor(it.id).breached }
dynamicPage(name: "mainPage", title: "Muse Bridge v${appVersion()}", install: true, uninstall: true) {
section() {
paragraph("Muse Bridge exposes your Hubitat to Muse (or any REST client) and runs " +
"spoken alert rules locally on the hub. Pick the devices to expose, define alert " +
"rules, then grab the API URLs from API Access.")
}
section("Setup") {
href(name: "devicesHref", page: "devicesPage",
title: "Devices to expose",
description: devCount ? "${devCount} device${devCount == 1 ? '' : 's'} selected" : "Tap to choose devices")
href(name: "rulesHref", page: "rulesPage",
title: "Alert rules",
description: rules ? "${rules.size()} rule${rules.size() == 1 ? '' : 's'} (${breached} breached)" : "Tap to create alert rules")
href(name: "museActionsHref", page: "museActionsPage",
title: "Muse automations",
description: museSideActions() ? "${museSideActions().size()} assistant-side automation${museSideActions().size() == 1 ? '' : 's'} listed" : "Assistant-side schedules (if any)")
href(name: "healthHref", page: "healthPage",
title: "Device health",
description: "Low-battery and inactive-device push alerts")
href(name: "apiHref", page: "apiPage",
title: "API Access",
description: state.accessToken ? "Endpoints and token ready" : "⚠️ OAuth not enabled — tap here for setup steps")
href(name: "linkHref", page: "linkPage",
title: "Link with Muse",
description: state.accessToken ? "Copy-paste setup message for your assistant" : "Needs OAuth first — see API Access")
}
section("Security") {
paragraph("A command passcode is required by the API before security-sensitive " +
"actions: unlocking locks, opening garage doors, opening/closing valves, " +
"siren control, location mode changes, and HSM arm/disarm.")
input "securityPasscode", "text", title: "Command passcode",
description: "Anyone with hub admin access can see this — that is expected"
input "requirePasscode", "bool", title: "Require the passcode for security-sensitive actions",
defaultValue: true
}
section("Options") {
input "logDebug", "bool", title: "Enable debug logging", defaultValue: false
}
section("Donations") {
paragraph("Muse Bridge is provided to the community for free. " +
"It takes a lot of time to build and support any complex app. " +
"If you wish to support the time and effort put into development " +
"(including the costs of the AI services it integrates with), " +
"you may submit a donation with one of the following:
" +
"
")
}
}
}
def devicesPage(params) {
dynamicPage(name: "devicesPage", title: "Devices Exposed to the API", nextPage: "mainPage") {
section() {
paragraph("The app can only use devices you authorize below. By default every " +
"authorized device is exposed to the API and rules — open the picker " +
"to narrow it down.")
}
section("Authorize devices") {
paragraph("Step 1 — let the app see your devices. Open the master list, " +
"Select All, Done.")
input "devMaster", "capability.*", title: "All devices (master list)", multiple: true, required: false, showFilter: true
}
section("Exposed devices") {
def exposed = exposedDeviceIds().size()
def total = exposureUniverse().size()
href(name: "exposeHref", page: "exposePage",
title: "Choose exposed devices",
description: "Step 2 (optional) — ${exposed} of ${total} authorized devices exposed; tap to uncheck ones you don't need")
}
section("Speech & announcements") {
paragraph("Alert rules speak through these devices, using the speak command " +
"when available and playTextAndResume/playText otherwise. " +
"Speakers are listed most-capable first — prefer ones with full volume " +
"support if you use announcement volumes.")
href(name: "speakerHref", page: "speakerPage",
title: "Choose speakers",
description: speakerDeviceIds() ? "${speakerDeviceIds().size()} speaker${speakerDeviceIds().size() == 1 ? '' : 's'} selected" : "Tap to choose speakers")
}
section("Announcement volume") {
paragraph("Control how loud announcements play, regardless of what the " +
"speaker is currently set to.")
input "speechVolume", "number", title: "Announcement volume (0-100, blank = leave volume alone)",
required: false, range: "0..100"
input "speechMinVolume", "number", title: "Minimum announcement volume (0-100, blank = none)",
required: false, range: "0..100",
description: "If a speaker is set lower than this, announcements play at least this loud"
input "restoreVolume", "bool", title: "Restore speaker volume after announcements",
defaultValue: true
def sDevs = speechDevices()
if (sDevs) {
def rows = sDevs.collect { d ->
def sup = deviceVolumeSupport(d)
def note = (!sup.canSet) ? "no volume commands — announcements only" :
(!sup.reports) ? "volume control, but no level reporting — restore unavailable" :
"full volume support"
"• ${d.displayName} — ${note}"
}.join("
")
paragraph("Speaker volume support:
${rows}")
} else {
paragraph("Select speech devices above and this will show which ones " +
"support volume control and restore.")
}
}
section("Phone / push notifications") {
paragraph("Each Hubitat mobile-app device is one phone or tablet. " +
"Rules can push text alerts to specific phones, so a text alert " +
"can go to one person instead of everyone.")
input "ntPhones", "capability.notification", title: "Notification devices", multiple: true, required: false, showFilter: true
}
}
}
def exposePage(params) {
ensureActivityCache()
if (state.exposureMigrated && !state.exposureSeeded) {
// Visitor of the pre-1.5.2 picker: preserve whatever they selected (possibly nothing).
state.exposureSeeded = true
}
if (!state.exposureSeeded) {
// First visit: check everything currently authorized, so the checklist
// matches reality from the start.
app.updateSetting("expDevices", (exposureUniverse()*.id*.toString()) as List)
state.exposureSeeded = true
}
def universeIds = (exposureUniverse()*.id*.toString()) as Set
def exposedIds = exposedDeviceIds()
def missing = universeIds - exposedIds
dynamicPage(name: "exposePage", title: "Choose Exposed Devices", nextPage: "devicesPage") {
section("Find devices") {
paragraph("Filters only change what's listed — never your selection. " +
"Check devices to expose them to the API and rules; uncheck to remove them. " +
"Already-selected devices always appear at the top, even when a filter hides them. " +
"Labels show when each device last reported.")
input "expSearch", "text", title: "Search by name", required: false, submitOnChange: true
input "expCap", "enum", title: "Device type", required: false, submitOnChange: true,
options: exposureCapOptions(), description: "Narrow by capability"
input "expActiveDays", "number",
title: "Hide devices quiet for longer than N days (0 = show all)",
defaultValue: 0, required: true, range: "0..365", submitOnChange: true,
description: "Opt-in: hide dead devices to make big lists manageable"
if (missing) paragraph("${missing.size()} authorized device${missing.size() == 1 ? ' is' : 's are'} " +
"not exposed. Find ${missing.size() == 1 ? 'it' : 'them'} below and check " +
"${missing.size() == 1 ? 'it' : 'them'} to include ${missing.size() == 1 ? 'it' : 'them'}.")
}
section("Exposed devices (${exposedIds.size()} selected of ${universeIds.size()} authorized)") {
input "expDevices", "enum", title: "Checked devices are exposed to the API and rules",
multiple: true, required: false, options: exposureOptions(), submitOnChange: true
}
}
}
def speakerPage(params) {
state.speakerMigrated = true
dynamicPage(name: "speakerPage", title: "Choose Speakers", nextPage: "devicesPage") {
section("Speakers") {
paragraph("Most capable first. Full = voice + volume + restore after " +
"announcements. Voice + volume = volume works but can't be restored. " +
"Voice only = announcements play, volume settings are ignored.")
input "spkFullOnly", "bool", title: "Only show fully-capable speakers",
defaultValue: false, submitOnChange: true,
description: "Hides voice-only and no-restore speakers from the list below"
input "spkDevices", "enum", title: "Speakers for announcements",
multiple: true, required: false, options: speakerOptions(), submitOnChange: true
}
}
}
// 3 = full (voice + volume + restore), 2 = voice + volume, 1 = voice only
def speakerTier(d) {
def vol = deviceVolumeSupport(d)
if (vol.canSet && vol.reports) return 3
if (vol.canSet) return 2
return 1
}
def speakerTierLabel(d) {
switch (speakerTier(d)) {
case 3: return "full: voice + volume + restore"
case 2: return "voice + volume (no restore)"
default: return "voice only"
}
}
def speakerCandidates() {
def cands = allVisibleDevices().findAll { d ->
try {
d.hasCommand("speak") || d.hasCommand("playText") || d.hasCommand("playTextAndResume") ||
d.hasCapability("SpeechSynthesis") || d.hasCapability("AudioNotification") || d.hasCapability("MusicPlayer")
} catch (e) { false }
}.unique { it.id.toString() }
if (settings.spkFullOnly == true) cands = cands.findAll { speakerTier(it) == 3 }
return cands.sort { a, b ->
(speakerTier(b) <=> speakerTier(a)) ?: (a.displayName?.toLowerCase() <=> b.displayName?.toLowerCase())
}
}
def speakerOptions() {
return speakerCandidates().collectEntries { d ->
[(d.id.toString()): "${d.displayName} — ${speakerTierLabel(d)}"]
}
}
def speakerDeviceIds() {
if (settings.spkDevices != null) return (settings.spkDevices*.toString()) as Set
if (state.speakerMigrated) return [] as Set
// Upgrade path: seed from the old per-capability speaker pickers.
def ids = [] as Set
["spSpeech", "spAudio", "spMusic"].each { k ->
settingDeviceList(k).each { d -> ids << d.id.toString() }
}
return ids
}
def healthPage(params) {
ensureActivityCache()
dynamicPage(name: "healthPage", title: "Device Health", nextPage: "mainPage") {
section("Low battery alerts") {
paragraph("Warn when a device's battery runs low. Battery-powered devices " +
"that never report a battery level are skipped.")
input "healthBattery", "bool", title: "Notify when batteries run low",
defaultValue: true, submitOnChange: true
if (settings.healthBattery != false) {
input "healthBatteryThreshold", "number", title: "Warn when battery is at or below (%)",
defaultValue: 20, required: true, range: "1..100"
input "healthBatteryIgnore", "enum", title: "Ignore these devices",
multiple: true, required: false, options: deviceOptions(),
description: "Checked devices never trigger battery alerts"
}
}
section("Inactive device alerts") {
paragraph("Warn when a device goes quiet — no events at all, not just " +
"no state changes.")
input "healthInactive", "bool", title: "Notify when devices go quiet",
defaultValue: true, submitOnChange: true
if (settings.healthInactive != false) {
input "healthInactiveDays", "number", title: "Warn when quiet for N days",
defaultValue: 7, required: true, range: "1..365"
input "healthInactiveIgnore", "enum", title: "Ignore these devices",
multiple: true, required: false, options: deviceOptions(),
description: "Checked devices never trigger inactivity alerts"
}
}
section("Delivery") {
paragraph("Health alerts are text push notifications to your Hubitat mobile " +
"app devices — one summary per day listing everything needing attention. " +
"They never play on speakers.")
input "healthTime", "time", title: "Run the health check daily at",
required: false, description: "Leave blank for 9:00 AM"
input "healthDays", "enum", title: "Check on these days",
multiple: true, required: false,
options: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
description: "Leave blank to check every day (e.g. weekends only)"
input "healthMaxProblems", "enum", title: "Devices listed per notification",
options: ["5", "10", "15", "20", "All"], defaultValue: "10", required: false,
description: "Most urgent first; the rest are summarized as “and N more”"
def problems = healthProblems()
paragraph(problems ?
"Right now:
• " + problems.join("
• ") :
"Right now: all clear.")
}
}
}
// --- device health engine -----------------------------------------------------
def healthProblems() {
ensureActivityCache()
// Each entry is [severityKey, text]; sorted most-urgent-first before returning.
def battery = []
def inactive = []
if (settings.healthBattery != false) {
def threshold = (settings.healthBatteryThreshold != null ? settings.healthBatteryThreshold as int : 20)
def ignore = (settings.healthBatteryIgnore ?: [])*.toString()
allExposedDevices().each { d ->
if (ignore.contains(d.id.toString())) return
try {
if (!d.hasAttribute("battery")) return
def v = d.currentValue("battery")
if (v == null) return
def n = v.toString().isNumber() ? (v as BigDecimal) : null
if (n != null && n <= threshold) battery << [n, "${d.displayName}: battery ${n.intValue()}%"]
} catch (e) {
logDebug("battery check failed for ${d.displayName}: ${e.message}")
}
}
}
if (settings.healthInactive != false) {
def days = (settings.healthInactiveDays != null ? settings.healthInactiveDays as int : 7)
def ignore = (settings.healthInactiveIgnore ?: [])*.toString()
allExposedDevices().each { d ->
if (ignore.contains(d.id.toString())) return
def inactiveDays = deviceInactiveDays(d)
if (inactiveDays == null) inactive << [999999, "${d.displayName}: never reported any activity"]
else if (inactiveDays >= days) inactive << [inactiveDays, "${d.displayName}: no activity for ${inactiveDays} days"]
}
}
battery.sort { a, b -> a[0] <=> b[0] } // lowest battery first
inactive.sort { a, b -> b[0] <=> a[0] } // longest quiet (never first) first
return (battery + inactive).collect { it[1] }
}
def deviceHealthCheck() {
def days = settings.healthDays
if (days) {
def today = new Date().format("EEEE")
if (!days.contains(today)) {
logDebug("device health check: skipping, ${today} not selected")
return
}
}
def problems = healthProblems()
if (!problems) {
logDebug("device health check: all clear")
return
}
// Notify about the most urgent only; summarize the rest.
def maxN = settings.healthMaxProblems ?: "10"
def shown = problems
if (maxN != "All" && problems.size() > (maxN as int)) {
shown = problems.take(maxN as int) + ["...and ${problems.size() - (maxN as int)} more"]
}
log.info "Muse Bridge device health: ${problems.size()} issue(s), notifying top ${shown.size()}"
def phones = settingDeviceList("ntPhones")
if (!phones) {
log.warn "Muse Bridge: health check found problems but no notification devices are configured"
return
}
// Split into ~200-char chunks so long lists survive push limits.
def chunks = []
def current = ""
shown.each { p ->
def add = (current ? "; " : "") + p
if ((current + add).length() > 200 && current) {
chunks << current
current = p
} else {
current += add
}
}
if (current) chunks << current
phones.each { ph ->
chunks.each { c ->
try { ph.deviceNotification("Muse Bridge health: ${c}") }
catch (e) { log.warn "Muse Bridge: health push failed: ${e.message}" }
}
}
}
def scheduleHealthCheck() {
unschedule("deviceHealthCheck")
if (settings.healthBattery == false && settings.healthInactive == false) return
def hour = 9
def minute = 0
try {
if (settings.healthTime) {
def cal = Calendar.getInstance()
cal.setTime(settings.healthTime as Date)
hour = cal.get(Calendar.HOUR_OF_DAY)
minute = cal.get(Calendar.MINUTE)
}
} catch (e) {
log.warn "Muse Bridge: bad health check time, using 09:00"
}
schedule("0 ${minute} ${hour} * * ?", "deviceHealthCheck")
logDebug("device health check scheduled daily at ${String.format('%02d', hour)}:${String.format('%02d', minute)}")
}
def rulesPage(params) {
if (params?.deleteId) {
if (params.deleteId == state.editingRuleId) state.editingRuleId = null
state.rules = getRules().findAll { it.id != params.deleteId }
if (state.ruleState) state.ruleState.remove(params.deleteId)
state.remove("schedActions_${params.deleteId}")
state.remove("delSeen_${params.deleteId}")
// drop the rule's orphaned settings
settings.keySet().findAll { it.startsWith("r_${params.deleteId}_") }.each { k ->
try { app.removeSetting(k) } catch (e) { /* older platforms: leave it, harmless */ }
}
initialize()
} else if (state.editingRuleId) {
syncRuleFromSettings(state.editingRuleId)
state.editingRuleId = null
initialize()
}
def rules = getRules()
dynamicPage(name: "rulesPage", title: "Alert Rules", nextPage: "mainPage") {
section() {
paragraph("A rule watches a device attribute and announces when it stays in a state " +
"longer than your duration — or clears sooner than it. Rules also support " +
"conditions on mode, thermostat state, time window, and days.")
}
section("Rules") {
if (!rules) {
paragraph("No rules yet. Add your first one below — e.g. “Garage door open 10 minutes”.")
}
rules.each { r ->
def st = ruleStateFor(r.id)
href(name: "rule_${r.id}", page: "rulePage", params: [ruleId: r.id],
title: "${r.enabled ? '' : '⏸ '}${r.name}",
description: ruleDescription(r, st))
}
}
section() {
href(name: "ruleNew", page: "rulePage", params: [ruleId: "new"],
title: "Add new rule", description: "Create an alert rule")
}
}
}
def museActionsPage(params) {
def actions = museSideActions()
dynamicPage(name: "museActionsPage", title: "Muse Automations", nextPage: "mainPage") {
section() {
paragraph("These automations run on the assistant side (not on this hub) — " +
"schedules and tasks your assistant manages for you. They are listed here " +
"so you can see everything acting on your home in one place. " +
"To add, change, or remove one, ask your assistant in chat.")
}
section("Assistant-side automations") {
if (!actions) {
paragraph("None registered.")
}
actions.each { a ->
def lines = ["${a.title ?: 'Untitled'}"]
def trig = a.trigger ?: a.schedule
if (trig) lines << "Trigger: ${trig}"
if (a.actions) lines << "Actions: ${a.actions}"
if (a.restrictions) lines << "Restrictions: ${a.restrictions}"
if (a.detail && !a.actions) lines << "${a.detail}"
paragraph(lines.join("
"))
}
}
}
}
def museSideActions() {
return (state.museSideActions instanceof List ? state.museSideActions : [])
}
/** Input title with " (optional)" appended when the field isn't required. */
def optT(String title, boolean required) { return required ? title : "${title} (optional)" }
def rulePage(params) {
def rid = params?.ruleId
if (!rid || rid == "new") rid = state.editingRuleId
if (!rid || rid == "new") rid = "r${now()}"
state.editingRuleId = rid
hydrateRuleEditor(rid) // show real values for API-created rules
def p = "r_${rid}_"
def st = ruleStateFor(rid)
// action-list builder bookkeeping (schedule rules)
def actsKey = "schedActions_${rid}"
if (params?.addAction) editingActionsAdd(rid, p)
if (params?.delActionIdx != null) {
// delete links carry a one-time token: if the page re-renders with
// stale params, the token is already spent and the delete won't repeat
def tok = params.delToken?.toString()
def seenKey = "delSeen_${rid}"
def seen = state[seenKey] instanceof List ? state[seenKey] : []
if (tok && !(tok in seen)) {
editingActionsDelete(rid, params.delActionIdx as int)
state[seenKey] = (seen + [tok]).takeRight(20)
}
}
def isSched = (settings["${p}trigType"] ?: "device") == "schedule"
dynamicPage(name: "rulePage", title: isSched ? "Scheduled Actions" : "Alert Rule", nextPage: "rulesPage") {
section("Rule") {
input "${p}enabled", "bool", title: "Enabled", defaultValue: true
input "${p}name", "text", title: "Rule name", required: true,
description: "e.g. Garage door left open"
}
section("Trigger") {
input "${p}trigType", "enum", title: "Trigger type", required: true,
defaultValue: "device", submitOnChange: true,
options: ["device": "📟 Device state", "schedule": "🕒 Day/time schedule"]
if (isSched) {
input "${p}schedDays", "enum", title: "Days", multiple: true, required: true,
options: scheduleDayOptions()
input "${p}schedTime", "time", title: "Time (hub-local)", required: true,
description: "e.g. 07:20"
input "${p}schedTimesExtra", "text", title: optT("Additional times", false),
description: "More times, comma-separated HH:mm (24h) — e.g. 12:30, 15:30"
} else {
input "${p}trigDevs", "enum", title: "Devices to watch", multiple: true, required: true,
options: deviceOptions(),
description: "Alert when ANY of these matches below"
input "${p}attr", "enum", title: "Attribute", required: true,
options: attributeOptions(settings["${p}trigDevs"]),
description: "Pick devices first to narrow this list"
input "${p}op", "enum", title: "Comparison", required: true, defaultValue: "=",
options: ["=": "is (=)", "!=": "is not (!=)",
">": "greater than (>)", "<": "less than (<)",
">=": "at least (>=)", "<=": "at most (<=)"]
input "${p}value", "text", title: "Value to compare against", required: true,
description: "e.g. open, active, on, locked, wet, 78"
}
}
if (isSched) {
section("Actions — run in order when the schedule fires") {
def acts = editingActions(rid)
if (!acts) {
paragraph("No actions yet — add one below. With no actions, the rule announces (if a message is set).")
}
acts.eachWithIndex { a, i ->
href(name: "delAct_${rid}_${i}_${now()}", page: "rulePage",
params: [ruleId: rid, delActionIdx: i, delToken: "${i}_${now()}"],
title: "Remove", description: describeAction(a))
}
input "${p}actType", "enum", title: optT("Action type", false), required: false,
submitOnChange: true,
options: ["announce": "📣 Announce (uses the message + channels below)",
"command" : "🎛 Device command",
"mode" : "🏠 Set location mode",
"hsm" : "🛡 Set HSM arm state"]
def at = settings["${p}actType"]?.toString()
if (at == "command") {
input "${p}actDevice", "enum", title: "Device", required: true,
options: deviceOptions()
input "${p}actCommand", "text", title: "Command", required: true,
description: "e.g. on, off, lock, setLevel"
input "${p}actArg", "text", title: optT("Argument (single value)", false), required: false,
description: "e.g. 80 for setLevel 80"
} else if (at == "mode") {
input "${p}actMode", "enum", title: "Mode", required: true,
options: modeOptions()
} else if (at == "hsm") {
input "${p}actHsm", "enum", title: "Arm state", required: true,
options: ["armAway": "Armed (away)", "armHome": "Armed (home)",
"armNight": "Armed (night)", "disarm": "Disarmed"]
}
if (at) {
href(name: "addAct_${rid}", page: "rulePage", params: [ruleId: rid, addAction: 1],
title: "Add action", description: "Append the action above to this rule")
}
}
}
section("Timing") {
if (!isSched) {
input "${p}alertWhen", "enum", title: "Alert when the state…", required: true,
defaultValue: "staysLongerThan",
options: ["staysLongerThan": "…persists LONGER than the duration",
"clearsSoonerThan": "…clears SOONER than the duration"]
input "${p}dur", "decimal", title: "Duration (minutes, 0 = announce immediately)", required: true, defaultValue: 10,
description: "Decimals allowed, e.g. 0.5 for 30 seconds. 0 fires the moment the condition is seen."
input "${p}repeat", "decimal", title: optT("Repeat the announcement every (minutes, 0 = once)", false), defaultValue: 0
}
input "${p}cooldown", "number", title: optT("Cooldown between announcements (seconds, 0 = none)", false), defaultValue: 0,
range: "0..3600",
description: "After an announcement, skip further announcements for this long. Handy for doors the kids run through."
}
section("Conditions — the rule only arms when ALL of these hold (blank = always)") {
input "${p}modes", "enum", title: optT("Location modes", false), multiple: true, required: false,
options: modeOptions()
input "${p}hsmStates", "enum", title: optT("Security monitor (HSM) is…", false), multiple: true, required: false,
options: ["armedAway": "Armed (away)", "armedHome": "Armed (home)",
"armedNight": "Armed (night)", "disarmed": "Disarmed"],
description: "Requires Hubitat Safety Monitor; blank = any state"
input "${p}tstat", "enum", title: optT("Thermostat", false), required: false,
options: thermostatOptions(),
description: "e.g. only alert about open windows while the A/C runs"
input "${p}tstatStates", "enum", title: optT("Thermostat is…", false), multiple: true, required: false,
options: ["heating": "heating", "cooling": "cooling", "idle": "idle",
"fan only": "fan only", "pending heat": "pending heat", "pending cool": "pending cool"]
input "${p}timeFrom", "time", title: optT("Only between (from)", false), required: false
input "${p}timeTo", "time", title: optT("…and (to)", false), required: false
input "${p}days", "enum", title: optT("Days of the week", false), multiple: true, required: false,
options: ["Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday",
"Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday"]
}
section("Notifications") {
paragraph("Choose how this rule announces. Text alerts (push) can target " +
"specific phones; spoken alerts use the house speakers; Muse chat " +
"messages arrive via the assistant's polling.")
input "${p}msg", "text", title: optT("Message", false), required: false,
description: "Blank = automatic. Tokens: %device% %attribute% %value% %rule%. Used for every channel."
input "${p}channels", "enum", title: "Send alerts via", multiple: true, required: true,
defaultValue: ["speech"],
options: ["speech": "🔊 Spoken on house speakers",
"push" : "📱 Push to phones (Hubitat app)",
"muse" : "💬 Message in Muse chat"]
input "${p}speech", "enum", title: optT("Speak on", false),
multiple: true, required: false, options: speechOptions(),
description: "Blank = all speech devices"
input "${p}pushDevs", "enum", title: optT("Push to", false),
multiple: true, required: false, options: pushOptions(),
description: "Blank = all phones. Each phone is a separate device — pick who gets the text"
input "${p}volume", "number", title: optT("Volume for this rule's announcements", false),
required: false, range: "0..100",
description: "0-100, blank = app default. Handy for making urgent rules louder than the rest"
input "${p}notifyClear", "bool", title: "Also notify when the condition clears", defaultValue: false
input "${p}urgent", "bool", title: "URGENT priority", defaultValue: false,
description: "Alerts are prefixed so they stand out on every channel"
}
section("Status") {
paragraph(ruleStatusText(rid, st))
}
section("Danger zone") {
href(name: "del_${rid}", page: "rulesPage", params: [deleteId: rid],
title: "Delete this rule", description: "Removes the rule permanently")
}
}
}
def linkPage(params) {
ensureToken()
dynamicPage(name: "linkPage", title: "Link with Muse", nextPage: "mainPage") {
section("Monitoring preferences") {
paragraph("These tell your assistant how closely to watch the hub. " +
"They're baked into the setup message below, so any assistant " +
"can configure itself from your choices.")
input "linkPollMinutes", "number", title: "Poll the hub every (minutes)",
defaultValue: 5, required: true
input "linkDownThreshold", "number",
title: "Message me after this many consecutive failed polls",
defaultValue: 3, required: true
input "linkDownWindow", "number", title: "…within the last X minutes",
defaultValue: 15, required: true
}
section("Setup — copy, paste, send") {
def base = cloudBase()
if (!state.accessToken || !base) {
paragraph("Enable OAuth first (see the API Access page), then come back here.")
} else {
paragraph("1. Copy the whole message below.
" +
"2. Paste it to your assistant (Muse) in chat and send it.
" +
"3. The assistant verifies the connection and starts monitoring.
" +
"Keep the token private — anyone with it can read and control your devices.
" +
"Muse Bridge was designed by Rayzurbock and coded by " +
"Muse, " +
"Meta's personal AI assistant. The API is open, so other assistants can use it too.")
paragraph("Copy everything below this line:
" +
linkMessage(base).replace("\n", "
"))
}
}
}
}
/** Pre-filled, copy-paste setup message for the user's assistant. */
def linkMessage(String base) {
def token = state.accessToken
def pollMin = settings.linkPollMinutes ?: 5
def threshold = settings.linkDownThreshold ?: 3
def windowMin = settings.linkDownWindow ?: 15
return """Hi Muse — please link with my Hubitat hub through the Muse Bridge app:
Cloud API base URL: ${base}
Access token: ${token}
Please:
- Poll the hub every ${pollMin} minutes: GET ${base}/health?access_token=${token}
- If the hub fails to respond ${threshold} times in a row within ${windowMin} minutes, message me in chat immediately (once per outage), and tell me when it recovers. Distinguish timeouts from HTTP 401 (revoked token).
- Each poll, also GET ${base}/rules?access_token=${token} — if any rule with the "muse" notification channel is newly breached, message me; lead with a siren emoji for urgent ones. Stay silent otherwise.
- I may ask you to check device states, run commands, change modes, arm/disarm HSM, or create alert rules. Security-sensitive actions need my command passcode as the "passcode" field — ask me for it when needed and never store it unless I say so.
- Confirm the link by calling /health and telling me what you see.
— via Muse Bridge v${appVersion()} by Rayzurbock (https://github.com/rayzurbock/hubitat-muse-bridge)""".strip()
}
/** The cloud base URL for this app's endpoints (no trailing path). */
def cloudBase() {
try {
def u = fullApiServerUrl("x").toString() // documented: base + "/" + path
return u.substring(0, u.length() - 2) // strip the trailing "/x"
} catch (e) {
log.warn "Muse Bridge: could not build cloud base URL: ${e.message}"
return null
}
}
def apiPage(params) {
ensureToken()
dynamicPage(name: "apiPage", title: "API Access", nextPage: "mainPage") {
section() {
if (!state.accessToken) {
paragraph("OAuth is not enabled for this app — the API won't work without it.
" +
"1. Go to Apps Code in the left sidebar.
" +
"2. Click Muse Bridge to open the code editor.
" +
"3. Click the ⋮ three-dot menu in the top-right corner of the editor.
" +
"4. Choose OAuth, then click Enable OAuth in the popup.
" +
"5. Come back here — the token and URLs will appear below.")
} else {
paragraph("Use these URLs with ?access_token=${state.accessToken} appended. " +
"Keep the token secret — anyone with it can read and control your devices.")
paragraph("Cloud health check:
${fullApiServerUrl('health')}?access_token=${state.accessToken}")
paragraph("Cloud devices:
${fullApiServerUrl('devices')}?access_token=${state.accessToken}")
paragraph("Local health check:
${fullLocalApiServerUrl('health')}?access_token=${state.accessToken}")
paragraph("Local devices:
${fullLocalApiServerUrl('devices')}?access_token=${state.accessToken}")
paragraph("Security-sensitive actions (unlock, garage open, valve open/close, " +
"siren control, mode changes, HSM arm/disarm) additionally require your " +
"command passcode as passcode in the JSON body or query string. " +
"Set it on the app's main page.")
paragraph("Full endpoint reference is in the README. To revoke access, disable OAuth " +
"in Apps Code or reinstall the app to rotate the token.")
}
}
}
}
// ============================================================================
// Lifecycle
// ============================================================================
def installed() {
log.info "Muse Bridge v${appVersion()} installed"
state.rules = []
state.ruleState = [:]
ensureToken()
initialize()
}
def updated() {
log.info "Muse Bridge v${appVersion()} updated"
if (state.editingRuleId) syncRuleFromSettings(state.editingRuleId)
state.editingRuleId = null
ensureToken()
initialize()
}
def uninstalled() {
log.info "Muse Bridge uninstalled"
}
def initialize() {
unsubscribe()
unschedule()
scheduleHealthCheck()
state.ruleState = state.ruleState ?: [:]
def rules = getRules()
rules.each { rule ->
if (rule.enabled) subscribeRule(rule)
}
if (rules) {
subscribe(location, "mode", "ruleEventHandler")
runEvery5Minutes("periodicRuleEval")
}
// Schedule-based rules: one per-minute tick checks them all.
unschedule("scheduledRuleTick")
if (rules.any { it.enabled && isScheduleRule(it) }) {
schedule("0 * * * * ?", "scheduledRuleTick")
}
// unschedule() above wiped all pending timers: drop stale "pending" flags so
// evaluateAllRules() re-arms them cleanly instead of relying on recovery.
rules.each { rule ->
if (!rule.enabled) return
def st = ruleStateFor(rule.id)
if (st.pending) {
st.pending = false
st.pendingSince = null
saveRuleState(rule.id, st)
}
}
evaluateAllRules("init")
// Re-schedule repeat announcements for rules that are still breached.
rules.each { rule ->
if (!rule.enabled) return
def st = ruleStateFor(rule.id)
if (st.breached && (rule.repeatMin as BigDecimal) > 0 &&
triggerConditionTrue(rule) && conditionsTrue(rule)) {
def secs = Math.max(30, ((rule.repeatMin as BigDecimal) * 60) as long)
runIn(secs, "ruleRepeat", [data: [ruleId: rule.id], overwrite: false])
}
}
logDebug("initialized with ${allExposedDevices().size()} devices and ${rules.count { it.enabled }} enabled rules")
}
def ensureToken() {
if (!state.accessToken) {
try {
createAccessToken()
log.info "Muse Bridge: OAuth access token created"
} catch (e) {
log.warn "Muse Bridge: could not create access token — is OAuth enabled in Apps Code? ${e.message}"
}
}
}
// ============================================================================
// Rule engine
// ============================================================================
/** True for day/time-triggered rules (as opposed to device-state alert rules). */
def isScheduleRule(Map rule) { return (rule.triggerType ?: "device") == "schedule" }
def scheduleDayOptions() {
return ["MON": "Monday", "TUE": "Tuesday", "WED": "Wednesday",
"THU": "Thursday", "FRI": "Friday", "SAT": "Saturday", "SUN": "Sunday"]
}
/** Accepts "WED", "Wed", "Wednesday" (any case) → "WED"; null when unknown. */
def normalizeDayName(String d) {
def m = ["MON": "MON", "MONDAY": "MON", "TUE": "TUE", "TUESDAY": "TUE",
"WED": "WED", "WEDNESDAY": "WED", "THU": "THU", "THURSDAY": "THU",
"FRI": "FRI", "FRIDAY": "FRI", "SAT": "SAT", "SATURDAY": "SAT",
"SUN": "SUN", "SUNDAY": "SUN"]
return m[d?.toString()?.trim()?.toUpperCase()]
}
/** A Hubitat `time` input setting (Date) → "HH:mm" in hub-local time. */
def timeSettingToHHmm(v) {
if (!v) return null
try {
def d = v instanceof Date ? v : Date.parse("yyyy-MM-dd'T'HH:mm:ss", v.toString())
return d.format("HH:mm", location?.timeZone)
} catch (e) {
return v.toString()
}
}
/** Parse "12:30, 15:30" → ["12:30", "15:30"]; invalid entries are dropped. */
def parseExtraTimes(String text) {
if (!text) return []
return text.split(/[,\s]+/).collect { it.trim() }.findAll { it ==~ /^([01]\d|2[0-3]):[0-5]\d$/ }.unique()
}
/** All HH:mm times a schedule rule fires at (scheduleTimes wins; scheduleTime is legacy). */
def scheduleRuleTimes(rule) {
def ts = rule?.scheduleTimes instanceof List ? rule.scheduleTimes : []
if (!ts && rule?.scheduleTime) ts = [rule.scheduleTime]
return ts.collect { it?.toString() }.findAll { it }.unique()
}
/**
* Runs every minute while at least one schedule rule is enabled. Fires each
* rule whose day + time match right now (hub-local), once per minute, when
* its conditions hold. A hub reboot or a missed minute simply skips — the
* lastScheduleFire guard prevents double-firing, never back-fills.
*/
def scheduledRuleTick() {
def tz = location?.timeZone ?: TimeZone.getDefault()
def now = new Date()
def day = now.format("EEE", tz).toUpperCase()
def hm = now.format("HH:mm", tz)
def fireKey = now.format("yyyy-MM-dd", tz) + " " + hm
getRules().findAll { it.enabled && isScheduleRule(it) }.each { rule ->
if (!(day in (rule.scheduleDays ?: []))) return
if (!(hm in scheduleRuleTimes(rule))) return
if (!conditionsTrue(rule)) {
logDebug("scheduled rule '${rule.name}': conditions not met, skipping")
return
}
def st = ruleStateFor(rule.id)
if (st.lastScheduleFire == fireKey) return // already fired this minute
if (inCooldown(rule, st)) {
logDebug("scheduled rule '${rule.name}': in cooldown, skipping")
return
}
def fired = []
(rule.actions ?: [[type: "announce"]]).each { action ->
try {
if (executeRuleAction(rule, action, st)) fired << describeAction(action)
} catch (e) {
log.warn "Muse Bridge: scheduled rule '${rule.name}' action failed: ${e.message}"
}
}
st.lastScheduleFire = fireKey
st.lastBreach = now()
if (fired) st.lastAction = [time: now(), text: fired.join("; ")]
saveRuleState(rule.id, st)
log.info "Muse Bridge: scheduled rule '${rule.name}' fired (${fired.size()} action${fired.size() == 1 ? '' : 's'})"
}
}
/** Runs one action of a schedule rule. Returns a short human description. */
def executeRuleAction(Map rule, Map action, Map st) {
def type = action.type?.toString()
switch (type) {
case "announce":
// cooldown-aware; stamps lastAlert on success
if (announce(rule, st, "scheduled")) return "announced: ${rule.message ?: rule.name}"
return null // in cooldown — not a failure
case "command":
def d = getDeviceById(action.deviceId?.toString())
if (!d) throw new Exception("unknown device ${action.deviceId}")
def cmd = action.command?.toString()
if (!cmd || !d.hasCommand(cmd)) throw new Exception("device '${d.displayName}' has no command '${cmd}'")
def args = (action.args instanceof List ? action.args : []).collect { coerceArg(it) }
log.info "Muse Bridge: scheduled rule '${rule.name}': ${d.displayName}.${cmd}(${args})"
d."$cmd"(*args)
return "${d.displayName}: ${cmd}"
case "mode":
def mode = action.mode?.toString()
if (!(mode in location.modes*.name)) throw new Exception("unknown mode '${mode}'")
log.info "Muse Bridge: scheduled rule '${rule.name}': setting mode to ${mode}"
setLocationMode(mode)
return "mode → ${mode}"
case "hsm":
def arm = action.arm?.toString()
if (!(arm in ["armAway", "armHome", "armNight", "disarm"])) throw new Exception("bad arm value '${arm}'")
log.info "Muse Bridge: scheduled rule '${rule.name}': setting HSM to ${arm}"
sendLocationEvent(name: "hsmSetArm", value: arm)
return "HSM → ${arm}"
default:
throw new Exception("unknown action type '${type}'")
}
}
def describeAction(Map action) {
switch (action.type?.toString()) {
case "announce": return "announce"
case "command": return "command ${action.command} on device ${action.deviceId}"
case "mode": return "set mode ${action.mode}"
case "hsm": return "set HSM ${action.arm}"
default: return "action ${action.type}"
}
}
def subscribeRule(rule) {
if (isScheduleRule(rule)) return // schedule rules are driven by the per-minute tick
if (!rule.attribute) {
log.warn "Muse Bridge: rule '${rule.name}' has no attribute, skipping subscriptions"
return
}
def devs = triggerDevices(rule)
if (!devs) {
log.warn "Muse Bridge: rule '${rule.name}' has no matching trigger devices, skipping subscriptions"
return
}
devs.each { d ->
try {
subscribe(d, rule.attribute, "ruleEventHandler")
} catch (e) {
log.warn "Muse Bridge: could not subscribe to ${d.displayName}.${rule.attribute}: ${e.message}"
}
}
if (rule.thermostatId) {
def t = getDeviceById(rule.thermostatId)
if (t) {
try { subscribe(t, "thermostatOperatingState", "ruleEventHandler") }
catch (e) { log.warn "Muse Bridge: could not subscribe to thermostat: ${e.message}" }
}
}
}
def ruleEventHandler(evt) {
def ids
if (evt.name == "mode") {
logDebug("mode changed to ${evt.value}, re-evaluating all rules")
ids = getRules().findAll { it.enabled }.collect { it.id }
} else {
def devId = evt.deviceId?.toString()
logDebug("event: device ${devId} ${evt.name} = ${evt.value}")
ids = getRules().findAll { rule ->
rule.enabled && (triggerDeviceIds(rule).contains(devId) || rule.thermostatId?.toString() == devId)
}.collect { it.id }
}
ids.each { id ->
def rule = getRule(id)
if (rule) evaluateRule(rule, "event")
}
}
def periodicRuleEval() {
// Catches time-window/day edges, missed events, and timers lost to a hub reboot.
getRules().each { rule ->
if (!rule.enabled) return
evaluateRule(rule, "periodic")
def st = ruleStateFor(rule.id)
if (st.pending && rule.alertWhen == "staysLongerThan") {
def durMs = (rule.durationMin as BigDecimal) * 60000
if (now() - (st.pendingSince ?: now()) > durMs + 300000) {
logDebug("rule '${rule.name}': pending timer appears lost, checking now")
ruleCheck([ruleId: rule.id])
}
}
}
}
def evaluateAllRules(String reason) {
getRules().each { rule ->
if (rule.enabled && !isScheduleRule(rule)) evaluateRule(rule, reason)
}
}
def evaluateRule(rule, String reason) {
def st = ruleStateFor(rule.id)
def trig = triggerConditionTrue(rule)
def cond = conditionsTrue(rule)
logDebug("evaluate '${rule.name}' (${reason}): trigger=${trig} conditions=${cond} pending=${st.pending} breached=${st.breached}")
if (trig && cond) {
if (rule.alertWhen == "clearsSoonerThan") {
if (!st.activeSince) {
st.activeSince = now()
saveRuleState(rule.id, st)
logDebug("rule '${rule.name}': timing active period")
}
} else { // staysLongerThan
if (!st.pending && !st.breached) {
def durMin = (rule.durationMin != null ? rule.durationMin : 10) as BigDecimal
if (durMin <= 0) {
// immediate mode: announce right away (cooldown-aware)
if (announce(rule, st, "immediate")) {
st.breached = true
st.lastBreach = now()
saveRuleState(rule.id, st)
scheduleRuleRepeat(rule)
logDebug("rule '${rule.name}': condition met, announced immediately")
} else {
logDebug("rule '${rule.name}': in cooldown, skipping immediate announcement")
}
} else {
st.pending = true
st.pendingSince = now()
saveRuleState(rule.id, st)
def secs = Math.max(5, (durMin * 60) as long)
runIn(secs, "ruleCheck", [data: [ruleId: rule.id], overwrite: false])
logDebug("rule '${rule.name}': condition met, checking again in ${secs}s")
}
}
}
} else {
if (rule.alertWhen == "clearsSoonerThan" && st.activeSince) {
def elapsedMin = (now() - st.activeSince) / 60000.0
if (elapsedMin < (rule.durationMin as BigDecimal)) {
announce(rule, st, "cleared after ${elapsedMin.round(1)} min (minimum ${rule.durationMin})")
} else {
logDebug("rule '${rule.name}': active period satisfied (${elapsedMin.round(1)} min)")
}
st.activeSince = null
}
if (st.pending) {
st.pending = false
st.pendingSince = null
logDebug("rule '${rule.name}': no longer pending")
}
if (st.breached) {
st.breached = false
log.info "Muse Bridge: rule '${rule.name}' cleared"
if (rule.notifyClear) notifyRule(rule, "Cleared: ${rule.name}.")
}
saveRuleState(rule.id, st)
}
}
def ruleCheck(data) {
def rule = getRule(data?.ruleId as String)
if (!rule || !rule.enabled || isScheduleRule(rule)) return
def st = ruleStateFor(rule.id)
if (!st.pending) return // superseded — condition already cleared
if (triggerConditionTrue(rule) && conditionsTrue(rule)) {
st.pending = false
st.pendingSince = null
saveRuleState(rule.id, st)
if (announce(rule, st, "active for ${rule.durationMin} min")) {
st.breached = true
st.lastBreach = now()
saveRuleState(rule.id, st)
scheduleRuleRepeat(rule)
}
} else {
st.pending = false
st.pendingSince = null
saveRuleState(rule.id, st)
}
}
def ruleRepeat(data) {
def rule = getRule(data?.ruleId as String)
if (!rule || !rule.enabled || isScheduleRule(rule)) return
def st = ruleStateFor(rule.id)
if (st.breached && triggerConditionTrue(rule) && conditionsTrue(rule)) {
fireAlert(rule, "still active")
if ((rule.repeatMin as BigDecimal) > 0) {
def secs = Math.max(30, ((rule.repeatMin as BigDecimal) * 60) as long)
runIn(secs, "ruleRepeat", [data: [ruleId: rule.id], overwrite: false])
}
} else {
st.breached = false
saveRuleState(rule.id, st)
}
}
/** Seconds that must pass between a rule's announcements (0 = none). */
def cooldownSecOf(rule) { return ((rule.cooldownSec != null ? rule.cooldownSec : 0) as BigDecimal) }
def inCooldown(rule, Map st) {
def cdMs = (cooldownSecOf(rule) * 1000) as long
if (cdMs <= 0) return false
def last = st.lastAlert as Long
return last != null && (now() - last) < cdMs
}
/**
* Cooldown-aware announcement: skips (returns false) while the rule is still
* cooling down from its last announcement. Stamps lastAlert on success.
* Manual test announcements (apiTestRule) bypass this via notifyRule directly.
*/
def announce(rule, Map st, String reasonDetail) {
if (inCooldown(rule, st)) {
logDebug("rule '${rule.name}': in cooldown, skipping announcement")
return false
}
fireAlert(rule, reasonDetail)
st.lastAlert = now()
saveRuleState(rule.id, st)
return true
}
def scheduleRuleRepeat(rule) {
if ((rule.repeatMin as BigDecimal) > 0) {
def secs = Math.max(30, ((rule.repeatMin as BigDecimal) * 60) as long)
runIn(secs, "ruleRepeat", [data: [ruleId: rule.id], overwrite: false])
}
}
def fireAlert(rule, String reasonDetail) {
def dev = triggerDevices(rule)?.find { d -> compareValues(d.currentValue(rule.attribute), rule.operator, rule.value) }
def msg = rule.message ?: "Alert: ${rule.name}."
msg = msg.replace("%rule%", rule.name ?: "")
.replace("%device%", dev?.displayName ?: "device")
.replace("%attribute%", rule.attribute ?: "")
.replace("%value%", dev ? "${dev.currentValue(rule.attribute)}" : "")
log.warn "Muse Bridge ALERT [${rule.name}]: ${msg} (${reasonDetail})"
notifyRule(rule, msg)
}
/**
* Send a rule notification through every channel the rule selected:
* speech — spoken on the house speakers (local, immediate)
* push — text push to the selected phones via the Hubitat mobile app
* muse — nothing the hub can do directly; the assistant's polling loop
* sees the breach in GET /rules and messages the user in chat.
*/
def notifyRule(rule, String text) {
def channels = rule.channels ?: ["speech"]
def urgent = rule.urgent == true
if ("speech" in channels) speakForRule(rule, urgent ? "Urgent. ${text}" : text)
if ("push" in channels) pushForRule(rule, urgent ? "🚨 URGENT: ${text}" : text)
if ("muse" in channels) log.info "Muse Bridge [muse channel${urgent ? ' URGENT' : ''}] ${rule.name}: ${text}"
}
def pushForRule(rule, String text) {
def ids = rule.pushDeviceIds ?: defaultPushDeviceIds()
if (!ids) {
log.warn "Muse Bridge: no notification devices configured, cannot push: ${text}"
return
}
ids.each { id ->
def d = getDeviceById(id)
if (!d) {
log.warn "Muse Bridge: notification device id ${id} not found"
return
}
try {
if (d.hasCommand("deviceNotification")) {
d.deviceNotification(text)
logDebug("pushed to ${d.displayName}: ${text}")
} else {
log.warn "Muse Bridge: ${d.displayName} has no deviceNotification command"
}
} catch (e) {
log.warn "Muse Bridge: push to ${d.displayName} failed: ${e.message}"
}
}
}
def speakForRule(rule, String text) {
def ids = rule.speechDeviceIds ?: defaultSpeechDeviceIds()
if (!ids) {
log.warn "Muse Bridge: no speech devices configured, cannot announce: ${text}"
return
}
speakOnDevices(ids, text, rule.volume != null ? rule.volume as BigDecimal : null)
}
def speakOnDevices(List ids, String text, BigDecimal volume = null) {
ids.each { id ->
def d = getDeviceById(id)
if (!d) {
log.warn "Muse Bridge: speech device id ${id} not found"
return
}
try {
def vol = effectiveVolume(d, volume)
def prevVol = null
def restoreToken = null
if (vol != null) {
prevVol = currentVolumeOf(d)
setDeviceVolume(d, vol)
if (settings.restoreVolume != false && prevVol != null && prevVol != vol) {
// Remember the pre-announcement volume; a later announcement
// supersedes this restore via its own token.
restoreToken = now()
if (!state.volRestore) state.volRestore = [:]
state.volRestore[id.toString()] = [level: prevVol, at: restoreToken]
}
}
if (d.hasCommand("speak")) {
d.speak(text)
} else if (d.hasCommand("playTextAndResume")) {
d.playTextAndResume(text) // music keeps playing after the announcement
} else if (d.hasCommand("playText")) {
d.playText(text)
} else {
log.warn "Muse Bridge: ${d.displayName} has no speak/playText command"
}
if (restoreToken) {
// Rough TTS estimate (~12 chars/sec) plus a buffer, minimum 15s.
def delay = Math.max(15, ((text.length() / 12) as int) + 5)
runIn(delay, "restoreDeviceVolume",
[data: [deviceId: id.toString(), at: restoreToken], overwrite: false])
}
logDebug("announced on ${d.displayName}${vol != null ? " at volume ${vol}" : ""}: ${text}")
} catch (e) {
log.warn "Muse Bridge: failed to announce on ${d.displayName}: ${e.message}"
}
}
}
/** Resolve the volume for an announcement: explicit override, app default, or minimum. Null = don't touch. */
def effectiveVolume(d, BigDecimal override) {
if (override != null) return clampVolume(override)
def v = settings.speechVolume
if (v != null) return clampVolume(v as BigDecimal)
def minV = settings.speechMinVolume
if (minV != null) {
def cur = currentVolumeOf(d)
if (cur != null && cur < (minV as BigDecimal)) return clampVolume(minV as BigDecimal)
}
return null
}
def currentVolumeOf(d) {
try {
def v = d.currentValue("level")
return v != null ? v as BigDecimal : null
} catch (e) {
return null
}
}
def setDeviceVolume(d, BigDecimal vol) {
def v = clampVolume(vol) as int
if (d.hasCommand("setVolume")) {
d.setVolume(v)
} else if (d.hasCommand("setLevel")) {
d.setLevel(v)
} else {
logDebug("Muse Bridge: ${d.displayName} has no volume command, skipping")
}
}
def clampVolume(v) {
def n = v as BigDecimal
if (n < 0) return 0
if (n > 100) return 100
return n
}
/** What volume features a speech device supports. Restore needs both. */
def deviceVolumeSupport(d) {
def canSet = d.hasCommand("setVolume") || d.hasCommand("setLevel")
def reports = false
try {
reports = d.supportedAttributes?.any { it.name == "level" } ?: (d.currentValue("level") != null)
} catch (e) {
try { reports = d.currentValue("level") != null } catch (e2) { reports = false }
}
return [canSet: canSet, reports: reports]
}
def restoreDeviceVolume(data) {
def devId = data?.deviceId?.toString()
def rec = state.volRestore?.get(devId)
if (!rec || rec.at != data?.at) return // superseded by a newer announcement
state.volRestore.remove(devId)
def d = getDeviceById(devId)
if (!d) return
try {
setDeviceVolume(d, rec.level as BigDecimal)
logDebug("Muse Bridge: restored ${d.displayName} volume to ${rec.level}")
} catch (e) {
log.warn "Muse Bridge: volume restore failed for ${d.displayName}: ${e.message}"
}
}
// --- rule condition helpers -------------------------------------------------
def triggerConditionTrue(rule) {
if (!rule.attribute) return false
def devs = triggerDevices(rule)
if (!devs) return false
return devs.any { d -> compareValues(d.currentValue(rule.attribute), rule.operator, rule.value) }
}
def conditionsTrue(rule) {
if (rule.modes && !(location.mode in rule.modes)) return false
if (rule.hsmStates) {
def hs = hsmStatus()
if (!(hs in rule.hsmStates)) return false
}
if (rule.thermostatId) {
def t = getDeviceById(rule.thermostatId)
if (!t) {
log.warn "Muse Bridge: rule '${rule.name}' references missing thermostat ${rule.thermostatId}"
return false
}
def opState = t.currentValue("thermostatOperatingState")?.toString()
if (rule.thermostatStates && !(opState in rule.thermostatStates)) return false
}
if (rule.timeFrom && rule.timeTo && !inTimeWindow(rule.timeFrom, rule.timeTo)) return false
if (rule.days && !(new Date().format("EEEE") in rule.days)) return false
return true
}
def compareValues(actual, String operator, expected) {
def a = actual?.toString()?.trim()
def e = expected?.toString()?.trim()
if (a == null || e == null) return false
def aNum = isNumeric(a)
def eNum = isNumeric(e)
if (aNum && eNum) {
def an = a as BigDecimal
def en = e as BigDecimal
switch (operator) {
case "=": return an == en
case "!=": return an != en
case ">": return an > en
case "<": return an < en
case ">=": return an >= en
case "<=": return an <= en
default: return false
}
}
switch (operator) {
case "=": return a.equalsIgnoreCase(e)
case "!=": return !a.equalsIgnoreCase(e)
default:
log.warn "Muse Bridge: operator '${operator}' needs numeric values (got '${a}' vs '${e}')"
return false
}
}
def isNumeric(String s) {
return s ==~ /-?\d+(\.\d+)?/
}
def inTimeWindow(String from, String to) {
def f = parseHourMinute(from)
def t = parseHourMinute(to)
if (f == null || t == null) return true
def n = minutesSinceMidnight(new Date())
if (f <= t) return n >= f && n <= t
return n >= f || n <= t // overnight window
}
def parseHourMinute(String s) {
try {
def hm = s
if (s.contains("T")) hm = s.substring(11, 16) // "yyyy-MM-ddTHH:mm:ss..."
def parts = hm.split(":")
return (parts[0] as int) * 60 + (parts[1] as int)
} catch (e) {
log.warn "Muse Bridge: could not parse time '${s}'"
return null
}
}
def minutesSinceMidnight(Date d) {
def cal = Calendar.getInstance()
cal.setTime(d)
return cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE)
}
// --- rule storage -----------------------------------------------------------
def getRules() {
return state.rules ?: []
}
def getRule(String id) {
return getRules().find { it.id == id }
}
def ruleStateFor(String rid) {
if (!state.ruleState) state.ruleState = [:]
def st = state.ruleState[rid] ?: [:]
if (!st.containsKey("pending")) st.pending = false
if (!st.containsKey("breached")) st.breached = false
state.ruleState[rid] = st
return st
}
def saveRuleState(String rid, Map st) {
if (!state.ruleState) state.ruleState = [:]
state.ruleState[rid] = st
}
def triggerDeviceIds(rule) {
return (rule.triggerDevices ?: []).collect { it.toString() }
}
def triggerDevices(rule) {
return triggerDeviceIds(rule).collect { getDeviceById(it) }.findAll { it != null }
}
def defaultSpeechDeviceIds() {
return speechDevices().collect { it.id.toString() }
}
/**
* Fill the rule editor's settings inputs from the stored rule, so rules created
* via the API (which never went through the editor) show their real values
* instead of a blank form. Runs once per rule: after the first hydration the
* settings keys exist, so later renders leave the user's edits — including
* deliberately cleared fields — alone.
*/
def hydrateRuleEditor(String rid) {
def rule = getRule(rid)
if (!rule) return
def p = "r_${rid}_"
if (settings["${p}name"] != null) return // already hydrated or UI-built
def put = { String key, String type, value ->
if (value == null) return
if (value instanceof List && value.isEmpty()) return
try { app.updateSetting(key, [type: type, value: value]) }
catch (e) { logDebug("hydrateRuleEditor: could not set ${key}: ${e.message}") }
}
put("${p}enabled", "bool", rule.enabled != false)
put("${p}name", "text", rule.name?.toString())
put("${p}trigType", "enum", rule.triggerType?.toString() ?: "device")
put("${p}schedDays", "enum", (rule.scheduleDays ?: []).collect { it.toString() })
def hTimes = (rule.scheduleTimes instanceof List ? rule.scheduleTimes : [])
if (!hTimes && rule.scheduleTime) hTimes = [rule.scheduleTime?.toString()]
if (hTimes.size() > 1 && settings["${p}schedTimesExtra"] == null) {
put("${p}schedTimesExtra", "text", hTimes[1..-1].join(", "))
}
// schedTime is a `time` input (Date); seed it via today's date + the HH:mm
if (rule.scheduleTime && settings["${p}schedTime"] == null) {
try {
def parts = rule.scheduleTime.toString().split(":")
def cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, parts[0] as int)
cal.set(Calendar.MINUTE, parts[1] as int)
cal.set(Calendar.SECOND, 0)
app.updateSetting("${p}schedTime", [type: "time", value: cal.getTime()])
} catch (e) { logDebug("hydrateRuleEditor: could not set ${p}schedTime: ${e.message}") }
}
put("${p}trigDevs", "enum", (rule.triggerDevices ?: []).collect { it.toString() })
put("${p}attr", "enum", rule.attribute?.toString())
put("${p}op", "enum", rule.operator?.toString() ?: "=")
put("${p}value", "text", rule.value?.toString())
put("${p}alertWhen", "enum", rule.alertWhen?.toString() ?: "staysLongerThan")
put("${p}dur", "decimal", rule.durationMin)
put("${p}repeat", "decimal", rule.repeatMin)
put("${p}cooldown", "number", (rule.cooldownSec != null ? rule.cooldownSec : 0))
put("${p}modes", "enum", (rule.modes ?: []).collect { it.toString() })
put("${p}hsmStates", "enum", (rule.hsmStates ?: []).collect { it.toString() })
put("${p}tstat", "enum", rule.thermostatId?.toString())
put("${p}tstatStates", "enum", (rule.thermostatStates ?: []).collect { it.toString() })
put("${p}timeFrom", "time", rule.timeFrom?.toString())
put("${p}timeTo", "time", rule.timeTo?.toString())
put("${p}days", "enum", (rule.days ?: []).collect { it.toString() })
put("${p}msg", "text", rule.message?.toString())
put("${p}channels", "enum", (rule.channels ?: ["speech"]).collect { it.toString() })
put("${p}speech", "enum", (rule.speechDeviceIds ?: []).collect { it.toString() })
put("${p}pushDevs", "enum", (rule.pushDeviceIds ?: []).collect { it.toString() })
put("${p}volume", "number", rule.volume)
put("${p}notifyClear", "bool", rule.notifyClear == true)
put("${p}urgent", "bool", rule.urgent == true)
logDebug("hydrateRuleEditor: populated editor for rule '${rule.name}'")
}
/**
* Working list of a schedule rule's actions while the editor is open.
* Stored in state (not settings) because actions are structured data.
* Seeded from the stored rule on first open; saved into the rule by
* syncRuleFromSettings.
*/
def editingActions(String rid) {
def key = "schedActions_${rid}"
if (state[key] == null) {
def rule = getRule(rid)
state[key] = (rule?.actions instanceof List ? rule.actions : []).collect { new LinkedHashMap(it) }
}
return state[key] ?: []
}
def editingActionsAdd(String rid, String p) {
def type = settings["${p}actType"]?.toString()
if (!type) return
def action = [type: type]
if (type == "command") {
action.deviceId = settings["${p}actDevice"]?.toString()
action.command = settings["${p}actCommand"]?.toString()?.trim()
def arg = settings["${p}actArg"]?.toString()?.trim()
action.args = arg ? [arg] : []
if (!action.deviceId || !action.command) {
log.warn "Muse Bridge: command action needs a device and a command — not added"
return
}
} else if (type == "mode") {
action.mode = settings["${p}actMode"]?.toString()
if (!action.mode) { log.warn "Muse Bridge: mode action needs a mode — not added"; return }
} else if (type == "hsm") {
action.arm = settings["${p}actHsm"]?.toString()
if (!action.arm) { log.warn "Muse Bridge: HSM action needs an arm state — not added"; return }
}
def acts = editingActions(rid)
acts << action
state["schedActions_${rid}"] = acts
// clear the builder inputs for the next action
["actType", "actDevice", "actCommand", "actArg", "actMode", "actHsm"].each { k ->
try { app.removeSetting("${p}${k}") } catch (e) {}
}
logDebug("added ${type} action to rule ${rid}")
}
def editingActionsDelete(String rid, int idx) {
def acts = editingActions(rid)
if (idx >= 0 && idx < acts.size()) {
acts.remove(idx)
state["schedActions_${rid}"] = acts
}
}
/** Copy the rule editor's settings into state.rules (single source of truth). */
def syncRuleFromSettings(String rid) {
if (!rid) return
def p = "r_${rid}_"
def name = settings["${p}name"]?.toString()?.trim()
if (!name) return // editor opened but never filled in — nothing to save
def rule = [
id : rid,
name : name,
enabled : settings["${p}enabled"] != false,
triggerType : settings["${p}trigType"]?.toString() ?: "device",
scheduleDays : (settings["${p}schedDays"] ?: []).collect { it.toString() },
scheduleTime : timeSettingToHHmm(settings["${p}schedTime"]),
scheduleTimes : ([timeSettingToHHmm(settings["${p}schedTime"])] + parseExtraTimes(settings["${p}schedTimesExtra"]?.toString())).findAll().unique(),
actions : (state["schedActions_${rid}"] instanceof List ? state["schedActions_${rid}"] : []).collect { new LinkedHashMap(it) },
triggerDevices : (settings["${p}trigDevs"] ?: []).collect { it.toString() },
attribute : settings["${p}attr"]?.toString(),
operator : settings["${p}op"]?.toString() ?: "=",
value : settings["${p}value"]?.toString(),
durationMin : (settings["${p}dur"] != null ? settings["${p}dur"] : 10) as BigDecimal,
alertWhen : settings["${p}alertWhen"]?.toString() ?: "staysLongerThan",
repeatMin : (settings["${p}repeat"] ?: 0) as BigDecimal,
cooldownSec : (settings["${p}cooldown"] != null ? settings["${p}cooldown"] : 0) as BigDecimal,
modes : (settings["${p}modes"] ?: []).collect { it.toString() },
hsmStates : (settings["${p}hsmStates"] ?: []).collect { it.toString() },
thermostatId : settings["${p}tstat"]?.toString(),
thermostatStates: (settings["${p}tstatStates"] ?: []).collect { it.toString() },
timeFrom : settings["${p}timeFrom"]?.toString(),
timeTo : settings["${p}timeTo"]?.toString(),
days : (settings["${p}days"] ?: []).collect { it.toString() },
message : settings["${p}msg"]?.toString()?.trim() ?: null,
speechDeviceIds: (settings["${p}speech"] ?: []).collect { it.toString() },
channels : (settings["${p}channels"] ?: ["speech"]).collect { it.toString() },
pushDeviceIds : (settings["${p}pushDevs"] ?: []).collect { it.toString() },
notifyClear : settings["${p}notifyClear"] == true,
urgent : settings["${p}urgent"] == true,
volume : settings["${p}volume"] == null ? null : clampVolume(settings["${p}volume"] as BigDecimal),
updatedAt : now()
]
rule.sensitive = ruleHasSensitiveActions(rule)
def rules = getRules()
def existing = rules.find { it.id == rid }
if (existing) {
rule.createdAt = existing.createdAt
rules[rules.indexOf(existing)] = rule
} else {
rule.createdAt = now()
rules << rule
}
state.rules = rules
logDebug("synced rule '${name}' (${rid})")
}
def ruleDescription(rule, st) {
def cd = (rule.cooldownSec != null ? rule.cooldownSec : 0) as BigDecimal
def cdTxt = cd > 0 ? " (cooldown ${cd} s)" : ""
def stateTxt = st.breached ? " — ⚠ BREACHED" : st.pending ? " — ⏳ pending" : ""
if (isScheduleRule(rule)) {
def days = (rule.scheduleDays ?: []).collect { scheduleDayOptions()[it] ?: it }.join(", ")
def times = scheduleRuleTimes(rule).join(", ")
def n = (rule.actions ?: []).size()
def lock = rule.sensitive == true ? " 🔒" : ""
return "Every ${days} at ${times} → ${n} action${n == 1 ? '' : 's'}${cdTxt}${lock}${stateTxt}"
}
def when = rule.alertWhen == "clearsSoonerThan" ? "clears sooner than" : "stays longer than"
def durMin = (rule.durationMin != null ? rule.durationMin : 10) as BigDecimal
def s = "${rule.attribute} ${rule.operator} ${rule.value} — "
s += durMin <= 0 ? "alerts immediately" : "alerts if it ${when} ${rule.durationMin} min"
return s + cdTxt + stateTxt
}
def ruleStatusText(String rid, Map st) {
def rule = getRule(rid)
if (!rule) return "New rule — fill in the sections above, then go back to save it."
def last = st.lastBreach ? new Date(st.lastBreach as long).format("yyyy-MM-dd HH:mm") : "never"
def sens = rule.sensitive == true ? "\n🔒 Contains security-sensitive actions" : ""
return "State: ${st.breached ? '⚠ BREACHED' : st.pending ? '⏳ pending confirmation' : 'ok — watching'}\n" +
"Last alert: ${last}${sens}"
}
// ============================================================================
// REST API
// ============================================================================
def authorized() {
return state.accessToken && params.access_token == state.accessToken
}
def requireAuth() {
if (!authorized()) {
render status: 401, contentType: "application/json",
data: JsonOutput.toJson([error: "unauthorized", hint: "pass ?access_token=..."])
return false
}
return true
}
def renderJson(obj, int status = 200) {
render status: status, contentType: "application/json", data: JsonOutput.toJson(obj)
}
// --- command passcode --------------------------------------------------------
// Security-sensitive actions (anything that grants access or changes the
// security posture) require the command passcode configured in the app,
// in addition to the API access token. Fail closed: with no passcode set,
// sensitive actions are refused.
def sensitiveCommandMap() {
return ["lock" : ["unlock"],
"garageDoorControl": ["open"],
"valve" : ["open", "close"],
"alarm" : ["off", "siren", "strobe", "both"]]
}
def isSensitiveCommand(d, String cmd) {
def caps = d.capabilities*.name
return sensitiveCommandMap().any { cap, cmds -> cap in caps && cmd in cmds }
}
def passcodeRequired() {
return settings.requirePasscode != false
}
/** Returns [ok: true] or [ok: false, error: "..."]. Never logs the passcode. */
def checkPasscode() {
if (!passcodeRequired()) return [ok: true]
def configured = settings.securityPasscode?.toString()?.trim()
if (!configured) {
return [ok: false,
error: "refused: set a command passcode in the Muse Bridge app before security-sensitive actions are allowed"]
}
def body = request.JSON ?: [:]
def supplied = (body.passcode ?: params.passcode)?.toString()
if (supplied == configured) return [ok: true]
log.warn "Muse Bridge: rejected a security-sensitive action (missing or wrong passcode)"
return [ok: false, error: "invalid or missing passcode"]
}
def apiHealth() {
if (!requireAuth()) return
def rules = getRules()
renderJson([
ok : true,
app : "Muse Bridge",
project : "https://github.com/rayzurbock/hubitat-muse-bridge",
version : appVersion(),
hub : location.name,
mode : location.mode,
devices : allExposedDevices().size(),
rules : rules.size(),
breached: rules.findAll { ruleStateFor(it.id).breached }.collect { it.name },
time : new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
def apiListDevices() {
if (!requireAuth()) return
renderJson([devices: allExposedDevices().collect { deviceSummary(it) }])
}
def apiGetDevice() {
if (!requireAuth()) return
def d = getDeviceById(params.id)
if (!d) { renderJson([error: "device not found: ${params.id}"], 404); return }
renderJson(deviceSummary(d))
}
def apiDeviceCommand() {
if (!requireAuth()) return
def d = getDeviceById(params.id)
if (!d) { renderJson([error: "device not found: ${params.id}"], 404); return }
def body = request.JSON ?: [:]
def cmd = (body.command ?: params.command)?.toString()
if (!cmd) { renderJson([error: "missing 'command'"], 400); return }
if (!d.hasCommand(cmd)) {
renderJson([error: "device '${d.displayName}' has no command '${cmd}'",
supported: d.supportedCommands*.name], 400)
return
}
if (isSensitiveCommand(d, cmd)) {
def pc = checkPasscode()
if (!pc.ok) { renderJson([error: pc.error], 403); return }
}
def args = (body.args instanceof List) ? body.args : []
try {
def coerced = args.collect { coerceArg(it) }
log.info "Muse Bridge API: ${d.displayName}.${cmd}(${coerced})"
def result = d."$cmd"(*coerced)
renderJson([ok: true, device: d.displayName, command: cmd, args: coerced,
result: result?.toString()])
} catch (e) {
log.warn "Muse Bridge API: command failed: ${e.message}"
renderJson([error: "command failed: ${e.message}"], 500)
}
}
def apiDeviceEvents() {
if (!requireAuth()) return
def d = getDeviceById(params.id)
if (!d) { renderJson([error: "device not found: ${params.id}"], 404); return }
def max = Math.min(100, Math.max(1, (params.max ?: 20) as int))
def evts = []
try {
evts = d.events(max: max).collect { e ->
[date : e.date?.format("yyyy-MM-dd'T'HH:mm:ssZ"),
name : e.name,
value : e.value,
unit : e.unit,
displayName : e.displayName,
descriptionText: e.descriptionText]
}
} catch (e) {
log.warn "Muse Bridge API: could not read events: ${e.message}"
}
renderJson([device: d.displayName, events: evts])
}
def apiListModes() {
if (!requireAuth()) return
renderJson([current: location.mode, modes: location.modes*.name])
}
def apiGetMode() {
if (!requireAuth()) return
renderJson([mode: location.mode])
}
def apiSetMode() {
if (!requireAuth()) return
def pc = checkPasscode()
if (!pc.ok) { renderJson([error: pc.error], 403); return }
def body = request.JSON ?: [:]
def mode = (body.mode ?: params.mode)?.toString()
if (!mode) { renderJson([error: "missing 'mode'"], 400); return }
if (!(mode in location.modes*.name)) {
renderJson([error: "unknown mode '${mode}'", modes: location.modes*.name], 400)
return
}
log.info "Muse Bridge API: setting mode to ${mode}"
setLocationMode(mode)
renderJson([ok: true, mode: mode])
}
def apiGetHsm() {
if (!requireAuth()) return
renderJson([hsm: hsmStatus()])
}
def apiSetHsm() {
if (!requireAuth()) return
def pc = checkPasscode()
if (!pc.ok) { renderJson([error: pc.error], 403); return }
def body = request.JSON ?: [:]
def arm = (body.arm ?: params.arm)?.toString()
if (!(arm in ["armAway", "armHome", "armNight", "disarm"])) {
renderJson([error: "arm must be one of: armAway, armHome, armNight, disarm"], 400)
return
}
log.info "Muse Bridge API: setting HSM to ${arm}"
sendLocationEvent(name: "hsmSetArm", value: arm)
renderJson([ok: true, hsm: arm])
}
def hsmStatus() {
try {
return location.hsmStatus
} catch (e) {
return null
}
}
def apiSpeak() {
if (!requireAuth()) return
def body = request.JSON ?: [:]
def text = (body.text ?: params.text)?.toString()?.trim()
if (!text) { renderJson([error: "missing 'text'"], 400); return }
def volume = null
if (body.volume != null || params.volume != null) {
try { volume = clampVolume((body.volume ?: params.volume) as BigDecimal) }
catch (e) { renderJson([error: "bad 'volume' (0-100)"], 400); return }
}
def ids = (body.devices instanceof List ? body.devices : [])*.toString()
if (!ids) ids = defaultSpeechDeviceIds()
if (!ids) { renderJson([error: "no speech devices configured"], 400); return }
speakOnDevices(ids, text, volume)
renderJson([ok: true, devices: ids.size(), text: text, volume: volume])
}
def apiNotify() {
if (!requireAuth()) return
def body = request.JSON ?: [:]
def text = (body.text ?: params.text)?.toString()?.trim()
if (!text) { renderJson([error: "missing 'text'"], 400); return }
def ids = (body.devices instanceof List ? body.devices : [])*.toString()
if (!ids) ids = defaultPushDeviceIds()
if (!ids) { renderJson([error: "no notification devices configured"], 400); return }
def sent = 0
ids.each { id ->
def d = getDeviceById(id)
if (d?.hasCommand("deviceNotification")) {
try { d.deviceNotification(text); sent++ }
catch (e) { log.warn "Muse Bridge API: push to ${d.displayName} failed: ${e.message}" }
}
}
renderJson([ok: true, devices: sent, text: text])
}
def apiListRules() {
if (!requireAuth()) return
renderJson([rules: getRules().collect { ruleSummary(it) }])
}
def apiGetRule() {
if (!requireAuth()) return
def rule = getRule(params.id as String)
if (!rule) { renderJson([error: "rule not found: ${params.id}"], 404); return }
renderJson(ruleSummary(rule))
}
/**
* True when any of the rule's actions is security-sensitive: a sensitive
* device command (unlock, open, siren, ...), a mode change, or an HSM change.
*/
def ruleHasSensitiveActions(Map rule) {
return (rule.actions instanceof List) && rule.actions.any { a ->
def t = a.type?.toString()
if (t == "mode" || t == "hsm") return true
if (t == "command") {
def d = getDeviceById(a.deviceId?.toString())
return d != null && isSensitiveCommand(d, a.command?.toString())
}
return false
}
}
/**
* Gate for API writes that would leave a rule holding sensitive actions.
* The passcode is verified once, here, from the request — it is never stored.
* Verify-and-forget: rotating the passcode later does NOT retract the rule;
* deleting the rule is the off-switch. The rule is flagged `sensitive` so it
* stays visible/auditable in the app and API.
* Returns true when the write may proceed (renders the error otherwise).
*/
def requirePasscodeForSensitiveRule(Map rule) {
if (!ruleHasSensitiveActions(rule)) return true
def pc = checkPasscode()
if (!pc.ok) { renderJson([error: pc.error], 403); return false }
rule.sensitive = true
return true
}
def apiCreateRule() {
if (!requireAuth()) return
def body = request.JSON ?: [:]
def (rule, error) = buildRuleFromApi("r${now()}", body)
if (error) { renderJson([error: error], 400); return }
if (!requirePasscodeForSensitiveRule(rule)) return
state.rules = getRules() + [rule]
initialize()
log.info "Muse Bridge API: created rule '${rule.name}'${rule.sensitive ? ' (sensitive actions)' : ''}"
renderJson(ruleSummary(rule), 201)
}
def apiUpdateRule() {
if (!requireAuth()) return
def existing = getRule(params.id as String)
if (!existing) { renderJson([error: "rule not found: ${params.id}"], 404); return }
def body = request.JSON ?: [:]
// merge: start from the stored rule, overlay supplied fields
def merged = existing + body
def (rule, error) = buildRuleFromApi(existing.id, merged)
if (error) { renderJson([error: error], 400); return }
if (!requirePasscodeForSensitiveRule(rule)) return
rule.createdAt = existing.createdAt
def rules = getRules()
rules[rules.indexOf(existing)] = rule
state.rules = rules
initialize()
log.info "Muse Bridge API: updated rule '${rule.name}'"
renderJson(ruleSummary(rule))
}
def apiDeleteRule() {
if (!requireAuth()) return
def rule = getRule(params.id as String)
if (!rule) { renderJson([error: "rule not found: ${params.id}"], 404); return }
state.rules = getRules().findAll { it.id != rule.id }
if (state.ruleState) state.ruleState.remove(rule.id)
initialize()
renderJson([ok: true, deleted: rule.id])
}
def apiEnableRule() {
if (!requireAuth()) return
setRuleEnabled(params.id as String, true)
}
def apiDisableRule() {
if (!requireAuth()) return
setRuleEnabled(params.id as String, false)
}
def setRuleEnabled(String id, boolean enabled) {
def rule = getRule(id)
if (!rule) { renderJson([error: "rule not found: ${id}"], 404); return }
if (enabled && (rule.sensitive == true || ruleHasSensitiveActions(rule))) {
// arming a sensitive rule is the same risk as creating one
def pc = checkPasscode()
if (!pc.ok) { renderJson([error: pc.error], 403); return }
}
rule.enabled = enabled
def rules = getRules()
rules[rules.indexOf(getRule(id))] = rule
state.rules = rules
// keep the UI editor in sync if this rule was edited there
try { app.updateSetting("r_${id}_enabled", [type: "bool", value: enabled]) } catch (e) {}
initialize()
renderJson([ok: true, id: id, enabled: enabled])
}
def apiTestRule() {
if (!requireAuth()) return
def rule = getRule(params.id as String)
if (!rule) { renderJson([error: "rule not found: ${params.id}"], 404); return }
def msg = rule.message?.replace("%rule%", rule.name ?: "")?.replace("%device%", "test device")
?.replace("%attribute%", rule.attribute ?: "")?.replace("%value%", rule.value ?: "") ?: "Test announcement for rule ${rule.name}."
notifyRule(rule, msg)
renderJson([ok: true, id: rule.id, text: msg])
}
/** Assistant-side automations visible in the app (informational only). */
def apiListSideActions() {
if (!requireAuth()) return
renderJson([actions: museSideActions()])
}
def apiSetSideActions() {
if (!requireAuth()) return
def body = request.JSON ?: [:]
def list = body.actions instanceof List ? body.actions : null
if (list == null) { renderJson([error: "'actions' must be a list"], 400); return }
state.museSideActions = list.collect { a ->
[id : a.id?.toString() ?: "a${now()}",
title : a.title?.toString()?.trim() ?: "Untitled",
schedule : a.schedule?.toString(),
trigger : a.trigger?.toString() ?: a.schedule?.toString(),
actions : a.actions?.toString(),
restrictions: a.restrictions?.toString(),
detail : a.detail?.toString()]
}
renderJson([ok: true, count: state.museSideActions.size()])
}
/** Validate + normalize a rule map coming from the API. Returns [rule, error]. */
def buildRuleFromApi(String rid, Map body) {
def name = body.name?.toString()?.trim()
if (!name) return [null, "missing 'name'"]
def triggerType = (body.triggerType ?: "device").toString()
if (!(triggerType in ["device", "schedule"])) return [null, "bad 'triggerType': ${triggerType} (use device, schedule)"]
def schedDays = []
def schedTime = null
def schedTimes = []
def actions = []
if (triggerType == "schedule") {
schedDays = (body.scheduleDays instanceof List ? body.scheduleDays : [])*.toString().collect { normalizeDayName(it) }
if (schedDays.any { it == null }) return [null, "bad 'scheduleDays': ${body.scheduleDays} (use MON..SUN or full names)"]
if (!schedDays) return [null, "'scheduleDays' must be a non-empty list for schedule rules"]
def rawTimes = (body.scheduleTimes instanceof List ? body.scheduleTimes : [])*.toString()
schedTime = body.scheduleTime?.toString()
if (rawTimes) {
def bad = rawTimes.findAll { !(it ==~ /^([01]\d|2[0-3]):[0-5]\d$/) }
if (bad) return [null, "bad 'scheduleTimes' entries: ${bad} (use HH:mm, 24h)"]
schedTimes = rawTimes.unique()
schedTime = schedTimes[0]
} else {
if (!(schedTime ==~ /^([01]\d|2[0-3]):[0-5]\d$/)) return [null, "bad 'scheduleTime': ${schedTime} (use HH:mm, 24h)"]
schedTimes = [schedTime]
}
def rawActions = body.actions instanceof List ? body.actions : [[type: "announce"]]
for (a in rawActions) {
def (action, err) = validateActionFromApi(a)
if (err) return [null, err]
actions << action
}
} else {
if (body.actions) return [null, "'actions' are only supported on schedule-triggered rules"]
}
def trigIds = []
def attribute = null
def operator = "="
def value = null
def alertWhen = "staysLongerThan"
def durationMin = 10
def repeatMin = 0
if (triggerType == "device") {
trigIds = (body.triggerDevices instanceof List ? body.triggerDevices : [])*.toString()
if (!trigIds) return [null, "'triggerDevices' must be a non-empty list of device ids"]
def unknown = trigIds.findAll { !getDeviceById(it) }
if (unknown) return [null, "unknown device ids: ${unknown}"]
attribute = body.attribute?.toString()
if (!attribute) return [null, "missing 'attribute'"]
operator = (body.operator ?: "=").toString()
if (!(operator in ["=", "!=", ">", "<", ">=", "<="])) return [null, "bad 'operator': ${operator}"]
value = body.value?.toString()
alertWhen = (body.alertWhen ?: "staysLongerThan").toString()
if (!(alertWhen in ["staysLongerThan", "clearsSoonerThan"])) return [null, "bad 'alertWhen': ${alertWhen}"]
durationMin = (body.durationMin != null ? body.durationMin : 10) as BigDecimal
repeatMin = (body.repeatMin ?: 0) as BigDecimal
}
def tstatId = body.thermostatId?.toString()
if (tstatId && !getDeviceById(tstatId)) return [null, "unknown thermostatId: ${tstatId}"]
def modes = (body.modes instanceof List ? body.modes : [])*.toString()
def badModes = modes.findAll { !(it in location.modes*.name) }
if (badModes) return [null, "unknown modes: ${badModes}"]
def hsmStates = (body.hsmStates instanceof List ? body.hsmStates : [])*.toString()
def badHsm = hsmStates.findAll { !(it in ["armedAway", "armedHome", "armedNight", "disarmed"]) }
if (badHsm) return [null, "bad hsmStates: ${badHsm} (use armedAway, armedHome, armedNight, disarmed)"]
def channels = (body.channels instanceof List ? body.channels : ["speech"])*.toString()
def badChannels = channels.findAll { !(it in ["speech", "push", "muse"]) }
if (badChannels) return [null, "bad channels: ${badChannels} (use speech, push, muse)"]
def volume = null
if (body.volume != null) {
try { volume = clampVolume(body.volume as BigDecimal) }
catch (e) { return [null, "bad 'volume': ${body.volume} (0-100)"] }
}
def cooldownSec = 0
if (body.cooldownSec != null) {
try { cooldownSec = body.cooldownSec as BigDecimal }
catch (e) { return [null, "bad 'cooldownSec': ${body.cooldownSec} (seconds, >= 0)"] }
if (cooldownSec < 0) return [null, "bad 'cooldownSec': ${body.cooldownSec} (seconds, >= 0)"]
}
def rule = [
id : rid,
name : name,
enabled : body.enabled != false,
triggerType : triggerType,
scheduleDays : schedDays,
scheduleTime : schedTime,
scheduleTimes : schedTimes,
actions : actions,
triggerDevices : trigIds,
attribute : attribute,
operator : operator,
value : value,
durationMin : durationMin as BigDecimal,
alertWhen : alertWhen,
repeatMin : repeatMin as BigDecimal,
cooldownSec : cooldownSec,
modes : modes,
hsmStates : hsmStates,
thermostatId : tstatId,
thermostatStates: (body.thermostatStates instanceof List ? body.thermostatStates : [])*.toString(),
timeFrom : body.timeFrom?.toString(),
timeTo : body.timeTo?.toString(),
days : (body.days instanceof List ? body.days : [])*.toString(),
message : body.message?.toString()?.trim() ?: null,
speechDeviceIds : (body.speechDeviceIds instanceof List ? body.speechDeviceIds : [])*.toString(),
channels : channels,
pushDeviceIds : (body.pushDeviceIds instanceof List ? body.pushDeviceIds : [])*.toString(),
notifyClear : body.notifyClear == true,
urgent : body.urgent == true,
volume : volume,
createdAt : now(),
updatedAt : now()
]
return [rule, null]
}
/**
* Validate one action map from the API. Returns [action, error].
* Sensitive actions (sensitive device commands, mode, HSM) are structurally
* allowed here — the endpoint gates them behind the command passcode via
* requirePasscodeForSensitiveRule (verified once, never stored).
*/
def validateActionFromApi(a) {
if (!(a instanceof Map)) return [null, "each 'actions' entry must be an object"]
def type = a.type?.toString()
if (!(type in ["announce", "command", "mode", "hsm"])) {
return [null, "bad action type '${type}' (use announce, command, mode, hsm)"]
}
if (type == "announce") return [[type: "announce"], null]
if (type == "command") {
def d = getDeviceById(a.deviceId?.toString())
if (!d) return [null, "action: unknown deviceId '${a.deviceId}'"]
def cmd = a.command?.toString()
if (!cmd || !d.hasCommand(cmd)) {
return [null, "action: device '${d.displayName}' has no command '${cmd}'"]
}
return [[type: "command", deviceId: d.id.toString(), command: cmd,
args: (a.args instanceof List ? a.args : [])*.toString()], null]
}
if (type == "mode") {
def mode = a.mode?.toString()
if (!(mode in location.modes*.name)) return [null, "action: unknown mode '${mode}'"]
return [[type: "mode", mode: mode], null]
}
def arm = a.arm?.toString()
if (!(arm in ["armAway", "armHome", "armNight", "disarm"])) {
return [null, "action: bad arm value '${arm}'"]
}
return [[type: "hsm", arm: arm], null]
}
def ruleSummary(rule) {
def st = ruleStateFor(rule.id)
return [
id : rule.id,
name : rule.name,
enabled : rule.enabled,
triggerType : rule.triggerType ?: "device",
scheduleDays : rule.scheduleDays ?: [],
scheduleTime : rule.scheduleTime,
scheduleTimes : scheduleRuleTimes(rule),
actions : rule.actions ?: [],
sensitive : rule.sensitive == true,
triggerDevices: triggerDeviceIds(rule).collect { id ->
def d = getDeviceById(id)
[id: id, name: d?.displayName]
},
attribute : rule.attribute,
operator : rule.operator,
value : rule.value,
durationMin : rule.durationMin,
alertWhen : rule.alertWhen,
modes : rule.modes,
hsmStates : rule.hsmStates,
thermostatId : rule.thermostatId,
thermostatStates: rule.thermostatStates,
timeFrom : rule.timeFrom,
timeTo : rule.timeTo,
days : rule.days,
message : rule.message,
repeatMin : rule.repeatMin,
cooldownSec : rule.cooldownSec != null ? rule.cooldownSec : 0,
channels : rule.channels ?: ["speech"],
pushDevices : (rule.pushDeviceIds ?: []).collect { pid ->
def pd = getDeviceById(pid)
[id: pid, name: pd?.displayName]
},
notifyClear : rule.notifyClear == true,
urgent : rule.urgent == true,
volume : rule.volume,
state : [
pending : st.pending,
breached : st.breached,
lastBreach : st.lastBreach ? new Date(st.lastBreach as long).format("yyyy-MM-dd'T'HH:mm:ssZ") : null,
lastAction : st.lastAction ? [time: new Date(st.lastAction.time as long).format("yyyy-MM-dd'T'HH:mm:ssZ"),
text: st.lastAction.text] : null
]
]
}
// ============================================================================
// Device helpers
// ============================================================================
def appVersion() { return "1.3.1" }
def logDebug(String msg) {
if (settings.logDebug) log.debug "Muse Bridge: ${msg}"
}
// Setting keys of the pre-1.5.0 per-capability pickers. Kept for upgrade
// migration: their selections seed the exposure picker below.
def legacyExposureKeys() {
return ["swSwitches", "swLevels", "swColors",
"swLocks", "swGarage", "swValves", "swShades", "swButtons",
"seContact", "seMotion", "sePresence", "seAccel", "seTamper",
"enTemp", "enHumidity", "enIllum", "enPower", "enEnergy", "enBattery",
"saWater", "saSmoke", "saCO",
"clThermostats",
"alSirens"]
}
def settingDeviceList(String name) {
def v = settings[name]
return v instanceof List ? v : (v ? [v] : [])
}
/** Every device the app is allowed to see: master list + legacy picker selections. */
def exposureUniverse() {
def seen = [] as Set
def all = []
(["devMaster"] + legacyExposureKeys()).each { k ->
settingDeviceList(k).each { d ->
if (d && seen.add(d.id.toString())) all << d
}
}
return all
}
/** The device IDs exposed to the API and rules (strings).
* Default: everything authorized. Opening the picker snapshots the current
* list into settings.expDevices, after which the checklist is the truth. */
def exposedDeviceIds() {
if (state.exposureSeeded && settings.expDevices != null) return (settings.expDevices*.toString()) as Set
if (state.exposureSeeded) return [] as Set
return (exposureUniverse()*.id*.toString()) as Set
}
/** Devices the app can address anywhere (exposure universe + speech/siren/phone inputs). */
def allVisibleDevices() {
def seen = [] as Set
def all = []
(["devMaster"] + legacyExposureKeys() +
["spSpeech", "spAudio", "spMusic", "alSirens", "ntPhones"]).each { k ->
settingDeviceList(k).each { d ->
if (d && seen.add(d.id.toString())) all << d
}
}
return all
}
// --- device activity (last-event tracking, cached) ---------------------------
def ensureActivityCache() {
if (!(state.activityCache instanceof Map)) state.activityCache = [:]
// Refresh at most every 6 hours; lookups below repopulate lazily.
if (!state.activityCacheAt || now() - (state.activityCacheAt as Long) > 6 * 3600 * 1000) {
state.activityCache = [:]
state.activityCacheAt = now()
}
}
/** Epoch ms of the device's most recent event (within the last year), or null. */
def deviceLastEventMs(d) {
if (!(state.activityCache instanceof Map)) state.activityCache = [:]
def key = d.id.toString()
if (state.activityCache.containsKey(key)) return state.activityCache[key]
def ts = null
try {
def yearAgo = new Date(now() - 365L * 86400000L)
def evts = d.eventsSince(yearAgo, [max: 1])
def latest = evts?.max { it?.date?.time ?: 0 }
ts = latest?.date?.time
} catch (e) {
logDebug("activity lookup failed for ${d.displayName}: ${e.message}")
}
state.activityCache[key] = ts
return ts
}
/** Whole days since the device last reported; null = never (within the last year). */
def deviceInactiveDays(d) {
def ts = deviceLastEventMs(d)
if (ts == null) return null
return ((now() - (ts as Long)) / 86400000L) as int
}
def activityLabel(d) {
def days = deviceInactiveDays(d)
if (days == null) return "(never)"
if (days == 0) return "(today)"
if (days == 1) return "(yesterday)"
return "(${days}d)"
}
// --- exposure picker ----------------------------------------------------------
def exposureCapOptions() {
def caps = [] as Set
exposureUniverse().each { d ->
try { d.capabilities?.each { caps << it.name } } catch (e) { /* ignore */ }
}
return caps.sort().collectEntries { [(it): it] }
}
def exposureCandidates() {
def q = settings.expSearch?.toString()?.trim()?.toLowerCase()
def cap = settings.expCap?.toString()
def days = (settings.expActiveDays != null ? settings.expActiveDays as int : 0)
return exposureUniverse().findAll { d ->
if (q && !(d.displayName?.toLowerCase()?.contains(q))) return false
if (cap) {
def has = false
try { has = d.capabilities?.any { it.name == cap } } catch (e) { /* ignore */ }
if (!has) return false
}
if (days > 0) {
def inactive = deviceInactiveDays(d)
if (inactive == null || inactive > days) return false
}
return true
}.sort { it.displayName?.toLowerCase() }
}
def exposureOptions() {
def opts = [:]
// Currently-selected devices always appear (checked), so they can be
// unchecked even when the filters hide them.
exposedDeviceIds().each { id ->
def d = allVisibleDevices().find { it.id.toString() == id }
if (d) opts[id] = "${d.displayName} ${activityLabel(d)}"
}
exposureCandidates().each { d ->
def id = d.id.toString()
if (!opts.containsKey(id)) opts[id] = "${d.displayName} ${activityLabel(d)}"
}
return opts
}
def allExposedDevices() {
def ids = exposedDeviceIds()
return exposureUniverse().findAll { ids.contains(it.id.toString()) }
}
def getDeviceById(id) {
if (!id) return null
def s = id.toString()
return allVisibleDevices().find { it.id.toString() == s }
}
def speechDevices() {
def ids = speakerDeviceIds()
return allVisibleDevices().findAll { ids.contains(it.id.toString()) }
}
def deviceSummary(d) {
return [
id : d.id.toString(),
name : d.name,
label : d.label,
displayName : d.displayName,
capabilities: d.capabilities*.name,
attributes : currentAttributeMap(d),
commands : d.supportedCommands*.name
]
}
/** Coerce a JSON-decoded argument to the most useful Groovy type for device commands. */
def coerceArg(arg) {
if (arg instanceof Map || arg instanceof List) return arg
if (arg instanceof Boolean || arg instanceof Number) return arg
def s = arg?.toString()?.trim()
if (s == null) return null
if (s.equalsIgnoreCase("true")) return true
if (s.equalsIgnoreCase("false")) return false
if (s ==~ /-?\d+/) {
try { return s as Integer } catch (e) { return s as Long }
}
if (s ==~ /-?\d+\.\d+/) {
try { return s as BigDecimal } catch (e) { /* fall through */ }
}
return s
}
def currentAttributeMap(d) {
def m = [:]
supportedAttrNames(d).each { n ->
try { m[n] = d.currentValue(n) } catch (e) { /* ignore */ }
}
return m
}
def supportedAttrNames(d) {
try {
def names = d.supportedAttributes?.collect { it.name }
if (names) return names.unique()
} catch (e) { /* fall through to probe list */ }
// Fallback: probe common attributes (older/alternate firmwares).
return ["switch", "level", "hue", "saturation", "colorTemperature", "colorMode", "colorName",
"contact", "motion", "presence", "acceleration", "tamper", "temperature", "humidity",
"illuminance", "power", "energy", "battery", "voltage",
"water", "smoke", "carbonMonoxide",
"lock", "door", "valve", "windowShade", "position", "buttonNumber", "pushed", "held", "doubleTapped",
"thermostatMode", "thermostatOperatingState", "thermostatFanMode",
"heatingSetpoint", "coolingSetpoint", "thermostatSetpoint", "thermostatThreshold",
"alarm", "mute", "volume", "trackDescription", "status"]
.findAll { n -> try { d.hasAttribute(n) } catch (e) { false } }
}
// --- option builders for the UI ---------------------------------------------
def deviceOptions() {
return allExposedDevices().sort { it.displayName }.collectEntries { [(it.id.toString()): it.displayName] }
}
def attributeOptions(trigIds) {
def attrs = [] as LinkedHashSet
(trigIds ?: []).each { id ->
def d = getDeviceById(id?.toString())
if (d) attrs.addAll(supportedAttrNames(d))
}
if (!attrs) {
attrs.addAll(["switch", "level", "contact", "motion", "presence", "acceleration", "tamper",
"temperature", "humidity", "illuminance", "power", "energy", "battery",
"water", "smoke", "carbonMonoxide", "lock", "door", "valve", "windowShade",
"thermostatMode", "thermostatOperatingState", "heatingSetpoint", "coolingSetpoint", "alarm"])
}
return attrs.sort().collectEntries { [(it): it] }
}
def modeOptions() {
return (location.modes*.name ?: []).sort().collectEntries { [(it): it] }
}
def thermostatOptions() {
def list = allExposedDevices().findAll {
try { it.capabilities?.any { c -> c.name == "Thermostat" } } catch (e) { false }
}
return list.sort { it.displayName }.collectEntries { [(it.id.toString()): it.displayName] }
}
def speechOptions() {
return speechDevices().sort { it.displayName }.collectEntries { [(it.id.toString()): it.displayName] }
}
def pushDevices() {
def v = settings.ntPhones
def all = v ? (v instanceof List ? v : [v]) : []
return all.unique { it.id }
}
def defaultPushDeviceIds() {
return pushDevices().collect { it.id.toString() }
}
def pushOptions() {
return pushDevices().sort { it.displayName }.collectEntries { [(it.id.toString()): it.displayName] }
}