831 lines
27 KiB
Go
831 lines
27 KiB
Go
// Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
|
|
|
package main
|
|
|
|
import (
|
|
"crypto/ecdsa"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"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"
|
|
"github.com/enbility/eebus-go/usecases/cem/evcem"
|
|
"github.com/enbility/eebus-go/usecases/cem/evsecc"
|
|
"github.com/enbility/eebus-go/usecases/cem/evsoc"
|
|
"github.com/enbility/eebus-go/usecases/cem/opev"
|
|
"github.com/enbility/eebus-go/usecases/cem/vabd"
|
|
"github.com/enbility/eebus-go/usecases/cem/vapd"
|
|
eglpc "github.com/enbility/eebus-go/usecases/eg/lpc"
|
|
"github.com/enbility/eebus-go/usecases/ma/mgcp"
|
|
"github.com/enbility/eebus-go/usecases/ma/mpc"
|
|
shipapi "github.com/enbility/ship-go/api"
|
|
"github.com/enbility/ship-go/cert"
|
|
"github.com/enbility/ship-go/mdns"
|
|
spineapi "github.com/enbility/spine-go/api"
|
|
"github.com/enbility/spine-go/model"
|
|
)
|
|
|
|
// EEBUS: the bridge as a CEM (energy management system) with enbility's
|
|
// eebus-go (SHIP and SPINE). Use cases:
|
|
//
|
|
// cs/lpc controllable system: receives the grid operator's limit from
|
|
// a control box (grid guard); writes are approved only from the
|
|
// paired control box's SKI
|
|
// eg/lpc energy guard toward heat pumps (Cantabile passes limits on)
|
|
// ma/mpc monitoring of power consumption (heat pumps, appliances)
|
|
// ma/mgcp monitoring of the grid connection point
|
|
// cem/evsecc, evcc, evcem, evsoc, opev wallboxes and the car
|
|
// cem/vapd, vabd PV and battery visibility (inverters)
|
|
//
|
|
// The certificate (and so the bridge's SKI) is made at the first start and
|
|
// kept in the data directory (eebus.crt, eebus.key).
|
|
type EEBUS struct {
|
|
dir, brand, model, serial string
|
|
port int
|
|
ifaces []string
|
|
mdnsSel mdns.MdnsProviderSelection
|
|
svc *service.Service // the energy manager toward the devices
|
|
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
|
|
onGrid map[string]bool // SKIs that asked the grid identity to pair
|
|
|
|
cslpc ucapi.CsLPCInterface
|
|
eglpc ucapi.EgLPCInterface
|
|
mpc ucapi.MaMPCInterface
|
|
mgcp ucapi.MaMGCPInterface
|
|
evsecc ucapi.CemEVSECCInterface
|
|
evcc ucapi.CemEVCCInterface
|
|
evcem ucapi.CemEVCEMInterface
|
|
evsoc ucapi.CemEVSOCInterface
|
|
opev ucapi.CemOPEVInterface
|
|
vapd ucapi.CemVAPDInterface
|
|
vabd ucapi.CemVABDInterface
|
|
}
|
|
|
|
func NewEEBUS(dir string, port int, serial string, ifaces []string, zeroconfOnly bool) *EEBUS {
|
|
sel := mdns.MdnsProviderSelectionAll
|
|
if zeroconfOnly {
|
|
sel = mdns.MdnsProviderSelectionGoZeroConfOnly
|
|
}
|
|
return &EEBUS{dir: dir, port: port, brand: "Cantabile", model: "Cantabile EEBUS bridge", serial: serial, ifaces: ifaces,
|
|
mdnsSel: sel, onGrid: map[string]bool{}}
|
|
}
|
|
|
|
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 {
|
|
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) {
|
|
return loadCert(dir, "eebus", serial)
|
|
}
|
|
|
|
func loadCert(dir, name, serial string) (tls.Certificate, string, error) {
|
|
crt, key := filepath.Join(dir, name+".crt"), filepath.Join(dir, name+".key")
|
|
c, err := tls.LoadX509KeyPair(crt, key)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
c, err = cert.CreateCertificate("Cantabile", "Setti Solutions", "DE", "Cantabile-"+name+"-"+serial)
|
|
if err != nil {
|
|
return c, "", err
|
|
}
|
|
k, err := x509.MarshalECPrivateKey(c.PrivateKey.(*ecdsa.PrivateKey))
|
|
if err != nil {
|
|
return c, "", err
|
|
}
|
|
if err := writeAtomic(key, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: k}), 0o600); err != nil {
|
|
return c, "", err
|
|
}
|
|
if err := writeAtomic(crt, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate[0]}), 0o644); err != nil {
|
|
return c, "", err
|
|
}
|
|
} else if err != nil {
|
|
return c, "", err
|
|
}
|
|
leaf, err := x509.ParseCertificate(c.Certificate[0])
|
|
if err != nil {
|
|
return c, "", err
|
|
}
|
|
ski, err := cert.SkiFromCertificate(leaf)
|
|
return c, ski, err
|
|
}
|
|
|
|
// newService: one EEBUS identity (SHIP service, SPINE device).
|
|
func (e *EEBUS) newService(name, devModel string, port int, reader eebusapi.ServiceReaderInterface) (*service.Service, string, error) {
|
|
crt, ski, err := loadCert(e.dir, name, e.serial)
|
|
if err != nil {
|
|
return nil, "", fmt.Errorf("certificate: %w", err)
|
|
}
|
|
conf, err := eebusapi.NewConfiguration("Cantabile", e.brand, devModel, e.serial,
|
|
model_EMS, []model.EntityTypeType{model.EntityTypeTypeCEM}, port, crt, 4*time.Second)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
conf.SetAlternateIdentifier("Cantabile-" + name + "-" + e.serial)
|
|
conf.SetMdnsProviderSelection(e.mdnsSel)
|
|
if len(e.ifaces) > 0 {
|
|
conf.SetInterfaces(e.ifaces)
|
|
}
|
|
svc := service.NewService(conf, reader)
|
|
svc.SetLogging(ebLog{})
|
|
if err := svc.Setup(); err != nil {
|
|
return nil, "", err
|
|
}
|
|
svc.UserIsAbleToApproveOrCancelPairingRequests(true)
|
|
return svc, ski, nil
|
|
}
|
|
|
|
const model_EMS = model.DeviceTypeTypeEnergyManagementSystem
|
|
|
|
// Start: two EEBUS identities. eebus-go v0.7.0 can't hold both of LPC's
|
|
// roles in one SPINE device: with the energy guard (eg/lpc, toward heat
|
|
// pumps) beside the controllable system (cs/lpc), a control box never
|
|
// reads the bridge's limit ("data not available"; reproduced with a
|
|
// minimal pair). And two SHIP services in one process mix up their
|
|
// certificates (ship-go v0.6.0: the control box was dialled with the
|
|
// other identity's). So the grid operator's control box pairs with the
|
|
// bridge's grid identity, a child process of this binary (grid.go: cs/lpc
|
|
// only, port P), the devices with the energy manager here (everything
|
|
// else, port P+1). The page shows both SKIs.
|
|
func (e *EEBUS) Start(c *Core) error {
|
|
e.core = c
|
|
var err error
|
|
if e.svc, e.ski, err = e.newService("eebus", e.model, e.port+1, reader{e, false}); err != nil {
|
|
return err
|
|
}
|
|
ent := e.svc.LocalDevice().EntityForType(model.EntityTypeTypeCEM)
|
|
e.eglpc = eglpc.NewLPC(ent, e.onEvent)
|
|
e.mpc = mpc.NewMPC(ent, e.onEvent)
|
|
e.mgcp = mgcp.NewMGCP(ent, e.onEvent)
|
|
e.evsecc = evsecc.NewEVSECC(ent, e.onEvent)
|
|
e.evcc = evcc.NewEVCC(e.svc, ent, e.onEvent)
|
|
e.evcem = evcem.NewEVCEM(e.svc, ent, e.onEvent)
|
|
e.evsoc = evsoc.NewEVSOC(ent, e.onEvent)
|
|
e.opev = opev.NewOPEV(ent, e.onEvent)
|
|
e.vapd = vapd.NewVAPD(ent, e.onEvent)
|
|
e.vabd = vabd.NewVABD(ent, e.onEvent)
|
|
for _, uc := range []eebusapi.UseCaseInterface{e.eglpc, e.mpc, e.mgcp, e.evsecc, e.evcc, e.evcem, e.evsoc, e.opev, e.vapd, e.vabd} {
|
|
e.svc.AddUseCase(uc)
|
|
}
|
|
grid := []string{}
|
|
for ski, d := range c.store.Devices {
|
|
if !d.Paired {
|
|
continue
|
|
}
|
|
if d.Kind == KindControlBox {
|
|
grid = append(grid, ski)
|
|
} else {
|
|
e.svc.RegisterRemoteSKI(ski)
|
|
}
|
|
}
|
|
if e.grid, err = startGrid(e, grid); err != nil {
|
|
return err
|
|
}
|
|
// the declared nominal power follows the devices (core.nominalChanged)
|
|
gl := e.grid
|
|
e.core.mu.Lock()
|
|
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)
|
|
go e.poll()
|
|
return nil
|
|
}
|
|
|
|
// serviceFor: the identity a device pairs with: the grid's for the control
|
|
// box (or a device that asked the grid identity), else the devices'.
|
|
func (e *EEBUS) onGridIdentity(ski, kind string) bool {
|
|
e.mu.Lock()
|
|
asked := e.onGrid[strings.ToLower(ski)]
|
|
e.mu.Unlock()
|
|
return kind == KindControlBox || asked
|
|
}
|
|
|
|
// reader: eebus-go's callbacks of one identity.
|
|
type reader struct {
|
|
e *EEBUS
|
|
grid bool
|
|
}
|
|
|
|
func (r reader) RemoteSKIConnected(_ eebusapi.ServiceInterface, ski string) {
|
|
r.e.async(ski, func() { r.e.core.Connected(ski, true) })
|
|
}
|
|
func (r reader) RemoteSKIDisconnected(_ eebusapi.ServiceInterface, ski string) {
|
|
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()) {
|
|
continue // the bridge's other identity
|
|
}
|
|
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) {
|
|
switch detail.State() {
|
|
case shipapi.ConnectionStateReceivedPairingRequest:
|
|
if r.grid {
|
|
r.e.mu.Lock()
|
|
r.e.onGrid[strings.ToLower(ski)] = true
|
|
r.e.mu.Unlock()
|
|
}
|
|
r.e.async(ski, func() { r.e.core.PairingRequest(ski) })
|
|
case shipapi.ConnectionStateRemoteDeniedTrust:
|
|
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})
|
|
return nil
|
|
}
|
|
e.svc.RegisterRemoteSKI(ski)
|
|
return nil
|
|
}
|
|
|
|
func (e *EEBUS) Unpair(ski string) error {
|
|
e.svc.UnregisterRemoteSKI(ski)
|
|
e.svc.DisconnectSKI(ski, "unpaired by the owner")
|
|
e.grid.send(gridMsg{Cmd: "unpair", SKI: ski})
|
|
return nil
|
|
}
|
|
|
|
func (e *EEBUS) Deny(ski string) error {
|
|
if e.onGridIdentity(ski, "") {
|
|
e.grid.send(gridMsg{Cmd: "deny", SKI: ski})
|
|
return nil
|
|
}
|
|
e.svc.CancelPairingWithSKI(ski)
|
|
return nil
|
|
}
|
|
|
|
// entityOf: the device's entity offering a use case, on its live
|
|
// connection. When both sides connect at once SHIP keeps one connection;
|
|
// eebus-go v0.7.0 then still lists the dropped connection's entity, which
|
|
// answers nothing ("data not available"): the one of the device SPINE
|
|
// knows now wins (found by TestSHIPControlBoxAndHeatPump).
|
|
func entityOf(uc eebusapi.UseCaseInterface, ski string, live spineapi.DeviceRemoteInterface) spineapi.EntityRemoteInterface {
|
|
if uc == nil {
|
|
return nil
|
|
}
|
|
var found spineapi.EntityRemoteInterface
|
|
for _, r := range uc.RemoteEntitiesScenarios() {
|
|
if r.Entity == nil || r.Entity.Device() == nil || !strings.EqualFold(r.Entity.Device().Ski(), ski) {
|
|
continue
|
|
}
|
|
if live != nil && r.Entity.Device() == live {
|
|
return r.Entity
|
|
}
|
|
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
|
|
}
|
|
|
|
func (e *EEBUS) entity(uc eebusapi.UseCaseInterface, ski string) spineapi.EntityRemoteInterface {
|
|
return entityOf(uc, ski, e.svc.LocalDevice().RemoteDeviceForSki(ski))
|
|
}
|
|
|
|
func (e *EEBUS) WriteLimit(d *Device, watts float64, active bool) error {
|
|
ent := e.entity(e.eglpc, d.SKI)
|
|
if ent == nil {
|
|
return fmt.Errorf("%s offers no LPC", d.Name)
|
|
}
|
|
_, err := e.eglpc.WriteConsumptionLimit(ent, ucapi.LoadLimit{Value: watts, IsActive: active},
|
|
e.onRefusal(d, fmt.Sprintf("the limit %.0f W", watts), ent))
|
|
return err
|
|
}
|
|
|
|
func (e *EEBUS) WriteCurrent(d *Device, amps float64) error {
|
|
ent := e.entity(e.opev, d.SKI)
|
|
if ent == nil {
|
|
return fmt.Errorf("%s offers no OPEV", d.Name)
|
|
}
|
|
phases := []model.ElectricalConnectionPhaseNameType{model.ElectricalConnectionPhaseNameTypeA,
|
|
model.ElectricalConnectionPhaseNameTypeB, model.ElectricalConnectionPhaseNameTypeC}
|
|
limits := []ucapi.LoadLimitsPhase{}
|
|
for _, p := range phases {
|
|
limits = append(limits, ucapi.LoadLimitsPhase{Phase: p, IsActive: true, Value: amps})
|
|
}
|
|
_, 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) {
|
|
e.later(ski)
|
|
}
|
|
|
|
// later: a refresh off eebus-go's own goroutine. Its events come while SPINE
|
|
// handles a message; reading the use cases' data there (and the core's lock
|
|
// behind it) held SPINE's message handling, and a control box's first
|
|
// requests went unanswered (TestSHIPControlBoxAndHeatPump). Several events
|
|
// in a row make one refresh.
|
|
func (e *EEBUS) later(ski string) {
|
|
ski = strings.ToLower(ski)
|
|
e.pmu.Lock()
|
|
if e.pending == nil {
|
|
e.pending = map[string]bool{}
|
|
}
|
|
if e.pending[ski] {
|
|
e.pmu.Unlock()
|
|
return
|
|
}
|
|
e.pending[ski] = true
|
|
e.pmu.Unlock()
|
|
go func() {
|
|
time.Sleep(200 * time.Millisecond)
|
|
e.pmu.Lock()
|
|
delete(e.pending, ski)
|
|
e.pmu.Unlock()
|
|
e.guard(ski, "reading", func() { e.refresh(ski) })
|
|
}()
|
|
}
|
|
|
|
// poll: the control box's heartbeat and the failsafe timers need a look
|
|
// even when nothing happens.
|
|
func (e *EEBUS) poll() {
|
|
for range time.Tick(5 * time.Second) {
|
|
if ski := e.core.ControlBoxSKI(); 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) })
|
|
}
|
|
}
|
|
}
|
|
|
|
// refresh: everything the device's use cases give now, as the catalogue's
|
|
// keys.
|
|
func (e *EEBUS) refresh(ski string) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
ucs, vals := Read(e.useCases(), ski, e.core.IsControlBox(ski))
|
|
if len(ucs) > 0 || len(vals) > 0 {
|
|
e.core.Update(ski, ucs, vals)
|
|
}
|
|
}
|
|
|
|
func (e *EEBUS) useCases() UseCases {
|
|
return UseCases{CSLPC: e.cslpc, EGLPC: e.eglpc, MPC: e.mpc, MGCP: e.mgcp, EVSECC: e.evsecc, EVCC: e.evcc,
|
|
EVCEM: e.evcem, EVSOC: e.evsoc, OPEV: e.opev, VAPD: e.vapd, VABD: e.vabd,
|
|
Entity: e.entity}
|
|
}
|
|
|
|
// UseCases: the use case interfaces Read takes (eebus-go's, or its mocks in
|
|
// the tests).
|
|
type UseCases struct {
|
|
CSLPC ucapi.CsLPCInterface
|
|
EGLPC ucapi.EgLPCInterface
|
|
MPC ucapi.MaMPCInterface
|
|
MGCP ucapi.MaMGCPInterface
|
|
EVSECC ucapi.CemEVSECCInterface
|
|
EVCC ucapi.CemEVCCInterface
|
|
EVCEM ucapi.CemEVCEMInterface
|
|
EVSOC ucapi.CemEVSOCInterface
|
|
OPEV ucapi.CemOPEVInterface
|
|
VAPD ucapi.CemVAPDInterface
|
|
VABD ucapi.CemVABDInterface
|
|
Entity func(uc eebusapi.UseCaseInterface, ski string) spineapi.EntityRemoteInterface
|
|
}
|
|
|
|
func sum(xs []float64) float64 {
|
|
t := 0.0
|
|
for _, x := range xs {
|
|
t += x
|
|
}
|
|
return t
|
|
}
|
|
|
|
// Read: (use cases, values) a device gives now, in Cantabile's units and
|
|
// signs. controlBox: the device is the paired control box (cs/lpc's limit
|
|
// is the bridge's own, written by it).
|
|
func Read(u UseCases, ski string, controlBox bool) ([]string, map[string]any) {
|
|
ucs := []string{}
|
|
v := map[string]any{}
|
|
ent := func(uc eebusapi.UseCaseInterface) spineapi.EntityRemoteInterface {
|
|
if uc == nil || u.Entity == nil {
|
|
return nil
|
|
}
|
|
return u.Entity(uc, ski)
|
|
}
|
|
if controlBox && u.CSLPC != nil {
|
|
ucs = append(ucs, "LPC-CB")
|
|
if l, err := u.CSLPC.ConsumptionLimit(); err == nil {
|
|
v["grid_limit"], v["grid_limit_active"] = l.Value, l.IsActive
|
|
v["_limit_duration"] = l.Duration.Seconds()
|
|
}
|
|
if w, _, err := u.CSLPC.FailsafeConsumptionActivePowerLimit(); err == nil {
|
|
v["failsafe_limit"] = w
|
|
}
|
|
if d, _, err := u.CSLPC.FailsafeDurationMinimum(); err == nil {
|
|
v["failsafe_duration"] = d.Minutes()
|
|
}
|
|
v["heartbeat"] = u.CSLPC.IsHeartbeatWithinDuration()
|
|
}
|
|
if e := ent(u.MGCP); e != nil {
|
|
ucs = append(ucs, "MGCP")
|
|
if x, err := u.MGCP.Power(e); err == nil {
|
|
v["grid_power"] = x // EEBUS: + is drawn from the grid, as Cantabile's grid.power
|
|
}
|
|
if x, err := u.MGCP.EnergyConsumed(e); err == nil {
|
|
v["grid_import_energy"] = x
|
|
}
|
|
if x, err := u.MGCP.EnergyFeedIn(e); err == nil {
|
|
v["grid_export_energy"] = x
|
|
}
|
|
if x, err := u.MGCP.PowerLimitationFactor(e); err == nil {
|
|
v["feed_in_factor"] = x
|
|
}
|
|
}
|
|
if e := ent(u.MPC); e != nil {
|
|
ucs = append(ucs, "MPC")
|
|
if x, err := u.MPC.Power(e); err == nil {
|
|
v["power"] = x
|
|
}
|
|
if x, err := u.MPC.EnergyConsumed(e); err == nil {
|
|
v["energy"] = x
|
|
}
|
|
}
|
|
if e := ent(u.EGLPC); e != nil {
|
|
ucs = append(ucs, "LPC-EG")
|
|
if l, err := u.EGLPC.ConsumptionLimit(e); err == nil {
|
|
v["limit"], v["limit_active"] = l.Value, l.IsActive
|
|
}
|
|
if x, err := u.EGLPC.ConsumptionNominalMax(e); err == nil {
|
|
v["nominal_max"] = x
|
|
}
|
|
}
|
|
if e := ent(u.EVSECC); e != nil {
|
|
ucs = append(ucs, "EVSECC")
|
|
if st, _, err := u.EVSECC.OperatingState(e); err == nil {
|
|
v["evse_state"] = string(st)
|
|
}
|
|
}
|
|
if e := ent(u.EVCC); e != nil {
|
|
ucs = append(ucs, "EVCC")
|
|
v["ev_connected"] = u.EVCC.EVConnected(e)
|
|
if st, err := u.EVCC.ChargeState(e); err == nil {
|
|
v["charge_state"] = string(st)
|
|
}
|
|
} else if u.EVCC != nil && ent(u.EVSECC) != nil {
|
|
v["ev_connected"] = false
|
|
}
|
|
if e := ent(u.EVSOC); e != nil {
|
|
ucs = append(ucs, "EVSOC")
|
|
if x, err := u.EVSOC.StateOfCharge(e); err == nil {
|
|
v["ev_soc"] = x
|
|
}
|
|
}
|
|
if e := ent(u.EVCEM); e != nil {
|
|
ucs = append(ucs, "EVCEM")
|
|
if x, err := u.EVCEM.PowerPerPhase(e); err == nil {
|
|
v["charge_power"] = sum(x)
|
|
}
|
|
if x, err := u.EVCEM.EnergyCharged(e); err == nil {
|
|
v["charged_energy"] = x
|
|
}
|
|
if x, err := u.EVCEM.PhasesConnected(e); err == nil && x > 0 {
|
|
v["phases"] = float64(x)
|
|
}
|
|
}
|
|
if e := ent(u.OPEV); e != nil {
|
|
ucs = append(ucs, "OPEV")
|
|
if mins, maxs, _, err := u.OPEV.CurrentLimits(e); err == nil && len(maxs) > 0 {
|
|
v["current_min"], v["current_max"] = mins[0], maxs[0]
|
|
}
|
|
if ls, err := u.OPEV.LoadControlLimits(e); err == nil && len(ls) > 0 {
|
|
v["current_limit"] = ls[0].Value
|
|
}
|
|
}
|
|
if e := ent(u.VAPD); e != nil {
|
|
ucs = append(ucs, "VAPD")
|
|
if x, err := u.VAPD.Power(e); err == nil {
|
|
v["pv_power"] = x
|
|
}
|
|
if x, err := u.VAPD.PVYieldTotal(e); err == nil {
|
|
v["pv_energy"] = x
|
|
}
|
|
if x, err := u.VAPD.PowerNominalPeak(e); err == nil {
|
|
v["pv_peak"] = x
|
|
}
|
|
}
|
|
if e := ent(u.VABD); e != nil {
|
|
ucs = append(ucs, "VABD")
|
|
if x, err := u.VABD.Power(e); err == nil {
|
|
v["battery_power"] = x // EEBUS: + charging (consumption), as Cantabile's battery.power
|
|
}
|
|
if x, err := u.VABD.StateOfCharge(e); err == nil {
|
|
v["battery_soc"] = x
|
|
}
|
|
if x, err := u.VABD.EnergyCharged(e); err == nil {
|
|
v["battery_charge_energy"] = x
|
|
}
|
|
if x, err := u.VABD.EnergyDischarged(e); err == nil {
|
|
v["battery_discharge_energy"] = x
|
|
}
|
|
}
|
|
return ucs, v
|
|
}
|
|
|
|
// ebLog: eebus-go's log through ours (debug and trace left out).
|
|
type ebLog struct{}
|
|
|
|
func (ebLog) Trace(...interface{}) {}
|
|
func (ebLog) Tracef(string, ...interface{}) {}
|
|
func (ebLog) Debug(a ...interface{}) {
|
|
if os.Getenv("EBDEBUG") != "" {
|
|
log.Print(append([]interface{}{"eebus debug: "}, a...)...)
|
|
}
|
|
}
|
|
func (ebLog) Debugf(f string, a ...interface{}) {
|
|
if os.Getenv("EBDEBUG") != "" {
|
|
log.Printf("eebus debug: "+f, a...)
|
|
}
|
|
}
|
|
func (ebLog) Info(a ...interface{}) { log.Print(append([]interface{}{"eebus: "}, a...)...) }
|
|
func (ebLog) Infof(f string, a ...interface{}) {
|
|
log.Printf("eebus: "+f, a...)
|
|
}
|
|
func (ebLog) Error(a ...interface{}) { log.Print(append([]interface{}{"eebus error: "}, a...)...) }
|
|
func (ebLog) Errorf(f string, a ...interface{}) {
|
|
log.Printf("eebus error: "+f, a...)
|
|
}
|