cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.2148: EEBUS bridge 0.1.2 (connection and grid-limit fixes); full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-13 23:39:25 +00:00
1 parent b3dfc9bb68
commit 87e4a42274
387 files changed
+66823 -127

No files matched your search

+276 -21
View File
@@ -12,11 +12,14 @@ import (
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"unicode"
eebusapi "github.com/enbility/eebus-go/api"
"github.com/enbility/eebus-go/features/client"
"github.com/enbility/eebus-go/service"
ucapi "github.com/enbility/eebus-go/usecases/api"
"github.com/enbility/eebus-go/usecases/cem/evcc"
@@ -56,9 +59,18 @@ type EEBUS struct {
ifaces []string
mdnsSel mdns.MdnsProviderSelection
svc *service.Service // the energy manager toward the devices
grid *gridLink // the controllable system toward the control box, its own process (grid.go)
qmu sync.Mutex // the callback queue (async)
queue []func()
qrun bool
grid *gridLink // the controllable system toward the control box, its own process (grid.go)
core *Core
ski, gridSKI string
smu sync.Mutex // gridSKI (set when the grid identity's child reports it)
bmu sync.Mutex // bound
bound map[string]time.Time // binding requests sent again, by SKI and feature (bindDue)
bindFails map[string]bindFailure // binding requests not sent, by SKI and feature (bindFailed)
drop func(ski string) // drops a device's connection after a panic (nil: disconnect; tests)
panics panicLog // contained panics (panics.go)
mu sync.Mutex
pmu sync.Mutex
pending map[string]bool
@@ -90,7 +102,11 @@ func (e *EEBUS) Name() string { return "eebus" }
func (e *EEBUS) LocalSKI() string { return e.ski }
// GridSKI: the identity the grid operator's control box pairs with.
func (e *EEBUS) GridSKI() string { return e.gridSKI }
func (e *EEBUS) GridSKI() string {
e.smu.Lock()
defer e.smu.Unlock()
return e.gridSKI
}
// LoadCertificate: the bridge's own (name: "eebus" or "eebus-grid"), made once.
func LoadCertificate(dir, serial string) (tls.Certificate, string, error) {
@@ -203,7 +219,7 @@ func (e *EEBUS) Start(c *Core) error {
e.core.OnNominal = func(w float64) { gl.send(gridMsg{Cmd: "nominal", W: w}) }
e.core.mu.Unlock()
e.svc.Start()
log.Printf("EEBUS: devices SKI %s (port %d), grid SKI %s (port %d)", e.ski, e.port+1, e.gridSKI, e.port)
log.Printf("EEBUS: devices SKI %s (port %d), grid SKI %s (port %d)", e.ski, e.port+1, e.GridSKI(), e.port)
go e.poll()
return nil
}
@@ -224,18 +240,20 @@ type reader struct {
}
func (r reader) RemoteSKIConnected(_ eebusapi.ServiceInterface, ski string) {
r.e.core.Connected(ski, true)
r.e.async(ski, func() { r.e.core.Connected(ski, true) })
}
func (r reader) RemoteSKIDisconnected(_ eebusapi.ServiceInterface, ski string) {
r.e.core.Connected(ski, false)
r.e.forgetBindings(ski) // (not the panics' back-off: a renewed connection must not restart it)
r.e.async(ski, func() { r.e.core.Connected(ski, false) })
}
func (r reader) ServiceShipIDUpdate(string, string) {}
func (r reader) VisibleRemoteServicesUpdated(_ eebusapi.ServiceInterface, entries []shipapi.RemoteService) {
for _, s := range entries {
if strings.EqualFold(s.Ski, r.e.ski) || strings.EqualFold(s.Ski, r.e.gridSKI) {
if strings.EqualFold(s.Ski, r.e.ski) || strings.EqualFold(s.Ski, r.e.GridSKI()) {
continue // the bridge's other identity
}
r.e.core.Seen(s.Ski, s.Brand, s.Model, s.Type, s.Name)
s := s
r.e.async(s.Ski, func() { r.e.core.Seen(s.Ski, s.Brand, s.Model, s.Type, s.Name) })
}
}
func (r reader) ServicePairingDetailUpdate(ski string, detail *shipapi.ConnectionStateDetail) {
@@ -246,12 +264,55 @@ func (r reader) ServicePairingDetailUpdate(ski string, detail *shipapi.Connectio
r.e.onGrid[strings.ToLower(ski)] = true
r.e.mu.Unlock()
}
r.e.core.PairingRequest(ski)
r.e.async(ski, func() { r.e.core.PairingRequest(ski) })
case shipapi.ConnectionStateRemoteDeniedTrust:
r.e.core.Denied(ski)
r.e.async(ski, func() { r.e.core.Denied(ski) })
}
}
// async: what the library reports reaches the core in order, but on the
// bridge's own goroutine. The core holds its lock while it writes to a
// device through the library (passOn); the library's callbacks run inside
// its own locks (ship-go's per-connection sync.Once on a close), so a
// callback that waited for the core's lock made a deadlock: the writer
// waited for the Once, the Once's holder for the core (the hang of CI run
// 709ea10b, 2026-11-13). Each runs guarded for its device (guard).
func (e *EEBUS) async(ski string, f func()) {
e.qmu.Lock()
e.queue = append(e.queue, func() { e.guard(ski, "a library callback", f) })
start := !e.qrun
e.qrun = true
e.qmu.Unlock()
if !start {
return
}
go func() {
for {
e.qmu.Lock()
if len(e.queue) == 0 {
e.qrun = false
e.qmu.Unlock()
return
}
f := e.queue[0]
e.queue = e.queue[1:]
e.qmu.Unlock()
f()
}
}()
}
// disconnect: drop a device's connection after a panic (itself guarded: a
// broken connection must not take the bridge down either).
func (e *EEBUS) disconnect(ski string) {
defer func() {
if r := recover(); r != nil {
log.Printf("EEBUS: dropping %s panicked: %v", ski, r)
}
}()
e.svc.DisconnectSKI(ski, "internal error")
}
func (e *EEBUS) Pair(ski, kind string) error {
if e.onGridIdentity(ski, kind) {
e.grid.send(gridMsg{Cmd: "pair", SKI: ski})
@@ -296,6 +357,14 @@ func entityOf(uc eebusapi.UseCaseInterface, ski string, live spineapi.DeviceRemo
}
found = r.Entity // the newest when SPINE knows none
}
// only a dropped connection's entity is listed (the use case hasn't seen
// the live connection's yet): the live device's entity at the same
// address. Writes to the dropped one go nowhere, without an error.
if found != nil && live != nil && found.Device() != live && found.Address() != nil {
if e := live.Entity(found.Address().Entity); e != nil {
return e
}
}
return found
}
@@ -308,15 +377,8 @@ func (e *EEBUS) WriteLimit(d *Device, watts float64, active bool) error {
if ent == nil {
return fmt.Errorf("%s offers no LPC", d.Name)
}
_, err := e.eglpc.WriteConsumptionLimit(ent, ucapi.LoadLimit{Value: watts, IsActive: active}, func(r model.ResultDataType) {
if r.ErrorNumber != nil && *r.ErrorNumber != model.ErrorNumberTypeNoError {
desc := ""
if r.Description != nil {
desc = string(*r.Description)
}
log.Printf("%s refused the limit %.0f W: %s", d.Name, watts, desc)
}
})
_, err := e.eglpc.WriteConsumptionLimit(ent, ucapi.LoadLimit{Value: watts, IsActive: active},
e.onRefusal(d, fmt.Sprintf("the limit %.0f W", watts), ent))
return err
}
@@ -331,10 +393,199 @@ func (e *EEBUS) WriteCurrent(d *Device, amps float64) error {
for _, p := range phases {
limits = append(limits, ucapi.LoadLimitsPhase{Phase: p, IsActive: true, Value: amps})
}
_, err := e.opev.WriteLoadControlLimits(ent, limits, nil)
_, err := e.opev.WriteLoadControlLimits(ent, limits, e.onRefusal(d, fmt.Sprintf("the current %.0f A", amps), ent))
return err
}
// onRefusal: the result callback of a write to a device's LoadControl
// server (an LPC limit, an OPEV current): a refusal is logged; one for a
// missing binding requests the binding again (bind), and the core's next
// check writes the value again (Core.checkPassedOn).
func (e *EEBUS) onRefusal(d *Device, what string, ent spineapi.EntityRemoteInterface) func(model.ResultDataType) {
return func(r model.ResultDataType) {
if r.ErrorNumber == nil || *r.ErrorNumber == model.ErrorNumberTypeNoError {
return
}
desc := ""
if r.Description != nil {
desc = string(*r.Description)
}
log.Printf("%s refused %s: %s", d.Name, what, desc)
if bindingMissing(r) {
go e.bind(d.SKI, ent)
}
}
}
// bindingMissing: the refusal for a missing binding: its error number;
// spine-go's text ("write denied due to missing binding", sent as a general
// error); or another stack's general error that names the binding and is a
// refusal (any case: "Binding required", "not bound", "write refused: no
// binding"), not just any text with "binding" in it.
func bindingMissing(r model.ResultDataType) bool {
if *r.ErrorNumber == model.ErrorNumberTypeBindingIsNecessaryForThisCommand {
return true
}
if r.Description == nil {
return false
}
desc := strings.ToLower(string(*r.Description))
if strings.Contains(desc, "denied due to missing binding") {
return true
}
if *r.ErrorNumber != model.ErrorNumberTypeGeneralError {
return false
}
// whole words only: "out of bounds" is a value's refusal, not a binding's
words := strings.FieldsFunc(desc, func(r rune) bool { return !unicode.IsLetter(r) })
has := func(w string) bool { return slices.Contains(words, w) }
phrase := func(a, b string) bool {
for i := 0; i+1 < len(words); i++ {
if words[i] == a && words[i+1] == b {
return true
}
}
return false
}
if has("unbound") || phrase("not", "bound") || phrase("no", "binding") || phrase("without", "binding") {
return true
}
if !has("binding") && !has("bindings") {
return false
}
for _, w := range []string{"denied", "refused", "rejected", "missing", "required", "necessary", "needed"} {
if has(w) {
return true
}
}
return false
}
// BindRetryMin: the shortest time between two binding requests to the same
// feature of a device (a device that refuses each write would otherwise get
// one per refused write).
const BindRetryMin = 30 * time.Second
// bind: request the binding to the device's LoadControl server again, at
// most once per BindRetryMin per device and feature. The bridge's own
// record says it is bound (eebus-go binds once per entity), but the device
// lost the binding: it was made on a connection that SHIP replaced, or the
// device removed it with the dropped side of a double connection. The
// device then refuses every write ("write denied due to missing binding")
// until a new binding request.
func (e *EEBUS) bind(ski string, ent spineapi.EntityRemoteInterface) {
e.guard(ski, "binding", func() {
path := entityPath(ent)
// the slot is held while the request is made (no second at once),
// and kept only if it was sent
if !e.bindDue(ski, path, time.Now()) {
return
}
lc, err := client.NewLoadControl(e.svc.LocalDevice().EntityForType(model.EntityTypeTypeCEM), ent)
if err == nil {
_, err = lc.Bind()
}
if err != nil {
e.bindFailed(ski, path, time.Now(), err)
return
}
e.bindSent(ski, path)
log.Printf("EEBUS: %s lost its binding: requested again", ski)
})
}
// entityPath: the entity's address within its device ("1.2"), the same for
// the entity of a connection and of its successor (not the pointer).
func entityPath(ent spineapi.EntityRemoteInterface) string {
if ent == nil || ent.Address() == nil {
return ""
}
parts := []string{}
for _, a := range ent.Address().Entity {
parts = append(parts, fmt.Sprint(uint(a)))
}
return strings.Join(parts, ".")
}
// forgetBindings: a device's binding requests (its connection ended: the
// next connection binds as new).
func (e *EEBUS) forgetBindings(ski string) {
e.bmu.Lock()
defer e.bmu.Unlock()
prefix := strings.ToLower(ski) + " "
for k := range e.bound {
if strings.HasPrefix(k, prefix) {
delete(e.bound, k)
}
}
for k := range e.bindFails {
if strings.HasPrefix(k, prefix) {
delete(e.bindFails, k)
}
}
}
// BindFailMax: the longest wait after binding requests that couldn't be
// sent (BindRetryMin, doubling up to it).
const BindFailMax = 10 * time.Minute
// bindFailure: requests to one device's feature that couldn't be sent.
type bindFailure struct {
n int
next time.Time
}
// bindFailed: the request wasn't sent (the client couldn't be made, or the
// request not written): its slot freed, and a back-off for this device and
// feature (BindRetryMin, doubling up to BindFailMax) so a lasting failure
// isn't retried on every refused write; logged once per step.
func (e *EEBUS) bindFailed(ski, feature string, now time.Time, err error) {
e.bmu.Lock()
defer e.bmu.Unlock()
key := strings.ToLower(ski) + " " + feature
delete(e.bound, key)
if e.bindFails == nil {
e.bindFails = map[string]bindFailure{}
}
f := e.bindFails[key]
wait := BindRetryMin << f.n
if wait > BindFailMax || wait <= 0 {
wait = BindFailMax
}
f.n++
f.next = now.Add(wait)
e.bindFails[key] = f
log.Printf("EEBUS: binding to %s (%s) not sent (%v): next try after %s", ski, feature, err, wait)
}
// bindDue: whether a binding request to this device's feature may go out
// now (one in flight, sent less than BindRetryMin ago, or within a failure's
// back-off: not); true takes the slot (bindFailed frees it, bindSent keeps
// it and ends a failure's back-off).
func (e *EEBUS) bindDue(ski, feature string, now time.Time) bool {
e.bmu.Lock()
defer e.bmu.Unlock()
if e.bound == nil {
e.bound = map[string]time.Time{}
}
key := strings.ToLower(ski) + " " + feature
if last, ok := e.bound[key]; ok && now.Sub(last) < BindRetryMin {
return false
}
if f, ok := e.bindFails[key]; ok && now.Before(f.next) {
return false
}
e.bound[key] = now
return true
}
// bindSent: the request went out: a failure's back-off ends.
func (e *EEBUS) bindSent(ski, feature string) {
e.bmu.Lock()
defer e.bmu.Unlock()
delete(e.bindFails, strings.ToLower(ski)+" "+feature)
}
// -- eebus-go's callbacks ----------------------------------------------------
func (e *EEBUS) onEvent(ski string, _ spineapi.DeviceRemoteInterface, _ spineapi.EntityRemoteInterface, _ eebusapi.EventType) {
@@ -363,7 +614,7 @@ func (e *EEBUS) later(ski string) {
e.pmu.Lock()
delete(e.pending, ski)
e.pmu.Unlock()
e.refresh(ski)
e.guard(ski, "reading", func() { e.refresh(ski) })
}()
}
@@ -372,7 +623,11 @@ func (e *EEBUS) later(ski string) {
func (e *EEBUS) poll() {
for range time.Tick(5 * time.Second) {
if ski := e.core.ControlBoxSKI(); ski != "" {
e.refresh(ski)
e.guard(ski, "reading", func() { e.refresh(ski) })
}
// the devices holding the grid limit: one that lost it gets it again (Core.checkPassedOn)
for _, ski := range e.core.PassedOnSKIs() {
e.guard(ski, "reading", func() { e.refresh(ski) })
}
}
}