326 lines
14 KiB
Python
Executable File
326 lines
14 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
|
"""The Edge Agent's start as a Home Assistant add-on (runs as root).
|
|
|
|
- Home Assistant's instance id: .storage/core.uuid is root-only; a copy in
|
|
/data for the link (the site id comes from it, as on the Hub).
|
|
- The add-on's options (/data/options.json): the owner's consent, mode,
|
|
claim code, dashboards.
|
|
- Consent (the owner's decision of 2026-10-30): given when the
|
|
add-on is installed from Cantabile's repository, in its configuration:
|
|
sharing the energy data of the devices chosen for Cantabile (needed: until
|
|
it is given the add-on does not enrol or connect, and its page says why)
|
|
and, separately, control. The same texts and version as the Hub's setup
|
|
wizard and panel; recorded in the agent's consent file
|
|
(/data/state/consent.json: share, control, when, the texts' version, the
|
|
source), which the link sends to Cantabile with its heartbeat. Taken
|
|
back in the configuration: nothing more is collected or sent.
|
|
- The hardware fingerprint (hashed ids: the DMI ones are root-only): written
|
|
once per start for the link, which recognises a reinstall with it.
|
|
- MQTT: the broker the Supervisor offers (the Mosquitto add-on), with the
|
|
login it made for this add-on; without one, no discovery in HA.
|
|
- First start: config.yaml and an empty mapping, as the Hub's edge-prepare;
|
|
the agent then proposes one from Home Assistant's devices (propose.py),
|
|
consent off: nothing is read for Cantabile until the owner agrees.
|
|
- An earlier install's mapping (/share/cantabile/mapping.yaml, the owner or
|
|
support puts it there): copied to /data/mapping-import.yaml for the agent,
|
|
which imports it once per content, consent off.
|
|
Then the link and the agent (cantabile-run) as uid 10001, without root's
|
|
capabilities: /homeassistant stays mapped, but only what is readable for
|
|
everyone is readable for them.
|
|
ADDON_DATA, ADDON_HA_CONFIG, ADDON_ETC, SUPERVISOR_URL and ADDON_DRY_RUN=1
|
|
(print the environment instead of starting) are for tests.
|
|
"""
|
|
import html
|
|
import json
|
|
import os
|
|
import pwd
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
|
|
DATA = os.environ.get("ADDON_DATA", "/data")
|
|
HA_CONFIG = os.environ.get("ADDON_HA_CONFIG", "/homeassistant")
|
|
SHARE = os.environ.get("ADDON_SHARE", "/share")
|
|
ETC = os.environ.get("ADDON_ETC", "/etc/cantabile")
|
|
SUPERVISOR = os.environ.get("SUPERVISOR_URL", "http://supervisor")
|
|
DRY = os.environ.get("ADDON_DRY_RUN") == "1"
|
|
USER = "cantabile" # edge/Dockerfile: uid 10001
|
|
|
|
CONFIG = """# The Edge Agent as a Home Assistant add-on (written once by addon-run).
|
|
mode: shadow
|
|
mapping: /data/mapping.yaml
|
|
state_dir: /data/state
|
|
sink: {kind: link, path: /run/cantabile/link.sock}
|
|
"""
|
|
MAPPING = """# Which HA entities Cantabile may read (edge/cantabile_edge/mapping.py).
|
|
# None yet: the agent proposes them from Home Assistant's devices, or imports
|
|
# an earlier install's mapping (/share/cantabile/mapping.yaml), consent off.
|
|
version: 1
|
|
assets: []
|
|
"""
|
|
IMPORT = "cantabile/mapping.yaml"
|
|
INGRESS_PORT = 8099
|
|
RESTART = 75
|
|
# The consent's texts: the Hub's (hub/.../cantabile/web CONSENT_TEXT,
|
|
# CONTROL_TEXT and CONSENT_VERSION), working texts until the legal team's.
|
|
CONSENT_TEXT = "Cantabile may receive the energy data of the devices chosen for it."
|
|
CONTROL_TEXT = ("Allow Cantabile to control the devices you choose (heating, charging, battery, shades) "
|
|
"within the limits you set.")
|
|
CONSENT_VERSION = "working-2026-10-29"
|
|
CONSENT_SOURCE = "given at installation in the add-on's configuration"
|
|
WAITING = {
|
|
"en": ("Cantabile is not connected",
|
|
"Cantabile connects only with your consent. In the add-on's Configuration (Settings, Apps or Add-ons, "
|
|
"Cantabile Edge Agent), turn on \"Share energy data with Cantabile\" (and, if you want, \"Cantabile may "
|
|
"control devices\"), save and restart the add-on.", "Open the configuration"),
|
|
"de": ("Cantabile ist nicht verbunden",
|
|
"Cantabile verbindet sich nur mit Ihrer Einwilligung. Schalten Sie in der Konfiguration des Add-ons "
|
|
"(Einstellungen, Apps bzw. Add-ons, Cantabile Edge Agent) „Energiedaten mit Cantabile teilen“ ein (und, "
|
|
"wenn Sie möchten, „Cantabile darf Geräte steuern“), speichern Sie und starten Sie das Add-on neu.",
|
|
"Konfiguration öffnen"),
|
|
}
|
|
|
|
|
|
def log(msg):
|
|
print(f"addon-run: {msg}", flush=True)
|
|
|
|
|
|
def owner():
|
|
if DRY or os.geteuid() != 0:
|
|
return None
|
|
pw = pwd.getpwnam(USER)
|
|
return pw.pw_uid, pw.pw_gid
|
|
|
|
|
|
def put(path, text, mode=0o600, own=None, keep=False):
|
|
"""Write a file the agent's user owns; keep=True: only if missing."""
|
|
if keep and os.path.exists(path):
|
|
return
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
tmp = path + ".tmp"
|
|
with open(tmp, "w") as f:
|
|
f.write(text)
|
|
os.chmod(tmp, mode)
|
|
if own:
|
|
os.chown(tmp, *own)
|
|
os.replace(tmp, path)
|
|
|
|
|
|
def chown_tree(path, own):
|
|
"""The agent's files in /data (options.json stays the Supervisor's)."""
|
|
for root, dirs, files in os.walk(path):
|
|
for n in dirs + files:
|
|
p = os.path.join(root, n)
|
|
if p != os.path.join(DATA, "options.json") and not os.path.islink(p):
|
|
os.chown(p, *own)
|
|
os.chown(path, *own)
|
|
|
|
|
|
def consent(opts, own, now=None):
|
|
"""The owner's consent from the configuration into the agent's consent
|
|
file; True when sharing is given. Kept as it was (and when it was given)
|
|
while unchanged; the operators' consents (the add-on's page) stay."""
|
|
path = f"{DATA}/state/consent.json"
|
|
try:
|
|
with open(path) as f:
|
|
d = json.load(f)
|
|
d = d if isinstance(d, dict) else {}
|
|
except (OSError, ValueError):
|
|
d = {}
|
|
share = opts.get("consent_data") is True
|
|
control = share and opts.get("consent_control") is True
|
|
if (d.get("share"), d.get("control"), d.get("text_version"), d.get("by")) != \
|
|
(share, control, CONSENT_VERSION, "ha-addon-config") or not os.path.exists(path):
|
|
d.update(share=share, control=control, at=int(now or time.time()), by="ha-addon-config",
|
|
source=CONSENT_SOURCE, text_version=CONSENT_VERSION,
|
|
texts={"share": CONSENT_TEXT, "control": CONTROL_TEXT})
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
put(path, json.dumps(d, ensure_ascii=False), 0o600, own)
|
|
log(f"consent from the configuration: sharing {'given' if share else 'not given'}, "
|
|
f"control {'given' if control else 'not given'} (texts {CONSENT_VERSION})")
|
|
return share
|
|
|
|
|
|
def own_slug():
|
|
"""This add-on's slug from the Supervisor (for the link to its
|
|
configuration); "" when it can't be asked."""
|
|
token = os.environ.get("SUPERVISOR_TOKEN", "")
|
|
req = urllib.request.Request(f"{SUPERVISOR}/addons/self/info", headers={"Authorization": f"Bearer {token}"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return str((json.load(r).get("data") or {}).get("slug") or "")
|
|
except (OSError, ValueError):
|
|
return ""
|
|
|
|
|
|
def waiting_html(accept_language, slug=""):
|
|
"""The page while there is no consent, in German or English, in HA's
|
|
light or dark look, with a button to the add-on's configuration."""
|
|
lang = "de" if (accept_language or "").strip().lower().startswith("de") else "en"
|
|
title, text, button = WAITING[lang]
|
|
link = (f'<p><a class="b" target="_top" href="/hassio/addon/{html.escape(slug)}/config">{html.escape(button)}</a></p>'
|
|
if re.fullmatch(r"[a-z0-9_]+", slug or "") else "")
|
|
return (f'<!doctype html><html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" '
|
|
f'content="width=device-width,initial-scale=1"><title>{html.escape(title)}</title><style>'
|
|
"body{font-family:system-ui,sans-serif;margin:16px;max-width:46rem;background:#fff;color:#1c1c1c}"
|
|
"a.b{display:inline-block;padding:.6rem 1rem;border-radius:8px;background:#03a9f4;color:#fff;"
|
|
"text-decoration:none}"
|
|
"@media (prefers-color-scheme:dark){body{background:#111;color:#e1e1e1}}</style></head><body>"
|
|
f"<h2>{html.escape(title)}</h2><p>{html.escape(text)}</p>{link}</body></html>")
|
|
|
|
|
|
def waiting_page(own):
|
|
"""No consent: the add-on's page (HA's ingress) says why Cantabile is not
|
|
connected and where to give it; nothing is enrolled or sent."""
|
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
slug = own_slug()
|
|
|
|
class Page(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
body = waiting_html(self.headers.get("Accept-Language"), slug).encode()
|
|
ok = self.client_address[0] in ("172.30.32.2", "127.0.0.1", "::1")
|
|
self.send_response(200 if ok else 403)
|
|
self.send_header("Content-Type", "text/html; charset=utf-8" if ok else "text/plain")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.end_headers()
|
|
self.wfile.write(body if ok else b"Open this page from Home Assistant.")
|
|
|
|
do_POST = do_GET
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
server = HTTPServer(("0.0.0.0", INGRESS_PORT), Page)
|
|
if own:
|
|
os.setgroups([])
|
|
os.setgid(own[1])
|
|
os.setuid(own[0])
|
|
server.serve_forever()
|
|
|
|
|
|
def mqtt(env, own):
|
|
token = os.environ.get("SUPERVISOR_TOKEN", "")
|
|
req = urllib.request.Request(f"{SUPERVISOR}/services/mqtt", headers={"Authorization": f"Bearer {token}"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
d = json.load(r)["data"]
|
|
except Exception as e: # no broker add-on: the agent runs without HA discovery
|
|
log(f"no MQTT broker from the Supervisor ({e}): no Cantabile device in Home Assistant")
|
|
return
|
|
if d.get("ssl"):
|
|
log("the MQTT broker wants TLS, which the agent does not speak yet: no Cantabile device in Home Assistant")
|
|
return
|
|
env["CANTABILE_MQTT_HOST"] = str(d["host"])
|
|
env["CANTABILE_MQTT_PORT"] = str(d.get("port", 1883))
|
|
if d.get("username"):
|
|
env["CANTABILE_MQTT_USER"] = d["username"]
|
|
put(f"{DATA}/mqtt-password", d.get("password", ""), own=own)
|
|
env["CANTABILE_MQTT_PASSWORD_FILE"] = f"{DATA}/mqtt-password"
|
|
log(f"MQTT broker {d['host']}:{env['CANTABILE_MQTT_PORT']}")
|
|
|
|
|
|
def fingerprint(env, own):
|
|
"""The box's hardware ids, hashed by the link itself (`cantabile-link
|
|
fingerprint`, as root); no raw serial is written."""
|
|
if DRY:
|
|
return
|
|
try:
|
|
out = subprocess.run(["cantabile-link", "fingerprint"], capture_output=True, text=True, timeout=30).stdout
|
|
json.loads(out)
|
|
except (OSError, ValueError, subprocess.TimeoutExpired) as e:
|
|
log(f"no hardware fingerprint: {e}")
|
|
return
|
|
put(f"{DATA}/fingerprint.json", out, own=own)
|
|
env["CANTABILE_FINGERPRINT_FILE"] = f"{DATA}/fingerprint.json"
|
|
|
|
|
|
def main():
|
|
own = owner()
|
|
with open(f"{DATA}/options.json") as f:
|
|
opts = json.load(f)
|
|
env = dict(os.environ)
|
|
# The platform this build belongs to (ha-addon/build.sh: addon.env).
|
|
with open(f"{ETC}/addon.env") as f:
|
|
for line in f:
|
|
k, sep, v = line.strip().partition("=")
|
|
if sep and not k.startswith("#"):
|
|
env.setdefault(k, v)
|
|
env["CANTABILE_COMMAND_CERT"] = f"{ETC}/commands.pem"
|
|
if os.path.exists(f"{ETC}/bundles.pem"):
|
|
env["CANTABILE_BUNDLE_CERT"] = f"{ETC}/bundles.pem"
|
|
if os.path.exists(f"{ETC}/devices-ca.pem"): # the direct path's CA (docs/direct-link.md)
|
|
env["CANTABILE_DEVICES_CA"] = f"{ETC}/devices-ca.pem"
|
|
|
|
with open(f"{HA_CONFIG}/.storage/core.uuid") as f:
|
|
put(f"{DATA}/ha-core.uuid", f.read(), own=own)
|
|
env["CANTABILE_HA_UUID_FILE"] = f"{DATA}/ha-core.uuid"
|
|
|
|
if not consent(opts, own):
|
|
log("no consent to share energy data (the add-on's configuration): not connecting to Cantabile. "
|
|
"Turn on \"Share energy data with Cantabile\" in the Configuration tab and restart the add-on.")
|
|
if DRY:
|
|
print(json.dumps({"consent": False}))
|
|
return
|
|
waiting_page(own)
|
|
return
|
|
|
|
fingerprint(env, own)
|
|
|
|
code = (opts.get("claim_code") or "").strip()
|
|
if code:
|
|
put(f"{DATA}/claim-code", code + "\n", own=own)
|
|
env["CANTABILE_MODE"] = opts.get("mode", "shadow")
|
|
env["CANTABILE_DASHBOARDS"] = "1" if opts.get("dashboards", True) else "0"
|
|
mqtt(env, own)
|
|
|
|
put(f"{DATA}/config.yaml", CONFIG, 0o644, own, keep=True)
|
|
put(f"{DATA}/mapping.yaml", MAPPING, 0o644, own, keep=True)
|
|
env["CANTABILE_PROPOSE"] = "1"
|
|
try:
|
|
with open(f"{SHARE}/{IMPORT}") as f:
|
|
put(f"{DATA}/mapping-import.yaml", f.read(), 0o600, own)
|
|
log(f"an earlier install's mapping in /share/{IMPORT}: the agent imports it once, consent off")
|
|
except FileNotFoundError:
|
|
pass
|
|
except (OSError, UnicodeDecodeError) as e:
|
|
log(f"/share/{IMPORT} not read: {e}")
|
|
os.makedirs(f"{DATA}/state", exist_ok=True)
|
|
if own:
|
|
chown_tree(DATA, own)
|
|
|
|
cmd = ["cantabile-run", "--config", f"{DATA}/config.yaml", "run"]
|
|
if DRY:
|
|
print(json.dumps({"cmd": cmd, "env": {k: v for k, v in env.items() if k.startswith(("CANTABILE_", "HA_"))}}))
|
|
return
|
|
if own:
|
|
# Drop to the agent's user and every capability; no way back.
|
|
cmd = ["setpriv", f"--reuid={own[0]}", f"--regid={own[1]}", "--init-groups",
|
|
"--inh-caps=-all", "--bounding-set=-all", "--no-new-privs"] + cmd
|
|
# 75: the agent asks to start again (a device's consent or controls
|
|
# changed on its page, as the Hub's devices tool restarts it)
|
|
child = None
|
|
|
|
def forward(sig, _frame):
|
|
if child is not None:
|
|
child.send_signal(sig)
|
|
for sig in (signal.SIGTERM, signal.SIGINT):
|
|
signal.signal(sig, forward)
|
|
while True:
|
|
child = subprocess.Popen(cmd, env=env)
|
|
rc = child.wait()
|
|
if rc != RESTART:
|
|
sys.exit(rc)
|
|
log("the agent starts again")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except FileNotFoundError as e:
|
|
log(f"missing {e.filename}")
|
|
sys.exit(1)
|