cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-10-30 08:26:45 +02:00
1 parent 343331d234
commit d5fbcacaa4
176 files changed
+32511 -19

No files matched your search

+570
View File
@@ -0,0 +1,570 @@
// 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"
"strings"
"sync"
"time"
eebusapi "github.com/enbility/eebus-go/api"
"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
grid *gridLink // the controllable system toward the control box, its own process (grid.go)
core *Core
ski, gridSKI string
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 { 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
}
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.core.Connected(ski, true)
}
func (r reader) RemoteSKIDisconnected(_ eebusapi.ServiceInterface, ski string) {
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
}
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.core.PairingRequest(ski)
case shipapi.ConnectionStateRemoteDeniedTrust:
r.e.core.Denied(ski)
}
}
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
}
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}, 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)
}
})
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, nil)
return err
}
// -- 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.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.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...)
}