// Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. package main import ( "errors" "fmt" "html/template" "net" "net/http" "sort" "strconv" "strings" "time" ) // Page: the bridge's own page (the Hub panel's frame, or HA's ingress): // devices found and asking to pair (the owner compares the SKI with the // device's own and confirms), paired devices with their values and // controls, each control's protection, the grid operator's limit, and the // audit log. # opens one device (deep links from the agent's // dashboard). English and German by the browser's language; HA's light and // dark. Only the panel or HA's ingress proxy may open it (PAGE_PEERS). type Page struct { core *Core sim *Sim peers []string ha bool } var texts = map[string]map[string]string{ "en": { "title": "Cantabile EEBUS", "intro": "Heat pumps, wallboxes and the grid operator's control box speak EEBUS. Pair each one here once: compare the SKI with the one on the device's display, label or app, then confirm.", "grid": "Grid operator's limit", "normal": "No limit", "limited": "Limited", "failsafe": "Failsafe (no heartbeat from the control box)", "autonomous": "Autonomous (failsafe time over)", "no_cb": "No control box paired.", "limit_until": "until", "until_changed": "until the grid operator changes it", "found": "Found on the network", "asking": "asks to be paired", "pair": "Pair", "deny": "Deny", "unpair": "Unpair", "confirm_pair": "Pair with {}? Only if the SKI matches the one on the device.", "confirm_unpair": "Unpair {}? Cantabile stops reading and controlling it.", "paired": "Paired devices", "none": "None yet.", "online": "online", "offline": "offline", "connecting": "connecting", "values": "Values", "controls": "Controls", "set": "Set", "protection": "Protection", "protected": "protected", "lvl_none": "not protected", "sealed": "sealed", "custodian": "custodian", "lift": "Lift", "protect": "Protect", "back": "All devices", "confirm_lift": "Lift the protection of {}? Cantabile may then set it to 0.", "ro": "read only (a dry run)", "use_cases": "Use cases", "profile": "Profile", "ski": "SKI", "own_ski": "This bridge's SKI (heat pumps, wallboxes, inverters)", "grid_ski": "This bridge's SKI for the grid operator's control box", "log": "Log", "events": "Recent events", "sim": "Simulator", "sim_limit": "Control box: send a 4.2 kW limit for 15 min", "sim_end": "Control box: end the limit", "sim_hb_off": "Control box: lose the heartbeat", "sim_hb_on": "Control box: heartbeat back", "sim_plug": "Car in/out", "sealed_note": "Sealed by its custodian: only the grid operator changes it, through Cantabile, signed.", "passon": "Passed on to", "kind_control-box": "Control box", "kind_heat-pump": "Heat pump", "kind_wallbox": "Wallbox", "kind_inverter": "Inverter", "kind_meter": "Meter", "kind_other": "Device", "untested": "untested on hardware", "on": "on", "off": "off", "no_control": "Control: no consent. Cantabile reads these devices and hands the grid operator's limit to its agent, but writes nothing to them (not even the grid operator's limit). Give your consent in the add-on's configuration (Cantabile may control devices).", "all_ro": "Read only (a dry run): commands are checked and logged, nothing is written to the devices.", "lpc_declared": "Toward the control box: nominal power {} W declared (LPC offered).", "lpc_refused": "LPC not offered: {}. Nothing is declared to the grid operator's control box until it is known.", "rating": "Rated power (kW)", "rating_none": "not entered", "rating_note": "From the device's nameplate, where it reports no power itself: the bridge declares the devices' power to the grid operator's control box only when it knows it, never a guess.", }, "de": { "title": "Cantabile EEBUS", "intro": "Wärmepumpen, Wallboxen und die Steuerbox des Netzbetreibers sprechen EEBUS. Koppeln Sie jedes Gerät hier einmal: vergleichen Sie die SKI mit der auf dem Display, dem Etikett oder in der App des Geräts, dann bestätigen.", "grid": "Limit des Netzbetreibers", "normal": "Kein Limit", "limited": "Begrenzt", "failsafe": "Failsafe (kein Heartbeat der Steuerbox)", "autonomous": "Autonom (Failsafe-Zeit vorbei)", "no_cb": "Keine Steuerbox gekoppelt.", "limit_until": "bis", "until_changed": "bis der Netzbetreiber es ändert", "found": "Im Netz gefunden", "asking": "möchte gekoppelt werden", "pair": "Koppeln", "deny": "Ablehnen", "unpair": "Entkoppeln", "confirm_pair": "Mit {} koppeln? Nur wenn die SKI mit der am Gerät übereinstimmt.", "confirm_unpair": "{} entkoppeln? Cantabile liest und steuert es dann nicht mehr.", "paired": "Gekoppelte Geräte", "none": "Noch keine.", "online": "online", "offline": "offline", "connecting": "verbindet", "values": "Werte", "controls": "Steuerungen", "set": "Setzen", "protection": "Schutz", "protected": "geschützt", "lvl_none": "nicht geschützt", "sealed": "versiegelt", "custodian": "Verwalter", "lift": "Aufheben", "protect": "Schützen", "back": "Alle Geräte", "confirm_lift": "Schutz von {} aufheben? Cantabile darf es dann auf 0 setzen.", "ro": "nur lesen (Probelauf)", "use_cases": "Anwendungsfälle", "profile": "Profil", "ski": "SKI", "own_ski": "SKI dieser Bridge (Wärmepumpen, Wallboxen, Wechselrichter)", "grid_ski": "SKI dieser Bridge für die Steuerbox des Netzbetreibers", "log": "Protokoll", "events": "Letzte Ereignisse", "sim": "Simulator", "sim_limit": "Steuerbox: 4,2 kW Limit für 15 min senden", "sim_end": "Steuerbox: Limit beenden", "sim_hb_off": "Steuerbox: Heartbeat verlieren", "sim_hb_on": "Steuerbox: Heartbeat zurück", "sim_plug": "Auto ein/aus", "sealed_note": "Vom Verwalter versiegelt: nur der Netzbetreiber ändert es, über Cantabile, signiert.", "passon": "Weitergegeben an", "kind_control-box": "Steuerbox", "kind_heat-pump": "Wärmepumpe", "kind_wallbox": "Wallbox", "kind_inverter": "Wechselrichter", "kind_meter": "Zähler", "kind_other": "Gerät", "untested": "nicht an echter Hardware getestet", "on": "an", "off": "aus", "no_control": "Steuern: keine Einwilligung. Cantabile liest diese Geräte und gibt das Limit des Netzbetreibers an seinen Agenten weiter, schreibt aber nichts an sie (auch nicht das Limit des Netzbetreibers). Geben Sie Ihre Einwilligung in der Konfiguration des Add-ons (Cantabile darf Geräte steuern).", "all_ro": "Nur lesen (Probelauf): Befehle werden geprüft und protokolliert, nichts wird an die Geräte geschrieben.", "lpc_declared": "Gegenüber der Steuerbox: Nennleistung {} W gemeldet (LPC angeboten).", "lpc_refused": "LPC nicht angeboten: {}. Der Steuerbox des Netzbetreibers wird nichts gemeldet, bis sie bekannt ist.", "rating": "Nennleistung (kW)", "rating_none": "nicht eingetragen", "rating_note": "Vom Typenschild des Geräts, wo es selbst keine Leistung meldet: Die Bridge meldet der Steuerbox des Netzbetreibers die Leistung der Geräte nur, wenn sie bekannt ist, nie geschätzt.", }, } func langOf(h string) string { for _, part := range strings.Split(h, ",") { l := strings.ToLower(strings.TrimSpace(strings.SplitN(part, ";", 2)[0])) if strings.HasPrefix(l, "de") { return "de" } if strings.HasPrefix(l, "en") { return "en" } } return "en" } const css = `:root{--bg:#f6f8f7;--fg:#1d2a24;--card:#fff;--line:#d5ded9;--soft:#e3e9e5;--mute:#5a6b62;--acc:#2f6f55;--prot:#1f6b45;--warn:#7a4b00;--bar:#cfe3d8} @media (prefers-color-scheme:dark){:root{--bg:#111915;--fg:#e3ebe6;--card:#18221d;--line:#2b3a32;--soft:#22302a;--mute:#9fb0a6;--acc:#5fb38c;--prot:#7fd1a6;--warn:#e0a54a;--bar:#2c4a3b}} body{font-family:system-ui,sans-serif;margin:0;padding:16px;overflow-wrap:anywhere;max-width:56rem;color:var(--fg);background:var(--bg)} h2{margin:.2rem 0 1rem}h3{margin:0 0 .4rem;font-size:1rem}a{color:inherit} .card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.7rem .8rem;margin:.5rem 0} a.card{display:block;text-decoration:none}a.card:hover{border-color:var(--acc)} .row{display:flex;flex-wrap:wrap;gap:.3rem .9rem;align-items:baseline}.grow{flex:1} .note{color:var(--mute);font-size:.88rem}.big{font-size:1.4rem;font-weight:600}.small{font-size:.82rem;color:var(--mute)} .badge{display:inline-block;font-size:.75rem;padding:.05rem .45rem;border-radius:9px;background:var(--soft);color:var(--mute)} .ok{color:var(--prot)}.bad{color:var(--warn)}.prot{background:var(--bar);color:var(--prot);font-weight:600}.lock{color:var(--warn);font-weight:600} table{border-collapse:collapse;width:100%}td,th{text-align:left;padding:.3rem .4rem;border-bottom:1px solid var(--soft);font-size:.9rem}td.v{text-align:right;white-space:nowrap} button{font:inherit;font-size:.82rem;padding:.2rem .7rem;border:0;border-radius:6px;background:var(--acc);color:#fff;cursor:pointer} button.off{background:var(--soft);color:var(--fg)}form{display:inline;margin:0}input[type=number]{width:6.5rem;font:inherit;font-size:.85rem} code{font-size:.8rem;word-break:break-all}pre{white-space:pre-wrap;font-size:.8rem}details summary{cursor:pointer;color:var(--mute);font-size:.88rem} section.dev{display:none}section.dev:target{display:block}body:has(section.dev:target) #list{display:none}` // The script (served as page.js: the panel's frame allows its own scripts // only): in HA's app panel the page is an iframe whose address has no // #; take the parent's at start and keep both in step. A reload // every 30 s while nothing is being typed. const pageJS = `(function(){var P=null;try{if(window.parent!==window){P=window.parent;P.location.hash}}catch(x){P=null} function dev(h){return h&&h.length>1&&document.getElementById(decodeURIComponent(h.slice(1)))?h:''} if(P&&!location.hash){var h=dev(P.location.hash);if(h)location.replace(h)} if(P){window.addEventListener('hashchange',function(){try{var h=location.hash;if(P.location.hash!==h&&!(h===''&&P.location.hash==='#'))P.location.hash=h}catch(x){}}); P.addEventListener('hashchange',function(){var h=dev(P.location.hash);if(h!==location.hash&&!(h===''&&location.hash==='#'))location.hash=h})} document.querySelectorAll('form[data-confirm]').forEach(function(f){f.addEventListener('submit',function(e){if(!confirm(f.dataset.confirm))e.preventDefault()})}); setInterval(function(){var a=document.activeElement;if(!a||a.tagName!=='INPUT')location.reload()},30000)})();` type vrow struct { Key, Name, Value string } type crow struct { Key, Name, Value, Unit, Level, Custodian string Min, Max, Step float64 Switch bool } type dview struct { Device KindText string Rows []vrow Controls []crow Level string Custodian string Status string Untested bool Applied string Rated bool // a heat pump or wallbox: the owner may enter its rating RatedKW string // its rating now (kW), "" none Reported bool // the device reports its power itself } type pview struct { T map[string]string Lang string OwnSKI, GridSKI string Backend string Grid Grid GridText, Until string Found, Paired []dview Events, Log []string Sim bool Version string Notice string // no consent to control, or the whole bridge read only AllReadOnly bool LPC string // the nominal power declared toward the control box, or why none (docs/parameters.md U3) LPCRefused bool } func fmtValue(s Spec, v any, lang string) string { switch x := v.(type) { case bool: if x { return texts[lang]["on"] } return texts[lang]["off"] case string: return x case float64: u := s.Unit if u == "Wh" { x, u = x/1000, "kWh" } out := strconv.FormatFloat(x, 'f', -1, 64) if x != float64(int64(x)) { out = strconv.FormatFloat(x, 'f', 2, 64) } if lang == "de" { out = strings.Replace(out, ".", ",", 1) } if u != "" { out += " " + u } return out } return fmt.Sprint(v) } func (p *Page) view(lang string) pview { devs, grid, events := p.core.Snapshot() t := texts[lang] pv := pview{T: t, Lang: lang, OwnSKI: p.core.backend.LocalSKI(), Backend: p.core.backend.Name(), Grid: grid, GridSKI: gridSKI(p.core.backend), Events: events, Log: p.core.store.Recent(20), Sim: p.sim != nil, Version: version} pv.GridText = t[grid.State] if w, missing := p.core.NominalW(); w > 0 { pv.LPC = strings.Replace(t["lpc_declared"], "{}", strconv.FormatFloat(w, 'f', 0, 64), 1) } else { pv.LPC, pv.LPCRefused = strings.Replace(t["lpc_refused"], "{}", NominalRefusal(w, missing), 1), true } pv.AllReadOnly = p.core.opts.ReadOnly if p.core.opts.NoControl { pv.Notice = t["no_control"] } else if p.core.opts.ReadOnly { pv.Notice = t["all_ro"] } if grid.State == "limited" { if grid.Until > 0 { pv.Until = t["limit_until"] + " " + time.Unix(grid.Until, 0).Local().Format("15:04") } else { pv.Until = t["until_changed"] } } for i := range devs { d := devs[i] dv := dview{Device: d, KindText: t["kind_"+firstNonEmpty(d.Kind, "other")], Status: t[d.State]} if dv.Status == "" { dv.Status = d.State } if !d.Paired { pv.Found = append(pv.Found, dv) continue } p.core.mu.Lock() dv.Level, dv.Custodian = p.core.Level(&d, "*") if d.Controllable() { dv.Rated = true if d.RatedW > 0 { dv.RatedKW = strconv.FormatFloat(d.RatedW/1000, 'f', -1, 64) } x := d x.RatedW = 0 _, dv.Reported = p.core.maxW(&x) } if pr := p.core.profiles[d.Profile]; pr != nil && pr.Status != "verified" { dv.Untested = true } p.core.mu.Unlock() keys := d.Keys() sort.SliceStable(keys, func(i, j int) bool { return catIndex(keys[i]) < catIndex(keys[j]) }) for _, k := range keys { s, ok := SpecFor(k) if !ok { continue } name := s.Name if lang == "de" && s.NameDE != "" { name = s.NameDE } val := fmtValue(s, d.Values[k], lang) if s.Write != nil { p.core.mu.Lock() lvl, cust := p.core.Level(&d, k) p.core.mu.Unlock() c := crow{Key: k, Name: name, Value: val, Unit: s.Unit, Level: lvl, Custodian: cust, Min: s.Write.Min, Max: s.Write.Max, Step: s.Write.Step, Switch: s.Write.Switch} if k == "limit" { if n, ok := d.Number("nominal_max"); ok && n > 0 { c.Max = n } } if k == "current_limit" { if n, ok := d.Number("current_max"); ok && n > 0 { c.Max = n } } dv.Controls = append(dv.Controls, c) continue } dv.Rows = append(dv.Rows, vrow{Key: k, Name: name, Value: val}) } pv.Paired = append(pv.Paired, dv) } return pv } // gridSKI: the identity the control box pairs with (EEBUS: its own; the // simulator and tests: the bridge's one). func gridSKI(b Backend) string { if g, ok := b.(interface{ GridSKI() string }); ok { return g.GridSKI() } return b.LocalSKI() } func catIndex(k string) int { for i, s := range Catalogue { if s.Key == k { return i } } return len(Catalogue) } var tmpl = template.Must(template.New("page").Funcs(template.FuncMap{ "tr": func(t map[string]string, k string, a ...any) string { s := t[k] for _, x := range a { s = strings.Replace(s, "{}", fmt.Sprint(x), 1) } return s }, "css": func() template.CSS { return template.CSS(css) }, "short": func(s string) string { if len(s) > 12 { return s[:12] + "…" } return s }, }).Parse(` {{.T.title}}

{{.T.title}}{{if .Sim}} {{.T.sim}}{{end}}

{{.T.intro}}

{{if .Notice}}
{{.Notice}}
{{end}}

{{.T.grid}}

{{if .Grid.ControlBox}}
{{.GridText}} {{if .Grid.Active}}{{printf "%.0f" .Grid.LimitW}} W {{.Until}}{{end}}
{{.T.sealed_note}}
{{else}}
{{.T.no_cb}}
{{end}}
{{.LPC}}
{{if .Sim}}
{{end}}
{{if .Found}}

{{.T.found}}

{{range .Found}}
{{.Name}} {{if eq .State "requesting"}}{{$.T.asking}}{{end}}{{.Brand}} {{.Model}} {{.Type}}
{{$.T.ski}}: {{.SKI}}
{{if eq .State "requesting"}}
{{end}}
{{end}}{{end}}

{{.T.paired}}

{{if not .Paired}}

{{.T.none}}

{{end}} {{range .Paired}}
{{.Name}}{{.KindText}} {{.Status}}{{if eq .Level "sealed"}}{{$.T.sealed}}{{end}}
{{.Brand}} {{.Model}}{{if .UseCases}} · {{range $i, $u := .UseCases}}{{if $i}}, {{end}}{{$u}}{{end}}{{end}}
{{end}}
{{.T.events}}
{{range .Events}}{{.}}
{{end}}
{{.T.log}}
{{range .Log}}{{.}}
{{end}}

{{.T.own_ski}}: {{.OwnSKI}}
{{.T.grid_ski}}: {{.GridSKI}}
{{.Backend}} · {{.Version}}

{{range .Paired}}

← {{$.T.back}}

{{.Name}}

{{.KindText}}{{.Status}} {{if or .ReadOnly $.AllReadOnly}}{{$.T.ro}}{{end}}{{if .Untested}}{{$.T.untested}}{{end}}
{{.Brand}} {{.Model}} · {{$.T.profile}}: {{.Profile}} · {{$.T.ski}}: {{.SKI}}
{{$.T.use_cases}}: {{range $i, $u := .UseCases}}{{if $i}}, {{end}}{{$u}}{{end}}
{{if .Rows}}

{{$.T.values}}

{{range .Rows}}{{end}}
{{.Name}}{{.Value}}
{{end}} {{if .Controls}}

{{$.T.controls}}

{{$d := .}}{{range .Controls}}{{end}}
{{.Name}}
{{.Value}}
{{if eq .Level "sealed"}}{{$.T.sealed}}{{else if eq .Level "protected"}}{{$.T.protected}}{{else}}{{$.T.lvl_none}}{{end}} {{if ne .Level "sealed"}}{{if .Switch}}
{{else}}
{{.Unit}}
{{end}} {{if eq .Level "protected"}}
{{else}}
{{end}}{{end}}
{{end}} {{if .Rated}}

{{$.T.rating}}

{{$.T.rating_note}}

kW
{{end}} {{if eq .Level "sealed"}}

{{$.T.sealed_note}} ({{$.T.custodian}}: {{.Custodian}})

{{else}}
{{end}}
{{end}} `)) func (p *Page) allowed(r *http.Request) bool { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return false } for _, x := range p.peers { if strings.TrimSpace(x) == host { return true } } return false } func (p *Page) who(r *http.Request) string { for _, h := range []string{"X-Remote-User-Display-Name", "X-Remote-User-Name"} { if v := r.Header.Get(h); v != "" { return v + " (the page)" } } if p.ha { return "a Home Assistant administrator (the page)" } return "the owner (the panel)" } func (p *Page) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !p.allowed(r) { http.Error(w, "forbidden", http.StatusForbidden) return } w.Header().Set("Cache-Control", "no-store") if strings.HasSuffix(r.URL.Path, "/page.js") { w.Header().Set("Content-Type", "text/javascript") _, _ = w.Write([]byte(pageJS)) return } if r.Method == http.MethodPost { p.post(w, r) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := tmpl.Execute(w, p.view(langOf(r.Header.Get("Accept-Language")))); err != nil { p.core.event("page: %v", err) } } func (p *Page) post(w http.ResponseWriter, r *http.Request) { _ = r.ParseForm() who := p.who(r) dev := r.FormValue("dev") var err error switch r.FormValue("action") { case "pair": err = p.core.Pair(r.FormValue("ski"), who) case "deny": err = p.core.Deny(r.FormValue("ski"), who) case "unpair": err = p.core.Unpair(dev, who) dev = "" case "protect": err = p.core.SetLevel(dev, r.FormValue("key"), r.FormValue("level"), who) case "command": _, err = p.core.Command(dev, r.FormValue("key"), r.FormValue("value"), who) case "rating": kw := 0.0 if v := strings.TrimSpace(r.FormValue("kw")); v != "" { if kw, err = strconv.ParseFloat(strings.Replace(v, ",", ".", 1), 64); err != nil { break } } err = p.core.SetRating(dev, kw*1000, who) case "sim_limit", "sim_end", "sim_hb_off", "sim_hb_on", "sim_plug": if p.sim == nil { err = errors.New("not simulating") break } switch r.FormValue("action") { case "sim_limit": p.sim.GridLimit(Para14aMinW, 15) // the simulated control box: §14a's minimum case "sim_end": p.sim.GridLimit(0, 0) case "sim_hb_off": p.sim.Heartbeat(false) case "sim_hb_on": p.sim.Heartbeat(true) case "sim_plug": p.sim.mu.Lock() in := !p.sim.dev(SimWallboxSKI).connected p.sim.mu.Unlock() p.sim.Plug(in) } } if err != nil { p.core.mu.Lock() p.core.event("page: %v", err) p.core.mu.Unlock() } loc := r.Header.Get("X-Ingress-Path") + "/" if !p.ha { loc = "./" } if dev != "" { loc += "#" + dev } http.Redirect(w, r, loc, http.StatusSeeOther) }