Files
cantabile-ha-addons/src/edge/cantabile_edge/devpage.py
T

777 lines
42 KiB
Python

# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The add-on's Devices page ("HA-only sites"): what the Hub
panel's Devices section does with devices Home Assistant has already, on
the add-on's own page (HA's ingress; reached from Cantabile's dashboard,
not the sidebar). With the Building or community page (joinpage.py) it
makes the add-on's small app (App): ?p=devices (the first page) and
?p=building; Cantabile's dashboard opens them as /app/<slug>#devices and
#building (the page takes HA's hash at start, as the Modbus bridge's does).
For each HA device a device profile recognises (specific profiles first; a
generic one such as ha-thermostat only where none fits) the page shows what
Cantabile would read and could control. "Use with Cantabile" writes the
device's mapping fragment, <mapping dir>/mapping.d/<id>.yaml, as the Hub's
devices tool does and with the same shared code (devprofiles.py): every
value and control with consent off, the profile's protection defaults in
<state dir>/protection.json, the device in <state dir>/devices.json and its
specs for the inventory (devices-specs.json). The agent then loads the
mapping again (agent.devices_changed): the device is on Cantabile's
dashboard, and in HA's area "Cantabile" when it has no area of its own.
Nothing is installed or set up in HA here: no add-on installs, no
integrations (the owner's own HA does that); only devices HA has.
The mapping's proposal (propose.py) and the owner's devices: a proposal is
a starting point; "Use with Cantabile" is the owner's confirmation, and
from then on the proposal leaves that device (its entities, ids and summed
systems) to its fragment. Removing the device gives it back to the
proposal. A mapping written by hand is never changed: its entries win and
are left out of a device's fragment (shown). One writer per entity: a
control on an entity another control writes is left out.
Owner only, both pages: every request must come from a Home Assistant
administrator.
panel_admin only keeps the sidebar entry from other users; HA lets any
signed-in user open an add-on's ingress session. So the page asks HA who
the user is (the ingress proxy's X-Remote-User-Id) and refuses anyone else.
Consent: an HA add-on site's consent is
given when the add-on is installed from Cantabile's repository, in its
configuration (addon-run records it in <state dir>/consent.json: share,
control, the texts' version, source). With it, each device's reading and
control are switched on here as on the Hub's Devices page (the agent starts
again, as the Hub's tool restarts it); without it the page points to the
add-on's configuration. Protection (protected / not, never sealed) and a thermostat's heating or
cooling choice are the owner's, here as on the Hub.
"""
import asyncio
import json
import logging
import os
import time
import urllib.parse
import yaml
from . import devprofiles as dp
from .consent import Consent
from . import i18n
from .i18n import M, T, TN
from .joinpage import CSS, E, JoinPage
log = logging.getLogger(__name__)
PAGES = ("devices", "building")
SWITCHOVER_WORDS = {"heating": M("Heating"), "cooling": M("Cooling"),
"season": M("By season (heating October to April, cooling May to September)"),
"outdoor": M("By outdoor temperature")}
CUSTODIAN_WORDS = {"building_operator": M("the building's operator"), "grid_operator": M("the grid operator"),
"metering_operator": M("the metering operator"), "community_operator": M("the energy community's operator")}
PROFILE_STATUS = {"verified": M("Checked on a device"),
"documented": M("From the maker's documentation, not yet checked on a device"),
"draft": M("Draft: check the values before you turn reading on")}
CONTROL_WORDS = {"battery": M("battery"), "heating": M("heating"), "cooling": M("cooling"), "ev": M("charging"),
"cover": M("blinds and curtains")}
MORE_CSS = """nav{display:flex;gap:1rem;margin:0 0 1rem;border-bottom:1px solid #d5ded9;padding-bottom:.5rem}
nav a{color:inherit;text-decoration:none}nav a.on{font-weight:600;border-bottom:2px solid #2f6f55}
.badge{display:inline-block;font-size:.8rem;padding:.05rem .45rem;border-radius:4px;background:#e2e9e5;margin-left:.3rem}
ul.plain{margin:.3rem 0;padding-left:1.2rem}form.inline{display:inline}form.inline button{margin:0 0 0 .4rem;padding:.2rem .6rem}
@media (prefers-color-scheme:dark){nav{border-color:#2b3a32}.badge{background:#2b3a32}}"""
# HA's hash (#devices, #building: Cantabile's dashboard) to this page's ?p=
HASH_SCRIPT = ("(function(){try{var P=window.parent;if(P===window)return;var m=/^#(devices|building)$/.exec(P.location.hash||'');"
"if(m&&location.search.indexOf('p=')<0&&location.search.indexOf('code=')<0)location.replace('?p='+m[1])}"
"catch(x){}})();")
def _read_json(path: str, default):
try:
with open(path) as f:
v = json.load(f)
except (OSError, ValueError):
return default
return v if isinstance(v, type(default)) else default
def _write_json(path: str, data, mode: int = 0o644):
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
tmp = path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=1, sort_keys=True, ensure_ascii=False)
f.write("\n")
os.replace(tmp, path)
def quantity_words(q: str) -> str:
return q.replace("_", " ").replace(".", ": ", 1)
def with_attrs(ents: list[dict], states: dict) -> list[dict]:
"""Registry entries with HA's attributes now (where the state is known:
the profiles' conditions on attributes, as the Hub's registry has them)."""
out = []
for e in ents:
st = states.get(e["entity_id"])
if st and st.get("state") not in ("unavailable", "unknown"):
e = dict(e, attributes=st.get("attributes") or {})
out.append(e)
return out
class Devices:
"""The devices used with Cantabile on this site and HA's offers; the
page's actions. ha(): the agent's HA client (None while not connected);
changed(): the agent loads the mapping again."""
def __init__(self, mapping_path: str, state_dir: str, profiles: list[dict], ha=lambda: None, changed=None):
self.mapping_path, self.state_dir, self.profiles = mapping_path, state_dir, profiles
self.ha, self.changed = ha, changed
self.mapping_d = os.path.join(os.path.dirname(mapping_path) or ".", "mapping.d")
self.devices_path = os.path.join(state_dir, "devices.json")
self.lock = asyncio.Lock()
# -- files ------------------------------------------------------------------------
def load(self) -> dict:
return {k: v for k, v in _read_json(self.devices_path, {}).items() if isinstance(v, dict)}
def save(self, devs: dict):
_write_json(self.devices_path, devs, 0o600)
def frag_path(self, dev_id: str) -> str:
return os.path.join(self.mapping_d, f"{dev_id}.yaml")
def frag(self, dev_id: str) -> dict:
return _read_json(self.frag_path(dev_id), {})
def write_frag(self, dev_id: str, frag: dict):
os.makedirs(self.mapping_d, mode=0o755, exist_ok=True)
_write_json(self.frag_path(dev_id), frag, 0o644) # JSON is YAML
def main(self) -> dict:
"""The site's own mapping (mapping.yaml)."""
try:
with open(self.mapping_path) as f:
raw = yaml.safe_load(f) or {}
except (OSError, yaml.YAMLError):
raw = {}
return raw if isinstance(raw, dict) else {}
def local(self) -> dict:
return dp.local_entries(_read_json(os.path.join(self.state_dir, "protection.json"), {}))
def save_local(self, entries: dict):
_write_json(os.path.join(self.state_dir, "protection.json"), {"v": 1, "entries": entries})
def policy(self) -> dict:
return dp.merge_policy(dp.acl_entries(_read_json(os.path.join(self.state_dir, "acl.json"), {})), self.local())
def profile(self, pid: str) -> dict | None:
return next((p for p in self.profiles if p.get("id") == pid), None)
def write_specs(self, devs: dict):
"""Each device's specs for the agent's inventory (as the Hub's tool)."""
policy, out = self.policy(), {}
for d in devs.values():
p = self.profile(d["profile"]) or {}
frag = self.frag(d["id"])
lvl, e = dp.level_of(policy, [f"device:{d['id']}"])
out[d["id"]] = {"name": d["name"], "profile": d["profile"], "profile_version": d.get("profile_version", ""),
"category": d.get("category") or p.get("category", ""), "manufacturer": p.get("manufacturer", ""),
"model": p.get("name", d["profile"]), "path": "existing", "ratings": d.get("ratings") or {},
"ha_device": d.get("ha_device"), "entry_id": None, "entities": dp.fragment_entities(frag),
"controls": [c["id"] for c in frag.get("controls", [])], "protection": lvl,
"custodian": (e or {}).get("custodian")}
_write_json(os.path.join(self.state_dir, "devices-specs.json"), {"v": 1, "made": int(time.time()), "devices": out})
# -- HA ---------------------------------------------------------------------------
async def snapshot(self) -> tuple[dict, dict]:
client = self.ha()
if client is None:
raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment."))
reg = dict(await client.registries())
# each device's integrations, as the Hub's registry gives them: its
# entities' platforms (the profiles' recognise.ha "domain")
plat = {}
for e in reg.get("entities") or []:
if e.get("device_id") and e.get("platform"):
plat.setdefault(e["device_id"], set()).add(e["platform"])
reg["devices"] = [dict(d, domains=sorted(plat.get(d["id"], ()))) for d in reg.get("devices") or []]
states = {s["entity_id"]: s for s in await client.send("get_states") or []}
# each entity's device class (HA's state attribute: the owner's choice
# in HA wins; also while unavailable): which profile fits (a garage
# door is never a shade, a CPU temperature never a room's)
reg["entities"] = [dict(e, device_class=((states.get(e.get("entity_id")) or {}).get("attributes") or {})
.get("device_class") or e.get("device_class") or e.get("original_device_class"))
for e in reg.get("entities") or []]
return reg, states
# -- what a device would give ----------------------------------------------------------
def plan(self, reg: dict, states: dict, ha_device: str, p: dict, dev_id: str, devs: dict) -> tuple:
"""(setup path, fragment, missing, left out, entities) for an HA
device with this profile, as "Use with Cantabile" would write it."""
dv = next((d for d in reg.get("devices") or [] if d["id"] == ha_device), None)
if not dv:
raise dp.Fail(T("Home Assistant has no such device."))
s = dp.setup_for(p, dv.get("domains") or [])
if not s:
raise dp.Fail(T("{profile}: this profile does not know the device's integration.", profile=p["name"]))
s = dict(s, path="existing", fields=[])
ents = with_attrs([e for e in reg.get("entities") or [] if e.get("device_id") == ha_device
and not e.get("disabled_by")], states)
main = self.main()
proposed = main.get("source") == "proposed" # yields to the owner's devices (propose.py)
others = [self.frag(i) for i in devs if i != dev_id]
m_assets = [] if proposed else [a for a in main.get("assets") or [] if isinstance(a, dict)]
m_controls = [] if proposed else [c for c in main.get("controls") or [] if isinstance(c, dict)]
main_ids = {a.get("asset") for a in m_assets} | {c.get("id") for c in m_controls}
taken = set(main_ids) | {a["asset"] for f in others for a in f.get("assets", [])} \
| {c["id"] for f in others for c in f.get("controls", [])}
frag, missing = dp.mapping_for(dev_id, p, s, ents, dp.area_of(reg, ents, ha_device), taken, main_ids)
busy = {a.get("entity") for a in m_assets} | {a["entity"] for f in others for a in f.get("assets", [])}
writes = dp.control_writes(m_controls) | {e for f in others for e in dp.control_writes(f.get("controls"))}
gone_a, gone_c = dp.leave_out(frag, busy, writes)
return s, frag, missing, {"values": gone_a, "controls": gone_c}, ents
async def view(self) -> dict:
"""The page's data: the devices used here, HA's devices with a
profile (and what each would give), the rest, or HA's error."""
devs, policy = self.load(), self.policy()
used = []
for d in sorted(devs.values(), key=lambda d: d.get("added", 0)):
frag, p = self.frag(d["id"]), self.profile(d["profile"]) or {}
targets = dp.device_targets(d, frag, self.local())
used.append(dict(d, manufacturer=p.get("manufacturer", ""), model=p.get("name", d["profile"]),
status=p.get("status", ""), assets=frag.get("assets", []), controls=frag.get("controls", []),
switchover=dp.switchover_of(frag), shade=dp.shade_of(frag), place=dp.place_of(frag),
weather=dp.weather_of(frag), policy={t: policy[t] for t in targets if t in policy},
protection=dp.level_of(policy, [f"device:{d['id']}"])[0]))
try:
reg, states = await self.snapshot()
except Exception as e:
return {"devices": used, "offers": [], "rest": [], "ha_error": str(e), "site": self.site(), "rooms": []}
main = self.main()
src = main.get("source")
mapped = {}
for a in main.get("assets") or []:
if isinstance(a, dict):
mapped.setdefault(a.get("entity"), []).append(a.get("asset"))
by_dev = {}
for e in reg.get("entities") or []:
by_dev.setdefault(e.get("device_id"), []).append(e["entity_id"])
offers, rest = [], []
for h in dp.offers(reg, self.profiles, {d.get("ha_device") for d in devs.values()}):
if not h["profiles"]:
rest.append(h)
continue
p = self.profile(h["profiles"][0])
try:
_, frag, missing, gone, _ = self.plan(reg, states, h["id"], p, "preview", devs)
except dp.Fail as e:
frag, missing, gone = {"assets": [], "controls": []}, [str(e)], {"values": [], "controls": []}
ids = [i for e in by_dev.get(h["id"], []) for i in mapped.get(e, [])]
offers.append(dict(h, profile=p, assets=frag["assets"], controls=frag["controls"], missing=missing,
left_out=gone, in_mapping=ids, mapping_source=src))
rooms = sorted({a.get("name") for a in reg.get("areas") or [] if a.get("name")})
return {"devices": used, "offers": offers, "rest": rest, "site": self.site(), "rooms": rooms}
# -- actions --------------------------------------------------------------------------
def site(self) -> dict:
"""The site's consent (the add-on's configuration): share, control."""
c = Consent(self.state_dir)
return {"share": c.share, "control": c.control}
async def _done(self, devs: dict, restart: bool = False):
self.write_specs(devs)
if self.changed is not None:
await (self.changed(restart=True) if restart else self.changed())
async def use(self, ha_device: str, pid: str, name: str = "") -> dict:
async with self.lock:
p = self.profile(pid)
if not p:
raise dp.Fail(T("No such profile."))
devs = self.load()
if any(d.get("ha_device") == ha_device for d in devs.values()):
raise dp.Fail(T("This device is used with Cantabile already."))
reg, states = await self.snapshot()
dev_id = dp.new_id(p, devs)
s, frag, missing, gone, ents = self.plan(reg, states, ha_device, p, dev_id, devs)
if not frag["assets"] and not frag["controls"]:
raise dp.Fail(T("Home Assistant shows none of the values this profile knows, or your mapping has them "
"all already."))
dv = next(d for d in reg["devices"] if d["id"] == ha_device)
name = (name or "").strip()[:60] or dv.get("name_by_user") or dv.get("name") or f"{p['manufacturer']} {p['name']}"
dev = {"id": dev_id, "name": name, "profile": p["id"], "profile_version": p.get("version", ""),
"path": "existing", "ha_device": ha_device, "added": int(time.time()), "read": False,
"control": False, "category": p.get("category", ""), "ratings": dp.ratings_of(p, {}),
"missing": missing, "left_out": gone}
dp.one_weather(frag, [self.frag(i) for i in devs]) # one weather service plans
self.write_frag(dev_id, frag)
defaults = dp.profile_protection(dev_id, p, s, ents, frag)
if defaults:
entries = self.local()
entries.update(defaults)
self.save_local(entries)
devs[dev_id] = dev
self.save(devs)
log.info("device %s (%s) used with Cantabile: %d values, %d controls, consent off", name, p["id"],
len(frag["assets"]), len(frag["controls"]))
await self._done(devs)
return dev
def _dev(self, devs: dict, dev_id: str) -> dict:
d = devs.get(dev_id)
if not d:
raise dp.Fail(T("No such device."))
return d
async def remove(self, dev_id: str):
async with self.lock:
devs = self.load()
dev = self._dev(devs, dev_id)
frag = self.frag(dev_id)
seal = dp.sealed(self.policy(), dev_id)
if seal:
raise dp.Fail(T("Sealed: only {who} can remove it.", who=custodian(seal)))
mine = set(dp.device_targets(dev, frag, self.local()))
try:
os.remove(self.frag_path(dev_id))
except OSError:
pass
entries = self.local()
if mine & set(entries):
self.save_local({t: e for t, e in entries.items() if t not in mine})
del devs[dev_id]
self.save(devs)
log.info("device %s no longer used with Cantabile", dev["name"])
await self._done(devs, restart=bool(dev.get("read") or dev.get("control")))
async def consent(self, dev_id: str, read: bool, control: bool):
if not self.site()["share"]:
raise dp.Fail(T("First give your consent in the add-on's configuration (Settings, Add-ons, Cantabile Edge "
"Agent, Configuration)."))
async with self.lock:
devs = self.load()
dev = self._dev(devs, dev_id)
frag = self.frag(dev_id)
if not frag:
raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again."))
seal = dp.sealed(self.policy(), dev_id)
if seal and bool(control) != bool(dev.get("control")):
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
dev["read"], dev["control"] = bool(read), bool(control)
dp.set_consent(frag, dev["read"], dev["control"])
self.write_frag(dev_id, frag)
self.save(devs)
log.info("consent: %s: reading %s, control %s", dev["name"], "on" if dev["read"] else "off",
"on" if dev["control"] else "off")
await self._done(devs, restart=True)
async def protect(self, dev_id: str, target: str, level: str, by: str):
async with self.lock:
devs = self.load()
dev = self._dev(devs, dev_id)
frag = self.frag(dev_id)
entries = self.local()
target = target or f"device:{dev_id}"
entries[target] = dp.owner_entry(self.policy(), dp.device_targets(dev, frag, entries), dev_id, target,
level, by)
self.save_local(entries)
log.info("protection: %s: %s %s (by %s)", dev["name"], target, level, by)
await self._done(devs)
async def switchover(self, dev_id: str, data: dict):
async with self.lock:
devs = self.load()
dev = self._dev(devs, dev_id)
frag = self.frag(dev_id)
seal = dp.sealed(self.policy(), dev_id)
if seal:
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
sw = dp.set_switchover(frag, data)
self.write_frag(dev_id, frag)
log.info("heating or cooling: %s: %s", dev["name"], sw["mode"])
await self._done(devs, restart=True)
async def _setting(self, dev_id: str):
devs = self.load()
dev = self._dev(devs, dev_id)
frag = self.frag(dev_id)
if not frag:
raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again."))
seal = dp.sealed(self.policy(), dev_id)
if seal:
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
return devs, dev, frag
async def shade(self, dev_id: str, data: dict):
"""A shade's room and its window's orientation."""
async with self.lock:
devs, dev, frag = await self._setting(dev_id)
sh = dp.set_shade(frag, data, [self.frag(i) for i in devs if i != dev_id])
self.write_frag(dev_id, frag)
log.info("shade: %s: room %s, facing %g", dev["name"], sh["area"] or "-", sh["facing"])
await self._done(devs, restart=True)
async def place(self, dev_id: str, data: dict):
"""A temperature sensor indoor (its room) or outdoor."""
async with self.lock:
devs, dev, frag = await self._setting(dev_id)
main = self.main()
taken = {a.get("asset") for a in main.get("assets") or [] if isinstance(a, dict)} \
| {a["asset"] for i in devs if i != dev_id for a in self.frag(i).get("assets", [])}
pl = dp.set_place(frag, data, taken)
self.write_frag(dev_id, frag)
log.info("place: %s: %s %s", dev["name"], pl["place"], pl["area"])
await self._done(devs, restart=True)
async def weather(self, dev_id: str):
"""This weather service's forecast plans; the others are kept, unused."""
async with self.lock:
devs, dev, _ = await self._setting(dev_id)
frags = {i: self.frag(i) for i in devs}
dp.set_weather(frags, dev_id)
for i, f in frags.items():
if f.get("profile") == "ha-weather":
self.write_frag(i, f)
log.info("weather: %s plans", dev["name"])
await self._done(devs, restart=True)
def custodian(e: dict | None) -> str:
c = (e or {}).get("custodian")
return T(CUSTODIAN_WORDS[c]) if c in CUSTODIAN_WORDS else T("its custodian")
# ---- the page -----------------------------------------------------------------------------
def form(do: str, inner: str, button: str, cls: str = "", inline: bool = False) -> str:
return (f'<form method="post" action=""{" class=" + chr(34) + "inline" + chr(34) if inline else ""}>'
f'<input type="hidden" name="do" value="{E(do)}">{inner}'
f'<button{" class=" + chr(34) + cls + chr(34) if cls else ""}>{E(button)}</button></form>')
def hidden(**kw) -> str:
return "".join(f'<input type="hidden" name="{E(k)}" value="{E(str(v))}">' for k, v in kw.items())
def what_lines(assets: list, controls: list, would: bool) -> str:
reads = ", ".join(quantity_words(a["asset"]) for a in assets) or T("nothing")
kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in controls))
if would:
out = T("Cantabile would read: {values}.", values=reads)
if kinds:
out += " " + T("It could control: {controls}.", controls=kinds)
else:
out = T("Cantabile reads: {values}.", values=reads)
if kinds:
out += " " + T("It may control: {controls}.", controls=kinds)
return f'<p class="note">{E(out)}</p>'
def notes(d: dict) -> str:
out = []
if d.get("missing"):
out.append(T("Not found in Home Assistant: {entities}.", entities=", ".join(d["missing"])))
gone = d.get("left_out") or {}
if gone.get("values"):
out.append(T("Read by your own mapping already, so left out here: {values}.",
values=", ".join(quantity_words(q) for q in gone["values"])))
if gone.get("controls"):
out.append(T("Another control writes to this device already, so Cantabile leaves out: {controls}.",
controls=", ".join(T(CONTROL_WORDS.get(k, k)) for k in gone["controls"])))
assumed = [a["asset"] for a in d.get("assets") or [] if a.get("assumed")]
if assumed:
out.append(T("Assumed, not measured: {values}. This device does not report back (infrared): Cantabile shows "
"what was last sent to it and never takes it as feedback.",
values=", ".join(quantity_words(q) for q in assumed)))
return "".join(f'<p class="note">{E(x)}</p>' for x in out)
def consent_html(d: dict, site: dict) -> str:
"""Reading and control, the owner's per device, as on the Hub's Devices
page; only with the site's consent (the add-on's configuration)."""
kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in d.get("controls") or []))
if not site.get("share"):
return ('<p class="note">' + E(T("Reading and control are off. To switch them on, first give your consent in the "
"add-on's configuration (Settings, Add-ons, Cantabile Edge Agent, Configuration)."))
+ "</p>")
ctl = ('<label class="check"><input type="checkbox" name="control" value="1"' + (" checked" if d.get("control") else "")
+ "><span>" + E(T("Cantabile may control it ({controls}), within your limits", controls=kinds))
+ "</span></label>") if kinds else ""
note = ('<p class="note">' + E(T("Control also needs your consent to control devices in the add-on's configuration."))
+ "</p>") if kinds and not site.get("control") else ""
return form("consent", hidden(id=d["id"]) + '<label class="check"><input type="checkbox" name="read" value="1"'
+ (" checked" if d.get("read") else "") + "><span>" + E(T("Cantabile may read these values"))
+ f"</span></label>{ctl}", T("Save")) + note
def switchover_html(d: dict) -> str:
sw = d.get("switchover")
if not sw:
return ""
mode = sw.get("mode", "season")
lo, hi = sw.get("heat_below_c", 15), sw.get("cool_above_c", 22)
radios = "".join(f'<label class="check"><input type="radio" name="mode" value="{k}"{" checked" if k == mode else ""}>'
f"<span>{E(T(w))}</span></label>" for k, w in SWITCHOVER_WORDS.items())
inner = (hidden(id=d["id"]) + f'<p class="note">{E(T("This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched."))}</p>'
+ radios
+ f'<label for="lo-{E(d["id"])}">{E(T("By outdoor temperature: heat below (°C)"))}</label>'
f'<input id="lo-{E(d["id"])}" type="number" step="0.5" name="heat_below_c" value="{E(f"{lo:g}")}">'
f'<label for="hi-{E(d["id"])}">{E(T("cool above (°C)"))}</label>'
f'<input id="hi-{E(d["id"])}" type="number" step="0.5" name="cool_above_c" value="{E(f"{hi:g}")}">'
f'<p class="note">{E(T("Between the two it stays as it is, so it does not switch back and forth on a mild day."))}</p>')
return f"<details><summary>{E(T('Heating or cooling'))}</summary>{form('switchover', inner, T('Save'))}</details>"
FACING_WORDS = {"": M("Not known"), "N": M("North"), "NE": M("North-east"), "E": M("East"), "SE": M("South-east"),
"S": M("South"), "SW": M("South-west"), "W": M("West"), "NW": M("North-west")}
def _room_options(rooms, current: str) -> str:
names = list(rooms)
if current and current not in {dp.slug(r) for r in names}:
names.append(current)
return f'<option value="">{E(T("No room"))}</option>' + "".join(
f'<option value="{E(r)}"{" selected" if dp.slug(r) == current else ""}>{E(r)}</option>' for r in names)
def shade_html(d: dict, rooms) -> str:
"""A shade (ha-cover): the room it shades and the window's orientation."""
sh = d.get("shade")
if not sh:
return ""
face = sh.get("facing", -1)
cur = next((k for k, v in dp.ORIENTATIONS.items() if face >= 0 and abs(v - face) < 0.5), "" if face < 0 else None)
opts = "".join(f'<option value="{k}"{" selected" if k == cur else ""}>{E(T(w))}</option>' for k, w in FACING_WORDS.items())
if cur is None:
opts += f'<option value="{face:g}" selected>{face:g}°</option>'
inner = (hidden(id=d["id"]) + '<p class="note">' + E(T(
"Cantabile moves it by the sun: in summer it closes it while the sun is on the window and the room is warm; in "
"winter it opens it for the sun's warmth and closes it at night. Never between 22:00 and 07:00, and after you "
"move it by hand it waits 4 hours.")) + "</p>"
f'<label for="area-{E(d["id"])}">{E(T("Room it shades"))}</label><select id="area-{E(d["id"])}" name="area">'
f'{_room_options(rooms, sh.get("area") or "")}</select>'
f'<label for="face-{E(d["id"])}">{E(T("The window faces"))}</label><select id="face-{E(d["id"])}" name="facing">{opts}</select>'
'<p class="note">' + E(T("Without the window's direction Cantabile only closes it at night in winter.")) + "</p>")
return f"<details><summary>{E(T('Room and window'))}</summary>{form('shade', inner, T('Save'))}</details>"
def place_html(d: dict, rooms) -> str:
"""A temperature sensor (ha-climate-sensor): indoor (its room) or outdoor."""
pl = d.get("place")
if not pl:
return ""
chk = lambda k: " checked" if pl["place"] == k else "" # noqa: E731
inner = (hidden(id=d["id"])
+ f'<label class="check"><input type="radio" name="place" value="indoor"{chk("indoor")}><span>{E(T("Indoor, in the room:"))}</span></label>'
+ f'<select name="area" aria-label="{E(T("Room"))}">{_room_options(rooms, pl.get("area") or "")}</select>'
+ f'<label class="check"><input type="radio" name="place" value="outdoor"{chk("outdoor")}><span>{E(T("Outdoor: Cantabile's outside temperature"))}</span></label>'
+ '<p class="note">' + E(T("An outdoor sensor counts before the weather service's temperature.")) + "</p>")
return f"<details><summary>{E(T('Indoor or outdoor'))}</summary>{form('place', inner, T('Save'))}</details>"
def weather_html(d: dict) -> str:
"""A weather service (ha-weather): whether its forecast plans."""
w = d.get("weather")
if not w:
return ""
if w.get("active"):
return '<p class="note">' + E(T("Cantabile plans with this forecast: solar, heating, cooling and the shades.")) + "</p>"
return ('<p class="note">' + E(T("Not used for planning: Cantabile plans with one weather forecast, another one's."))
+ "</p>" + form("weather", hidden(id=d["id"]), T("Plan with this forecast"), "secondary"))
def protection_html(d: dict) -> str:
"""Per target a switch for the owner; sealed ones locked with their
custodian."""
pol = d.get("policy") or {}
targets = [f"device:{d['id']}"] + [f"control:{c['id']}" for c in d.get("controls") or [] if c.get("id")]
targets += [t for t in pol if t not in targets]
seal = (pol.get(f"device:{d['id']}") or {}) if d.get("protection") == "sealed" else None
rows = []
covers = {f"control:{c['id']}" for c in d.get("controls") or [] if c.get("kind") == "cover" and c.get("id")}
for t in targets:
e = pol.get(t) or {}
kind, _, name = t.partition(":")
what = {"device": T("The whole device"), "control": T("Control {name}", name=name)}.get(kind, name)
lift = T("Allow Cantabile to move it") if t in covers else T("Allow switching off")
lvl = "sealed" if seal else e.get("level", "none")
if lvl == "sealed":
why = (seal or e).get("why")
rows.append(f'<li>{E(what)}: <b>{E(T("Sealed"))}</b> · {E(T("only {who} can change it", who=custodian(seal or e)))}'
f'{": " + E(why) if why else ""}</li>')
continue
why = f" ({E(e['why'])})" if e.get("why") and lvl == "protected" else ""
state = f"<b>{E(T('protected'))}</b>" if lvl == "protected" else E(T("not protected"))
rows.append(f"<li>{E(what)}: {state}{why} "
+ form("protect", hidden(id=d["id"], target=t, level="none" if lvl == "protected" else "protected"),
lift if lvl == "protected" else T("Protect"), "secondary", inline=True)
+ "</li>")
return (f"<details><summary>{E(T('Protection'))}</summary><p class=\"note\">"
+ E(T("Protected: Cantabile never switches it off or cuts it; you still can, by hand. Sealed: only its "
"custodian can change it.")) + ("" if not covers else " " + E(T(
"A protected blind or curtain is not moved by Cantabile at all.")))
+ f'</p><ul class="plain">{"".join(rows)}</ul></details>')
def badges(d: dict) -> str:
st = PROFILE_STATUS.get(d.get("status"))
out = f'<span class="badge">{E(d.get("manufacturer", ""))} {E(d.get("model", ""))}</span>'
if d.get("generic"):
out += f'<span class="badge">{E(T("generic profile"))}</span>'
if st:
out += f'<span class="badge">{E(T(st))}</span>'
return out
def device_card(d: dict, site: dict, rooms=()) -> str:
return (f'<div class="box"><b>{E(d["name"])}</b>{badges(d)}{what_lines(d.get("assets") or [], d.get("controls") or [], False)}'
f'{notes(d)}{consent_html(d, site)}{switchover_html(d)}{shade_html(d, rooms)}{place_html(d, rooms)}'
f'{weather_html(d)}{protection_html(d)}'
f"<details><summary>{E(T('Remove'))}</summary><p class=\"note\">"
+ E(T("Cantabile stops using it. Home Assistant keeps the device as it is."))
+ "</p>" + form("remove", hidden(id=d["id"]), T("Stop using it with Cantabile"), "secondary") + "</details></div>")
def offer_card(h: dict) -> str:
p = h["profile"]
name = h["name"] or h["model"]
proposed = ""
if h.get("in_mapping"):
ids = ", ".join(quantity_words(i) for i in h["in_mapping"])
proposed = '<p class="note">' + E(
T("Proposed by Cantabile (not checked yet): {values}. Use it with Cantabile to confirm it as this profile "
"sees it.", values=ids) if h.get("mapping_source") in ("proposed", "imported")
else T("In your own mapping: {values}. Those stay as they are.", values=ids)) + "</p>"
body = what_lines(h["assets"], h["controls"], True) + notes(h) + proposed
view = dict(h, status=p.get("status"))
if not h["assets"] and not h["controls"]:
return f'<div class="box"><b>{E(name)}</b>{badges(view)}{body}</div>'
return (f'<div class="box"><b>{E(name)}</b>{badges(view)}{body}'
+ form("use", hidden(ha_device=h["id"], profile=p["id"], name=name), T("Use with Cantabile")) + "</div>")
def nav(page: str) -> str:
items = (("devices", T("Devices")), ("building", T("Building or community")))
return "<nav>" + "".join(f'<a href="?p={k}"{" class=" + chr(34) + "on" + chr(34) if k == page else ""}>{E(w)}</a>'
for k, w in items) + "</nav>"
def html(title: str, body: str, page: str) -> str:
return (f"<!doctype html><html lang=\"{i18n.current()}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" "
f"content=\"width=device-width,initial-scale=1\"><title>{E(title)}</title><style>{CSS}\n{MORE_CSS}</style>"
f"<script>{HASH_SCRIPT}</script></head><body>{nav(page)}{body}</body></html>")
def page_devices(v: dict, msg: str = "", err: str = "") -> str:
body = [f"<h2>{E(T('Devices'))}</h2><p class=\"note\">"
+ E(T("Home Assistant's devices that a Cantabile device profile knows. Use one with Cantabile to see it on "
"Cantabile's dashboard and to let Cantabile read it once you have given your consent.")) + "</p>"]
if msg:
body.append(f'<div class="box ok">{E(msg)}</div>')
if err:
body.append(f'<div class="box err">{E(err)}</div>')
if v.get("devices"):
body.append(f"<h3>{E(T('Used with Cantabile'))}</h3>")
body += [device_card(d, v.get("site") or {}, v.get("rooms") or []) for d in v["devices"]]
if v.get("offers"):
body.append(f"<h3>{E(T('In Home Assistant, with a profile'))}</h3>")
body += [offer_card(h) for h in v["offers"]]
elif not v.get("ha_error") and not v.get("devices"):
body.append('<p class="note">' + E(T("No device in Home Assistant fits a Cantabile profile yet.")) + "</p>")
if v.get("rest"):
n = len(v["rest"])
body.append(f"<details><summary>{E(TN('{n} more in Home Assistant without a profile (not used by Cantabile)', '{n} more in Home Assistant without a profile (not used by Cantabile)', n))}</summary><ul class=\"plain\">"
+ "".join(f"<li>{E(h['name'] or h['model'])} <small>{E(h['manufacturer'])} {E(h['model'])}</small></li>"
for h in v["rest"]) + "</ul></details>")
if v.get("ha_error"):
body.append('<p class="note">' + E(T("Home Assistant's devices could not be read: {error}", error=v["ha_error"])) + "</p>")
return html(T("Cantabile: devices"), "".join(body), "devices")
def page_refused(why: str, page: str = "devices") -> str:
head = T("Devices") if page == "devices" else T("Building or community")
return html("Cantabile", f"<h2>{E(head)}</h2><div class=\"box err\">{E(why)}</div>", page)
class App(JoinPage):
"""The add-on's pages: Devices (the first) and Building or community."""
def __init__(self, fleet, devices: Devices, location=None, admin=None):
super().__init__(fleet, **({"location": location} if location else {}))
self.devices = devices
# admin(user_id) -> bool: the agent's HA client asks HA (ha.is_admin)
self.admin = admin or self._admin
async def _admin(self, user_id: str) -> bool:
client = self.devices.ha()
if client is None:
raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment."))
return await client.is_admin(user_id)
async def respond(self, method, url, hdr, data, peer):
q = urllib.parse.parse_qs(url.query)
page = (q.get("p") or [""])[0]
if page not in PAGES:
page = "building" if q.get("code") else "devices"
# owner only, both pages: an administrator of Home Assistant (HA's
# ingress names the user; this container itself is trusted)
user = hdr.get("x-remote-user-id", "")
if peer not in ("127.0.0.1", "::1"):
try:
ok = bool(user) and await self.admin(user)
except Exception as e:
return 200, page_refused(T("Cantabile could not ask Home Assistant who you are ({error}).", error=e), page)
if not ok:
return 200, page_refused(T("Only an administrator of Home Assistant can use this page."), page)
if page == "building":
status, out = await super().respond(method, url, hdr, data, peer)
if status == 200:
out = out.replace("</style>", f"\n{MORE_CSS}</style><script>{HASH_SCRIPT}</script>", 1) \
.replace("<body>", "<body>" + nav("building"), 1)
return status, out
if url.path not in ("/", "") or method not in ("GET", "POST"):
return 404, T("Not found")
if method == "GET":
return 200, page_devices(await self.devices.view())
f = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode("utf-8", "replace")).items()}
by = hdr.get("x-remote-user-display-name") or hdr.get("x-remote-user-name") or "owner"
return 200, await self.post_devices(f, by)
async def post_devices(self, f: dict, by: str = "owner") -> str:
dv, do, msg, err = self.devices, f.get("do", ""), "", ""
try:
if do == "use":
d = await dv.use(f.get("ha_device", ""), f.get("profile", ""), f.get("name", ""))
msg = T("{name} is used with Cantabile now. It is on Cantabile's dashboard; reading and control are off "
"until you switch them on below.",
name=d["name"])
elif do == "remove":
await dv.remove(f.get("id", ""))
msg = T("Cantabile no longer uses it.")
elif do == "consent":
await dv.consent(f.get("id", ""), f.get("read") == "1", f.get("control") == "1")
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
elif do == "protect":
await dv.protect(f.get("id", ""), f.get("target", ""), f.get("level", ""), by)
msg = T("Saved.")
elif do == "shade":
await dv.shade(f.get("id", ""), {"area": f.get("area", ""), "facing": f.get("facing", "")})
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
elif do == "place":
await dv.place(f.get("id", ""), {"place": f.get("place", ""), "area": f.get("area", "")})
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
elif do == "weather":
await dv.weather(f.get("id", ""))
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
elif do == "switchover":
data = {"mode": f.get("mode", "")}
if data["mode"] == "outdoor":
data.update(heat_below_c=f.get("heat_below_c", ""), cool_above_c=f.get("cool_above_c", ""))
await dv.switchover(f.get("id", ""), data)
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
except dp.Fail as e:
err = str(e)
return page_devices(await dv.view(), msg, err)