cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.629: full source
This commit is contained in:
1 parent
d5fbcacaa4
commit
85edd56ec8
46 files changed
+3518
-267
No files matched your search
@@ -4,8 +4,10 @@ package main
|
||||
|
||||
// Data bundles for the agent (data only, never code that runs):
|
||||
// tariffs (prices for the next 48 h), models (the forecasts' data), a
|
||||
// building box's flats and the devices' protection (acl: it
|
||||
// never expires; a newer one replaces it). Fleet
|
||||
// building box's flats, the devices' protection (acl: it
|
||||
// never expires; a newer one replaces it) and the shadow market's values
|
||||
// for the box's own nodes (market, the market's step 1.5: shown in HA, never
|
||||
// a command). Fleet
|
||||
// sends one as a signed command, `tariff` or `model`, with args
|
||||
// {"bundle": base64 of the bundle's JSON bytes, "sig": base64 of their
|
||||
// signature with the BUNDLE key}. The command itself is checked with the
|
||||
@@ -84,7 +86,7 @@ func checkBundle(key crypto.PublicKey, kind, site string, args map[string]string
|
||||
return data, h, nil
|
||||
}
|
||||
|
||||
// bundleCmd: a `tariff`, `model` or `flats` command (already checked as a
|
||||
// bundleCmd: a `tariff`, `model`, `flats`, `acl` or `market` command (already checked as a
|
||||
// command); flats: a building's own box gets its flats for Home Assistant.
|
||||
func (l *link) bundleCmd(c command, now time.Time) (bool, string) {
|
||||
key, err := l.bundleCert()
|
||||
|
||||
@@ -118,6 +118,30 @@ func TestBundles(t *testing.T) {
|
||||
if ok, _ := l.bundleCmd(cmd("acl", bundleArgs(t, k, acl)), now); ok {
|
||||
t.Error("another site's acl stored")
|
||||
}
|
||||
// the shadow market (step 1.5): for this site only, signed with the bundle key, newest kept
|
||||
market := func(id string, issued int64, site string) map[string]any {
|
||||
return map[string]any{"v": 1, "kind": "market", "id": id, "site": site, "issued": issued, "expires": now.Add(6 * time.Hour).Unix(),
|
||||
"shadow": true, "commands": "none", "contracts": []map[string]any{{"id": "k1", "direction": "sells"}}}
|
||||
}
|
||||
if ok, msg := l.bundleCmd(cmd("market", bundleArgs(t, k, market("mk2", now.Unix(), site))), now); !ok {
|
||||
t.Errorf("market: %s", msg)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(l.cfg.AgentState, "market.json")); !strings.Contains(string(b), `"id":"mk2"`) {
|
||||
t.Errorf("market.json: %s", b)
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
args map[string]string
|
||||
want string
|
||||
}{
|
||||
"other site": {bundleArgs(t, k, market("mk3", now.Unix()+1, strings.Repeat("cd", 16))), "not for this site"},
|
||||
"other key": {bundleArgs(t, other, market("mk4", now.Unix()+1, site)), "bad bundle signature"},
|
||||
"older": {bundleArgs(t, k, market("mk1", now.Add(-time.Hour).Unix(), site)), "older than the one the agent has (mk2)"},
|
||||
"every site": {bundleArgs(t, k, market("mk5", now.Unix()+1, "*")), "not for this site"},
|
||||
} {
|
||||
if ok, msg := l.bundleCmd(cmd("market", c.args), now); ok || !strings.HasSuffix(msg, c.want) {
|
||||
t.Errorf("market %s: %v %q", name, ok, msg)
|
||||
}
|
||||
}
|
||||
// no certificate on the box: refused, not crashed
|
||||
l.cfg.BundleCert = filepath.Join(t.TempDir(), "missing.pem")
|
||||
if ok, msg := l.bundleCmd(cmd("tariff", bundleArgs(t, k, tariff("t7", now.Unix()))), now); ok || !strings.HasPrefix(msg, "no bundle certificate") {
|
||||
|
||||
@@ -123,6 +123,27 @@ func setupDone(path string) bool {
|
||||
return done
|
||||
}
|
||||
|
||||
// boxLocation: the site's country and postcode as the owner gave them in
|
||||
// the panel's Location (config.json "location"), and when they last
|
||||
// changed ("at", Unix seconds: fleet keeps the newer of the box's and the
|
||||
// console's). Never the latitude and longitude. nil without a country.
|
||||
func boxLocation(path string) map[string]any {
|
||||
loc, _ := jsonFile(path)["location"].(map[string]any)
|
||||
country, _ := loc["country"].(string)
|
||||
if len(country) != 2 {
|
||||
return nil
|
||||
}
|
||||
code, _ := loc["postal_code"].(string)
|
||||
if len(code) > 16 {
|
||||
code = code[:16]
|
||||
}
|
||||
out := map[string]any{"country": country, "postal_code": code}
|
||||
if at, ok := loc["at"].(float64); ok && at > 0 {
|
||||
out["at"] = int64(at)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// updateState: cantabile-update's state and the release the channel offers
|
||||
// (update.json in /run). Until its first check after a boot (the timer:
|
||||
// 2 minutes) there is no file: "not-checked", not null (dev.20's first
|
||||
@@ -238,6 +259,8 @@ func (l *link) status() map[string]any {
|
||||
return map[string]any{"v": 1, "version": osVersion(), "link": version, "slot": slot(), "uptime_s": uptime(),
|
||||
"load": load, "cpu_pct": cpuPct, "ram_pct": ram, "temp_c": temperature(), "cpu_mhz": mhz, "disk": disk,
|
||||
"wifi": wifiState(), "addons": addons, "channel": ch,
|
||||
// its interfaces and addresses, an IPv4 default route (netstate.go)
|
||||
"net": netState(), "route4": defaultRoute4(read("/proc/net/route")),
|
||||
"update": map[string]any{"state": ust, "available": uav},
|
||||
// SMART on the box's own disk, as cantabile-status read it (null
|
||||
// until its first run); fleet's hardware view counts the bad ones.
|
||||
|
||||
@@ -23,3 +23,24 @@ func TestSetupDone(t *testing.T) {
|
||||
t.Fatal("not a bool")
|
||||
}
|
||||
}
|
||||
|
||||
// The heartbeat's location: country and postcode (never lat/lon), "at".
|
||||
func TestBoxLocation(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "config.json")
|
||||
if boxLocation(p) != nil {
|
||||
t.Fatal("no file: none")
|
||||
}
|
||||
os.WriteFile(p, []byte(`{"location": {"country": "DE", "postal_code": "10115", "latitude": 52.53, "longitude": 13.38, "at": 1761800000}}`), 0o600)
|
||||
l := boxLocation(p)
|
||||
if l["country"] != "DE" || l["postal_code"] != "10115" || l["at"] != int64(1761800000) || l["latitude"] != nil || len(l) != 3 {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
os.WriteFile(p, []byte(`{"location": {"country": "AT"}}`), 0o600)
|
||||
if l := boxLocation(p); l["country"] != "AT" || l["postal_code"] != "" || l["at"] != nil {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
os.WriteFile(p, []byte(`{"location": {"latitude": 1}}`), 0o600)
|
||||
if boxLocation(p) != nil {
|
||||
t.Fatal("no country: none")
|
||||
}
|
||||
}
|
||||
+33
-2
@@ -30,6 +30,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"math/bits"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
@@ -755,11 +756,41 @@ func (l *link) heartbeat() map[string]any {
|
||||
if p := l.pathInfo(); p != nil {
|
||||
hb["path"] = p
|
||||
}
|
||||
hb["consents"] = consents(env("CANTABILE_CONSENT_FILE",
|
||||
c := consents(env("CANTABILE_CONSENT_FILE",
|
||||
map[bool]string{true: "/data/cantabile/edge/consent.json", false: "/data/state/consent.json"}[isHub()]))
|
||||
hb["consents"] = c
|
||||
// the site's weather cell (0.1°), for the cloud's weather: only with
|
||||
// the owner's share consent
|
||||
if c["share"] == true {
|
||||
if cell := siteCell(filepath.Join(l.cfg.AgentState, "site_cell.json")); cell != nil {
|
||||
hb["cell"] = cell
|
||||
}
|
||||
// the Hub's country and postcode (the panel's Location; tariffs,
|
||||
// Mieterstrom and energy sharing go by them): with the same consent
|
||||
if isHub() {
|
||||
if loc := boxLocation(boxConfig); loc != nil {
|
||||
hb["location"] = loc
|
||||
}
|
||||
}
|
||||
}
|
||||
return hb
|
||||
}
|
||||
|
||||
// siteCell: [lat, lon] rounded to 0.1° from the agent's site_cell.json
|
||||
// (written from HA's configuration), or nil (none, malformed, out of range).
|
||||
func siteCell(path string) []float64 {
|
||||
var c struct{ Lat, Lon *float64 }
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil || json.Unmarshal(b, &c) != nil || c.Lat == nil || c.Lon == nil {
|
||||
return nil
|
||||
}
|
||||
lat, lon := math.Round(*c.Lat*10)/10, math.Round(*c.Lon*10)/10
|
||||
if math.Abs(lat) > 90 || math.Abs(lon) > 180 {
|
||||
return nil
|
||||
}
|
||||
return []float64{lat, lon}
|
||||
}
|
||||
|
||||
// consents: the owner's consents as fleet keeps them (per
|
||||
// recipient; nothing goes to a recipient without its yes): share (with
|
||||
// Cantabile), control, and the recipients granted (building, grid,
|
||||
@@ -900,7 +931,7 @@ func (l *link) do(c command) (bool, string, func()) {
|
||||
case "refresh":
|
||||
l.publish("hb", l.heartbeat())
|
||||
return true, "heartbeat sent", nil
|
||||
case "tariff", "model", "flats", "acl": // data bundles: checked here, read by the agent (bundles.go; flats: a building's box; acl: the devices' protection)
|
||||
case "tariff", "model", "flats", "acl", "market": // data bundles: checked here, read by the agent (bundles.go; flats: a building's box; acl: the devices' protection; market: the shadow market's values)
|
||||
ok, msg := l.bundleCmd(c, time.Now())
|
||||
if ok && c.Cmd == "acl" && isHub() {
|
||||
devicesPolicy() // the policy in force for add-ons and the Modbus bridge (/usr/lib/cantabile/devices)
|
||||
|
||||
@@ -253,3 +253,37 @@ func TestConsentsCarrySourceAndVersion(t *testing.T) {
|
||||
t.Fatalf("no file: %v", c)
|
||||
}
|
||||
}
|
||||
|
||||
// The site's weather cell (the agent's site_cell.json) goes into the
|
||||
// heartbeat only with the share consent, rounded to 0.1°, on a Hub too;
|
||||
// a missing or bad file: no cell.
|
||||
func TestHeartbeatCell(t *testing.T) {
|
||||
for _, hub := range []string{"0", "1"} {
|
||||
t.Setenv("CANTABILE_HUB", hub)
|
||||
dir := t.TempDir()
|
||||
cons := filepath.Join(dir, "consent.json")
|
||||
t.Setenv("CANTABILE_CONSENT_FILE", cons)
|
||||
l := &link{cfg: config{AgentState: dir}, loc: &local{}}
|
||||
cell := filepath.Join(dir, "site_cell.json")
|
||||
os.WriteFile(cell, []byte(`{"lat": 47.0234, "lon": 28.86}`), 0o644)
|
||||
os.WriteFile(cons, []byte(`{"share": true}`), 0o600)
|
||||
if c, ok := l.heartbeat()["cell"].([]float64); !ok || len(c) != 2 || c[0] != 47.0 || c[1] != 28.9 {
|
||||
t.Fatalf("hub %s, shared: %v", hub, l.heartbeat()["cell"])
|
||||
}
|
||||
os.WriteFile(cons, []byte(`{"share": false, "control": true}`), 0o600)
|
||||
if c, ok := l.heartbeat()["cell"]; ok {
|
||||
t.Fatalf("hub %s, not shared: %v", hub, c)
|
||||
}
|
||||
os.WriteFile(cons, []byte(`{"share": true}`), 0o600)
|
||||
for _, bad := range []string{`not json`, `{"lat": 47.0}`, `{"lat": 95, "lon": 28}`, `{"lat": 47, "lon": -181}`, `{"lat": "47", "lon": 28}`} {
|
||||
os.WriteFile(cell, []byte(bad), 0o644)
|
||||
if c, ok := l.heartbeat()["cell"]; ok {
|
||||
t.Fatalf("hub %s, %s: %v", hub, bad, c)
|
||||
}
|
||||
}
|
||||
os.Remove(cell)
|
||||
if c, ok := l.heartbeat()["cell"]; ok {
|
||||
t.Fatalf("hub %s, no file: %v", hub, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
|
||||
package main
|
||||
|
||||
// The box's own network in its status report: a new
|
||||
// Hub whose Wi-Fi chip was not recognised enrolled over Ethernet, and its
|
||||
// owner could not find its panel on the LAN. Support sees in the console
|
||||
// which interfaces the box has, their MAC, link and addresses, and whether
|
||||
// it has an IPv4 default route ("no IPv4"), next to the hardware report's
|
||||
// Wi-Fi chip and driver. Box-level operations data (no network names, no
|
||||
// other devices on the LAN); sent also before the owner claims the box
|
||||
// (fleet unclaimed.go).
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ifaceInfo: one interface as the kernel reports it.
|
||||
type ifaceInfo struct {
|
||||
Name, MAC string
|
||||
Addrs []string // CIDR
|
||||
}
|
||||
|
||||
// netState: the physical interfaces (the box's own adapters: those with
|
||||
// /sys/class/net/<if>/device; not containers' or loopback).
|
||||
func netState() []map[string]any {
|
||||
ifs, _ := net.Interfaces()
|
||||
var in []ifaceInfo
|
||||
for _, i := range ifs {
|
||||
x := ifaceInfo{Name: i.Name, MAC: i.HardwareAddr.String()}
|
||||
addrs, _ := i.Addrs()
|
||||
for _, a := range addrs {
|
||||
x.Addrs = append(x.Addrs, a.String())
|
||||
}
|
||||
in = append(in, x)
|
||||
}
|
||||
return netEntries("/sys/class/net", in)
|
||||
}
|
||||
|
||||
// netEntries: the report's entries for these interfaces (sys: the sysfs
|
||||
// net directory).
|
||||
func netEntries(sys string, ifs []ifaceInfo) []map[string]any {
|
||||
out := []map[string]any{}
|
||||
for _, i := range ifs {
|
||||
p := filepath.Join(sys, i.Name)
|
||||
if _, err := os.Stat(p + "/device"); err != nil {
|
||||
continue
|
||||
}
|
||||
kind := "ethernet"
|
||||
if _, err := os.Stat(p + "/wireless"); err == nil {
|
||||
kind = "wifi"
|
||||
}
|
||||
v4, v6 := []string{}, []string{}
|
||||
for _, a := range i.Addrs {
|
||||
pfx, err := netip.ParsePrefix(a)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
switch ad := pfx.Addr(); {
|
||||
case ad.Is4():
|
||||
v4 = append(v4, pfx.String())
|
||||
case ad.IsGlobalUnicast(): // global and unique local; not link-local
|
||||
v6 = append(v6, pfx.String())
|
||||
}
|
||||
}
|
||||
out = append(out, map[string]any{"interface": i.Name, "kind": kind, "mac": i.MAC,
|
||||
"link": read(p + "/operstate"), "ipv4": v4, "ipv6": v6})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// defaultRoute4: /proc/net/route has an IPv4 default route (destination
|
||||
// 00000000) that is up.
|
||||
func defaultRoute4(table string) bool {
|
||||
for _, ln := range strings.Split(table, "\n")[1:] {
|
||||
f := strings.Fields(ln)
|
||||
if len(f) >= 4 && f[1] == "00000000" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNetEntries: the box's own adapters only, Wi-Fi told apart, IPv4 and
|
||||
// routable IPv6 (not link-local).
|
||||
func TestNetEntries(t *testing.T) {
|
||||
sys := t.TempDir()
|
||||
for _, d := range []string{"enp1s0/device", "wlp2s0/device", "wlp2s0/wireless", "veth1234", "lo"} {
|
||||
os.MkdirAll(filepath.Join(sys, d), 0o755)
|
||||
}
|
||||
os.WriteFile(filepath.Join(sys, "enp1s0", "operstate"), []byte("up\n"), 0o644)
|
||||
got := netEntries(sys, []ifaceInfo{
|
||||
{Name: "lo", Addrs: []string{"127.0.0.1/8"}},
|
||||
{Name: "enp1s0", MAC: "00:11:22:33:44:55", Addrs: []string{"192.0.2.23/24", "fe80::1/64", "2001:db8::23/64"}},
|
||||
{Name: "wlp2s0", MAC: "66:77:88:99:aa:bb"},
|
||||
{Name: "veth1234", Addrs: []string{"198.51.100.1/16"}},
|
||||
})
|
||||
want := []map[string]any{
|
||||
{"interface": "enp1s0", "kind": "ethernet", "mac": "00:11:22:33:44:55", "link": "up",
|
||||
"ipv4": []string{"192.0.2.23/24"}, "ipv6": []string{"2001:db8::23/64"}},
|
||||
{"interface": "wlp2s0", "kind": "wifi", "mac": "66:77:88:99:aa:bb", "link": "", "ipv4": []string{}, "ipv6": []string{}},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v", got)
|
||||
}
|
||||
table := "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n" +
|
||||
"enp1s0\t0001A8C0\t00000000\t0001\t0\t0\t100\t00FFFFFF\t0\t0\t0\n"
|
||||
if defaultRoute4(table) {
|
||||
t.Error("a LAN route is no default route")
|
||||
}
|
||||
if !defaultRoute4(table+"enp1s0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\t0\t0\t0\n") || defaultRoute4("") {
|
||||
t.Error("default route")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user