Greencell: the charger on your own broker, not a cloud it never had
The HabuDen has no cloud API to connect to. It is commissioned over Bluetooth in
the Greencell GC app, pointed at an MQTT broker the owner runs, and from then on
publishes there — so the connector is an MQTT client rather than an HTTP one,
and nothing in it reaches Greencell. The wire contract is Home Assistant's own
greencell component and the greencell_client 1.0.3 library beneath it, which is
the only published description of the topics: a BROADCAST on /greencell/broadcast
draws device announcements, and /greencell/evse/{sn}/ carries current in
milliamps, voltage, power under "momentary", the EVSE state, and the access level
chosen in the app.
That meant an MQTT client, and the server takes no dependencies, so internal/mqtt
is hand-rolled the way internal/ocpp's RFC 6455 layer is. It is scoped to what
this connector needs and says so: QoS 0 for everything we send, clean session,
no reconnect — a connection lives for one plugin call, which is exactly how the
manager builds and tears down an instance. Inbound PUBLISH is accepted at QoS 0,
1 and 2 with the acknowledgements each requires, because the QoS of a delivery is
the broker's choice and not ours; an unacknowledged QoS 1 is redelivered forever.
Read-only, and the reason is worth writing down rather than rediscovering. A
device in EXECUTE mode accepts START, STOP, SET_CURRENT and QUERY — but the topic
those go to appears in no source: not Greencell's integration page, not
greencell_client, and Home Assistant ships sensor-only for that same reason.
Publishing to a guessed topic would be a control feature whose failure mode is a
driver believing they stopped a charge. So the access level is reported, and
commandTopic is the seam: an operator who has watched their own broker and found
theirs sets it, and a state read then sends QUERY — the one command a READ-mode
device also honours — instead of waiting out the charger's publish cadence. The
day the topic is public, control is a payload away from the same field.
What the cascade resolves here is a broker, not an account, so host, port, TLS and
credentials resolve together from the highest layer that names a host: an
organization's address paired with a user's password would address a broker with
credentials never meant for it. The serial, the QUERY topic and the listen window
each describe the charger rather than the endpoint, so each resolves on its own.
Two reading rules the tests pin. A phase the device did not report stays nil
rather than zero, because zero amps on a charger is a real measurement — a JSON
null decoding to 0.0 was a live bug until a test caught it — and a partial read
returns with received/complete flags instead of failing, since a device that
publishes some topics on a slower cadence is still worth reading. And a reachable
broker with no charger on it is degraded, not down: the half we configure works
and the missing half is the device. The plugin's end-to-end tests run against an
in-process broker written to the raw wire format, so a bug in the client cannot
hide behind a matching bug in the fixture.
The apps get the third connector card. The panel needed nothing — it renders a
plugin's ConfigFields itself — but the per-user panes are still hand-written per
integration, which is now three near-copies and the argument for the generic
version already noted in the plugins README. The web form splits the broker from
the charger because the server resolves them differently. The phone card is a
declarative config against the shared widget, which gained a number field type, a
degraded state that reads amber rather than red, and a fix for a locked field
that was covering its own displayed value with dots. Twenty keys in three
languages across both apps; Greencell, HabuDen and the literal QUERY join the
proper nouns that stay in English.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
5e6b8b4b1c
commit
340a81b0d6
+24
-6
@@ -26,15 +26,16 @@ internal/
|
|||||||
│ ├── technical.go fuel.go charging.go maintenance.go documents.go
|
│ ├── technical.go fuel.go charging.go maintenance.go documents.go
|
||||||
│ ├── reminders.go
|
│ ├── reminders.go
|
||||||
│ ├── attachments.go # one optional file per record (shared handlers)
|
│ ├── attachments.go # one optional file per record (shared handlers)
|
||||||
│ ├── integrations*.go # per-user Toyota / Anker Solix settings + OCPP control
|
│ ├── integrations*.go # per-user Toyota / Anker Solix / Greencell settings + OCPP control
|
||||||
│ └── dist/ # built panel, embedded via go:embed
|
│ └── dist/ # built panel, embedded via go:embed
|
||||||
├── config/config.go # env + .env load, .env write-back
|
├── config/config.go # env + .env load, .env write-back
|
||||||
├── models/models.go # domain types + derived-field computation
|
├── models/models.go # domain types + derived-field computation
|
||||||
|
├── mqtt/ # hand-rolled MQTT 3.1.1 client (Greencell EVSE telemetry)
|
||||||
├── ocpp/ # OCPP 1.6J Central System (Anker Solix charging control)
|
├── ocpp/ # OCPP 1.6J Central System (Anker Solix charging control)
|
||||||
├── pb/client.go # PocketBase superuser client (runtime-retargetable)
|
├── pb/client.go # PocketBase superuser client (runtime-retargetable)
|
||||||
└── plugins/ # plugin system — see plugins/README.md
|
└── plugins/ # plugin system — see plugins/README.md
|
||||||
├── plugin.go manager.go external.go doc.go
|
├── plugin.go manager.go external.go doc.go
|
||||||
└── builtin/ # built-in connectors: toyota, ankersolix
|
└── builtin/ # built-in connectors: toyota, ankersolix, greencell
|
||||||
panel/ # Vue 3 + Tailwind panel source
|
panel/ # Vue 3 + Tailwind panel source
|
||||||
scripts/ # Node/Python maintenance scripts
|
scripts/ # Node/Python maintenance scripts
|
||||||
bin/api-server.exe # prebuilt binary the deployment runs
|
bin/api-server.exe # prebuilt binary the deployment runs
|
||||||
@@ -177,6 +178,9 @@ GET /api/integrations/toyota PUT /api/integrations/toyota POST /a
|
|||||||
GET /api/integrations/toyota/vehicles
|
GET /api/integrations/toyota/vehicles
|
||||||
GET /api/integrations/anker-solix PUT /api/integrations/anker-solix POST /api/integrations/anker-solix/health
|
GET /api/integrations/anker-solix PUT /api/integrations/anker-solix POST /api/integrations/anker-solix/health
|
||||||
GET /api/integrations/anker-solix/chargers
|
GET /api/integrations/anker-solix/chargers
|
||||||
|
GET /api/integrations/greencell PUT /api/integrations/greencell POST /api/integrations/greencell/health
|
||||||
|
GET /api/integrations/greencell/chargers
|
||||||
|
GET /api/integrations/greencell/chargers/{sn}/state
|
||||||
|
|
||||||
# Anker Solix OCPP charging control (own/proxy mode + a live CSMS session)
|
# Anker Solix OCPP charging control (own/proxy mode + a live CSMS session)
|
||||||
GET /api/integrations/anker-solix/chargers/{sn}/control
|
GET /api/integrations/anker-solix/chargers/{sn}/control
|
||||||
@@ -292,10 +296,10 @@ state and global config persist to PocketBase, in the `app_settings` singleton
|
|||||||
the same place the per-org and per-user layers of the cascade live.
|
the same place the per-org and per-user layers of the cascade live.
|
||||||
|
|
||||||
See **[`internal/plugins/README.md`](internal/plugins/README.md)** for the full
|
See **[`internal/plugins/README.md`](internal/plugins/README.md)** for the full
|
||||||
guide. Two built-in connectors ship today — **Toyota Connected** (`toyota`,
|
guide. Three built-in connectors ship today — **Toyota Connected** (`toyota`,
|
||||||
read-only MyToyota vehicle data) and the **Anker Solix** V1 EV charger
|
read-only MyToyota vehicle data), the **Anker Solix** V1 EV charger
|
||||||
(`anker-solix`) — and any number of external HTTP plugins can be registered at
|
(`anker-solix`) and the **Greencell** HabuDen EV charger (`greencell`) — and any
|
||||||
runtime with no rebuild.
|
number of external HTTP plugins can be registered at runtime with no rebuild.
|
||||||
|
|
||||||
### Integrations & charging control
|
### Integrations & charging control
|
||||||
|
|
||||||
@@ -309,6 +313,20 @@ per-charger control token, not a bearer token) and the owner can start/stop and
|
|||||||
set charge limits, with every command rate-limited and written to a
|
set charge limits, with every command rate-limited and written to a
|
||||||
`control_audit` trail.
|
`control_audit` trail.
|
||||||
|
|
||||||
|
**Greencell** takes the other route. The HabuDen wallbox has no cloud API: it is
|
||||||
|
commissioned over Bluetooth in the Greencell GC app, pointed at an MQTT broker
|
||||||
|
the owner runs, and from then on publishes its telemetry there. The connector is
|
||||||
|
therefore an MQTT client (`internal/mqtt`, hand-rolled like the WebSocket layer,
|
||||||
|
since the server takes no dependencies) that joins the same broker and reads
|
||||||
|
`/greencell/evse/{sn}/…` — the topics Home Assistant's own `greencell`
|
||||||
|
integration speaks, which is the only published description of the protocol. It
|
||||||
|
is read-only: the device accepts START/STOP/SET_CURRENT in EXECUTE mode, but the
|
||||||
|
topic those go to is documented nowhere, and Home Assistant ships without control
|
||||||
|
for the same reason. An operator who has identified their own command topic can
|
||||||
|
set `commandTopic`, which is used only to send `QUERY` — the one command a
|
||||||
|
READ-mode device also honours — so a read does not have to wait out the
|
||||||
|
charger's own publish cadence.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Copy `.env.example` to `.env` and fill in. Summary:
|
Copy `.env.example` to `.env` and fill in. Summary:
|
||||||
|
|||||||
+4
-4
File diff suppressed because one or more lines are too long
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="theme-color" content="#2563eb" />
|
<meta name="theme-color" content="#2563eb" />
|
||||||
<title>DriverVault · API Server</title>
|
<title>DriverVault · API Server</title>
|
||||||
<script type="module" crossorigin src="/assets/index-E4ifC_ff.js"></script>
|
<script type="module" crossorigin src="/assets/index-DYiq470x.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/assets/index-CGuUVjJH.css">
|
<link rel="stylesheet" crossorigin href="/assets/index-CGuUVjJH.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -0,0 +1,605 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This file mirrors integrations.go and integrations_ankersolix.go for the
|
||||||
|
// Greencell HabuDen EV charger: the same three-layer cascade (global → org →
|
||||||
|
// user) lets everyone point the integration at their own MQTT broker while a
|
||||||
|
// superadmin (and, in an organization, an org admin) can impose settings from
|
||||||
|
// above. See integrations.go for the full rationale; only the fields differ.
|
||||||
|
//
|
||||||
|
// - global (L1): pluginSettings on the app_settings singleton, set in the API
|
||||||
|
// Server panel by a superadmin — the top of the cascade for everyone.
|
||||||
|
// - org (L2): pluginSettings.greencell on the caller's organization record.
|
||||||
|
// - user (L3): pluginSettings.greencell on the caller's own user record.
|
||||||
|
//
|
||||||
|
// Unlike the cloud connectors, what resolves here is a *broker*, not an account:
|
||||||
|
// host, port, TLS and the broker credentials describe one endpoint and therefore
|
||||||
|
// resolve together as a unit from the highest layer that supplies a host. Mixing
|
||||||
|
// a host from the organization with a password from a user would address a broker
|
||||||
|
// with credentials that were never meant for it. The charger serial, the QUERY
|
||||||
|
// command topic and the listen window resolve on their own, because each
|
||||||
|
// describes the charger rather than the endpoint.
|
||||||
|
//
|
||||||
|
// Enablement is strictly per-user (L3), gated by the global master switch (the
|
||||||
|
// plugin being enabled in the panel) and, for org users, by the org gate.
|
||||||
|
|
||||||
|
const (
|
||||||
|
greencellPlugin = "greencell"
|
||||||
|
greencellSecretMask = "••••••••"
|
||||||
|
)
|
||||||
|
|
||||||
|
// greencellConfig is one layer's Greencell settings.
|
||||||
|
type greencellConfig struct {
|
||||||
|
// Broker identity — these five resolve together (see the file comment).
|
||||||
|
Host string `json:"host"`
|
||||||
|
Port string `json:"port"`
|
||||||
|
TLS string `json:"tls"` // "on" | "off"; empty means unset so the cascade continues
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
|
||||||
|
// Serial is the charger to read; blank means "discover whatever is there".
|
||||||
|
Serial string `json:"serial"`
|
||||||
|
// CommandTopic is the optional MQTT topic a QUERY is sent on to make the
|
||||||
|
// charger publish at once. Greencell does not document it, so it is left to
|
||||||
|
// whoever found theirs; blank means read-only listening.
|
||||||
|
CommandTopic string `json:"commandTopic"`
|
||||||
|
// Timeout is the listen window in seconds — how long a read waits for the
|
||||||
|
// charger to publish before answering with what it has.
|
||||||
|
Timeout string `json:"timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellStored is what we persist per user/org under pluginSettings.greencell.
|
||||||
|
type greencellStored struct {
|
||||||
|
Config greencellConfig `json:"config"`
|
||||||
|
// Enabled is the personal per-user opt-in (user layer). Default false.
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
// Disabled is the organization layer's off switch, stored inverted so that
|
||||||
|
// absent == enabled. Only meaningful on the org record; ignored on user records.
|
||||||
|
Disabled bool `json:"disabled,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellSettingsDoc is the pluginSettings JSON shape for the greencell key.
|
||||||
|
type greencellSettingsDoc struct {
|
||||||
|
Greencell greencellStored `json:"greencell"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellFieldView is one field's resolved state for the UI.
|
||||||
|
type greencellFieldView struct {
|
||||||
|
Effective string `json:"effective"` // resolved value in force (secrets/inherited identity masked)
|
||||||
|
Own string `json:"own"` // the caller's own editable-layer value (secret masked)
|
||||||
|
Source string `json:"source"` // global | org | user | unset
|
||||||
|
Locked bool `json:"locked"` // set above the caller's editable layer
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellResolution is the fully-resolved Greencell state for one caller.
|
||||||
|
type greencellResolution struct {
|
||||||
|
eff greencellConfig // effective (unmasked) — used only server-side (probes)
|
||||||
|
userOwn greencellConfig // caller's personal (L3) values (unmasked)
|
||||||
|
orgOwn greencellConfig // organization (L2) values (unmasked)
|
||||||
|
source map[string]string // field -> layer name (global|org|user|unset)
|
||||||
|
isSuper bool // superadmin: manages the global layer in the panel
|
||||||
|
canOrg bool // caller may edit the organization layer (org admin)
|
||||||
|
available bool // global master switch (plugin enabled in the panel)
|
||||||
|
orgEnabled bool // org gate (default true; gates the org's users)
|
||||||
|
enabled bool // caller's personal enable flag
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellBrokerFields are the fields that resolve as one unit with the host.
|
||||||
|
var greencellBrokerFields = []string{"host", "port", "tls", "username", "password"}
|
||||||
|
|
||||||
|
// greencellLayerRank orders the cascade layers; a higher number is lower priority.
|
||||||
|
var greencellLayerRank = map[string]int{"global": 1, "org": 2, "user": 3}
|
||||||
|
|
||||||
|
// normalizeGreencellTLS maps a raw TLS value to "on"/"off", or "" when unset or
|
||||||
|
// unrecognized so the cascade continues to the next layer.
|
||||||
|
func normalizeGreencellTLS(v string) string {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||||
|
case "on", "true", "yes", "1", "tls", "mqtts":
|
||||||
|
return "on"
|
||||||
|
case "off", "false", "no", "0", "plain":
|
||||||
|
return "off"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeGreencellPort validates a broker port, returning "" for anything that
|
||||||
|
// is not a usable TCP port so a typo does not silently address port 0.
|
||||||
|
func normalizeGreencellPort(v string) string {
|
||||||
|
v = strings.TrimSpace(v)
|
||||||
|
if v == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil || n < 1 || n > 65535 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strconv.Itoa(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeGreencellTimeout validates the listen window in seconds. The plugin
|
||||||
|
// clamps the value it is given as well; rejecting nonsense here keeps a bad entry
|
||||||
|
// from being stored and shown back as if it had taken effect.
|
||||||
|
func normalizeGreencellTimeout(v string) string {
|
||||||
|
v = strings.TrimSpace(v)
|
||||||
|
if v == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil || n < 1 || n > 60 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strconv.Itoa(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveGreencell computes the cascade for a caller. userRaw is the caller's
|
||||||
|
// pluginSettings blob (read from their user record).
|
||||||
|
func (s *Server) resolveGreencell(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) greencellResolution {
|
||||||
|
g, masterEnabled, _ := s.plugins.RawConfig(greencellPlugin)
|
||||||
|
gc := greencellConfig{
|
||||||
|
Host: g["host"], Port: g["port"], TLS: g["tls"],
|
||||||
|
Username: g["username"], Password: g["password"],
|
||||||
|
Serial: g["serial"], CommandTopic: g["commandTopic"], Timeout: g["timeout"],
|
||||||
|
}
|
||||||
|
|
||||||
|
var oStored greencellStored
|
||||||
|
if who.OrgID != "" {
|
||||||
|
oStored, _ = s.orgGreencell(ctx, who.OrgID)
|
||||||
|
}
|
||||||
|
oc := oStored.Config
|
||||||
|
|
||||||
|
var uStored greencellStored
|
||||||
|
if len(userRaw) > 0 {
|
||||||
|
var d greencellSettingsDoc
|
||||||
|
_ = json.Unmarshal(userRaw, &d)
|
||||||
|
uStored = d.Greencell
|
||||||
|
}
|
||||||
|
uc := uStored.Config
|
||||||
|
|
||||||
|
res := greencellResolution{
|
||||||
|
source: map[string]string{},
|
||||||
|
userOwn: uc,
|
||||||
|
orgOwn: oc,
|
||||||
|
isSuper: who.isSuperadmin(),
|
||||||
|
// An org admin may edit the organization layer in addition to their own
|
||||||
|
// personal layer. Requires the service account (org writes go through it).
|
||||||
|
canOrg: who.isManager() && !who.isSuperadmin() && who.OrgID != "" && s.pb.Configured(),
|
||||||
|
available: masterEnabled,
|
||||||
|
orgEnabled: !oStored.Disabled, // default true; off only when the org disabled it
|
||||||
|
enabled: uStored.Enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordered layers, top (highest priority) first.
|
||||||
|
type layer struct {
|
||||||
|
name string
|
||||||
|
c greencellConfig
|
||||||
|
}
|
||||||
|
layers := []layer{{"global", gc}}
|
||||||
|
if who.OrgID != "" {
|
||||||
|
layers = append(layers, layer{"org", oc})
|
||||||
|
}
|
||||||
|
layers = append(layers, layer{"user", uc})
|
||||||
|
|
||||||
|
// The broker resolves as a unit from the highest layer that names a host, so
|
||||||
|
// an address is never combined with credentials from a different layer.
|
||||||
|
brokerSrc := "unset"
|
||||||
|
for _, l := range layers {
|
||||||
|
if h := strings.TrimSpace(l.c.Host); h != "" {
|
||||||
|
res.eff.Host = h
|
||||||
|
res.eff.Port = normalizeGreencellPort(l.c.Port)
|
||||||
|
res.eff.TLS = normalizeGreencellTLS(l.c.TLS)
|
||||||
|
res.eff.Username = strings.TrimSpace(l.c.Username)
|
||||||
|
res.eff.Password = l.c.Password
|
||||||
|
brokerSrc = l.name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range greencellBrokerFields {
|
||||||
|
res.source[f] = brokerSrc
|
||||||
|
}
|
||||||
|
|
||||||
|
// The serial and the listen window say nothing about the broker, so each
|
||||||
|
// resolves on its own: the highest layer that sets it wins.
|
||||||
|
res.source["serial"] = "unset"
|
||||||
|
for _, l := range layers {
|
||||||
|
if v := strings.TrimSpace(l.c.Serial); v != "" {
|
||||||
|
res.eff.Serial, res.source["serial"] = v, l.name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.source["commandTopic"] = "unset"
|
||||||
|
for _, l := range layers {
|
||||||
|
if v := strings.TrimSpace(l.c.CommandTopic); v != "" {
|
||||||
|
res.eff.CommandTopic, res.source["commandTopic"] = v, l.name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.source["timeout"] = "unset"
|
||||||
|
for _, l := range layers {
|
||||||
|
if v := normalizeGreencellTimeout(l.c.Timeout); v != "" {
|
||||||
|
res.eff.Timeout, res.source["timeout"] = v, l.name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellLockedFor reports whether a field whose value comes from source is
|
||||||
|
// locked for a caller whose editable layer is editable (i.e. set above them).
|
||||||
|
func greencellLockedFor(source, editable string) bool {
|
||||||
|
if editable == "none" {
|
||||||
|
return true // superadmin edits the global layer in the panel, not here
|
||||||
|
}
|
||||||
|
sr, ok := greencellLayerRank[source]
|
||||||
|
if !ok {
|
||||||
|
return false // unset — the caller may be the first to set it
|
||||||
|
}
|
||||||
|
return sr < greencellLayerRank[editable]
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellMaskPresent returns the secret mask when v is non-empty, else "".
|
||||||
|
func greencellMaskPresent(v string) string {
|
||||||
|
if strings.TrimSpace(v) != "" {
|
||||||
|
return greencellSecretMask
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// orgGreencell reads an organization's stored Greencell settings (config + the
|
||||||
|
// org gate) and its raw pluginSettings blob via the service account. Best effort:
|
||||||
|
// zero values on any miss so callers proceed as if the org layer were empty.
|
||||||
|
func (s *Server) orgGreencell(ctx context.Context, orgID string) (greencellStored, json.RawMessage) {
|
||||||
|
if orgID == "" || !s.pb.Configured() {
|
||||||
|
return greencellStored{}, nil
|
||||||
|
}
|
||||||
|
data, status, err := s.pb.Raw(ctx, http.MethodGet,
|
||||||
|
"/api/collections/"+colOrgs+"/records/"+url.PathEscape(orgID)+"?fields=pluginSettings", nil)
|
||||||
|
if err != nil || status != http.StatusOK {
|
||||||
|
return greencellStored{}, nil
|
||||||
|
}
|
||||||
|
var rec struct {
|
||||||
|
PluginSettings json.RawMessage `json:"pluginSettings"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(data, &rec)
|
||||||
|
var doc greencellSettingsDoc
|
||||||
|
if len(rec.PluginSettings) > 0 {
|
||||||
|
_ = json.Unmarshal(rec.PluginSettings, &doc)
|
||||||
|
}
|
||||||
|
return doc.Greencell, rec.PluginSettings
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeGreencell applies a mutation to the greencell entry of a pluginSettings
|
||||||
|
// blob, preserving any other plugin keys, and returns the new blob.
|
||||||
|
func mergeGreencell(existing json.RawMessage, apply func(*greencellStored)) json.RawMessage {
|
||||||
|
doc := map[string]json.RawMessage{}
|
||||||
|
if len(existing) > 0 {
|
||||||
|
_ = json.Unmarshal(existing, &doc)
|
||||||
|
}
|
||||||
|
if doc == nil {
|
||||||
|
doc = map[string]json.RawMessage{} // existing was JSON null
|
||||||
|
}
|
||||||
|
var gs greencellStored
|
||||||
|
if raw, ok := doc["greencell"]; ok {
|
||||||
|
_ = json.Unmarshal(raw, &gs)
|
||||||
|
}
|
||||||
|
apply(&gs)
|
||||||
|
b, _ := json.Marshal(gs)
|
||||||
|
doc["greencell"] = b
|
||||||
|
out, _ := json.Marshal(doc)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellScopeView builds the masked field set for one editable scope. editable
|
||||||
|
// is the layer the caller edits in this scope ("user" | "org" | "none"); a field
|
||||||
|
// is locked when its effective value is set above that layer.
|
||||||
|
func (s *Server) greencellScopeView(res greencellResolution, editable string) map[string]any {
|
||||||
|
own := res.userOwn
|
||||||
|
if editable == "org" {
|
||||||
|
own = res.orgOwn
|
||||||
|
}
|
||||||
|
field := func(key, eff, ownv string, secret bool) greencellFieldView {
|
||||||
|
src := res.source[key]
|
||||||
|
locked := greencellLockedFor(src, editable)
|
||||||
|
fv := greencellFieldView{Source: src, Locked: locked}
|
||||||
|
switch {
|
||||||
|
case secret:
|
||||||
|
// Never expose a secret; show only presence.
|
||||||
|
fv.Effective, fv.Own = greencellMaskPresent(eff), greencellMaskPresent(ownv)
|
||||||
|
case (key == "host" || key == "username") && locked:
|
||||||
|
// An inherited broker address or account belongs to the layer above;
|
||||||
|
// show only that it is set.
|
||||||
|
fv.Effective, fv.Own = greencellMaskPresent(eff), greencellMaskPresent(ownv)
|
||||||
|
default:
|
||||||
|
fv.Effective, fv.Own = eff, ownv
|
||||||
|
}
|
||||||
|
return fv
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"editableLayer": editable,
|
||||||
|
"fields": map[string]greencellFieldView{
|
||||||
|
"host": field("host", res.eff.Host, own.Host, false),
|
||||||
|
"port": field("port", res.eff.Port, normalizeGreencellPort(own.Port), false),
|
||||||
|
"tls": field("tls", res.eff.TLS, normalizeGreencellTLS(own.TLS), false),
|
||||||
|
"username": field("username", res.eff.Username, own.Username, false),
|
||||||
|
"password": field("password", res.eff.Password, own.Password, true),
|
||||||
|
"serial": field("serial", res.eff.Serial, own.Serial, false),
|
||||||
|
"timeout": field("timeout", res.eff.Timeout, normalizeGreencellTimeout(own.Timeout), false),
|
||||||
|
"commandTopic": field("commandTopic", res.eff.CommandTopic, own.CommandTopic, false),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellView builds the masked, client-safe response body from a resolution.
|
||||||
|
func (s *Server) greencellView(who *callerIdentity, res greencellResolution) map[string]any {
|
||||||
|
out := map[string]any{
|
||||||
|
"available": res.available,
|
||||||
|
"orgEnabled": res.orgEnabled,
|
||||||
|
"enabled": res.enabled,
|
||||||
|
"role": who.Role,
|
||||||
|
"orgId": who.OrgID,
|
||||||
|
"canEditOrg": res.canOrg,
|
||||||
|
"isSuperadmin": res.isSuper,
|
||||||
|
}
|
||||||
|
if res.isSuper {
|
||||||
|
// Superadmin manages the global layer in the panel; here it is read-only.
|
||||||
|
out["editableLayer"] = "none"
|
||||||
|
out["scopes"] = map[string]any{"user": s.greencellScopeView(res, "none")}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
scopes := map[string]any{"user": s.greencellScopeView(res, "user")}
|
||||||
|
if res.canOrg {
|
||||||
|
scopes["org"] = s.greencellScopeView(res, "org")
|
||||||
|
}
|
||||||
|
out["scopes"] = scopes
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellPluginConfig turns a resolution into the config map the plugin takes.
|
||||||
|
func greencellPluginConfig(res greencellResolution) map[string]string {
|
||||||
|
return map[string]string{
|
||||||
|
"host": res.eff.Host,
|
||||||
|
"port": res.eff.Port,
|
||||||
|
"tls": res.eff.TLS,
|
||||||
|
"username": res.eff.Username,
|
||||||
|
"password": res.eff.Password,
|
||||||
|
"serial": res.eff.Serial,
|
||||||
|
"commandTopic": res.eff.CommandTopic,
|
||||||
|
"timeout": res.eff.Timeout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// greencellGate returns the reason the integration cannot run for this caller, or
|
||||||
|
// "" when it can. requireOptIn additionally demands the personal enable flag,
|
||||||
|
// which a live probe deliberately does not (the probe is how you check settings
|
||||||
|
// before turning it on).
|
||||||
|
func greencellGate(res greencellResolution, requireOptIn bool) string {
|
||||||
|
switch {
|
||||||
|
case !res.available:
|
||||||
|
return "The Greencell integration is disabled by the administrator"
|
||||||
|
case !res.orgEnabled:
|
||||||
|
return "The Greencell integration is disabled for your organization"
|
||||||
|
case requireOptIn && !res.enabled:
|
||||||
|
return "Enable the Greencell integration in Settings to load your chargers"
|
||||||
|
case strings.TrimSpace(res.eff.Host) == "":
|
||||||
|
return "Enter the address of the MQTT broker your charger publishes to"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/integrations/greencell — resolved Greencell view for the caller.
|
||||||
|
func (s *Server) handleGetGreencell(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who := caller(r)
|
||||||
|
if who == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res := s.resolveGreencell(r.Context(), who, userRaw)
|
||||||
|
writeJSON(w, http.StatusOK, s.greencellView(who, res))
|
||||||
|
}
|
||||||
|
|
||||||
|
// PUT /api/integrations/greencell — save the caller's editable layer. Body:
|
||||||
|
// {enabled?: bool, scope?: "user"|"org", config?: {host, port, tls, username,
|
||||||
|
// password, serial, commandTopic, timeout}}. Fields locked above the caller are
|
||||||
|
// ignored; a password left at the mask is preserved.
|
||||||
|
func (s *Server) handlePutGreencell(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who := caller(r)
|
||||||
|
if who == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.pb.Configured() {
|
||||||
|
writeError(w, http.StatusServiceUnavailable, "integration settings not configured on the server")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Enabled *bool `json:"enabled"`
|
||||||
|
Scope string `json:"scope"` // "user" (default) | "org" (admins only)
|
||||||
|
Config map[string]string `json:"config"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid json")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res := s.resolveGreencell(r.Context(), who, userRaw)
|
||||||
|
|
||||||
|
// Resolve which layer this write targets. Everyone edits their own personal
|
||||||
|
// (user) layer by default; an org admin may target the organization layer by
|
||||||
|
// asking for scope "org". Superadmins are read-only here (they manage global
|
||||||
|
// in the panel) and may only toggle their personal enable flag.
|
||||||
|
editable := "user"
|
||||||
|
switch {
|
||||||
|
case res.isSuper:
|
||||||
|
editable = "none"
|
||||||
|
case strings.EqualFold(strings.TrimSpace(body.Scope), "org"):
|
||||||
|
if !res.canOrg {
|
||||||
|
writeError(w, http.StatusForbidden, "only an organization admin can edit organization settings")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
editable = "org"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the new target-layer config from its current own values, overlaying
|
||||||
|
// only fields the caller is allowed to change in this scope.
|
||||||
|
newOwn := res.userOwn
|
||||||
|
if editable == "org" {
|
||||||
|
newOwn = res.orgOwn
|
||||||
|
}
|
||||||
|
applyField := func(key string, set func(*greencellConfig, string)) {
|
||||||
|
v, ok := body.Config[key]
|
||||||
|
if !ok || greencellLockedFor(res.source[key], editable) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "password" && v == greencellSecretMask {
|
||||||
|
return // keep current secret
|
||||||
|
}
|
||||||
|
set(&newOwn, strings.TrimSpace(v))
|
||||||
|
}
|
||||||
|
applyField("host", func(c *greencellConfig, v string) { c.Host = v })
|
||||||
|
applyField("port", func(c *greencellConfig, v string) { c.Port = normalizeGreencellPort(v) })
|
||||||
|
applyField("tls", func(c *greencellConfig, v string) { c.TLS = normalizeGreencellTLS(v) })
|
||||||
|
applyField("username", func(c *greencellConfig, v string) { c.Username = v })
|
||||||
|
applyField("password", func(c *greencellConfig, v string) { c.Password = v })
|
||||||
|
applyField("serial", func(c *greencellConfig, v string) { c.Serial = strings.ToUpper(v) })
|
||||||
|
applyField("commandTopic", func(c *greencellConfig, v string) { c.CommandTopic = v })
|
||||||
|
applyField("timeout", func(c *greencellConfig, v string) { c.Timeout = normalizeGreencellTimeout(v) })
|
||||||
|
|
||||||
|
// Persist the organization layer (admins) via the service account.
|
||||||
|
if editable == "org" {
|
||||||
|
_, orgRaw := s.orgGreencell(r.Context(), who.OrgID)
|
||||||
|
newDoc := mergeGreencell(orgRaw, func(gs *greencellStored) {
|
||||||
|
gs.Config = newOwn
|
||||||
|
// In the org scope the enable flag is the org master switch, stored
|
||||||
|
// inverted (disabled) so absent means enabled.
|
||||||
|
if body.Enabled != nil {
|
||||||
|
gs.Disabled = !*body.Enabled
|
||||||
|
}
|
||||||
|
})
|
||||||
|
_, st, err := s.pb.Raw(r.Context(), http.MethodPatch,
|
||||||
|
"/api/collections/"+colOrgs+"/records/"+url.PathEscape(who.OrgID),
|
||||||
|
map[string]json.RawMessage{"pluginSettings": newDoc})
|
||||||
|
if err != nil {
|
||||||
|
writeUpstreamDown(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if st != http.StatusOK {
|
||||||
|
writeError(w, http.StatusBadGateway, "could not save organization settings")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist the user record: the personal enable flag lives here (user/
|
||||||
|
// superadmin scope — in the org scope it targets the org gate instead), and
|
||||||
|
// so does the personal config layer when this write targets the user scope.
|
||||||
|
personalEnable := body.Enabled != nil && editable != "org"
|
||||||
|
if personalEnable || editable == "user" {
|
||||||
|
newDoc := mergeGreencell(userRaw, func(gs *greencellStored) {
|
||||||
|
if personalEnable {
|
||||||
|
gs.Enabled = *body.Enabled
|
||||||
|
}
|
||||||
|
if editable == "user" {
|
||||||
|
gs.Config = newOwn
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err := s.pb.Update(r.Context(), s.usersCollection(), who.ID,
|
||||||
|
map[string]any{"pluginSettings": newDoc}, nil); err != nil {
|
||||||
|
writePBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-resolve and return the fresh view.
|
||||||
|
fresh := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res2 := s.resolveGreencell(r.Context(), who, fresh)
|
||||||
|
writeJSON(w, http.StatusOK, s.greencellView(who, res2))
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/integrations/greencell/health — live probe using the caller's
|
||||||
|
// resolved config: connect to the broker and ask any charger to announce itself.
|
||||||
|
// Never returns secrets.
|
||||||
|
func (s *Server) handleGreencellHealth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who := caller(r)
|
||||||
|
if who == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res := s.resolveGreencell(r.Context(), who, userRaw)
|
||||||
|
|
||||||
|
if reason := greencellGate(res, false); reason != "" {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"health": map[string]any{"status": "down", "detail": reason}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h, err := s.plugins.HealthCheckWith(r.Context(), greencellPlugin, greencellPluginConfig(res))
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"health": h})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/integrations/greencell/chargers — the chargers that answer a discovery
|
||||||
|
// broadcast on the caller's resolved broker. Gated by the same switches as the
|
||||||
|
// settings view; when any gate is off it returns 200 with an empty list plus a
|
||||||
|
// reason, so the UI can degrade quietly rather than error.
|
||||||
|
func (s *Server) handleGreencellChargers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who := caller(r)
|
||||||
|
if who == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res := s.resolveGreencell(r.Context(), who, userRaw)
|
||||||
|
|
||||||
|
if reason := greencellGate(res, true); reason != "" {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"chargers": []any{}, "unavailable": true, "detail": reason})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := s.plugins.InvokeWith(r.Context(), greencellPlugin, greencellPluginConfig(res), "chargers", nil)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The plugin already answers {"chargers": [...]}; relay it verbatim.
|
||||||
|
writeJSON(w, http.StatusOK, json.RawMessage(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/integrations/greencell/chargers/{sn}/state — one charger's live state,
|
||||||
|
// read off the broker under the caller's resolved config.
|
||||||
|
func (s *Server) handleGreencellChargerState(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who := caller(r)
|
||||||
|
if who == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sn := strings.TrimSpace(r.PathValue("sn"))
|
||||||
|
if sn == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "charger serial is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||||
|
res := s.resolveGreencell(r.Context(), who, userRaw)
|
||||||
|
|
||||||
|
if reason := greencellGate(res, true); reason != "" {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"unavailable": true, "detail": reason})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
params, _ := json.Marshal(map[string]string{"sn": sn})
|
||||||
|
raw, err := s.plugins.InvokeWith(r.Context(), greencellPlugin, greencellPluginConfig(res), "charger-state", params)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, json.RawMessage(raw))
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNormalizeGreencellTLS(t *testing.T) {
|
||||||
|
for _, in := range []string{"on", "ON", "true", "yes", "1", " tls ", "mqtts"} {
|
||||||
|
if got := normalizeGreencellTLS(in); got != "on" {
|
||||||
|
t.Errorf("normalizeGreencellTLS(%q) = %q, want on", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, in := range []string{"off", "FALSE", "no", "0", "plain"} {
|
||||||
|
if got := normalizeGreencellTLS(in); got != "off" {
|
||||||
|
t.Errorf("normalizeGreencellTLS(%q) = %q, want off", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unset and unrecognized both resolve to "", which lets the cascade fall
|
||||||
|
// through to the next layer rather than pinning it to a guess.
|
||||||
|
for _, in := range []string{"", " ", "maybe"} {
|
||||||
|
if got := normalizeGreencellTLS(in); got != "" {
|
||||||
|
t.Errorf("normalizeGreencellTLS(%q) = %q, want empty", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeGreencellPort(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"1883": "1883", " 8883 ": "8883", "1": "1", "65535": "65535",
|
||||||
|
"": "", "0": "", "-1": "", "65536": "", "abc": "", "18 83": "",
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := normalizeGreencellPort(in); got != want {
|
||||||
|
t.Errorf("normalizeGreencellPort(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeGreencellTimeout(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"12": "12", " 60 ": "60", "1": "1",
|
||||||
|
"": "", "0": "", "61": "", "-5": "", "abc": "",
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := normalizeGreencellTimeout(in); got != want {
|
||||||
|
t.Errorf("normalizeGreencellTimeout(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGreencellLockedFor(t *testing.T) {
|
||||||
|
// A value set above the caller's editable layer is locked to them.
|
||||||
|
if !greencellLockedFor("global", "user") {
|
||||||
|
t.Error("a global value should lock the user layer")
|
||||||
|
}
|
||||||
|
if !greencellLockedFor("org", "user") {
|
||||||
|
t.Error("an org value should lock the user layer")
|
||||||
|
}
|
||||||
|
if greencellLockedFor("user", "user") {
|
||||||
|
t.Error("a caller's own layer is never locked to them")
|
||||||
|
}
|
||||||
|
if greencellLockedFor("org", "org") {
|
||||||
|
t.Error("an org admin may edit the org layer")
|
||||||
|
}
|
||||||
|
if !greencellLockedFor("global", "org") {
|
||||||
|
t.Error("a global value should lock the org layer")
|
||||||
|
}
|
||||||
|
// Unset is editable: the caller may be the first to set it.
|
||||||
|
if greencellLockedFor("unset", "user") {
|
||||||
|
t.Error("an unset field should be editable")
|
||||||
|
}
|
||||||
|
// A superadmin manages the global layer in the panel, not here.
|
||||||
|
if !greencellLockedFor("unset", "none") {
|
||||||
|
t.Error("the read-only scope locks everything")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGreencellMaskPresent(t *testing.T) {
|
||||||
|
if got := greencellMaskPresent("hunter2"); got != greencellSecretMask {
|
||||||
|
t.Errorf("a present secret should mask, got %q", got)
|
||||||
|
}
|
||||||
|
for _, in := range []string{"", " "} {
|
||||||
|
if got := greencellMaskPresent(in); got != "" {
|
||||||
|
t.Errorf("an absent secret should stay empty, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeGreencellPreservesOtherPlugins(t *testing.T) {
|
||||||
|
existing := json.RawMessage(`{"toyota":{"enabled":true},"ankerSolix":{"enabled":true}}`)
|
||||||
|
out := mergeGreencell(existing, func(gs *greencellStored) {
|
||||||
|
gs.Enabled = true
|
||||||
|
gs.Config.Host = "10.2.1.10"
|
||||||
|
})
|
||||||
|
|
||||||
|
var doc map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(out, &doc); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"toyota", "ankerSolix", "greencell"} {
|
||||||
|
if _, ok := doc[key]; !ok {
|
||||||
|
t.Errorf("key %q should survive the merge", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var gs greencellStored
|
||||||
|
if err := json.Unmarshal(doc["greencell"], &gs); err != nil {
|
||||||
|
t.Fatalf("unmarshal greencell: %v", err)
|
||||||
|
}
|
||||||
|
if !gs.Enabled || gs.Config.Host != "10.2.1.10" {
|
||||||
|
t.Errorf("merged entry = %+v", gs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeGreencellHandlesEmptyAndNullBlobs(t *testing.T) {
|
||||||
|
for _, existing := range []json.RawMessage{nil, json.RawMessage(`null`), json.RawMessage(``)} {
|
||||||
|
out := mergeGreencell(existing, func(gs *greencellStored) { gs.Config.Serial = "SN1" })
|
||||||
|
var doc greencellSettingsDoc
|
||||||
|
if err := json.Unmarshal(out, &doc); err != nil {
|
||||||
|
t.Fatalf("unmarshal %q: %v", existing, err)
|
||||||
|
}
|
||||||
|
if doc.Greencell.Config.Serial != "SN1" {
|
||||||
|
t.Errorf("blob %q merged to %+v", existing, doc.Greencell)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeGreencellKeepsUntouchedFields(t *testing.T) {
|
||||||
|
// Toggling the enable flag must not wipe the stored broker config.
|
||||||
|
first := mergeGreencell(nil, func(gs *greencellStored) {
|
||||||
|
gs.Config = greencellConfig{Host: "mqtt.local", Port: "1883", Password: "secret"}
|
||||||
|
})
|
||||||
|
second := mergeGreencell(first, func(gs *greencellStored) { gs.Enabled = true })
|
||||||
|
|
||||||
|
var doc greencellSettingsDoc
|
||||||
|
if err := json.Unmarshal(second, &doc); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
if doc.Greencell.Config.Host != "mqtt.local" || doc.Greencell.Config.Password != "secret" {
|
||||||
|
t.Errorf("config lost across the merge: %+v", doc.Greencell.Config)
|
||||||
|
}
|
||||||
|
if !doc.Greencell.Enabled {
|
||||||
|
t.Error("enable flag should have been set")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGreencellPluginConfigCarriesEveryField(t *testing.T) {
|
||||||
|
res := greencellResolution{eff: greencellConfig{
|
||||||
|
Host: "10.2.1.10", Port: "8883", TLS: "on",
|
||||||
|
Username: "dv", Password: "secret", Serial: "SN1",
|
||||||
|
CommandTopic: "/greencell/evse/{sn}/command", Timeout: "20",
|
||||||
|
}}
|
||||||
|
cfg := greencellPluginConfig(res)
|
||||||
|
want := map[string]string{
|
||||||
|
"host": "10.2.1.10", "port": "8883", "tls": "on",
|
||||||
|
"username": "dv", "password": "secret", "serial": "SN1",
|
||||||
|
"commandTopic": "/greencell/evse/{sn}/command", "timeout": "20",
|
||||||
|
}
|
||||||
|
for k, v := range want {
|
||||||
|
if cfg[k] != v {
|
||||||
|
t.Errorf("config[%q] = %q, want %q", k, cfg[k], v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(cfg) != len(want) {
|
||||||
|
t.Errorf("config carries %d keys, want %d: %v", len(cfg), len(want), cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGreencellGate(t *testing.T) {
|
||||||
|
full := greencellResolution{
|
||||||
|
available: true, orgEnabled: true, enabled: true,
|
||||||
|
eff: greencellConfig{Host: "mqtt.local"},
|
||||||
|
}
|
||||||
|
if reason := greencellGate(full, true); reason != "" {
|
||||||
|
t.Errorf("a fully-configured integration should pass, got %q", reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
res greencellResolution
|
||||||
|
}{
|
||||||
|
{"master switch off", greencellResolution{orgEnabled: true, enabled: true, eff: greencellConfig{Host: "h"}}},
|
||||||
|
{"org gate off", greencellResolution{available: true, enabled: true, eff: greencellConfig{Host: "h"}}},
|
||||||
|
{"no broker", greencellResolution{available: true, orgEnabled: true, enabled: true}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if reason := greencellGate(tc.res, true); reason == "" {
|
||||||
|
t.Errorf("%s should have been gated", tc.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The personal opt-in gates data reads but not a probe: the probe is how you
|
||||||
|
// check the settings before turning the integration on.
|
||||||
|
noOptIn := greencellResolution{available: true, orgEnabled: true, eff: greencellConfig{Host: "h"}}
|
||||||
|
if reason := greencellGate(noOptIn, true); reason == "" {
|
||||||
|
t.Error("a data read requires the personal opt-in")
|
||||||
|
}
|
||||||
|
if reason := greencellGate(noOptIn, false); reason != "" {
|
||||||
|
t.Errorf("a probe should not require the opt-in, got %q", reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,10 @@
|
|||||||
// GET /api/integrations/anker-solix PUT /api/integrations/anker-solix
|
// GET /api/integrations/anker-solix PUT /api/integrations/anker-solix
|
||||||
// POST /api/integrations/anker-solix/health
|
// POST /api/integrations/anker-solix/health
|
||||||
// GET /api/integrations/anker-solix/chargers
|
// GET /api/integrations/anker-solix/chargers
|
||||||
|
// GET /api/integrations/greencell PUT /api/integrations/greencell
|
||||||
|
// POST /api/integrations/greencell/health
|
||||||
|
// GET /api/integrations/greencell/chargers
|
||||||
|
// GET /api/integrations/greencell/chargers/{sn}/state
|
||||||
//
|
//
|
||||||
// # vehicle providers (create a car from a manufacturer service; per-car tab)
|
// # vehicle providers (create a car from a manufacturer service; per-car tab)
|
||||||
// GET /api/vehicle-providers
|
// GET /api/vehicle-providers
|
||||||
@@ -434,6 +438,11 @@ func (s *Server) Handler() http.Handler {
|
|||||||
mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker)
|
mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker)
|
||||||
mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth)
|
mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth)
|
||||||
mux.HandleFunc("GET /api/integrations/anker-solix/chargers", s.handleAnkerChargers)
|
mux.HandleFunc("GET /api/integrations/anker-solix/chargers", s.handleAnkerChargers)
|
||||||
|
mux.HandleFunc("GET /api/integrations/greencell", s.handleGetGreencell)
|
||||||
|
mux.HandleFunc("PUT /api/integrations/greencell", s.handlePutGreencell)
|
||||||
|
mux.HandleFunc("POST /api/integrations/greencell/health", s.handleGreencellHealth)
|
||||||
|
mux.HandleFunc("GET /api/integrations/greencell/chargers", s.handleGreencellChargers)
|
||||||
|
mux.HandleFunc("GET /api/integrations/greencell/chargers/{sn}/state", s.handleGreencellChargerState)
|
||||||
|
|
||||||
// Anker Solix OCPP control (per-charger; gated by the same cascade plus a
|
// Anker Solix OCPP control (per-charger; gated by the same cascade plus a
|
||||||
// control mode of own/proxy and a live CSMS session). See
|
// control mode of own/proxy and a live CSMS session). See
|
||||||
|
|||||||
@@ -0,0 +1,479 @@
|
|||||||
|
// Package mqtt is a minimal MQTT 3.1.1 client, written against the OASIS spec
|
||||||
|
// rather than pulled in as a dependency: the whole API server is stdlib-only, so
|
||||||
|
// this sits beside internal/ocpp's hand-rolled RFC 6455 WebSocket for the same
|
||||||
|
// reason.
|
||||||
|
//
|
||||||
|
// It is deliberately scoped to what the Greencell EVSE connector needs
|
||||||
|
// (internal/plugins/builtin/greencell): connect to a broker, subscribe to a
|
||||||
|
// handful of topics, publish a discovery broadcast, and read the telemetry that
|
||||||
|
// comes back. Concretely that means:
|
||||||
|
//
|
||||||
|
// - QoS 0 for everything this client *sends* — subscriptions request QoS 0 and
|
||||||
|
// publishes are QoS 0. The Greencell device and Home Assistant's own
|
||||||
|
// integration both work at QoS 0.
|
||||||
|
// - Inbound PUBLISH at QoS 0, 1 and 2 is accepted and acknowledged correctly,
|
||||||
|
// because the QoS of a delivery is the broker's choice, not ours.
|
||||||
|
// - Clean session only. There is no persistent session, no offline queue and no
|
||||||
|
// automatic reconnect: a connection lives for the length of one plugin call
|
||||||
|
// and is closed again, which is exactly how the plugin manager constructs and
|
||||||
|
// tears down a plugin instance per request.
|
||||||
|
//
|
||||||
|
// A Client is safe for concurrent use; writes are serialized and a single reader
|
||||||
|
// goroutine owns the connection.
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Defaults applied by Options.normalize when a field is left zero.
|
||||||
|
const (
|
||||||
|
defaultKeepalive = 30 * time.Second
|
||||||
|
defaultConnectTimeout = 10 * time.Second
|
||||||
|
defaultBuffer = 256
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrClosed is returned by Publish and Subscribe once the connection is gone.
|
||||||
|
var ErrClosed = errors.New("mqtt: connection closed")
|
||||||
|
|
||||||
|
// Options configures a broker connection.
|
||||||
|
type Options struct {
|
||||||
|
// Address is the broker's host:port. Required.
|
||||||
|
Address string
|
||||||
|
// TLS wraps the connection in TLS. TLSConfig overrides the default, which
|
||||||
|
// verifies the broker against the system roots using the host from Address.
|
||||||
|
TLS bool
|
||||||
|
TLSConfig *tls.Config
|
||||||
|
// ClientID identifies this session to the broker. Empty means a random one.
|
||||||
|
ClientID string
|
||||||
|
// Username and Password are sent in CONNECT when Username is non-empty.
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
// Keepalive is the interval the broker is told to expect traffic within; the
|
||||||
|
// client pings at half of it.
|
||||||
|
Keepalive time.Duration
|
||||||
|
// ConnectTimeout bounds the TCP/TLS dial and the wait for CONNACK.
|
||||||
|
ConnectTimeout time.Duration
|
||||||
|
// Buffer sizes the delivery channel returned by Messages.
|
||||||
|
Buffer int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) normalize() {
|
||||||
|
if o.Keepalive <= 0 {
|
||||||
|
o.Keepalive = defaultKeepalive
|
||||||
|
}
|
||||||
|
if o.ConnectTimeout <= 0 {
|
||||||
|
o.ConnectTimeout = defaultConnectTimeout
|
||||||
|
}
|
||||||
|
if o.Buffer <= 0 {
|
||||||
|
o.Buffer = defaultBuffer
|
||||||
|
}
|
||||||
|
if o.ClientID == "" {
|
||||||
|
o.ClientID = randomClientID()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message is one delivered PUBLISH.
|
||||||
|
type Message struct {
|
||||||
|
Topic string
|
||||||
|
Payload []byte
|
||||||
|
Retain bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client is a connected MQTT session.
|
||||||
|
type Client struct {
|
||||||
|
raw net.Conn
|
||||||
|
br *bufio.Reader
|
||||||
|
|
||||||
|
keepalive time.Duration
|
||||||
|
|
||||||
|
wmu sync.Mutex // serializes writes; the spec requires whole packets
|
||||||
|
|
||||||
|
msgs chan Message
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
nextID uint16
|
||||||
|
pending map[uint16]chan []byte // packet id -> acknowledgement body
|
||||||
|
err error
|
||||||
|
|
||||||
|
closeOnce sync.Once
|
||||||
|
closed chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect dials the broker and completes the MQTT handshake. The returned Client
|
||||||
|
// owns the connection; call Close when done.
|
||||||
|
func Connect(ctx context.Context, opt Options) (*Client, error) {
|
||||||
|
opt.normalize()
|
||||||
|
if opt.Address == "" {
|
||||||
|
return nil, errors.New("mqtt: broker address is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := &net.Dialer{Timeout: opt.ConnectTimeout}
|
||||||
|
var (
|
||||||
|
conn net.Conn
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if opt.TLS {
|
||||||
|
cfg := opt.TLSConfig
|
||||||
|
if cfg == nil {
|
||||||
|
host, _, splitErr := net.SplitHostPort(opt.Address)
|
||||||
|
if splitErr != nil {
|
||||||
|
host = opt.Address
|
||||||
|
}
|
||||||
|
cfg = &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||||
|
}
|
||||||
|
conn, err = (&tls.Dialer{NetDialer: dialer, Config: cfg}).DialContext(ctx, "tcp", opt.Address)
|
||||||
|
} else {
|
||||||
|
conn, err = dialer.DialContext(ctx, "tcp", opt.Address)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("mqtt: cannot reach broker %s: %w", opt.Address, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &Client{
|
||||||
|
raw: conn,
|
||||||
|
br: bufio.NewReader(conn),
|
||||||
|
keepalive: opt.Keepalive,
|
||||||
|
msgs: make(chan Message, opt.Buffer),
|
||||||
|
nextID: 1,
|
||||||
|
pending: map[uint16]chan []byte{},
|
||||||
|
closed: make(chan struct{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
deadline := time.Now().Add(opt.ConnectTimeout)
|
||||||
|
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
|
||||||
|
deadline = d
|
||||||
|
}
|
||||||
|
if err := c.handshake(opt, deadline); err != nil {
|
||||||
|
_ = conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
go c.readLoop()
|
||||||
|
go c.pingLoop()
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handshake writes CONNECT and waits for an accepting CONNACK. It runs before the
|
||||||
|
// read loop starts, so it reads the response itself.
|
||||||
|
func (c *Client) handshake(opt Options, deadline time.Time) error {
|
||||||
|
if len(opt.ClientID) > 65535 || len(opt.Username) > 65535 || len(opt.Password) > 65535 {
|
||||||
|
return errors.New("mqtt: client id or credentials too long")
|
||||||
|
}
|
||||||
|
|
||||||
|
var flags byte = 0x02 // clean session
|
||||||
|
if opt.Username != "" {
|
||||||
|
flags |= 0x80
|
||||||
|
if opt.Password != "" {
|
||||||
|
flags |= 0x40
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body := make([]byte, 0, 64)
|
||||||
|
body = encodeString(body, protocolName)
|
||||||
|
body = append(body, protocolLevel, flags)
|
||||||
|
body = encodeUint16(body, uint16(opt.Keepalive/time.Second))
|
||||||
|
body = encodeString(body, opt.ClientID)
|
||||||
|
if opt.Username != "" {
|
||||||
|
body = encodeString(body, opt.Username)
|
||||||
|
if opt.Password != "" {
|
||||||
|
body = encodeString(body, opt.Password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.raw.SetWriteDeadline(deadline); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := c.raw.Write(buildPacket(pktConnect, 0, body)); err != nil {
|
||||||
|
return fmt.Errorf("mqtt: sending CONNECT: %w", err)
|
||||||
|
}
|
||||||
|
if err := c.raw.SetWriteDeadline(time.Time{}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.raw.SetReadDeadline(deadline); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pkt, err := readPacket(c.br)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("mqtt: waiting for CONNACK: %w", err)
|
||||||
|
}
|
||||||
|
if err := c.raw.SetReadDeadline(time.Time{}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if pkt.typ != pktConnack || len(pkt.body) < 2 {
|
||||||
|
return errors.New("mqtt: broker did not answer with a CONNACK")
|
||||||
|
}
|
||||||
|
return connackError(pkt.body[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Messages returns the stream of delivered publications. It is closed when the
|
||||||
|
// connection ends; check Err for the reason.
|
||||||
|
func (c *Client) Messages() <-chan Message { return c.msgs }
|
||||||
|
|
||||||
|
// Err reports why the connection ended, or nil while it is healthy or after a
|
||||||
|
// clean Close.
|
||||||
|
func (c *Client) Err() error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return c.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe requests QoS 0 on every given topic filter in one SUBSCRIBE and waits
|
||||||
|
// for the broker's SUBACK.
|
||||||
|
func (c *Client) Subscribe(ctx context.Context, topics ...string) error {
|
||||||
|
if len(topics) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
id, ack := c.reserveID()
|
||||||
|
defer c.releaseID(id)
|
||||||
|
|
||||||
|
body := encodeUint16(make([]byte, 0, 16*len(topics)), id)
|
||||||
|
for _, t := range topics {
|
||||||
|
if t == "" || len(t) > 65535 {
|
||||||
|
return fmt.Errorf("mqtt: invalid topic filter %q", t)
|
||||||
|
}
|
||||||
|
body = encodeString(body, t)
|
||||||
|
body = append(body, 0) // requested QoS 0
|
||||||
|
}
|
||||||
|
// SUBSCRIBE reserves the fixed-header flag bits 0010 (spec 3.8.1).
|
||||||
|
if err := c.write(buildPacket(pktSubscribe, 0x02, body)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case codes := <-ack:
|
||||||
|
for i, code := range codes {
|
||||||
|
if code == 0x80 {
|
||||||
|
return fmt.Errorf("mqtt: broker refused subscription to %s", topics[min(i, len(topics)-1)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case <-c.closed:
|
||||||
|
return c.closedErr()
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish sends a QoS 0, non-retained publication. QoS 0 is fire-and-forget, so
|
||||||
|
// it returns as soon as the packet is on the wire.
|
||||||
|
func (c *Client) Publish(ctx context.Context, topic string, payload []byte) error {
|
||||||
|
if topic == "" || len(topic) > 65535 {
|
||||||
|
return fmt.Errorf("mqtt: invalid topic %q", topic)
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
body := encodeString(make([]byte, 0, len(topic)+len(payload)+2), topic)
|
||||||
|
body = append(body, payload...)
|
||||||
|
return c.write(buildPacket(pktPublish, 0, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close ends the session, sending DISCONNECT while the connection still works.
|
||||||
|
func (c *Client) Close() error {
|
||||||
|
c.closeOnce.Do(func() {
|
||||||
|
// Best effort: a broker that has already gone away needs no goodbye.
|
||||||
|
_ = c.write(buildPacket(pktDisconnect, 0, nil))
|
||||||
|
close(c.closed)
|
||||||
|
_ = c.raw.Close()
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// write sends one whole packet under the write lock.
|
||||||
|
func (c *Client) write(b []byte) error {
|
||||||
|
select {
|
||||||
|
case <-c.closed:
|
||||||
|
return c.closedErr()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
c.wmu.Lock()
|
||||||
|
defer c.wmu.Unlock()
|
||||||
|
if err := c.raw.SetWriteDeadline(time.Now().Add(c.keepalive)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := c.raw.Write(b)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// closedErr reports the failure that ended the connection, falling back to
|
||||||
|
// ErrClosed after a clean shutdown.
|
||||||
|
func (c *Client) closedErr() error {
|
||||||
|
if err := c.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return ErrClosed
|
||||||
|
}
|
||||||
|
|
||||||
|
// reserveID allocates a packet identifier and the channel its acknowledgement
|
||||||
|
// will be delivered on. Identifier 0 is not valid on the wire, so it is skipped
|
||||||
|
// on wrap.
|
||||||
|
func (c *Client) reserveID() (uint16, chan []byte) {
|
||||||
|
ch := make(chan []byte, 1)
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
id := c.nextID
|
||||||
|
c.nextID++
|
||||||
|
if c.nextID == 0 {
|
||||||
|
c.nextID = 1
|
||||||
|
}
|
||||||
|
c.pending[id] = ch
|
||||||
|
return id, ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) releaseID(id uint16) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
delete(c.pending, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolve hands an acknowledgement body to whoever is waiting on that packet id.
|
||||||
|
func (c *Client) resolve(id uint16, body []byte) {
|
||||||
|
c.mu.Lock()
|
||||||
|
ch, ok := c.pending[id]
|
||||||
|
c.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case ch <- body:
|
||||||
|
default: // a waiter that already gave up
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fail records the error that ended the connection and tears it down.
|
||||||
|
func (c *Client) fail(err error) {
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.err == nil {
|
||||||
|
c.err = err
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
_ = c.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// readLoop owns the read side of the connection for the life of the session.
|
||||||
|
func (c *Client) readLoop() {
|
||||||
|
defer close(c.msgs)
|
||||||
|
for {
|
||||||
|
// The broker is expected to answer our pings, so silence for two
|
||||||
|
// keep-alive periods means the connection is dead.
|
||||||
|
if err := c.raw.SetReadDeadline(time.Now().Add(2 * c.keepalive)); err != nil {
|
||||||
|
c.fail(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pkt, err := readPacket(c.br)
|
||||||
|
if err != nil {
|
||||||
|
select {
|
||||||
|
case <-c.closed:
|
||||||
|
return // our own Close raced the read; not a failure
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
c.fail(fmt.Errorf("mqtt: reading from broker: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !c.dispatch(pkt) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dispatch handles one received packet and reports whether the loop continues.
|
||||||
|
func (c *Client) dispatch(pkt packet) bool {
|
||||||
|
switch pkt.typ {
|
||||||
|
case pktPublish:
|
||||||
|
return c.deliver(pkt)
|
||||||
|
case pktSuback, pktUnsuback, pktPuback:
|
||||||
|
if len(pkt.body) >= 2 {
|
||||||
|
c.resolve(binary.BigEndian.Uint16(pkt.body), pkt.body[2:])
|
||||||
|
}
|
||||||
|
case pktPubrel:
|
||||||
|
// Second half of an inbound QoS 2 delivery: the broker released the
|
||||||
|
// message, so complete the exchange.
|
||||||
|
if len(pkt.body) >= 2 {
|
||||||
|
body := encodeUint16(nil, binary.BigEndian.Uint16(pkt.body))
|
||||||
|
if err := c.write(buildPacket(pktPubcomp, 0, body)); err != nil {
|
||||||
|
c.fail(err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case pktPingresp, pktPubrec, pktPubcomp:
|
||||||
|
// Nothing to do: we send no QoS >0 publications of our own.
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// deliver parses an inbound PUBLISH, acknowledges it at its QoS, and hands it to
|
||||||
|
// the consumer.
|
||||||
|
func (c *Client) deliver(pkt packet) bool {
|
||||||
|
qos := (pkt.flags >> 1) & 0x03
|
||||||
|
topic, rest, err := readString(pkt.body)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(fmt.Errorf("mqtt: malformed PUBLISH: %w", err))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if qos > 0 {
|
||||||
|
if len(rest) < 2 {
|
||||||
|
c.fail(errors.New("mqtt: PUBLISH missing packet identifier"))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
id := binary.BigEndian.Uint16(rest)
|
||||||
|
rest = rest[2:]
|
||||||
|
// QoS 1 completes with PUBACK; QoS 2 starts the four-way exchange whose
|
||||||
|
// PUBREL half is handled in dispatch.
|
||||||
|
ackType := pktPuback
|
||||||
|
if qos == 2 {
|
||||||
|
ackType = pktPubrec
|
||||||
|
}
|
||||||
|
if err := c.write(buildPacket(ackType, 0, encodeUint16(nil, id))); err != nil {
|
||||||
|
c.fail(err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := Message{Topic: topic, Payload: rest, Retain: pkt.flags&0x01 != 0}
|
||||||
|
select {
|
||||||
|
case c.msgs <- msg:
|
||||||
|
case <-c.closed:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// pingLoop keeps the session alive, pinging at half the negotiated interval so a
|
||||||
|
// single lost PINGREQ does not expire it.
|
||||||
|
func (c *Client) pingLoop() {
|
||||||
|
t := time.NewTicker(c.keepalive / 2)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-c.closed:
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
if err := c.write(buildPacket(pktPingreq, 0, nil)); err != nil {
|
||||||
|
c.fail(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// randomClientID builds an identifier the broker has not seen before, so two
|
||||||
|
// concurrent plugin calls never evict each other's session.
|
||||||
|
func randomClientID() string {
|
||||||
|
var b [8]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return fmt.Sprintf("drivervault-%d", time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
return "drivervault-" + hex.EncodeToString(b[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,566 @@
|
|||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---- a broker just real enough to test the client against ---------------------
|
||||||
|
|
||||||
|
// brokerConn is the server side of one connection, speaking the same wire codec
|
||||||
|
// the client does.
|
||||||
|
type brokerConn struct {
|
||||||
|
conn net.Conn
|
||||||
|
br *bufio.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brokerConn) read() (packet, error) { return readPacket(b.br) }
|
||||||
|
|
||||||
|
func (b *brokerConn) send(typ, flags byte, body []byte) error {
|
||||||
|
_, err := b.conn.Write(buildPacket(typ, flags, body))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// accept reads the CONNECT and answers with an accepting CONNACK, returning the
|
||||||
|
// CONNECT body so a test can assert on what the client sent.
|
||||||
|
func (b *brokerConn) accept(t *testing.T) []byte {
|
||||||
|
t.Helper()
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading CONNECT: %v", err)
|
||||||
|
}
|
||||||
|
if pkt.typ != pktConnect {
|
||||||
|
t.Fatalf("first packet type = %d, want CONNECT(%d)", pkt.typ, pktConnect)
|
||||||
|
}
|
||||||
|
if err := b.send(pktConnack, 0, []byte{0, 0}); err != nil {
|
||||||
|
t.Fatalf("sending CONNACK: %v", err)
|
||||||
|
}
|
||||||
|
return pkt.body
|
||||||
|
}
|
||||||
|
|
||||||
|
// publish pushes a PUBLISH to the client at the given QoS.
|
||||||
|
func (b *brokerConn) publish(topic string, payload []byte, qos byte, id uint16, retain bool) error {
|
||||||
|
body := encodeString(nil, topic)
|
||||||
|
if qos > 0 {
|
||||||
|
body = encodeUint16(body, id)
|
||||||
|
}
|
||||||
|
body = append(body, payload...)
|
||||||
|
flags := qos << 1
|
||||||
|
if retain {
|
||||||
|
flags |= 0x01
|
||||||
|
}
|
||||||
|
return b.send(pktPublish, flags, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// startBroker listens on a loopback port and hands the first connection to
|
||||||
|
// handle. It returns the address to dial.
|
||||||
|
func startBroker(t *testing.T, handle func(b *brokerConn)) string {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
// Close the listener before waiting: cleanups run last-registered first, so
|
||||||
|
// registering both together keeps the order right.
|
||||||
|
t.Cleanup(func() { _ = ln.Close(); wg.Wait() })
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
handle(&brokerConn{conn: conn, br: bufio.NewReader(conn)})
|
||||||
|
}()
|
||||||
|
return ln.Addr().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func dial(t *testing.T, addr string, opt Options) *Client {
|
||||||
|
t.Helper()
|
||||||
|
opt.Address = addr
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
c, err := Connect(ctx, opt)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Connect: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = c.Close() })
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- wire codec --------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestRemainingLengthRoundTrip(t *testing.T) {
|
||||||
|
// The boundaries of each varint width, per the MQTT spec's own table.
|
||||||
|
for _, n := range []int{0, 1, 127, 128, 16383, 16384, 2097151, 2097152, maxRemainingLength} {
|
||||||
|
encoded := encodeRemainingLength(nil, n)
|
||||||
|
got, err := readRemainingLength(bufio.NewReader(strings.NewReader(string(encoded))))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("readRemainingLength(%d): %v", n, err)
|
||||||
|
}
|
||||||
|
if got != n {
|
||||||
|
t.Errorf("round trip %d -> %d", n, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemainingLengthRejectsOverlongVarint(t *testing.T) {
|
||||||
|
// Five continuation bytes is malformed; the spec caps the field at four.
|
||||||
|
br := bufio.NewReader(strings.NewReader("\xff\xff\xff\xff\xff"))
|
||||||
|
if _, err := readRemainingLength(br); err == nil {
|
||||||
|
t.Fatal("expected an error for a five-byte remaining length")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadString(t *testing.T) {
|
||||||
|
b := encodeString(nil, "/greencell/broadcast")
|
||||||
|
b = append(b, 'x', 'y')
|
||||||
|
s, rest, err := readString(b)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("readString: %v", err)
|
||||||
|
}
|
||||||
|
if s != "/greencell/broadcast" {
|
||||||
|
t.Errorf("string = %q", s)
|
||||||
|
}
|
||||||
|
if string(rest) != "xy" {
|
||||||
|
t.Errorf("rest = %q, want xy", rest)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, _, err := readString([]byte{0x00, 0x05, 'a'}); err == nil {
|
||||||
|
t.Error("expected an error for a truncated string")
|
||||||
|
}
|
||||||
|
if _, _, err := readString([]byte{0x00}); err == nil {
|
||||||
|
t.Error("expected an error for a truncated length")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnackError(t *testing.T) {
|
||||||
|
if err := connackError(0); err != nil {
|
||||||
|
t.Errorf("code 0 should be accepted, got %v", err)
|
||||||
|
}
|
||||||
|
if err := connackError(4); err == nil || !strings.Contains(err.Error(), "username or password") {
|
||||||
|
t.Errorf("code 4 = %v, want a credentials error", err)
|
||||||
|
}
|
||||||
|
if err := connackError(9); err == nil {
|
||||||
|
t.Error("an unknown code should still be an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- handshake ---------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestConnectSendsCredentialsAndKeepalive(t *testing.T) {
|
||||||
|
var got []byte
|
||||||
|
done := make(chan struct{})
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
got = b.accept(t)
|
||||||
|
close(done)
|
||||||
|
// Hold the connection open so the client stays up for the assertions.
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
|
||||||
|
dial(t, addr, Options{ClientID: "dv-test", Username: "user", Password: "pass", Keepalive: 42 * time.Second})
|
||||||
|
<-done
|
||||||
|
|
||||||
|
name, rest, err := readString(got)
|
||||||
|
if err != nil || name != protocolName {
|
||||||
|
t.Fatalf("protocol name = %q (err %v), want MQTT", name, err)
|
||||||
|
}
|
||||||
|
if rest[0] != protocolLevel {
|
||||||
|
t.Errorf("protocol level = %d, want %d", rest[0], protocolLevel)
|
||||||
|
}
|
||||||
|
flags := rest[1]
|
||||||
|
if flags&0x02 == 0 {
|
||||||
|
t.Error("clean session flag should be set")
|
||||||
|
}
|
||||||
|
if flags&0x80 == 0 || flags&0x40 == 0 {
|
||||||
|
t.Errorf("username+password flags should be set, got %#x", flags)
|
||||||
|
}
|
||||||
|
if ka := binary.BigEndian.Uint16(rest[2:]); ka != 42 {
|
||||||
|
t.Errorf("keepalive = %d, want 42", ka)
|
||||||
|
}
|
||||||
|
|
||||||
|
id, rest, err := readString(rest[4:])
|
||||||
|
if err != nil || id != "dv-test" {
|
||||||
|
t.Fatalf("client id = %q (err %v)", id, err)
|
||||||
|
}
|
||||||
|
user, rest, err := readString(rest)
|
||||||
|
if err != nil || user != "user" {
|
||||||
|
t.Fatalf("username = %q (err %v)", user, err)
|
||||||
|
}
|
||||||
|
pass, _, err := readString(rest)
|
||||||
|
if err != nil || pass != "pass" {
|
||||||
|
t.Fatalf("password = %q (err %v)", pass, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectOmitsCredentialsWhenUnset(t *testing.T) {
|
||||||
|
var got []byte
|
||||||
|
done := make(chan struct{})
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
got = b.accept(t)
|
||||||
|
close(done)
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
|
||||||
|
dial(t, addr, Options{ClientID: "dv-test"})
|
||||||
|
<-done
|
||||||
|
|
||||||
|
_, rest, err := readString(got)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("readString: %v", err)
|
||||||
|
}
|
||||||
|
if flags := rest[1]; flags&0xC0 != 0 {
|
||||||
|
t.Errorf("credential flags should be clear on an anonymous connect, got %#x", flags)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectRefused(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
if _, err := b.read(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = b.send(pktConnack, 0, []byte{0, 5}) // not authorized
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_, err := Connect(ctx, Options{Address: addr})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected the refusal to surface as an error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "not authorized") {
|
||||||
|
t.Errorf("error = %v, want the CONNACK reason", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectRejectsNonConnack(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
if _, err := b.read(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = b.send(pktPingresp, 0, nil)
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := Connect(ctx, Options{Address: addr}); err == nil {
|
||||||
|
t.Fatal("expected an error when the broker answers something other than CONNACK")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectUnreachableBroker(t *testing.T) {
|
||||||
|
// Port 0 never accepts, so this fails at dial rather than at handshake.
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_, err := Connect(ctx, Options{Address: "127.0.0.1:0", ConnectTimeout: time.Second})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected a dial error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "cannot reach broker") {
|
||||||
|
t.Errorf("error = %v, want a broker-unreachable message", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectRequiresAddress(t *testing.T) {
|
||||||
|
if _, err := Connect(context.Background(), Options{}); err == nil {
|
||||||
|
t.Fatal("expected an error when no broker address is configured")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- subscribe / publish -----------------------------------------------------
|
||||||
|
|
||||||
|
func TestSubscribeAndDeliver(t *testing.T) {
|
||||||
|
var topics []string
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pkt.typ != pktSubscribe {
|
||||||
|
t.Errorf("packet type = %d, want SUBSCRIBE(%d)", pkt.typ, pktSubscribe)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pkt.flags != 0x02 {
|
||||||
|
t.Errorf("SUBSCRIBE flags = %#x, want 0x02", pkt.flags)
|
||||||
|
}
|
||||||
|
id := binary.BigEndian.Uint16(pkt.body)
|
||||||
|
rest := pkt.body[2:]
|
||||||
|
for len(rest) > 0 {
|
||||||
|
var topic string
|
||||||
|
topic, rest, err = readString(rest)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
topics = append(topics, topic)
|
||||||
|
rest = rest[1:] // requested QoS
|
||||||
|
}
|
||||||
|
_ = b.send(pktSuback, 0, append(encodeUint16(nil, id), 0, 0))
|
||||||
|
_ = b.publish("/greencell/evse/SN1/power", []byte(`{"momentary":7360}`), 0, 0, true)
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := c.Subscribe(ctx, "/greencell/broadcast/device", "/greencell/evse/SN1/power"); err != nil {
|
||||||
|
t.Fatalf("Subscribe: %v", err)
|
||||||
|
}
|
||||||
|
if len(topics) != 2 || topics[0] != "/greencell/broadcast/device" {
|
||||||
|
t.Errorf("broker saw topics %v", topics)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case msg := <-c.Messages():
|
||||||
|
if msg.Topic != "/greencell/evse/SN1/power" {
|
||||||
|
t.Errorf("topic = %q", msg.Topic)
|
||||||
|
}
|
||||||
|
if string(msg.Payload) != `{"momentary":7360}` {
|
||||||
|
t.Errorf("payload = %q", msg.Payload)
|
||||||
|
}
|
||||||
|
if !msg.Retain {
|
||||||
|
t.Error("retain flag should have been carried through")
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the delivery")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubscribeRefused(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := binary.BigEndian.Uint16(pkt.body)
|
||||||
|
_ = b.send(pktSuback, 0, append(encodeUint16(nil, id), 0x80))
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
err := c.Subscribe(ctx, "/greencell/broadcast/device")
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "refused subscription") {
|
||||||
|
t.Fatalf("Subscribe error = %v, want a refusal", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubscribeNoTopicsIsNoOp(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
if err := c.Subscribe(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Subscribe with no topics = %v, want nil", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublish(t *testing.T) {
|
||||||
|
type sent struct {
|
||||||
|
topic string
|
||||||
|
payload string
|
||||||
|
}
|
||||||
|
got := make(chan sent, 1)
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pkt.typ != pktPublish {
|
||||||
|
t.Errorf("packet type = %d, want PUBLISH(%d)", pkt.typ, pktPublish)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if qos := (pkt.flags >> 1) & 0x03; qos != 0 {
|
||||||
|
t.Errorf("published QoS = %d, want 0", qos)
|
||||||
|
}
|
||||||
|
topic, rest, err := readString(pkt.body)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
got <- sent{topic, string(rest)}
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
if err := c.Publish(context.Background(), "/greencell/broadcast", []byte(`{"name":"BROADCAST"}`)); err != nil {
|
||||||
|
t.Fatalf("Publish: %v", err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case s := <-got:
|
||||||
|
if s.topic != "/greencell/broadcast" || s.payload != `{"name":"BROADCAST"}` {
|
||||||
|
t.Errorf("broker received %+v", s)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the publish")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishRejectsEmptyTopic(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
_, _ = b.read()
|
||||||
|
})
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
if err := c.Publish(context.Background(), "", nil); err == nil {
|
||||||
|
t.Fatal("expected an error for an empty topic")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestInboundQoS1IsAcknowledged covers the case the client does not choose: the
|
||||||
|
// broker may upgrade a delivery to QoS 1, and an unacknowledged one is redelivered
|
||||||
|
// forever.
|
||||||
|
func TestInboundQoS1IsAcknowledged(t *testing.T) {
|
||||||
|
acked := make(chan uint16, 1)
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
_ = b.publish("/greencell/evse/SN1/status", []byte(`{"state":"CHARGING"}`), 1, 77, false)
|
||||||
|
for {
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pkt.typ == pktPuback && len(pkt.body) >= 2 {
|
||||||
|
acked <- binary.BigEndian.Uint16(pkt.body)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
select {
|
||||||
|
case msg := <-c.Messages():
|
||||||
|
if string(msg.Payload) != `{"state":"CHARGING"}` {
|
||||||
|
t.Errorf("payload = %q — the packet identifier should be stripped", msg.Payload)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the QoS 1 delivery")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case id := <-acked:
|
||||||
|
if id != 77 {
|
||||||
|
t.Errorf("PUBACK id = %d, want 77", id)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the PUBACK")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestInboundQoS2Completes walks the four-way exchange the broker drives.
|
||||||
|
func TestInboundQoS2Completes(t *testing.T) {
|
||||||
|
done := make(chan byte, 2)
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
_ = b.publish("/greencell/evse/SN1/status", []byte(`{"state":"IDLE"}`), 2, 88, false)
|
||||||
|
for {
|
||||||
|
pkt, err := b.read()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch pkt.typ {
|
||||||
|
case pktPubrec:
|
||||||
|
done <- pktPubrec
|
||||||
|
_ = b.send(pktPubrel, 0x02, encodeUint16(nil, 88))
|
||||||
|
case pktPubcomp:
|
||||||
|
done <- pktPubcomp
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
select {
|
||||||
|
case <-c.Messages():
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the QoS 2 delivery")
|
||||||
|
}
|
||||||
|
for _, want := range []byte{pktPubrec, pktPubcomp} {
|
||||||
|
select {
|
||||||
|
case got := <-done:
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("exchange step = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatalf("timed out waiting for step %d", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- teardown ----------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestMessagesCloseAndErrOnBrokerDisconnect(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
_ = b.conn.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
select {
|
||||||
|
case _, ok := <-c.Messages():
|
||||||
|
if ok {
|
||||||
|
t.Fatal("expected the message channel to close, not deliver")
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for the channel to close")
|
||||||
|
}
|
||||||
|
if c.Err() == nil {
|
||||||
|
t.Error("Err should report why the connection ended")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCloseIsIdempotentAndSilencesErr(t *testing.T) {
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
for {
|
||||||
|
if _, err := b.read(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
if err := c.Close(); err != nil {
|
||||||
|
t.Fatalf("Close: %v", err)
|
||||||
|
}
|
||||||
|
if err := c.Close(); err != nil {
|
||||||
|
t.Fatalf("second Close: %v", err)
|
||||||
|
}
|
||||||
|
if err := c.Err(); err != nil {
|
||||||
|
t.Errorf("a clean Close should leave Err nil, got %v", err)
|
||||||
|
}
|
||||||
|
if err := c.Publish(context.Background(), "/x", nil); !errors.Is(err, ErrClosed) {
|
||||||
|
t.Errorf("Publish after Close = %v, want ErrClosed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubscribeHonoursContextCancellation(t *testing.T) {
|
||||||
|
// A broker that never answers the SUBSCRIBE: the caller's deadline is what
|
||||||
|
// has to end the wait.
|
||||||
|
addr := startBroker(t, func(b *brokerConn) {
|
||||||
|
b.accept(t)
|
||||||
|
for {
|
||||||
|
if _, err := b.read(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
c := dial(t, addr, Options{})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if err := c.Subscribe(ctx, "/greencell/broadcast/device"); !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Fatalf("Subscribe = %v, want a deadline error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MQTT 3.1.1 control packet types (§2.2.1). Only the ones this client needs to
|
||||||
|
// send or recognize are named; anything else on the wire is skipped.
|
||||||
|
const (
|
||||||
|
pktConnect byte = 1
|
||||||
|
pktConnack byte = 2
|
||||||
|
pktPublish byte = 3
|
||||||
|
pktPuback byte = 4
|
||||||
|
pktPubrec byte = 5
|
||||||
|
pktPubrel byte = 6
|
||||||
|
pktPubcomp byte = 7
|
||||||
|
pktSubscribe byte = 8
|
||||||
|
pktSuback byte = 9
|
||||||
|
pktUnsubscribe byte = 10
|
||||||
|
pktUnsuback byte = 11
|
||||||
|
pktPingreq byte = 12
|
||||||
|
pktPingresp byte = 13
|
||||||
|
pktDisconnect byte = 14
|
||||||
|
)
|
||||||
|
|
||||||
|
// protocolName / protocolLevel identify MQTT 3.1.1 in the CONNECT packet (§3.1.2).
|
||||||
|
const (
|
||||||
|
protocolName = "MQTT"
|
||||||
|
protocolLevel = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxRemainingLength is the largest value the four-byte varint can express
|
||||||
|
// (§2.2.3). maxPacketBytes is the much tighter ceiling this client accepts from a
|
||||||
|
// broker: Greencell telemetry frames are a few dozen bytes, so a megabyte is
|
||||||
|
// generous while still bounding a hostile or broken peer.
|
||||||
|
const (
|
||||||
|
maxRemainingLength = 268435455
|
||||||
|
maxPacketBytes = 1 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
// errPacketTooLarge is returned when a broker announces a packet beyond
|
||||||
|
// maxPacketBytes; the connection is unusable afterwards because the stream can no
|
||||||
|
// longer be framed, so the read loop treats it as fatal.
|
||||||
|
var errPacketTooLarge = errors.New("mqtt: packet exceeds size limit")
|
||||||
|
|
||||||
|
// packet is one decoded control packet: its type, the four header flag bits, and
|
||||||
|
// the variable header plus payload as a single buffer for the caller to parse.
|
||||||
|
type packet struct {
|
||||||
|
typ byte
|
||||||
|
flags byte
|
||||||
|
body []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodeUint16 appends a two-byte big-endian integer, the encoding MQTT uses for
|
||||||
|
// packet identifiers and the keep-alive.
|
||||||
|
func encodeUint16(b []byte, v uint16) []byte {
|
||||||
|
return binary.BigEndian.AppendUint16(b, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodeString appends an MQTT UTF-8 string: a two-byte length followed by the
|
||||||
|
// bytes (§1.5.3). Strings longer than 65535 bytes cannot be represented and are
|
||||||
|
// rejected by the callers that build packets.
|
||||||
|
func encodeString(b []byte, s string) []byte {
|
||||||
|
b = encodeUint16(b, uint16(len(s)))
|
||||||
|
return append(b, s...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodeRemainingLength appends the variable-length integer that gives the number
|
||||||
|
// of bytes after the fixed header (§2.2.3).
|
||||||
|
func encodeRemainingLength(b []byte, n int) []byte {
|
||||||
|
for {
|
||||||
|
digit := byte(n % 128)
|
||||||
|
n /= 128
|
||||||
|
if n > 0 {
|
||||||
|
digit |= 0x80
|
||||||
|
}
|
||||||
|
b = append(b, digit)
|
||||||
|
if n == 0 {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildPacket frames a body as a complete control packet.
|
||||||
|
func buildPacket(typ, flags byte, body []byte) []byte {
|
||||||
|
out := make([]byte, 0, len(body)+5)
|
||||||
|
out = append(out, typ<<4|flags)
|
||||||
|
out = encodeRemainingLength(out, len(body))
|
||||||
|
return append(out, body...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readRemainingLength decodes the fixed header's variable-length integer.
|
||||||
|
func readRemainingLength(br *bufio.Reader) (int, error) {
|
||||||
|
var (
|
||||||
|
value int
|
||||||
|
multiplier = 1
|
||||||
|
)
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
digit, err := br.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
value += int(digit&0x7F) * multiplier
|
||||||
|
if digit&0x80 == 0 {
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
multiplier *= 128
|
||||||
|
}
|
||||||
|
return 0, errors.New("mqtt: malformed remaining length")
|
||||||
|
}
|
||||||
|
|
||||||
|
// readPacket reads one whole control packet off the wire.
|
||||||
|
func readPacket(br *bufio.Reader) (packet, error) {
|
||||||
|
head, err := br.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return packet{}, err
|
||||||
|
}
|
||||||
|
n, err := readRemainingLength(br)
|
||||||
|
if err != nil {
|
||||||
|
return packet{}, err
|
||||||
|
}
|
||||||
|
if n > maxPacketBytes {
|
||||||
|
return packet{}, fmt.Errorf("%w: %d bytes", errPacketTooLarge, n)
|
||||||
|
}
|
||||||
|
body := make([]byte, n)
|
||||||
|
if _, err := io.ReadFull(br, body); err != nil {
|
||||||
|
return packet{}, err
|
||||||
|
}
|
||||||
|
return packet{typ: head >> 4, flags: head & 0x0F, body: body}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readString decodes an MQTT UTF-8 string from the front of b and returns it with
|
||||||
|
// the remainder.
|
||||||
|
func readString(b []byte) (string, []byte, error) {
|
||||||
|
if len(b) < 2 {
|
||||||
|
return "", nil, errors.New("mqtt: truncated string length")
|
||||||
|
}
|
||||||
|
n := int(binary.BigEndian.Uint16(b))
|
||||||
|
if len(b) < 2+n {
|
||||||
|
return "", nil, errors.New("mqtt: truncated string")
|
||||||
|
}
|
||||||
|
return string(b[2 : 2+n]), b[2+n:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connackError maps a CONNACK return code (§3.2.2.3) to an error, or nil when the
|
||||||
|
// broker accepted the connection.
|
||||||
|
func connackError(code byte) error {
|
||||||
|
switch code {
|
||||||
|
case 0:
|
||||||
|
return nil
|
||||||
|
case 1:
|
||||||
|
return errors.New("mqtt: broker refused the connection: unacceptable protocol version")
|
||||||
|
case 2:
|
||||||
|
return errors.New("mqtt: broker refused the connection: client identifier rejected")
|
||||||
|
case 3:
|
||||||
|
return errors.New("mqtt: broker refused the connection: server unavailable")
|
||||||
|
case 4:
|
||||||
|
return errors.New("mqtt: broker refused the connection: bad username or password")
|
||||||
|
case 5:
|
||||||
|
return errors.New("mqtt: broker refused the connection: not authorized")
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("mqtt: broker refused the connection: code %d", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -167,10 +167,12 @@ go build -o bin/api-server.exe ./cmd/server
|
|||||||
Restart the server. The plugin appears in the panel's **Plugins** card,
|
Restart the server. The plugin appears in the panel's **Plugins** card,
|
||||||
**disabled** by default.
|
**disabled** by default.
|
||||||
|
|
||||||
> DriverVault ships two built-in connectors today — `toyota` (Toyota Connected /
|
> DriverVault ships three built-in connectors today — `toyota` (Toyota Connected /
|
||||||
> MyToyota, read-only vehicle data) and `anker-solix` (Anker Solix V1 EV charger)
|
> MyToyota, read-only vehicle data), `anker-solix` (Anker Solix V1 EV charger) and
|
||||||
> — both blank-imported from `builtin/builtin.go`. The **external** kind below
|
> `greencell` (Greencell HabuDen EV charger, read over the owner's MQTT broker
|
||||||
> needs no rebuild and is the easier place to start a new one.
|
> rather than a cloud API) — all blank-imported from `builtin/builtin.go`. The
|
||||||
|
> **external** kind below needs no rebuild and is the easier place to start a new
|
||||||
|
> one.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -320,10 +322,11 @@ The contract is shaped for these; see [`doc.go`](doc.go):
|
|||||||
exist (`Manager.InvokeWith` / `InvokeBatchWith`, driven by the integration routes
|
exist (`Manager.InvokeWith` / `InvokeBatchWith`, driven by the integration routes
|
||||||
and `internal/api/vehicleproviders.go`); what is missing is the generic route.
|
and `internal/api/vehicleproviders.go`); what is missing is the generic route.
|
||||||
- **Resilience** — retry/backoff, circuit breaker, per-plugin latency/error metrics.
|
- **Resilience** — retry/backoff, circuit breaker, per-plugin latency/error metrics.
|
||||||
- **Per-tenant credentials _for arbitrary plugins_** — the two built-in connectors
|
- **Per-tenant credentials _for arbitrary plugins_** — the built-in connectors
|
||||||
already have them, through the hand-written `/api/integrations/toyota` and
|
already have them, through the hand-written `/api/integrations/toyota`,
|
||||||
`/api/integrations/anker-solix` routes and their **superadmin → org admin →
|
`/api/integrations/anker-solix` and `/api/integrations/greencell` routes and
|
||||||
user** config cascade. What is missing is the generic version: per-org/per-user
|
their **superadmin → org admin → user** config cascade. Each is a near-copy of
|
||||||
|
the last, which is the argument for the generic version: per-org/per-user
|
||||||
config keyed off `ConfigFields`, so a newly registered plugin gets the same
|
config keyed off `ConfigFields`, so a newly registered plugin gets the same
|
||||||
treatment without new endpoints.
|
treatment without new endpoints.
|
||||||
- **Audit logging** of plugin access. (Charger *control* commands are already
|
- **Audit logging** of plugin access. (Charger *control* commands are already
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
// register them with the plugin registry. Import this package once (from the api
|
// register them with the plugin registry. Import this package once (from the api
|
||||||
// package) to make all built-in connectors available.
|
// package) to make all built-in connectors available.
|
||||||
//
|
//
|
||||||
// Built-in connectors that ship today: toyota and ankersolix (imported below).
|
// Built-in connectors that ship today: toyota, ankersolix and greencell
|
||||||
|
// (imported below).
|
||||||
// Add another under internal/plugins/builtin/<name>/ and blank-import it here, e.g.
|
// Add another under internal/plugins/builtin/<name>/ and blank-import it here, e.g.
|
||||||
//
|
//
|
||||||
// import _ "drivervault/apiserver/internal/plugins/builtin/acme"
|
// import _ "drivervault/apiserver/internal/plugins/builtin/acme"
|
||||||
@@ -14,6 +15,8 @@ package builtin
|
|||||||
import (
|
import (
|
||||||
// anker-solix — Anker Solix V1 Smart EV Charger read-only cloud data.
|
// anker-solix — Anker Solix V1 Smart EV Charger read-only cloud data.
|
||||||
_ "drivervault/apiserver/internal/plugins/builtin/ankersolix"
|
_ "drivervault/apiserver/internal/plugins/builtin/ankersolix"
|
||||||
|
// greencell — Greencell HabuDen EV charger, read over the owner's MQTT broker.
|
||||||
|
_ "drivervault/apiserver/internal/plugins/builtin/greencell"
|
||||||
// toyota — Toyota Connected Europe (MyToyota) read-only vehicle data.
|
// toyota — Toyota Connected Europe (MyToyota) read-only vehicle data.
|
||||||
_ "drivervault/apiserver/internal/plugins/builtin/toyota"
|
_ "drivervault/apiserver/internal/plugins/builtin/toyota"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,805 @@
|
|||||||
|
// Package greencell is a built-in connector for Greencell EV charging stations —
|
||||||
|
// today the HabuDen wallbox (11/22 kW, 32 A), the one device Greencell itself
|
||||||
|
// supports for third-party integration.
|
||||||
|
//
|
||||||
|
// There is no Greencell cloud API to talk to. The charger is commissioned over
|
||||||
|
// Bluetooth in the Greencell GC app, where the owner points it at an MQTT broker
|
||||||
|
// of their own and switches the "Home Assistant" integration on; from then on the
|
||||||
|
// wallbox publishes its telemetry to that broker. This connector is therefore an
|
||||||
|
// MQTT client, not an HTTP one: it joins the same broker and reads the topics the
|
||||||
|
// device publishes. The wire contract is the one Home Assistant's own greencell
|
||||||
|
// integration speaks (homeassistant/components/greencell, and the greencell_client
|
||||||
|
// 1.0.3 library it builds on), which is the only published description of it:
|
||||||
|
//
|
||||||
|
// publish /greencell/broadcast {"name":"BROADCAST"} — ask devices to announce
|
||||||
|
// subscribe /greencell/broadcast/device {"id":"<serial>", …} — a device announcing itself
|
||||||
|
// subscribe /greencell/evse/<sn>/current {"l1":…,"l2":…,"l3":…} milliamps
|
||||||
|
// subscribe /greencell/evse/<sn>/voltage {"l1":…,"l2":…,"l3":…} volts
|
||||||
|
// subscribe /greencell/evse/<sn>/power {"momentary":…} watts
|
||||||
|
// subscribe /greencell/evse/<sn>/status {"state":"CHARGING"}
|
||||||
|
// subscribe /greencell/evse/<sn>/device_state {"level":"EXECUTE"} access level
|
||||||
|
//
|
||||||
|
// Scope & limitations:
|
||||||
|
// - Read-only. The GC app can put a device in EXECUTE mode, in which it accepts
|
||||||
|
// START / STOP / SET_CURRENT / QUERY commands — but the topic those commands
|
||||||
|
// are published on is documented nowhere: not in Greencell's integration page,
|
||||||
|
// not in greencell_client, and Home Assistant's own integration ships without
|
||||||
|
// control for exactly that reason. The access level is reported (CanExecute)
|
||||||
|
// so the UI can say what the device would allow; acting on it needs that
|
||||||
|
// topic, which is the one missing piece. An operator who has found theirs can
|
||||||
|
// set commandTopic, and a state read will then send QUERY (the one command a
|
||||||
|
// READ-mode device also honours) to prompt an immediate publish.
|
||||||
|
// - Local, not cloud. The broker is the owner's; nothing here reaches Greencell.
|
||||||
|
// The charger and this server must both be able to reach it.
|
||||||
|
// - Pull-shaped over a push protocol. The plugin contract builds an instance per
|
||||||
|
// call, so each Invoke opens a short-lived session, asks for a broadcast, reads
|
||||||
|
// what arrives within a bounded window, and disconnects. It does not hold a
|
||||||
|
// subscription open between calls, so a reading is as fresh as the device's own
|
||||||
|
// publish cadence within that window.
|
||||||
|
// - HabuDen. Serials matching the HabuDen pattern are named as such; any other
|
||||||
|
// Greencell device that speaks these topics is still read, just generically.
|
||||||
|
package greencell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"drivervault/apiserver/internal/mqtt"
|
||||||
|
"drivervault/apiserver/internal/plugins"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Topics. The leading slash is part of the contract — Greencell publishes on
|
||||||
|
// absolute topics, not the relative ones MQTT conventions would suggest.
|
||||||
|
const (
|
||||||
|
broadcastTopic = "/greencell/broadcast"
|
||||||
|
discoveryTopic = "/greencell/broadcast/device"
|
||||||
|
evsePrefix = "/greencell/evse/"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Per-device topic suffixes, which double as the keys of the raw/received maps.
|
||||||
|
const (
|
||||||
|
topicCurrent = "current"
|
||||||
|
topicVoltage = "voltage"
|
||||||
|
topicPower = "power"
|
||||||
|
topicStatus = "status"
|
||||||
|
topicDeviceState = "device_state"
|
||||||
|
)
|
||||||
|
|
||||||
|
// telemetryTopics are the per-device suffixes a state read subscribes to.
|
||||||
|
var telemetryTopics = []string{topicCurrent, topicVoltage, topicPower, topicStatus, topicDeviceState}
|
||||||
|
|
||||||
|
// Device naming, mirroring the upstream integration.
|
||||||
|
const (
|
||||||
|
nameHabuDen = "Habu Den"
|
||||||
|
nameGeneric = "Greencell Device"
|
||||||
|
)
|
||||||
|
|
||||||
|
// habuDenSerial matches a HabuDen serial (greencell_client GreencellUtils).
|
||||||
|
var habuDenSerial = regexp.MustCompile(`^EVGC021[A-Z][0-9]{8}ZM[0-9]{4}$`)
|
||||||
|
|
||||||
|
// EVSE states the device reports on the status topic, lowercased. Anything the
|
||||||
|
// device sends that is not in this set is reported as stateUnknown rather than
|
||||||
|
// passed through, so a consumer can switch on a closed set.
|
||||||
|
const (
|
||||||
|
stateIdle = "idle"
|
||||||
|
stateConnected = "connected"
|
||||||
|
stateWaitingForCar = "waiting_for_car"
|
||||||
|
stateCharging = "charging"
|
||||||
|
stateFinished = "finished"
|
||||||
|
stateErrorCar = "error_car"
|
||||||
|
stateErrorEVSE = "error_evse"
|
||||||
|
stateUnavailable = "unavailable"
|
||||||
|
stateUnknown = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
var evseStates = map[string]bool{
|
||||||
|
stateIdle: true, stateConnected: true, stateWaitingForCar: true,
|
||||||
|
stateCharging: true, stateFinished: true, stateErrorCar: true,
|
||||||
|
stateErrorEVSE: true, stateUnavailable: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Access levels the device reports on device_state — the mode chosen in the GC
|
||||||
|
// app. OFFLINE is the deprecated spelling of UNAVAILABLE and is folded into it,
|
||||||
|
// as greencell_client does.
|
||||||
|
const (
|
||||||
|
accessDisabled = "disabled"
|
||||||
|
accessRead = "read"
|
||||||
|
accessExecute = "execute"
|
||||||
|
accessUnavailable = "unavailable"
|
||||||
|
accessUnknown = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Broker defaults. 1883 is plain MQTT, 8883 the TLS port.
|
||||||
|
const (
|
||||||
|
defaultPort = "1883"
|
||||||
|
defaultTLSPort = "8883"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Collection window bounds. A device answers a broadcast within 30 s per
|
||||||
|
// Greencell's own troubleshooting note, but that is far too long to hold an HTTP
|
||||||
|
// request open, so the default is shorter and the operator can raise it.
|
||||||
|
const (
|
||||||
|
defaultTimeout = 12 * time.Second
|
||||||
|
minTimeout = 1 * time.Second
|
||||||
|
maxTimeout = 60 * time.Second
|
||||||
|
// discoveryGrace is how much longer discovery listens after the first device
|
||||||
|
// replies, to catch the rest of a multi-charger site. Upstream uses the same
|
||||||
|
// half second.
|
||||||
|
discoveryGrace = 500 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
plugins.Register("greencell", func() plugins.Plugin { return &Plugin{} })
|
||||||
|
}
|
||||||
|
|
||||||
|
// snPlaceholder is substituted with the charger serial in a configured command
|
||||||
|
// topic, so one setting can serve every charger on a broker.
|
||||||
|
const snPlaceholder = "{sn}"
|
||||||
|
|
||||||
|
// queryCommand is the payload that asks a device to publish its state at once.
|
||||||
|
// Greencell documents QUERY as honoured in both READ and EXECUTE mode; what it
|
||||||
|
// does not document is the topic to send it on, hence commandTopic being an
|
||||||
|
// operator-supplied opt-in.
|
||||||
|
const queryCommand = "QUERY"
|
||||||
|
|
||||||
|
// Plugin is the Greencell EVSE connector.
|
||||||
|
type Plugin struct {
|
||||||
|
mu sync.Mutex // guards the config below; Invoke may run concurrently
|
||||||
|
address string
|
||||||
|
useTLS bool
|
||||||
|
username string
|
||||||
|
password string
|
||||||
|
serial string
|
||||||
|
commandTopic string
|
||||||
|
timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Descriptor returns the plugin's static metadata for the admin panel.
|
||||||
|
func (p *Plugin) Descriptor() plugins.Descriptor {
|
||||||
|
return plugins.Descriptor{
|
||||||
|
Name: "greencell",
|
||||||
|
Provider: "Greencell (HabuDen EV charger)",
|
||||||
|
Version: "1.0.0",
|
||||||
|
Kind: plugins.KindBuiltin,
|
||||||
|
Category: plugins.CategoryAPIsExternal,
|
||||||
|
AuthType: plugins.AuthBasic,
|
||||||
|
Capabilities: []plugins.Capability{
|
||||||
|
{ID: "chargers", Method: "SUB", Endpoint: discoveryTopic,
|
||||||
|
Description: "Discover Greencell chargers on the broker by publishing a broadcast and collecting the announcements."},
|
||||||
|
{ID: "charger-state", Method: "SUB", Endpoint: evsePrefix + "{sn}/#",
|
||||||
|
Description: "Normalized live state of one charger: EVSE status, access level, power, per-phase current and voltage (needs sn, or the configured serial)."},
|
||||||
|
},
|
||||||
|
ConfigFields: []plugins.ConfigField{
|
||||||
|
// As with the Toyota and Anker connectors, nothing is Required at the
|
||||||
|
// global layer: an operator may configure a shared broker here or leave
|
||||||
|
// it to the per-user cascade. Missing values surface as a clear error
|
||||||
|
// when a call is actually made.
|
||||||
|
{Key: "host", Label: "MQTT broker host", Type: "text",
|
||||||
|
Help: "Hostname or IP of the MQTT broker the charger was pointed at in the Greencell GC app (for example 10.2.1.10)."},
|
||||||
|
{Key: "port", Label: "MQTT broker port", Type: "number", Default: defaultPort,
|
||||||
|
Help: "Broker TCP port. Defaults to 1883, or 8883 when TLS is on."},
|
||||||
|
{Key: "tls", Label: "Use TLS", Type: "select", Default: "off",
|
||||||
|
Help: "Connect to the broker over TLS. Must match how the broker is configured.",
|
||||||
|
Options: []plugins.SelectOption{
|
||||||
|
{Value: "off", Label: "Off (plain MQTT)"},
|
||||||
|
{Value: "on", Label: "On (MQTTS)"},
|
||||||
|
}},
|
||||||
|
{Key: "username", Label: "MQTT username", Type: "text",
|
||||||
|
Help: "Broker username, if the broker requires authentication. Leave blank for an open broker."},
|
||||||
|
{Key: "password", Label: "MQTT password", Type: "password", Secret: true,
|
||||||
|
Help: "Broker password for the username above."},
|
||||||
|
{Key: "serial", Label: "Charger serial", Type: "text",
|
||||||
|
Help: "Serial of the charger, e.g. EVGC021B22752405ZM0018. Optional — leave blank and discovery will find whatever is on the broker."},
|
||||||
|
{Key: "commandTopic", Label: "QUERY command topic", Type: "text",
|
||||||
|
Help: "Optional. Greencell documents a QUERY command that makes the charger publish its state immediately, but not the topic to send it on — no published source names it. If you find yours (watch your broker while the GC app talks to the charger), put it here and reads stop waiting for the device's own cadence. Use " + snPlaceholder + " for the serial, e.g. /greencell/evse/" + snPlaceholder + "/command. Leave blank to listen only."},
|
||||||
|
{Key: "timeout", Label: "Listen window (seconds)", Type: "number", Default: "12",
|
||||||
|
Help: "How long to wait for the charger to publish before answering. Greencell allows a device up to 30 s to respond to a broadcast; raise this if discovery comes back empty."},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init applies resolved config. It performs no network I/O — every call opens its
|
||||||
|
// own short-lived broker session.
|
||||||
|
func (p *Plugin) Init(_ context.Context, config map[string]string) error {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
p.useTLS = truthy(config["tls"])
|
||||||
|
host := strings.TrimSpace(config["host"])
|
||||||
|
port := strings.TrimSpace(config["port"])
|
||||||
|
if port == "" {
|
||||||
|
port = defaultPort
|
||||||
|
if p.useTLS {
|
||||||
|
port = defaultTLSPort
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.address = ""
|
||||||
|
if host != "" {
|
||||||
|
p.address = net.JoinHostPort(host, port)
|
||||||
|
}
|
||||||
|
p.username = strings.TrimSpace(config["username"])
|
||||||
|
p.password = config["password"]
|
||||||
|
p.serial = strings.TrimSpace(config["serial"])
|
||||||
|
p.commandTopic = strings.TrimSpace(config["commandTopic"])
|
||||||
|
p.timeout = parseTimeout(config["timeout"])
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HealthCheck connects to the broker and asks whatever is listening to announce
|
||||||
|
// itself. A reachable broker with no charger on it is degraded rather than down:
|
||||||
|
// the half we configure works, and the missing half is the device.
|
||||||
|
func (p *Plugin) HealthCheck(ctx context.Context) plugins.Health {
|
||||||
|
start := time.Now()
|
||||||
|
found, err := p.discover(ctx)
|
||||||
|
lat := time.Since(start).Milliseconds()
|
||||||
|
if err != nil {
|
||||||
|
return plugins.Health{Status: plugins.StatusDown, LatencyMs: lat, Detail: shorten(err.Error())}
|
||||||
|
}
|
||||||
|
if len(found) == 0 {
|
||||||
|
return plugins.Health{Status: plugins.StatusDegraded, LatencyMs: lat,
|
||||||
|
Detail: "broker reachable, but no Greencell device answered the discovery broadcast"}
|
||||||
|
}
|
||||||
|
return plugins.Health{Status: plugins.StatusOK, LatencyMs: lat,
|
||||||
|
Detail: fmt.Sprintf("broker reachable; %d Greencell device(s) answered", len(found))}
|
||||||
|
}
|
||||||
|
|
||||||
|
// invokeParams is what an action may be given. Per-charger actions take "sn"; it
|
||||||
|
// falls back to the configured serial when omitted.
|
||||||
|
type invokeParams struct {
|
||||||
|
SN string `json:"sn"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invoke runs a named read-only capability.
|
||||||
|
func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessage) (json.RawMessage, error) {
|
||||||
|
var pp invokeParams
|
||||||
|
if len(params) > 0 {
|
||||||
|
if err := json.Unmarshal(params, &pp); err != nil {
|
||||||
|
return nil, fmt.Errorf("greencell: invalid params: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sn := strings.TrimSpace(pp.SN)
|
||||||
|
if sn == "" {
|
||||||
|
sn = p.configuredSerial()
|
||||||
|
}
|
||||||
|
|
||||||
|
switch action {
|
||||||
|
case "chargers":
|
||||||
|
found, err := p.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{"chargers": found})
|
||||||
|
case "charger-state":
|
||||||
|
if sn == "" {
|
||||||
|
return nil, errors.New("greencell: action \"charger-state\" requires an sn (charger serial), or a serial in the plugin config")
|
||||||
|
}
|
||||||
|
st, err := p.chargerState(ctx, sn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.Marshal(st)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("greencell: unknown action %q", action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown has nothing to release: sessions do not outlive a call.
|
||||||
|
func (p *Plugin) Shutdown(context.Context) error { return nil }
|
||||||
|
|
||||||
|
// ---- broker session ----------------------------------------------------------
|
||||||
|
|
||||||
|
// snapshot copies the config under the lock so a call is not affected by a
|
||||||
|
// concurrent Init.
|
||||||
|
func (p *Plugin) snapshot() (opts mqtt.Options, timeout time.Duration, err error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if p.address == "" {
|
||||||
|
return mqtt.Options{}, 0, errors.New("greencell: no MQTT broker configured — set the broker host the charger publishes to")
|
||||||
|
}
|
||||||
|
return mqtt.Options{
|
||||||
|
Address: p.address,
|
||||||
|
TLS: p.useTLS,
|
||||||
|
Username: p.username,
|
||||||
|
Password: p.password,
|
||||||
|
// One keep-alive period comfortably outlives a listen window, so the
|
||||||
|
// session never has to ping mid-collection.
|
||||||
|
Keepalive: 60 * time.Second,
|
||||||
|
ConnectTimeout: 10 * time.Second,
|
||||||
|
}, p.timeout, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) configuredSerial() string {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return p.serial
|
||||||
|
}
|
||||||
|
|
||||||
|
// commandTopicFor resolves the configured QUERY topic for one charger, or ""
|
||||||
|
// when the operator has not supplied one.
|
||||||
|
func (p *Plugin) commandTopicFor(sn string) string {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if p.commandTopic == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.ReplaceAll(p.commandTopic, snPlaceholder, sn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// session opens a broker connection, subscribes to topics, and publishes the
|
||||||
|
// discovery broadcast that prompts devices to speak up. The caller drains
|
||||||
|
// client.Messages until it has what it came for or its window runs out, then
|
||||||
|
// closes the client.
|
||||||
|
func (p *Plugin) session(ctx context.Context, topics []string) (*mqtt.Client, time.Duration, error) {
|
||||||
|
opts, timeout, err := p.snapshot()
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
client, err := mqtt.Connect(ctx, opts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
if err := client.Subscribe(ctx, topics...); err != nil {
|
||||||
|
_ = client.Close()
|
||||||
|
return nil, 0, fmt.Errorf("greencell: subscribing on the broker: %w", err)
|
||||||
|
}
|
||||||
|
// The broadcast is what makes an otherwise-quiet device announce itself; the
|
||||||
|
// telemetry topics then follow on the device's own cadence.
|
||||||
|
if err := client.Publish(ctx, broadcastTopic, []byte(`{"name":"BROADCAST"}`)); err != nil {
|
||||||
|
_ = client.Close()
|
||||||
|
return nil, 0, fmt.Errorf("greencell: publishing the discovery broadcast: %w", err)
|
||||||
|
}
|
||||||
|
return client, timeout, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- discovery ---------------------------------------------------------------
|
||||||
|
|
||||||
|
// Device is one charger that answered the discovery broadcast.
|
||||||
|
type Device struct {
|
||||||
|
SN string `json:"sn"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
// Announcement is the device's own broadcast payload, passed through
|
||||||
|
// unchanged: Greencell may carry firmware or capability fields there that
|
||||||
|
// this connector has no schema for.
|
||||||
|
Announcement json.RawMessage `json:"announcement,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// discover collects the devices that answer a broadcast. It listens for the full
|
||||||
|
// window, cut short by discoveryGrace once at least one device has replied.
|
||||||
|
func (p *Plugin) discover(ctx context.Context) ([]Device, error) {
|
||||||
|
client, timeout, err := p.session(ctx, []string{discoveryTopic})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer client.Close()
|
||||||
|
|
||||||
|
found := map[string]Device{}
|
||||||
|
var order []string
|
||||||
|
|
||||||
|
deadline := time.NewTimer(timeout)
|
||||||
|
defer deadline.Stop()
|
||||||
|
var grace *time.Timer
|
||||||
|
graceC := func() <-chan time.Time {
|
||||||
|
if grace == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return grace.C
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case msg, ok := <-client.Messages():
|
||||||
|
if !ok {
|
||||||
|
if err := client.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return devicesInOrder(found, order), nil
|
||||||
|
}
|
||||||
|
if msg.Topic != discoveryTopic {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dev, ok := parseAnnouncement(msg.Payload)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, seen := found[dev.SN]; !seen {
|
||||||
|
order = append(order, dev.SN)
|
||||||
|
}
|
||||||
|
found[dev.SN] = dev
|
||||||
|
if grace == nil {
|
||||||
|
grace = time.NewTimer(discoveryGrace)
|
||||||
|
defer grace.Stop()
|
||||||
|
}
|
||||||
|
case <-graceC():
|
||||||
|
return devicesInOrder(found, order), nil
|
||||||
|
case <-deadline.C:
|
||||||
|
return devicesInOrder(found, order), nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// devicesInOrder returns the collected devices in the order they answered.
|
||||||
|
func devicesInOrder(found map[string]Device, order []string) []Device {
|
||||||
|
out := make([]Device, 0, len(order))
|
||||||
|
for _, sn := range order {
|
||||||
|
out = append(out, found[sn])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseAnnouncement reads a device announcement. A payload without a usable "id"
|
||||||
|
// is not a device and is ignored.
|
||||||
|
func parseAnnouncement(payload []byte) (Device, bool) {
|
||||||
|
var doc struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(payload, &doc); err != nil {
|
||||||
|
return Device{}, false
|
||||||
|
}
|
||||||
|
sn := strings.TrimSpace(doc.ID)
|
||||||
|
if sn == "" {
|
||||||
|
return Device{}, false
|
||||||
|
}
|
||||||
|
model := deviceModel(sn)
|
||||||
|
return Device{
|
||||||
|
SN: sn,
|
||||||
|
Name: model + " " + sn,
|
||||||
|
Model: model,
|
||||||
|
Announcement: json.RawMessage(append([]byte(nil), payload...)),
|
||||||
|
}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceModel names a device from its serial.
|
||||||
|
func deviceModel(sn string) string {
|
||||||
|
if habuDenSerial.MatchString(sn) {
|
||||||
|
return nameHabuDen
|
||||||
|
}
|
||||||
|
return nameGeneric
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- live state --------------------------------------------------------------
|
||||||
|
|
||||||
|
// Phases holds a per-phase measurement. A phase the device did not report stays
|
||||||
|
// nil rather than reading as zero, which on a charger would be a real value.
|
||||||
|
type Phases struct {
|
||||||
|
L1 *float64 `json:"l1"`
|
||||||
|
L2 *float64 `json:"l2"`
|
||||||
|
L3 *float64 `json:"l3"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// State is one charger's normalized live state.
|
||||||
|
type State struct {
|
||||||
|
SN string `json:"sn"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
|
||||||
|
// Status is the EVSE state, lowercased and constrained to the known set.
|
||||||
|
Status string `json:"status"`
|
||||||
|
Charging bool `json:"charging"`
|
||||||
|
// Plugged is true in every state that implies a cable in the socket.
|
||||||
|
Plugged bool `json:"plugged"`
|
||||||
|
// Fault is true for the two error states.
|
||||||
|
Fault bool `json:"fault"`
|
||||||
|
|
||||||
|
// AccessLevel is the integration mode set in the Greencell GC app, and
|
||||||
|
// CanExecute is whether that mode would accept commands. Control is not
|
||||||
|
// implemented (see the package comment); this reports what the device allows.
|
||||||
|
AccessLevel string `json:"accessLevel"`
|
||||||
|
CanExecute bool `json:"canExecute"`
|
||||||
|
Available bool `json:"available"`
|
||||||
|
|
||||||
|
PowerW *float64 `json:"powerW"`
|
||||||
|
CurrentA Phases `json:"currentA"`
|
||||||
|
VoltageV Phases `json:"voltageV"`
|
||||||
|
// LivePhases counts the phases currently drawing a meaningful current, which
|
||||||
|
// is what separates a 1-phase from a 3-phase charge on a 22 kW wallbox.
|
||||||
|
LivePhases int `json:"livePhases"`
|
||||||
|
|
||||||
|
// Received says which topics were heard inside the listen window; a false
|
||||||
|
// entry means that field is unset, not zero.
|
||||||
|
Received map[string]bool `json:"received"`
|
||||||
|
// Raw is each topic's last payload, verbatim, for fields this connector has
|
||||||
|
// no schema for.
|
||||||
|
Raw map[string]json.RawMessage `json:"raw,omitempty"`
|
||||||
|
ObservedAt time.Time `json:"observedAt"`
|
||||||
|
// Complete is true when every telemetry topic reported inside the window.
|
||||||
|
Complete bool `json:"complete"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// chargerState listens for one charger's telemetry and normalizes it. It returns
|
||||||
|
// as soon as every topic has been heard, or at the end of the window with
|
||||||
|
// whatever arrived — a device that publishes some topics on a slower cadence
|
||||||
|
// still yields a useful partial reading, flagged by Received/Complete. Total
|
||||||
|
// silence is an error: that means the charger is not on this broker.
|
||||||
|
func (p *Plugin) chargerState(ctx context.Context, sn string) (State, error) {
|
||||||
|
topics := make([]string, 0, len(telemetryTopics)+1)
|
||||||
|
topics = append(topics, discoveryTopic)
|
||||||
|
for _, suffix := range telemetryTopics {
|
||||||
|
topics = append(topics, evsePrefix+sn+"/"+suffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
client, timeout, err := p.session(ctx, topics)
|
||||||
|
if err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
defer client.Close()
|
||||||
|
|
||||||
|
// When the operator has told us where the charger listens, ask it to publish
|
||||||
|
// now rather than waiting out its own cadence. A device in DISABLE or READ
|
||||||
|
// mode ignores every other command but this one, so it is safe to send
|
||||||
|
// whatever mode the charger is in. Failing to publish is not fatal: the
|
||||||
|
// listen-only path still works.
|
||||||
|
if topic := p.commandTopicFor(sn); topic != "" {
|
||||||
|
_ = client.Publish(ctx, topic, []byte(queryCommand))
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := map[string]json.RawMessage{}
|
||||||
|
deadline := time.NewTimer(timeout)
|
||||||
|
defer deadline.Stop()
|
||||||
|
|
||||||
|
collect:
|
||||||
|
for len(raw) < len(telemetryTopics) {
|
||||||
|
select {
|
||||||
|
case msg, ok := <-client.Messages():
|
||||||
|
if !ok {
|
||||||
|
if err := client.Err(); err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
break collect
|
||||||
|
}
|
||||||
|
if suffix, match := topicSuffix(msg.Topic, sn); match && json.Valid(msg.Payload) {
|
||||||
|
raw[suffix] = json.RawMessage(append([]byte(nil), msg.Payload...))
|
||||||
|
}
|
||||||
|
case <-deadline.C:
|
||||||
|
break collect
|
||||||
|
case <-ctx.Done():
|
||||||
|
return State{}, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return State{}, fmt.Errorf("greencell: no data from charger %s within %s — check that it is powered, on this broker, and not set to DISABLE in the GC app", sn, timeout)
|
||||||
|
}
|
||||||
|
return buildState(sn, raw), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// topicSuffix maps a received topic back to its per-device suffix.
|
||||||
|
func topicSuffix(topic, sn string) (string, bool) {
|
||||||
|
prefix := evsePrefix + sn + "/"
|
||||||
|
if !strings.HasPrefix(topic, prefix) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
suffix := strings.TrimPrefix(topic, prefix)
|
||||||
|
for _, known := range telemetryTopics {
|
||||||
|
if suffix == known {
|
||||||
|
return suffix, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildState turns the collected payloads into a normalized reading.
|
||||||
|
func buildState(sn string, raw map[string]json.RawMessage) State {
|
||||||
|
model := deviceModel(sn)
|
||||||
|
st := State{
|
||||||
|
SN: sn,
|
||||||
|
Name: model + " " + sn,
|
||||||
|
Model: model,
|
||||||
|
Status: stateUnknown,
|
||||||
|
AccessLevel: accessUnknown,
|
||||||
|
Received: map[string]bool{},
|
||||||
|
Raw: raw,
|
||||||
|
ObservedAt: time.Now().UTC(),
|
||||||
|
}
|
||||||
|
for _, suffix := range telemetryTopics {
|
||||||
|
st.Received[suffix] = raw[suffix] != nil
|
||||||
|
}
|
||||||
|
st.Complete = len(raw) == len(telemetryTopics)
|
||||||
|
|
||||||
|
// Current arrives in milliamps; every other consumer wants amperes.
|
||||||
|
st.CurrentA = scalePhases(parsePhases(raw[topicCurrent]), 1.0/1000.0)
|
||||||
|
st.VoltageV = parsePhases(raw[topicVoltage])
|
||||||
|
st.PowerW = numberField(raw[topicPower], "momentary")
|
||||||
|
|
||||||
|
if s, ok := stringField(raw[topicStatus], "state"); ok {
|
||||||
|
st.Status = normalizeState(s)
|
||||||
|
}
|
||||||
|
// The device also signals unavailability through the status topic itself,
|
||||||
|
// which upstream detects by substring because the payload is not a state
|
||||||
|
// document in that case.
|
||||||
|
if isUnavailable(raw[topicStatus]) {
|
||||||
|
st.Status = stateUnavailable
|
||||||
|
}
|
||||||
|
|
||||||
|
if s, ok := stringField(raw[topicDeviceState], "level"); ok {
|
||||||
|
st.AccessLevel = normalizeAccess(s)
|
||||||
|
}
|
||||||
|
st.CanExecute = st.AccessLevel == accessExecute
|
||||||
|
st.Available = st.AccessLevel != accessDisabled && st.AccessLevel != accessUnavailable &&
|
||||||
|
st.Status != stateUnavailable
|
||||||
|
|
||||||
|
st.Charging = st.Status == stateCharging
|
||||||
|
switch st.Status {
|
||||||
|
case stateConnected, stateWaitingForCar, stateCharging, stateFinished, stateErrorCar:
|
||||||
|
st.Plugged = true
|
||||||
|
}
|
||||||
|
st.Fault = st.Status == stateErrorCar || st.Status == stateErrorEVSE
|
||||||
|
st.LivePhases = countLivePhases(st.CurrentA)
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
// livePhaseThreshold is the current above which a phase counts as carrying a
|
||||||
|
// charge, in amperes. Greencell's own floor for a charging session is 6 A, so
|
||||||
|
// anything under an amp is measurement noise on an idle phase.
|
||||||
|
const livePhaseThreshold = 1.0
|
||||||
|
|
||||||
|
func countLivePhases(p Phases) int {
|
||||||
|
n := 0
|
||||||
|
for _, v := range []*float64{p.L1, p.L2, p.L3} {
|
||||||
|
if v != nil && *v >= livePhaseThreshold {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeState constrains a reported EVSE state to the known set.
|
||||||
|
func normalizeState(s string) string {
|
||||||
|
v := strings.ToLower(strings.TrimSpace(s))
|
||||||
|
if evseStates[v] {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return stateUnknown
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeAccess maps a reported access level to the known set, folding the
|
||||||
|
// deprecated OFFLINE into UNAVAILABLE as greencell_client does.
|
||||||
|
func normalizeAccess(s string) string {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||||
|
case "execute":
|
||||||
|
return accessExecute
|
||||||
|
case "read":
|
||||||
|
return accessRead
|
||||||
|
case "disabled", "disable":
|
||||||
|
return accessDisabled
|
||||||
|
case "offline", "unavailable":
|
||||||
|
return accessUnavailable
|
||||||
|
default:
|
||||||
|
return accessUnknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isUnavailable reports whether a status payload is one of the out-of-band
|
||||||
|
// unavailability markers rather than a state document.
|
||||||
|
func isUnavailable(payload json.RawMessage) bool {
|
||||||
|
if payload == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
up := strings.ToUpper(string(payload))
|
||||||
|
return strings.Contains(up, "UNAVAILABLE") || strings.Contains(up, "OFFLINE")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- payload parsing ---------------------------------------------------------
|
||||||
|
|
||||||
|
// parsePhases reads an {"l1":…,"l2":…,"l3":…} payload. A phase that is absent or
|
||||||
|
// not a number stays nil — the device is documented to send numbers, and a
|
||||||
|
// non-numeric value is better reported as missing than coerced to zero.
|
||||||
|
func parsePhases(payload json.RawMessage) Phases {
|
||||||
|
if payload == nil {
|
||||||
|
return Phases{}
|
||||||
|
}
|
||||||
|
var doc map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(payload, &doc); err != nil {
|
||||||
|
return Phases{}
|
||||||
|
}
|
||||||
|
return Phases{L1: asNumber(doc["l1"]), L2: asNumber(doc["l2"]), L3: asNumber(doc["l3"])}
|
||||||
|
}
|
||||||
|
|
||||||
|
// scalePhases multiplies every present phase by factor.
|
||||||
|
func scalePhases(p Phases, factor float64) Phases {
|
||||||
|
scale := func(v *float64) *float64 {
|
||||||
|
if v == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := *v * factor
|
||||||
|
return &out
|
||||||
|
}
|
||||||
|
return Phases{L1: scale(p.L1), L2: scale(p.L2), L3: scale(p.L3)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// numberField reads one numeric field out of a payload.
|
||||||
|
func numberField(payload json.RawMessage, key string) *float64 {
|
||||||
|
if payload == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var doc map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(payload, &doc); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return asNumber(doc[key])
|
||||||
|
}
|
||||||
|
|
||||||
|
// stringField reads one string field out of a payload.
|
||||||
|
func stringField(payload json.RawMessage, key string) (string, bool) {
|
||||||
|
if payload == nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
var doc map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(payload, &doc); err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
var s string
|
||||||
|
if err := json.Unmarshal(doc[key], &s); err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return s, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// asNumber decodes a JSON number, also accepting one quoted as a string, which
|
||||||
|
// some firmware revisions do.
|
||||||
|
func asNumber(raw json.RawMessage) *float64 {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// json.Unmarshal accepts null into a float64 and leaves it at zero, which on a
|
||||||
|
// charger is a real reading; an explicit null means "no value".
|
||||||
|
if string(raw) == "null" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var f float64
|
||||||
|
if err := json.Unmarshal(raw, &f); err == nil {
|
||||||
|
return &f
|
||||||
|
}
|
||||||
|
var s string
|
||||||
|
if err := json.Unmarshal(raw, &s); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
f, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &f
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- config helpers ----------------------------------------------------------
|
||||||
|
|
||||||
|
// truthy reads a boolean-ish config value; the panel writes selects as strings.
|
||||||
|
func truthy(v string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||||
|
case "on", "true", "yes", "1", "tls", "mqtts":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTimeout reads the listen window in seconds, clamped to a range that keeps
|
||||||
|
// an HTTP request honest at one end and useful at the other.
|
||||||
|
func parseTimeout(v string) time.Duration {
|
||||||
|
n, err := strconv.Atoi(strings.TrimSpace(v))
|
||||||
|
if err != nil || n <= 0 {
|
||||||
|
return defaultTimeout
|
||||||
|
}
|
||||||
|
d := time.Duration(n) * time.Second
|
||||||
|
return max(minTimeout, min(d, maxTimeout))
|
||||||
|
}
|
||||||
|
|
||||||
|
// shorten trims a message to something a health detail can carry.
|
||||||
|
func shorten(s string) string {
|
||||||
|
const limit = 200
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if len(s) <= limit {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s[:limit] + "…"
|
||||||
|
}
|
||||||
@@ -0,0 +1,852 @@
|
|||||||
|
package greencell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"drivervault/apiserver/internal/plugins"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---- descriptor & registration -----------------------------------------------
|
||||||
|
|
||||||
|
func TestDescriptor(t *testing.T) {
|
||||||
|
d := (&Plugin{}).Descriptor()
|
||||||
|
if d.Name != "greencell" {
|
||||||
|
t.Fatalf("name = %q, want greencell", d.Name)
|
||||||
|
}
|
||||||
|
if d.Kind != plugins.KindBuiltin {
|
||||||
|
t.Fatalf("kind = %q, want builtin", d.Kind)
|
||||||
|
}
|
||||||
|
if len(d.Capabilities) == 0 {
|
||||||
|
t.Fatal("expected capabilities")
|
||||||
|
}
|
||||||
|
|
||||||
|
fields := map[string]plugins.ConfigField{}
|
||||||
|
for _, f := range d.ConfigFields {
|
||||||
|
fields[f.Key] = f
|
||||||
|
}
|
||||||
|
for _, k := range []string{"host", "port", "tls", "username", "password", "serial", "commandTopic", "timeout"} {
|
||||||
|
if _, ok := fields[k]; !ok {
|
||||||
|
t.Errorf("config field %q should be present", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Nothing is required at the global layer — the per-user cascade may supply
|
||||||
|
// the broker instead, exactly as it does for the other connectors.
|
||||||
|
for k, f := range fields {
|
||||||
|
if f.Required {
|
||||||
|
t.Errorf("config field %q must not be required at the global layer", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !fields["password"].Secret {
|
||||||
|
t.Error("the broker password must be marked secret")
|
||||||
|
}
|
||||||
|
if fields["username"].Secret {
|
||||||
|
t.Error("the broker username is not a secret")
|
||||||
|
}
|
||||||
|
if fields["tls"].Type != "select" {
|
||||||
|
t.Errorf("tls type = %q, want select", fields["tls"].Type)
|
||||||
|
}
|
||||||
|
if fields["port"].Default != defaultPort {
|
||||||
|
t.Errorf("port default = %q, want %q", fields["port"].Default, defaultPort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistered(t *testing.T) {
|
||||||
|
// init() must have registered the factory; registering twice panics, so a
|
||||||
|
// duplicate name would surface at startup rather than here.
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r == nil {
|
||||||
|
t.Fatal("expected a panic on duplicate registration, meaning the plugin registered itself")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
plugins.Register("greencell", func() plugins.Plugin { return &Plugin{} })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- config ------------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestInitBuildsBrokerAddress(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
config map[string]string
|
||||||
|
address string
|
||||||
|
tls bool
|
||||||
|
}{
|
||||||
|
{"explicit port", map[string]string{"host": "10.2.1.10", "port": "1884"}, "10.2.1.10:1884", false},
|
||||||
|
{"default plain port", map[string]string{"host": "mqtt.local"}, "mqtt.local:1883", false},
|
||||||
|
{"default tls port", map[string]string{"host": "mqtt.local", "tls": "on"}, "mqtt.local:8883", true},
|
||||||
|
{"tls with explicit port", map[string]string{"host": "mqtt.local", "tls": "true", "port": "9001"}, "mqtt.local:9001", true},
|
||||||
|
{"ipv6 host", map[string]string{"host": "fd00::1", "port": "1883"}, "[fd00::1]:1883", false},
|
||||||
|
{"no host", map[string]string{}, "", false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
if err := p.Init(context.Background(), tc.config); err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
if p.address != tc.address {
|
||||||
|
t.Errorf("address = %q, want %q", p.address, tc.address)
|
||||||
|
}
|
||||||
|
if p.useTLS != tc.tls {
|
||||||
|
t.Errorf("useTLS = %v, want %v", p.useTLS, tc.tls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotWithoutBrokerIsAnError(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
_ = p.Init(context.Background(), map[string]string{})
|
||||||
|
if _, _, err := p.snapshot(); err == nil {
|
||||||
|
t.Fatal("expected an error when no broker is configured")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTimeout(t *testing.T) {
|
||||||
|
cases := map[string]time.Duration{
|
||||||
|
"": defaultTimeout,
|
||||||
|
"abc": defaultTimeout,
|
||||||
|
"0": defaultTimeout,
|
||||||
|
"-5": defaultTimeout,
|
||||||
|
" 20 ": 20 * time.Second,
|
||||||
|
"1": minTimeout,
|
||||||
|
"600": maxTimeout, // clamped
|
||||||
|
"999999": maxTimeout,
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := parseTimeout(in); got != want {
|
||||||
|
t.Errorf("parseTimeout(%q) = %v, want %v", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTruthy(t *testing.T) {
|
||||||
|
for _, v := range []string{"on", "ON", "true", "yes", "1", " tls "} {
|
||||||
|
if !truthy(v) {
|
||||||
|
t.Errorf("truthy(%q) = false", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, v := range []string{"", "off", "false", "no", "0", "maybe"} {
|
||||||
|
if truthy(v) {
|
||||||
|
t.Errorf("truthy(%q) = true", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- serials & announcements -------------------------------------------------
|
||||||
|
|
||||||
|
func TestDeviceModel(t *testing.T) {
|
||||||
|
// The HabuDen pattern comes from greencell_client's GreencellUtils.
|
||||||
|
if got := deviceModel("EVGC021B22752405ZM0018"); got != nameHabuDen {
|
||||||
|
t.Errorf("HabuDen serial named %q, want %q", got, nameHabuDen)
|
||||||
|
}
|
||||||
|
for _, sn := range []string{"EVGC031B22752405ZM0018", "EVGC022B22752405ZM0018", "HABU_DEN", ""} {
|
||||||
|
if got := deviceModel(sn); got != nameGeneric {
|
||||||
|
t.Errorf("deviceModel(%q) = %q, want %q", sn, got, nameGeneric)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseAnnouncement(t *testing.T) {
|
||||||
|
dev, ok := parseAnnouncement([]byte(`{"id":"EVGC021B22752405ZM0018","fw":"1.2.3"}`))
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("a payload with an id should parse")
|
||||||
|
}
|
||||||
|
if dev.SN != "EVGC021B22752405ZM0018" {
|
||||||
|
t.Errorf("sn = %q", dev.SN)
|
||||||
|
}
|
||||||
|
if dev.Model != nameHabuDen || !strings.HasPrefix(dev.Name, nameHabuDen+" ") {
|
||||||
|
t.Errorf("name/model = %q / %q", dev.Name, dev.Model)
|
||||||
|
}
|
||||||
|
// Fields this connector has no schema for must survive.
|
||||||
|
if !strings.Contains(string(dev.Announcement), `"fw":"1.2.3"`) {
|
||||||
|
t.Errorf("announcement should be passed through verbatim, got %s", dev.Announcement)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, bad := range []string{`{"id":""}`, `{"id":" "}`, `{"name":"BROADCAST"}`, `not json`, ``} {
|
||||||
|
if _, ok := parseAnnouncement([]byte(bad)); ok {
|
||||||
|
t.Errorf("parseAnnouncement(%q) should have been rejected", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTopicSuffix(t *testing.T) {
|
||||||
|
sn := "SN1"
|
||||||
|
for _, want := range telemetryTopics {
|
||||||
|
got, ok := topicSuffix(evsePrefix+sn+"/"+want, sn)
|
||||||
|
if !ok || got != want {
|
||||||
|
t.Errorf("topicSuffix for %q = %q/%v", want, got, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, topic := range []string{
|
||||||
|
evsePrefix + "OTHER/current", // another charger
|
||||||
|
evsePrefix + sn + "/unknown", // a topic we do not model
|
||||||
|
discoveryTopic,
|
||||||
|
evsePrefix + sn, // no suffix at all
|
||||||
|
} {
|
||||||
|
if _, ok := topicSuffix(topic, sn); ok {
|
||||||
|
t.Errorf("topicSuffix(%q) should not match", topic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- payload parsing ---------------------------------------------------------
|
||||||
|
|
||||||
|
func TestAsNumber(t *testing.T) {
|
||||||
|
f := asNumber(json.RawMessage(`230.5`))
|
||||||
|
if f == nil || *f != 230.5 {
|
||||||
|
t.Errorf("number = %v", f)
|
||||||
|
}
|
||||||
|
// Some firmware quotes its numbers.
|
||||||
|
f = asNumber(json.RawMessage(`"16000"`))
|
||||||
|
if f == nil || *f != 16000 {
|
||||||
|
t.Errorf("quoted number = %v", f)
|
||||||
|
}
|
||||||
|
for _, bad := range []string{`null`, `"abc"`, `{}`, ``} {
|
||||||
|
if got := asNumber(json.RawMessage(bad)); got != nil {
|
||||||
|
t.Errorf("asNumber(%q) = %v, want nil", bad, *got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParsePhasesLeavesMissingPhasesUnset(t *testing.T) {
|
||||||
|
// A single-phase charge reports only l1; l2/l3 must stay nil rather than
|
||||||
|
// reading as a real zero.
|
||||||
|
p := parsePhases(json.RawMessage(`{"l1":16000}`))
|
||||||
|
if p.L1 == nil || *p.L1 != 16000 {
|
||||||
|
t.Errorf("l1 = %v", p.L1)
|
||||||
|
}
|
||||||
|
if p.L2 != nil || p.L3 != nil {
|
||||||
|
t.Errorf("missing phases should be nil, got %v %v", p.L2, p.L3)
|
||||||
|
}
|
||||||
|
if got := parsePhases(json.RawMessage(`not json`)); got.L1 != nil {
|
||||||
|
t.Error("a malformed payload should yield no phases")
|
||||||
|
}
|
||||||
|
if got := parsePhases(nil); got.L1 != nil {
|
||||||
|
t.Error("a missing payload should yield no phases")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeState(t *testing.T) {
|
||||||
|
if got := normalizeState("CHARGING"); got != stateCharging {
|
||||||
|
t.Errorf("CHARGING -> %q", got)
|
||||||
|
}
|
||||||
|
if got := normalizeState(" waiting_for_car "); got != stateWaitingForCar {
|
||||||
|
t.Errorf("waiting_for_car -> %q", got)
|
||||||
|
}
|
||||||
|
for _, in := range []string{"", "SOMETHING_NEW", "UNKNOWN"} {
|
||||||
|
if got := normalizeState(in); got != stateUnknown {
|
||||||
|
t.Errorf("normalizeState(%q) = %q, want unknown", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeAccess(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"EXECUTE": accessExecute, "read": accessRead, "DISABLED": accessDisabled,
|
||||||
|
"UNAVAILABLE": accessUnavailable,
|
||||||
|
// OFFLINE is greencell_client's deprecated spelling of UNAVAILABLE.
|
||||||
|
"OFFLINE": accessUnavailable,
|
||||||
|
"": accessUnknown, "nonsense": accessUnknown,
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := normalizeAccess(in); got != want {
|
||||||
|
t.Errorf("normalizeAccess(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStateThreePhaseCharge(t *testing.T) {
|
||||||
|
raw := map[string]json.RawMessage{
|
||||||
|
topicCurrent: json.RawMessage(`{"l1":16000,"l2":15980,"l3":16010}`),
|
||||||
|
topicVoltage: json.RawMessage(`{"l1":230.1,"l2":229.7,"l3":231.0}`),
|
||||||
|
topicPower: json.RawMessage(`{"momentary":11040}`),
|
||||||
|
topicStatus: json.RawMessage(`{"state":"CHARGING"}`),
|
||||||
|
topicDeviceState: json.RawMessage(`{"level":"EXECUTE"}`),
|
||||||
|
}
|
||||||
|
st := buildState("EVGC021B22752405ZM0018", raw)
|
||||||
|
|
||||||
|
if !st.Complete {
|
||||||
|
t.Error("all five topics reported, so the reading is complete")
|
||||||
|
}
|
||||||
|
// Current is published in milliamps.
|
||||||
|
if st.CurrentA.L1 == nil || *st.CurrentA.L1 != 16 {
|
||||||
|
t.Errorf("l1 current = %v A, want 16", st.CurrentA.L1)
|
||||||
|
}
|
||||||
|
if st.VoltageV.L1 == nil || *st.VoltageV.L1 != 230.1 {
|
||||||
|
t.Errorf("l1 voltage = %v", st.VoltageV.L1)
|
||||||
|
}
|
||||||
|
if st.PowerW == nil || *st.PowerW != 11040 {
|
||||||
|
t.Errorf("power = %v", st.PowerW)
|
||||||
|
}
|
||||||
|
if st.Status != stateCharging || !st.Charging || !st.Plugged || st.Fault {
|
||||||
|
t.Errorf("status flags: %q charging=%v plugged=%v fault=%v", st.Status, st.Charging, st.Plugged, st.Fault)
|
||||||
|
}
|
||||||
|
if st.AccessLevel != accessExecute || !st.CanExecute || !st.Available {
|
||||||
|
t.Errorf("access: %q canExecute=%v available=%v", st.AccessLevel, st.CanExecute, st.Available)
|
||||||
|
}
|
||||||
|
if st.LivePhases != 3 {
|
||||||
|
t.Errorf("livePhases = %d, want 3", st.LivePhases)
|
||||||
|
}
|
||||||
|
if st.Model != nameHabuDen {
|
||||||
|
t.Errorf("model = %q", st.Model)
|
||||||
|
}
|
||||||
|
if st.ObservedAt.IsZero() {
|
||||||
|
t.Error("observedAt should be stamped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStateSinglePhaseAndPartial(t *testing.T) {
|
||||||
|
// Only two topics reported: the rest must read as unset, not as zero.
|
||||||
|
raw := map[string]json.RawMessage{
|
||||||
|
topicCurrent: json.RawMessage(`{"l1":16000,"l2":30,"l3":0}`),
|
||||||
|
topicStatus: json.RawMessage(`{"state":"CHARGING"}`),
|
||||||
|
}
|
||||||
|
st := buildState("SN1", raw)
|
||||||
|
|
||||||
|
if st.Complete {
|
||||||
|
t.Error("a partial reading must not claim to be complete")
|
||||||
|
}
|
||||||
|
if st.Received[topicCurrent] != true || st.Received[topicPower] != false {
|
||||||
|
t.Errorf("received map = %v", st.Received)
|
||||||
|
}
|
||||||
|
if st.PowerW != nil {
|
||||||
|
t.Errorf("power = %v, want nil when the topic was silent", *st.PowerW)
|
||||||
|
}
|
||||||
|
// 30 mA is 0.03 A — noise on an idle phase, not a live one.
|
||||||
|
if st.LivePhases != 1 {
|
||||||
|
t.Errorf("livePhases = %d, want 1", st.LivePhases)
|
||||||
|
}
|
||||||
|
if st.AccessLevel != accessUnknown {
|
||||||
|
t.Errorf("access level = %q, want unknown when device_state was silent", st.AccessLevel)
|
||||||
|
}
|
||||||
|
if st.Model != nameGeneric {
|
||||||
|
t.Errorf("model = %q, want the generic name for a non-HabuDen serial", st.Model)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStateUnavailable(t *testing.T) {
|
||||||
|
// The device signals unavailability through the status topic itself, which
|
||||||
|
// upstream detects by substring because the payload is not a state document.
|
||||||
|
for _, payload := range []string{`{"state":"UNAVAILABLE"}`, `"OFFLINE"`, `{"status":"UNAVAILABLE"}`} {
|
||||||
|
st := buildState("SN1", map[string]json.RawMessage{
|
||||||
|
topicStatus: json.RawMessage(payload),
|
||||||
|
topicDeviceState: json.RawMessage(`{"level":"READ"}`),
|
||||||
|
})
|
||||||
|
if st.Status != stateUnavailable {
|
||||||
|
t.Errorf("payload %s -> status %q, want unavailable", payload, st.Status)
|
||||||
|
}
|
||||||
|
if st.Available {
|
||||||
|
t.Errorf("payload %s should not read as available", payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStateErrorStates(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
state string
|
||||||
|
fault bool
|
||||||
|
plugged bool
|
||||||
|
}{
|
||||||
|
{"ERROR_CAR", true, true},
|
||||||
|
{"ERROR_EVSE", true, false},
|
||||||
|
{"IDLE", false, false},
|
||||||
|
{"FINISHED", false, true},
|
||||||
|
} {
|
||||||
|
st := buildState("SN1", map[string]json.RawMessage{
|
||||||
|
topicStatus: json.RawMessage(`{"state":"` + tc.state + `"}`),
|
||||||
|
})
|
||||||
|
if st.Fault != tc.fault || st.Plugged != tc.plugged {
|
||||||
|
t.Errorf("%s: fault=%v plugged=%v, want %v/%v", tc.state, st.Fault, st.Plugged, tc.fault, tc.plugged)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStateDisabledIsNotAvailable(t *testing.T) {
|
||||||
|
st := buildState("SN1", map[string]json.RawMessage{
|
||||||
|
topicStatus: json.RawMessage(`{"state":"IDLE"}`),
|
||||||
|
topicDeviceState: json.RawMessage(`{"level":"DISABLED"}`),
|
||||||
|
})
|
||||||
|
if st.Available || st.CanExecute {
|
||||||
|
t.Errorf("a DISABLED device is neither available nor executable: %+v", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Invoke dispatch ---------------------------------------------------------
|
||||||
|
|
||||||
|
func TestInvokeUnknownAction(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
_ = p.Init(context.Background(), map[string]string{"host": "127.0.0.1"})
|
||||||
|
if _, err := p.Invoke(context.Background(), "nope", nil); err == nil {
|
||||||
|
t.Fatal("expected an error for an unknown action")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeChargerStateRequiresSerial(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
_ = p.Init(context.Background(), map[string]string{"host": "127.0.0.1"})
|
||||||
|
_, err := p.Invoke(context.Background(), "charger-state", nil)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "serial") {
|
||||||
|
t.Fatalf("error = %v, want a missing-serial error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeRejectsMalformedParams(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
_ = p.Init(context.Background(), map[string]string{"host": "127.0.0.1"})
|
||||||
|
if _, err := p.Invoke(context.Background(), "chargers", json.RawMessage(`[`)); err == nil {
|
||||||
|
t.Fatal("expected an error for malformed params")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- end to end against a broker ---------------------------------------------
|
||||||
|
|
||||||
|
func TestDiscoverCollectsEveryDeviceThatAnswers(t *testing.T) {
|
||||||
|
addr := startBroker(t, []brokerMsg{
|
||||||
|
{discoveryTopic, `{"id":"EVGC021B22752405ZM0018"}`},
|
||||||
|
{discoveryTopic, `{"id":"SOMETHINGELSE"}`},
|
||||||
|
{discoveryTopic, `{"id":"EVGC021B22752405ZM0018"}`}, // a repeat is one device
|
||||||
|
{discoveryTopic, `{"name":"BROADCAST"}`}, // our own echo, not a device
|
||||||
|
})
|
||||||
|
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "5"})
|
||||||
|
devices, err := p.discover(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
if len(devices) != 2 {
|
||||||
|
t.Fatalf("found %d devices, want 2: %+v", len(devices), devices)
|
||||||
|
}
|
||||||
|
if devices[0].SN != "EVGC021B22752405ZM0018" || devices[0].Model != nameHabuDen {
|
||||||
|
t.Errorf("first device = %+v", devices[0])
|
||||||
|
}
|
||||||
|
if devices[1].Model != nameGeneric {
|
||||||
|
t.Errorf("second device model = %q, want the generic name", devices[1].Model)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiscoverReturnsEmptyOnSilence(t *testing.T) {
|
||||||
|
addr := startBroker(t, nil)
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1"})
|
||||||
|
devices, err := p.discover(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
if len(devices) != 0 {
|
||||||
|
t.Fatalf("want no devices, got %+v", devices)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateReadsTelemetry(t *testing.T) {
|
||||||
|
sn := "EVGC021B22752405ZM0018"
|
||||||
|
addr := startBroker(t, []brokerMsg{
|
||||||
|
{evsePrefix + sn + "/current", `{"l1":16000,"l2":0,"l3":0}`},
|
||||||
|
{evsePrefix + sn + "/voltage", `{"l1":230,"l2":231,"l3":229}`},
|
||||||
|
{evsePrefix + sn + "/power", `{"momentary":3680}`},
|
||||||
|
{evsePrefix + sn + "/status", `{"state":"CHARGING"}`},
|
||||||
|
{evsePrefix + sn + "/device_state", `{"level":"READ"}`},
|
||||||
|
// Another charger on the same broker must not bleed into this reading.
|
||||||
|
{evsePrefix + "OTHER/power", `{"momentary":99999}`},
|
||||||
|
})
|
||||||
|
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "5"})
|
||||||
|
st, err := p.chargerState(context.Background(), sn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("chargerState: %v", err)
|
||||||
|
}
|
||||||
|
if !st.Complete {
|
||||||
|
t.Errorf("expected a complete reading, got %v", st.Received)
|
||||||
|
}
|
||||||
|
if st.PowerW == nil || *st.PowerW != 3680 {
|
||||||
|
t.Errorf("power = %v, want 3680 (the other charger's reading must not leak in)", st.PowerW)
|
||||||
|
}
|
||||||
|
if st.CurrentA.L1 == nil || *st.CurrentA.L1 != 16 {
|
||||||
|
t.Errorf("l1 = %v A, want 16", st.CurrentA.L1)
|
||||||
|
}
|
||||||
|
if st.LivePhases != 1 {
|
||||||
|
t.Errorf("livePhases = %d, want 1", st.LivePhases)
|
||||||
|
}
|
||||||
|
if st.AccessLevel != accessRead || st.CanExecute {
|
||||||
|
t.Errorf("READ mode should not report as executable: %+v", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateReturnsPartialAtTheDeadline(t *testing.T) {
|
||||||
|
sn := "SN1"
|
||||||
|
addr := startBroker(t, []brokerMsg{
|
||||||
|
{evsePrefix + sn + "/status", `{"state":"IDLE"}`},
|
||||||
|
})
|
||||||
|
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1"})
|
||||||
|
st, err := p.chargerState(context.Background(), sn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("a partial reading should not be an error: %v", err)
|
||||||
|
}
|
||||||
|
if st.Complete || st.Status != stateIdle {
|
||||||
|
t.Errorf("state = %+v", st)
|
||||||
|
}
|
||||||
|
if st.Received[topicVoltage] {
|
||||||
|
t.Error("voltage was never published, so it must read as not received")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateErrorsOnSilence(t *testing.T) {
|
||||||
|
addr := startBroker(t, nil)
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1"})
|
||||||
|
_, err := p.chargerState(context.Background(), "SN1")
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "no data from charger") {
|
||||||
|
t.Fatalf("error = %v, want a no-data error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateFailsWithoutABroker(t *testing.T) {
|
||||||
|
// Nothing is listening, so the session cannot be opened at all.
|
||||||
|
p := pluginAt(t, "127.0.0.1:1", map[string]string{"timeout": "1"})
|
||||||
|
if _, err := p.chargerState(context.Background(), "SN1"); err == nil {
|
||||||
|
t.Fatal("expected a connection error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHealthCheckClassifiesTheThreeOutcomes(t *testing.T) {
|
||||||
|
t.Run("ok", func(t *testing.T) {
|
||||||
|
addr := startBroker(t, []brokerMsg{{discoveryTopic, `{"id":"EVGC021B22752405ZM0018"}`}})
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "5"})
|
||||||
|
h := p.HealthCheck(context.Background())
|
||||||
|
if h.Status != plugins.StatusOK {
|
||||||
|
t.Fatalf("status = %q (%s), want ok", h.Status, h.Detail)
|
||||||
|
}
|
||||||
|
if !strings.Contains(h.Detail, "1 Greencell device") {
|
||||||
|
t.Errorf("detail = %q", h.Detail)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("degraded when the broker answers but no charger does", func(t *testing.T) {
|
||||||
|
addr := startBroker(t, nil)
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1"})
|
||||||
|
h := p.HealthCheck(context.Background())
|
||||||
|
if h.Status != plugins.StatusDegraded {
|
||||||
|
t.Fatalf("status = %q (%s), want degraded", h.Status, h.Detail)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("down when the broker is unreachable", func(t *testing.T) {
|
||||||
|
p := pluginAt(t, "127.0.0.1:1", map[string]string{"timeout": "1"})
|
||||||
|
h := p.HealthCheck(context.Background())
|
||||||
|
if h.Status != plugins.StatusDown {
|
||||||
|
t.Fatalf("status = %q (%s), want down", h.Status, h.Detail)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeChargersShape(t *testing.T) {
|
||||||
|
addr := startBroker(t, []brokerMsg{{discoveryTopic, `{"id":"EVGC021B22752405ZM0018"}`}})
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "5"})
|
||||||
|
|
||||||
|
raw, err := p.Invoke(context.Background(), "chargers", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Invoke: %v", err)
|
||||||
|
}
|
||||||
|
var doc struct {
|
||||||
|
Chargers []Device `json:"chargers"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
if len(doc.Chargers) != 1 || doc.Chargers[0].SN != "EVGC021B22752405ZM0018" {
|
||||||
|
t.Fatalf("chargers = %+v", doc.Chargers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeChargerStateFallsBackToTheConfiguredSerial(t *testing.T) {
|
||||||
|
sn := "EVGC021B22752405ZM0018"
|
||||||
|
addr := startBroker(t, []brokerMsg{{evsePrefix + sn + "/status", `{"state":"FINISHED"}`}})
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1", "serial": sn})
|
||||||
|
|
||||||
|
raw, err := p.Invoke(context.Background(), "charger-state", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Invoke: %v", err)
|
||||||
|
}
|
||||||
|
var st State
|
||||||
|
if err := json.Unmarshal(raw, &st); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
if st.SN != sn || st.Status != stateFinished {
|
||||||
|
t.Fatalf("state = %+v", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- test broker -------------------------------------------------------------
|
||||||
|
|
||||||
|
// brokerMsg is one publication the test broker pushes once the plugin has
|
||||||
|
// subscribed and sent its discovery broadcast.
|
||||||
|
type brokerMsg struct {
|
||||||
|
topic string
|
||||||
|
payload string
|
||||||
|
}
|
||||||
|
|
||||||
|
// pluginAt returns a plugin configured to talk to addr.
|
||||||
|
func pluginAt(t *testing.T, addr string, extra map[string]string) *Plugin {
|
||||||
|
t.Helper()
|
||||||
|
host, port, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("bad address %q: %v", addr, err)
|
||||||
|
}
|
||||||
|
config := map[string]string{"host": host, "port": port}
|
||||||
|
for k, v := range extra {
|
||||||
|
config[k] = v
|
||||||
|
}
|
||||||
|
p := &Plugin{}
|
||||||
|
if err := p.Init(context.Background(), config); err != nil {
|
||||||
|
t.Fatalf("Init: %v", err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// startBroker runs an MQTT 3.1.1 broker that does just enough for these tests:
|
||||||
|
// accept a connection, acknowledge the subscription, and — once the client sends
|
||||||
|
// its discovery broadcast — push the scripted messages back. It speaks the wire
|
||||||
|
// format directly rather than reusing internal/mqtt, so a bug in the client
|
||||||
|
// cannot hide behind a matching bug in the fixture.
|
||||||
|
func startBroker(t *testing.T, script []brokerMsg) string {
|
||||||
|
t.Helper()
|
||||||
|
return startBrokerRecording(t, nil, script)
|
||||||
|
}
|
||||||
|
|
||||||
|
// startBrokerRecording is startBroker with a channel that receives everything the
|
||||||
|
// client publishes, so a test can assert on what went out as well as what came
|
||||||
|
// back. A nil channel records nothing.
|
||||||
|
func startBrokerRecording(t *testing.T, seen chan<- brokerMsg, script []brokerMsg) string {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
// Close the listener before waiting: the accept loop only ends when the
|
||||||
|
// listener does, and cleanups run last-registered first.
|
||||||
|
t.Cleanup(func() { _ = ln.Close(); wg.Wait() })
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
defer conn.Close()
|
||||||
|
serveBroker(conn, seen, script)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return ln.Addr().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveBroker(conn net.Conn, seen chan<- brokerMsg, script []brokerMsg) {
|
||||||
|
br := bufio.NewReader(conn)
|
||||||
|
for {
|
||||||
|
typ, _, body, err := readRaw(br)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch typ {
|
||||||
|
case 1: // CONNECT
|
||||||
|
if _, err := conn.Write(frame(2, 0, []byte{0, 0})); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case 8: // SUBSCRIBE — acknowledge every requested filter with QoS 0
|
||||||
|
if len(body) < 2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ack := append([]byte{body[0], body[1]}, make([]byte, countFilters(body[2:]))...)
|
||||||
|
if _, err := conn.Write(frame(9, 0, ack)); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case 3: // PUBLISH — from the client; record it, then answer with the script
|
||||||
|
if seen != nil {
|
||||||
|
if topic, rest, err := splitRawString(body); err == nil {
|
||||||
|
select {
|
||||||
|
case seen <- brokerMsg{topic, string(rest)}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range script {
|
||||||
|
pub := append(encRawString(m.topic), m.payload...)
|
||||||
|
if _, err := conn.Write(frame(3, 0, pub)); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 12: // PINGREQ
|
||||||
|
if _, err := conn.Write(frame(13, 0, nil)); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case 14: // DISCONNECT
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// countFilters counts the topic filters in a SUBSCRIBE payload so the SUBACK can
|
||||||
|
// carry one return code per filter.
|
||||||
|
func countFilters(b []byte) int {
|
||||||
|
n := 0
|
||||||
|
for len(b) >= 3 {
|
||||||
|
l := int(binary.BigEndian.Uint16(b))
|
||||||
|
if len(b) < 2+l+1 {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
b = b[2+l+1:]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitRawString peels an MQTT UTF-8 string off the front of b.
|
||||||
|
func splitRawString(b []byte) (string, []byte, error) {
|
||||||
|
if len(b) < 2 {
|
||||||
|
return "", nil, io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
n := int(binary.BigEndian.Uint16(b))
|
||||||
|
if len(b) < 2+n {
|
||||||
|
return "", nil, io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
return string(b[2 : 2+n]), b[2+n:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encRawString(s string) []byte {
|
||||||
|
out := binary.BigEndian.AppendUint16(nil, uint16(len(s)))
|
||||||
|
return append(out, s...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func frame(typ, flags byte, body []byte) []byte {
|
||||||
|
out := []byte{typ<<4 | flags}
|
||||||
|
n := len(body)
|
||||||
|
for {
|
||||||
|
digit := byte(n % 128)
|
||||||
|
n /= 128
|
||||||
|
if n > 0 {
|
||||||
|
digit |= 0x80
|
||||||
|
}
|
||||||
|
out = append(out, digit)
|
||||||
|
if n == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return append(out, body...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readRaw(br *bufio.Reader) (typ, flags byte, body []byte, err error) {
|
||||||
|
head, err := br.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, nil, err
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
length int
|
||||||
|
multiplier = 1
|
||||||
|
)
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
digit, err := br.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, nil, err
|
||||||
|
}
|
||||||
|
length += int(digit&0x7F) * multiplier
|
||||||
|
if digit&0x80 == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
multiplier *= 128
|
||||||
|
}
|
||||||
|
body = make([]byte, length)
|
||||||
|
if _, err := io.ReadFull(br, body); err != nil {
|
||||||
|
return 0, 0, nil, err
|
||||||
|
}
|
||||||
|
return head >> 4, head & 0x0F, body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the operator-supplied QUERY topic ---------------------------------------
|
||||||
|
|
||||||
|
func TestCommandTopicFor(t *testing.T) {
|
||||||
|
var p Plugin
|
||||||
|
_ = p.Init(context.Background(), map[string]string{
|
||||||
|
"host": "h", "commandTopic": "/greencell/evse/" + snPlaceholder + "/command",
|
||||||
|
})
|
||||||
|
if got := p.commandTopicFor("SN1"); got != "/greencell/evse/SN1/command" {
|
||||||
|
t.Errorf("commandTopicFor = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A topic without the placeholder is used as given.
|
||||||
|
_ = p.Init(context.Background(), map[string]string{"host": "h", "commandTopic": "/fixed/topic"})
|
||||||
|
if got := p.commandTopicFor("SN1"); got != "/fixed/topic" {
|
||||||
|
t.Errorf("commandTopicFor = %q, want the literal topic", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unset means listen-only; nothing is ever published.
|
||||||
|
_ = p.Init(context.Background(), map[string]string{"host": "h"})
|
||||||
|
if got := p.commandTopicFor("SN1"); got != "" {
|
||||||
|
t.Errorf("commandTopicFor = %q, want empty when unconfigured", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateSendsQueryWhenATopicIsConfigured(t *testing.T) {
|
||||||
|
sn := "SN1"
|
||||||
|
seen := make(chan brokerMsg, 4)
|
||||||
|
addr := startBrokerRecording(t, seen, []brokerMsg{
|
||||||
|
{evsePrefix + sn + "/status", `{"state":"IDLE"}`},
|
||||||
|
})
|
||||||
|
|
||||||
|
p := pluginAt(t, addr, map[string]string{
|
||||||
|
"timeout": "1", "commandTopic": "/greencell/evse/" + snPlaceholder + "/command",
|
||||||
|
})
|
||||||
|
if _, err := p.chargerState(context.Background(), sn); err != nil {
|
||||||
|
t.Fatalf("chargerState: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var got []brokerMsg
|
||||||
|
close(seen)
|
||||||
|
for m := range seen {
|
||||||
|
got = append(got, m)
|
||||||
|
}
|
||||||
|
// The discovery broadcast, then the QUERY on the configured topic.
|
||||||
|
var query *brokerMsg
|
||||||
|
for i := range got {
|
||||||
|
if got[i].topic == "/greencell/evse/SN1/command" {
|
||||||
|
query = &got[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if query == nil {
|
||||||
|
t.Fatalf("no QUERY was published; broker saw %+v", got)
|
||||||
|
}
|
||||||
|
if query.payload != queryCommand {
|
||||||
|
t.Errorf("QUERY payload = %q, want %q", query.payload, queryCommand)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChargerStateSendsNothingWithoutACommandTopic(t *testing.T) {
|
||||||
|
sn := "SN1"
|
||||||
|
seen := make(chan brokerMsg, 4)
|
||||||
|
addr := startBrokerRecording(t, seen, []brokerMsg{
|
||||||
|
{evsePrefix + sn + "/status", `{"state":"IDLE"}`},
|
||||||
|
})
|
||||||
|
|
||||||
|
p := pluginAt(t, addr, map[string]string{"timeout": "1"})
|
||||||
|
if _, err := p.chargerState(context.Background(), sn); err != nil {
|
||||||
|
t.Fatalf("chargerState: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
close(seen)
|
||||||
|
for m := range seen {
|
||||||
|
if m.topic != broadcastTopic {
|
||||||
|
t.Errorf("unconfigured, the plugin must publish only the discovery broadcast; it also sent %+v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -210,6 +210,11 @@ const integrationsApi = [
|
|||||||
{ method: "POST", path: "/api/integrations/anker-solix/chargers/{sn}/control/token", desc: "(Re)issue the charger's control token" },
|
{ method: "POST", path: "/api/integrations/anker-solix/chargers/{sn}/control/token", desc: "(Re)issue the charger's control token" },
|
||||||
{ method: "DELETE", path: "/api/integrations/anker-solix/chargers/{sn}/control/token", desc: "Revoke the control token" },
|
{ method: "DELETE", path: "/api/integrations/anker-solix/chargers/{sn}/control/token", desc: "Revoke the control token" },
|
||||||
{ method: "POST", path: "/api/integrations/anker-solix/chargers/{sn}/{action}", desc: "One OCPP command: start, stop, limit, clear-limit, availability, reset, unlock, trigger, config" },
|
{ method: "POST", path: "/api/integrations/anker-solix/chargers/{sn}/{action}", desc: "One OCPP command: start, stop, limit, clear-limit, availability, reset, unlock, trigger, config" },
|
||||||
|
{ method: "GET", path: "/api/integrations/greencell", desc: "Resolved Greencell settings (secrets masked)" },
|
||||||
|
{ method: "PUT", path: "/api/integrations/greencell", desc: "Save the caller's own layer (user or org scope)" },
|
||||||
|
{ method: "POST", path: "/api/integrations/greencell/health", desc: "Live probe: connect to the broker and broadcast for devices" },
|
||||||
|
{ method: "GET", path: "/api/integrations/greencell/chargers", desc: "Greencell chargers answering on the configured MQTT broker" },
|
||||||
|
{ method: "GET", path: "/api/integrations/greencell/chargers/{sn}/state", desc: "Live EVSE state, access level, power and per-phase current/voltage" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const ocppApi = [
|
const ocppApi = [
|
||||||
|
|||||||
@@ -339,6 +339,26 @@
|
|||||||
"controlRevokeConfirm": "Tilbagekald denne laders styringstoken? Den bliver afbrudt og kan ikke forbinde igen, før du genererer et nyt.",
|
"controlRevokeConfirm": "Tilbagekald denne laders styringstoken? Den bliver afbrudt og kan ikke forbinde igen, før du genererer et nyt.",
|
||||||
"controlConnected": "Forbundet til styrings-backend",
|
"controlConnected": "Forbundet til styrings-backend",
|
||||||
"controlDisconnected": "Ikke forbundet",
|
"controlDisconnected": "Ikke forbundet",
|
||||||
|
"greencell": "Greencell (HabuDen EV-lader)",
|
||||||
|
"greencellDesc": "Læs din Greencell-lader via den MQTT-broker, den publicerer til. Kun lokalt — ingen Greencell-skykonto er involveret.",
|
||||||
|
"greencellBroker": "MQTT-broker",
|
||||||
|
"greencellCharger": "Lader",
|
||||||
|
"greencellHost": "Brokerens vært",
|
||||||
|
"greencellHostHint": "Den broker, du pegede laderen på i Greencell GC-appen.",
|
||||||
|
"greencellPort": "Brokerens port",
|
||||||
|
"greencellPortHint": "Som standard 1883, eller 8883 når TLS er slået til.",
|
||||||
|
"greencellTls": "Forbindelse",
|
||||||
|
"greencellTlsOff": "Almindelig MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Brugernavn til broker",
|
||||||
|
"greencellUsernameHint": "Lad feltet stå tomt, hvis din broker tillader anonyme klienter.",
|
||||||
|
"greencellPassword": "Adgangskode til broker",
|
||||||
|
"greencellSerial": "Laderens serienummer",
|
||||||
|
"greencellSerialHint": "Valgfrit — lad det stå tomt, så finder søgningen det, der er på brokeren.",
|
||||||
|
"greencellTimeout": "Lyttevindue (sekunder)",
|
||||||
|
"greencellTimeoutHint": "Hvor længe der ventes på, at laderen publicerer. Greencell giver en enhed op til 30 s til at svare; hæv værdien, hvis intet findes.",
|
||||||
|
"greencellCommandTopic": "Emne for QUERY-kommandoen",
|
||||||
|
"greencellCommandTopicHint": "Valgfrit. Greencell beskriver en QUERY-kommando, der får laderen til at publicere med det samme, men ikke det emne, den lytter på. Finder du dit, så skriv det her, og læsninger behøver ikke vente på laderens egen kadence. Brug {sn} for serienummeret.",
|
||||||
"toyota": "Toyota Connected (MyToyota)",
|
"toyota": "Toyota Connected (MyToyota)",
|
||||||
"brandToyota": "Toyota",
|
"brandToyota": "Toyota",
|
||||||
"brandLexus": "Lexus",
|
"brandLexus": "Lexus",
|
||||||
|
|||||||
@@ -218,7 +218,27 @@
|
|||||||
"controlRevoke": "Revoke token",
|
"controlRevoke": "Revoke token",
|
||||||
"controlRevokeConfirm": "Revoke this charger's control token? It will disconnect and can't reconnect until you generate a new one.",
|
"controlRevokeConfirm": "Revoke this charger's control token? It will disconnect and can't reconnect until you generate a new one.",
|
||||||
"controlConnected": "Connected to control backend",
|
"controlConnected": "Connected to control backend",
|
||||||
"controlDisconnected": "Not connected"
|
"controlDisconnected": "Not connected",
|
||||||
|
"greencell": "Greencell (HabuDen EV charger)",
|
||||||
|
"greencellDesc": "Read your Greencell wallbox over the MQTT broker it publishes to. Local only — no Greencell cloud account is involved.",
|
||||||
|
"greencellBroker": "MQTT broker",
|
||||||
|
"greencellCharger": "Charger",
|
||||||
|
"greencellHost": "Broker host",
|
||||||
|
"greencellHostHint": "The broker you pointed the charger at in the Greencell GC app.",
|
||||||
|
"greencellPort": "Broker port",
|
||||||
|
"greencellPortHint": "Defaults to 1883, or 8883 with TLS on.",
|
||||||
|
"greencellTls": "Connection",
|
||||||
|
"greencellTlsOff": "Plain MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Broker username",
|
||||||
|
"greencellUsernameHint": "Leave blank if your broker allows anonymous clients.",
|
||||||
|
"greencellPassword": "Broker password",
|
||||||
|
"greencellSerial": "Charger serial",
|
||||||
|
"greencellSerialHint": "Optional — leave blank and discovery finds whatever is on the broker.",
|
||||||
|
"greencellTimeout": "Listen window (seconds)",
|
||||||
|
"greencellTimeoutHint": "How long to wait for the charger to publish. Greencell allows a device up to 30 s to answer; raise this if nothing is found.",
|
||||||
|
"greencellCommandTopic": "QUERY command topic",
|
||||||
|
"greencellCommandTopicHint": "Optional. Greencell documents a QUERY command that makes the charger publish at once, but not the topic it listens on. If you find yours, put it here and reads stop waiting for the charger's own cadence. Use {sn} for the serial."
|
||||||
},
|
},
|
||||||
"account": {
|
"account": {
|
||||||
"title": "Account",
|
"title": "Account",
|
||||||
|
|||||||
@@ -343,6 +343,26 @@
|
|||||||
"controlRevokeConfirm": "Unieważnić token sterowania tej ładowarki? Rozłączy się i nie połączy ponownie, dopóki nie wygenerujesz nowego.",
|
"controlRevokeConfirm": "Unieważnić token sterowania tej ładowarki? Rozłączy się i nie połączy ponownie, dopóki nie wygenerujesz nowego.",
|
||||||
"controlConnected": "Połączono z backendem sterowania",
|
"controlConnected": "Połączono z backendem sterowania",
|
||||||
"controlDisconnected": "Nie połączono",
|
"controlDisconnected": "Nie połączono",
|
||||||
|
"greencell": "Greencell (ładowarka EV HabuDen)",
|
||||||
|
"greencellDesc": "Odczytuj swoją ładowarkę Greencell przez brokera MQTT, do którego publikuje. Tylko lokalnie — konto w chmurze Greencell nie jest potrzebne.",
|
||||||
|
"greencellBroker": "Broker MQTT",
|
||||||
|
"greencellCharger": "Ładowarka",
|
||||||
|
"greencellHost": "Adres brokera",
|
||||||
|
"greencellHostHint": "Broker, który wskazałeś ładowarce w aplikacji Greencell GC.",
|
||||||
|
"greencellPort": "Port brokera",
|
||||||
|
"greencellPortHint": "Domyślnie 1883, a przy włączonym TLS 8883.",
|
||||||
|
"greencellTls": "Połączenie",
|
||||||
|
"greencellTlsOff": "Zwykłe MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Użytkownik brokera",
|
||||||
|
"greencellUsernameHint": "Pozostaw puste, jeśli broker dopuszcza klientów anonimowych.",
|
||||||
|
"greencellPassword": "Hasło brokera",
|
||||||
|
"greencellSerial": "Numer seryjny ładowarki",
|
||||||
|
"greencellSerialHint": "Opcjonalne — pozostaw puste, a wykrywanie znajdzie to, co jest na brokerze.",
|
||||||
|
"greencellTimeout": "Okno nasłuchu (sekundy)",
|
||||||
|
"greencellTimeoutHint": "Jak długo czekać, aż ładowarka opublikuje dane. Greencell daje urządzeniu do 30 s na odpowiedź; zwiększ tę wartość, jeśli nic nie zostaje znalezione.",
|
||||||
|
"greencellCommandTopic": "Temat polecenia QUERY",
|
||||||
|
"greencellCommandTopicHint": "Opcjonalne. Greencell opisuje polecenie QUERY, które każe ładowarce natychmiast opublikować dane, ale nie podaje tematu, na którym ona nasłuchuje. Jeśli poznasz swój, wpisz go tutaj, a odczyty przestaną czekać na własny rytm ładowarki. Użyj {sn} zamiast numeru seryjnego.",
|
||||||
"toyota": "Toyota Connected (MyToyota)",
|
"toyota": "Toyota Connected (MyToyota)",
|
||||||
"brandToyota": "Toyota",
|
"brandToyota": "Toyota",
|
||||||
"brandLexus": "Lexus",
|
"brandLexus": "Lexus",
|
||||||
|
|||||||
+24
-4
@@ -596,10 +596,10 @@ class ApiClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- integrations (per-user plugin settings, superadmin → org → user cascade) ---
|
// --- integrations (per-user plugin settings, superadmin → org → user cascade) ---
|
||||||
// getToyota/getAnkerSolix return the resolved view (effective/own/locked per
|
// Each connector has the same trio: get… returns the resolved view
|
||||||
// field, secrets and inherited values masked); saveToyota/saveAnkerSolix write
|
// (effective/own/locked per field, secrets and inherited values masked); save…
|
||||||
// the caller's editable layer (scope "user" by default, "org" for org admins);
|
// writes the caller's editable layer (scope "user" by default, "org" for org
|
||||||
// testToyota/testAnkerSolix run a live login probe under the resolved creds.
|
// admins); test… runs a live probe under the resolved config.
|
||||||
Future<IntegrationView> getToyota() async {
|
Future<IntegrationView> getToyota() async {
|
||||||
final data = await _send("GET", "/integrations/toyota");
|
final data = await _send("GET", "/integrations/toyota");
|
||||||
return IntegrationView.fromJson(Map<String, dynamic>.from(data));
|
return IntegrationView.fromJson(Map<String, dynamic>.from(data));
|
||||||
@@ -632,6 +632,26 @@ class ApiClient {
|
|||||||
return IntegrationHealth.fromJson(Map<String, dynamic>.from(h));
|
return IntegrationHealth.fromJson(Map<String, dynamic>.from(h));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Greencell (HabuDen EV charger). Same cascade, but what resolves is an MQTT
|
||||||
|
// broker rather than a cloud account — the charger publishes to a broker the
|
||||||
|
// owner runs and the server joins it. testGreencell connects to that broker and
|
||||||
|
// broadcasts for devices, so "degraded" means reachable-but-no-charger.
|
||||||
|
Future<IntegrationView> getGreencell() async {
|
||||||
|
final data = await _send("GET", "/integrations/greencell");
|
||||||
|
return IntegrationView.fromJson(Map<String, dynamic>.from(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<IntegrationView> saveGreencell(Map<String, dynamic> body) async {
|
||||||
|
final data = await _send("PUT", "/integrations/greencell", body: body);
|
||||||
|
return IntegrationView.fromJson(Map<String, dynamic>.from(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<IntegrationHealth> testGreencell() async {
|
||||||
|
final data = await _send("POST", "/integrations/greencell/health");
|
||||||
|
final h = (data is Map ? data["health"] : null) ?? {};
|
||||||
|
return IntegrationHealth.fromJson(Map<String, dynamic>.from(h));
|
||||||
|
}
|
||||||
|
|
||||||
// --- Anker Solix OCPP control (per charger) ---
|
// --- Anker Solix OCPP control (per charger) ---
|
||||||
// getAnkerControl returns the control mode, connection status, provisioning
|
// getAnkerControl returns the control mode, connection status, provisioning
|
||||||
// endpoint + token, and a live status snapshot; ankerControlToken (re)generates
|
// endpoint + token, and a live status snapshot; ankerControlToken (re)generates
|
||||||
|
|||||||
@@ -1477,14 +1477,14 @@ class _DangerSectionState extends State<_DangerSection> {
|
|||||||
|
|
||||||
// --- Integrations tab ------------------------------------------------------
|
// --- Integrations tab ------------------------------------------------------
|
||||||
//
|
//
|
||||||
// Two foldable connector cards (Toyota, Anker Solix) over a superadmin → org
|
// Three foldable connector cards (Toyota, Anker Solix, Greencell) over a
|
||||||
// admin → user cascade. Each card resolves, per field, the effective value
|
// superadmin → org admin → user cascade. Each card resolves, per field, the effective value
|
||||||
// (secrets/inherited values masked), the caller's own-layer value, its source
|
// (secrets/inherited values masked), the caller's own-layer value, its source
|
||||||
// layer, and whether it's locked (set above the caller). Org admins get a
|
// layer, and whether it's locked (set above the caller). Org admins get a
|
||||||
// second "org" scope to edit organization-wide defaults; superadmins manage the
|
// second "org" scope to edit organization-wide defaults; superadmins manage the
|
||||||
// shared layer in the API Server panel, so here it is read-only.
|
// shared layer in the API Server panel, so here it is read-only.
|
||||||
|
|
||||||
enum _FieldType { text, password, select }
|
enum _FieldType { text, number, password, select }
|
||||||
|
|
||||||
/// Describes one credential field within an integration card.
|
/// Describes one credential field within an integration card.
|
||||||
class _FieldSpec {
|
class _FieldSpec {
|
||||||
@@ -1593,6 +1593,77 @@ class _IntegrationsTab extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Greencell reads over an MQTT broker the owner runs rather than a vendor
|
||||||
|
// cloud, so the fields describe an endpoint (host/port/TLS/credentials,
|
||||||
|
// which the server resolves as one unit) plus the charger itself.
|
||||||
|
final greencell = _IntegrationConfig(
|
||||||
|
nameKey: "settings.integrations.greencell",
|
||||||
|
descKey: "settings.integrations.greencellDesc",
|
||||||
|
anker: false,
|
||||||
|
load: apiClient.getGreencell,
|
||||||
|
save: apiClient.saveGreencell,
|
||||||
|
test: apiClient.testGreencell,
|
||||||
|
fields: const [
|
||||||
|
_FieldSpec(
|
||||||
|
key: "host",
|
||||||
|
labelKey: "settings.integrations.greencellHost",
|
||||||
|
placeholder: "10.2.1.10",
|
||||||
|
hintKey: "settings.integrations.greencellHostHint",
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "port",
|
||||||
|
labelKey: "settings.integrations.greencellPort",
|
||||||
|
type: _FieldType.number,
|
||||||
|
placeholder: "1883",
|
||||||
|
hintKey: "settings.integrations.greencellPortHint",
|
||||||
|
showEffectiveWhenLocked: true,
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "tls",
|
||||||
|
labelKey: "settings.integrations.greencellTls",
|
||||||
|
type: _FieldType.select,
|
||||||
|
defaultValue: "off",
|
||||||
|
showEffectiveWhenLocked: true,
|
||||||
|
options: [
|
||||||
|
("off", "settings.integrations.greencellTlsOff"),
|
||||||
|
("on", "settings.integrations.greencellTlsOn"),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "username",
|
||||||
|
labelKey: "settings.integrations.greencellUsername",
|
||||||
|
hintKey: "settings.integrations.greencellUsernameHint",
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "password",
|
||||||
|
labelKey: "settings.integrations.greencellPassword",
|
||||||
|
type: _FieldType.password,
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "serial",
|
||||||
|
labelKey: "settings.integrations.greencellSerial",
|
||||||
|
placeholder: "EVGC021B22752405ZM0018",
|
||||||
|
hintKey: "settings.integrations.greencellSerialHint",
|
||||||
|
showEffectiveWhenLocked: true,
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "timeout",
|
||||||
|
labelKey: "settings.integrations.greencellTimeout",
|
||||||
|
type: _FieldType.number,
|
||||||
|
placeholder: "12",
|
||||||
|
hintKey: "settings.integrations.greencellTimeoutHint",
|
||||||
|
showEffectiveWhenLocked: true,
|
||||||
|
),
|
||||||
|
_FieldSpec(
|
||||||
|
key: "commandTopic",
|
||||||
|
labelKey: "settings.integrations.greencellCommandTopic",
|
||||||
|
placeholder: "/greencell/evse/{sn}/command",
|
||||||
|
hintKey: "settings.integrations.greencellCommandTopicHint",
|
||||||
|
showEffectiveWhenLocked: true,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
return ListView(
|
return ListView(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
children: [
|
children: [
|
||||||
@@ -1608,6 +1679,8 @@ class _IntegrationsTab extends StatelessWidget {
|
|||||||
_IntegrationCard(config: toyota),
|
_IntegrationCard(config: toyota),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
_IntegrationCard(config: anker),
|
_IntegrationCard(config: anker),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_IntegrationCard(config: greencell),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
@@ -1926,7 +1999,11 @@ class _IntegrationCardState extends State<_IntegrationCard> {
|
|||||||
_health!.detail.isNotEmpty ? _health!.detail : _health!.status,
|
_health!.detail.isNotEmpty ? _health!.detail : _health!.status,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 13,
|
fontSize: 13,
|
||||||
color: _health!.status == "ok" ? DriverVault.success : DriverVault.danger,
|
color: _health!.status == "ok"
|
||||||
|
? DriverVault.success
|
||||||
|
: _health!.status == "degraded"
|
||||||
|
? DriverVault.warning
|
||||||
|
: DriverVault.danger,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1963,12 +2040,17 @@ class _IntegrationCardState extends State<_IntegrationCard> {
|
|||||||
} else {
|
} else {
|
||||||
final isPassword = f.type == _FieldType.password;
|
final isPassword = f.type == _FieldType.password;
|
||||||
// Masked placeholder: locked non-secret shows dots; a set password too.
|
// Masked placeholder: locked non-secret shows dots; a set password too.
|
||||||
final showDots = isPassword ? field.effective.isNotEmpty : locked;
|
// A field that shows its effective value when locked has something real to
|
||||||
|
// display, so it never gets the dots.
|
||||||
|
final showDots = isPassword
|
||||||
|
? field.effective.isNotEmpty
|
||||||
|
: locked && !f.showEffectiveWhenLocked;
|
||||||
input = TextField(
|
input = TextField(
|
||||||
controller: _controllers[f.key],
|
controller: _controllers[f.key],
|
||||||
obscureText: isPassword,
|
obscureText: isPassword,
|
||||||
enabled: !locked,
|
enabled: !locked,
|
||||||
autocorrect: false,
|
autocorrect: false,
|
||||||
|
keyboardType: f.type == _FieldType.number ? TextInputType.number : null,
|
||||||
maxLength: f.maxLength,
|
maxLength: f.maxLength,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
border: const OutlineInputBorder(),
|
border: const OutlineInputBorder(),
|
||||||
|
|||||||
@@ -60,8 +60,9 @@ The Web and Phone apps are at feature parity.
|
|||||||
- **Per-user ownership & sharing** — each car has an owner and can be shared with
|
- **Per-user ownership & sharing** — each car has an owner and can be shared with
|
||||||
other users as read or write; the UI mirrors the server's access checks.
|
other users as read or write; the UI mirrors the server's access checks.
|
||||||
- **Integrations** — per-user connectors under a superadmin → org-admin → user
|
- **Integrations** — per-user connectors under a superadmin → org-admin → user
|
||||||
cascade. Built-in today: **Toyota Connected** (read-only vehicle data) and the
|
cascade. Built-in today: **Toyota Connected** (read-only vehicle data), the
|
||||||
**Anker Solix** V1 EV charger.
|
**Anker Solix** V1 EV charger and the **Greencell** HabuDen wallbox (read over
|
||||||
|
the owner's own MQTT broker — no Greencell cloud is involved).
|
||||||
- **Cars from the manufacturer's own service** — import a car straight off a
|
- **Cars from the manufacturer's own service** — import a car straight off a
|
||||||
connected account (MyToyota today), choosing what to pull in, and read everything
|
connected account (MyToyota today), choosing what to pull in, and read everything
|
||||||
that service knows about it from a dedicated first tab on the car. Generic over
|
that service knows about it from a dedicated first tab on the car. Generic over
|
||||||
|
|||||||
+3
-2
@@ -86,8 +86,9 @@ No screen code changes are needed to add a language.
|
|||||||
labels in `lib/format.js`.
|
labels in `lib/format.js`.
|
||||||
Both apps are complete in all three languages. The one place the wording is
|
Both apps are complete in all three languages. The one place the wording is
|
||||||
deliberately not translated is proper nouns: protocol and product names (OCPP,
|
deliberately not translated is proper nouns: protocol and product names (OCPP,
|
||||||
CSMS, Toyota Connected, MyToyota, Anker Solix, Lexus) read the same in every
|
CSMS, MQTT, MQTTS, TLS, Toyota Connected, MyToyota, Anker Solix, Greencell,
|
||||||
file, as do the units.
|
HabuDen, Lexus) read the same in every file, as do the units — and so does the
|
||||||
|
Greencell device command `QUERY`, which is a literal the charger listens for.
|
||||||
|
|
||||||
- **API Server panel** — UI chrome, cards, login, status, and the API section
|
- **API Server panel** — UI chrome, cards, login, status, and the API section
|
||||||
titles are translated. The individual REST endpoint **descriptions** in the
|
titles are translated. The individual REST endpoint **descriptions** in the
|
||||||
|
|||||||
@@ -317,6 +317,16 @@ export const api = {
|
|||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
// Greencell (HabuDen EV charger) — same cascade again, but what resolves is an
|
||||||
|
// MQTT broker rather than a cloud account: the charger publishes to a broker
|
||||||
|
// the owner runs, and the server joins it as a client. getGreencell returns the
|
||||||
|
// resolved view (secrets and inherited host/username masked); saveGreencell
|
||||||
|
// writes the caller's editable layer; testGreencell connects to the broker and
|
||||||
|
// broadcasts for devices.
|
||||||
|
getGreencell: () => request("/integrations/greencell"),
|
||||||
|
saveGreencell: (body) => request("/integrations/greencell", { method: "PUT", body: JSON.stringify(body) }),
|
||||||
|
testGreencell: () => request("/integrations/greencell/health", { method: "POST" }),
|
||||||
|
|
||||||
// Settings — advanced / danger zone
|
// Settings — advanced / danger zone
|
||||||
exportData: () => requestBlob("/me/export"),
|
exportData: () => requestBlob("/me/export"),
|
||||||
importData: (payload) => request("/me/import", { method: "POST", body: JSON.stringify(payload) }),
|
importData: (payload) => request("/me/import", { method: "POST", body: JSON.stringify(payload) }),
|
||||||
|
|||||||
@@ -296,7 +296,27 @@
|
|||||||
"controlRevoke": "Tilbagekald token",
|
"controlRevoke": "Tilbagekald token",
|
||||||
"controlRevokeConfirm": "Tilbagekald denne laders styringstoken? Den bliver afbrudt og kan ikke forbinde igen, før du genererer et nyt.",
|
"controlRevokeConfirm": "Tilbagekald denne laders styringstoken? Den bliver afbrudt og kan ikke forbinde igen, før du genererer et nyt.",
|
||||||
"controlConnected": "Forbundet til styrings-backend",
|
"controlConnected": "Forbundet til styrings-backend",
|
||||||
"controlDisconnected": "Ikke forbundet"
|
"controlDisconnected": "Ikke forbundet",
|
||||||
|
"greencell": "Greencell (HabuDen EV-lader)",
|
||||||
|
"greencellDesc": "Læs din Greencell-lader via den MQTT-broker, den publicerer til. Kun lokalt — ingen Greencell-skykonto er involveret.",
|
||||||
|
"greencellBroker": "MQTT-broker",
|
||||||
|
"greencellCharger": "Lader",
|
||||||
|
"greencellHost": "Brokerens vært",
|
||||||
|
"greencellHostHint": "Den broker, du pegede laderen på i Greencell GC-appen.",
|
||||||
|
"greencellPort": "Brokerens port",
|
||||||
|
"greencellPortHint": "Som standard 1883, eller 8883 når TLS er slået til.",
|
||||||
|
"greencellTls": "Forbindelse",
|
||||||
|
"greencellTlsOff": "Almindelig MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Brugernavn til broker",
|
||||||
|
"greencellUsernameHint": "Lad feltet stå tomt, hvis din broker tillader anonyme klienter.",
|
||||||
|
"greencellPassword": "Adgangskode til broker",
|
||||||
|
"greencellSerial": "Laderens serienummer",
|
||||||
|
"greencellSerialHint": "Valgfrit — lad det stå tomt, så finder søgningen det, der er på brokeren.",
|
||||||
|
"greencellTimeout": "Lyttevindue (sekunder)",
|
||||||
|
"greencellTimeoutHint": "Hvor længe der ventes på, at laderen publicerer. Greencell giver en enhed op til 30 s til at svare; hæv værdien, hvis intet findes.",
|
||||||
|
"greencellCommandTopic": "Emne for QUERY-kommandoen",
|
||||||
|
"greencellCommandTopicHint": "Valgfrit. Greencell beskriver en QUERY-kommando, der får laderen til at publicere med det samme, men ikke det emne, den lytter på. Finder du dit, så skriv det her, og læsninger behøver ikke vente på laderens egen kadence. Brug {sn} for serienummeret."
|
||||||
},
|
},
|
||||||
|
|
||||||
"org": {
|
"org": {
|
||||||
|
|||||||
@@ -295,7 +295,27 @@
|
|||||||
"controlRevoke": "Revoke token",
|
"controlRevoke": "Revoke token",
|
||||||
"controlRevokeConfirm": "Revoke this charger's control token? It will disconnect and can't reconnect until you generate a new one.",
|
"controlRevokeConfirm": "Revoke this charger's control token? It will disconnect and can't reconnect until you generate a new one.",
|
||||||
"controlConnected": "Connected to control backend",
|
"controlConnected": "Connected to control backend",
|
||||||
"controlDisconnected": "Not connected"
|
"controlDisconnected": "Not connected",
|
||||||
|
"greencell": "Greencell (HabuDen EV charger)",
|
||||||
|
"greencellDesc": "Read your Greencell wallbox over the MQTT broker it publishes to. Local only — no Greencell cloud account is involved.",
|
||||||
|
"greencellBroker": "MQTT broker",
|
||||||
|
"greencellCharger": "Charger",
|
||||||
|
"greencellHost": "Broker host",
|
||||||
|
"greencellHostHint": "The broker you pointed the charger at in the Greencell GC app.",
|
||||||
|
"greencellPort": "Broker port",
|
||||||
|
"greencellPortHint": "Defaults to 1883, or 8883 with TLS on.",
|
||||||
|
"greencellTls": "Connection",
|
||||||
|
"greencellTlsOff": "Plain MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Broker username",
|
||||||
|
"greencellUsernameHint": "Leave blank if your broker allows anonymous clients.",
|
||||||
|
"greencellPassword": "Broker password",
|
||||||
|
"greencellSerial": "Charger serial",
|
||||||
|
"greencellSerialHint": "Optional — leave blank and discovery finds whatever is on the broker.",
|
||||||
|
"greencellTimeout": "Listen window (seconds)",
|
||||||
|
"greencellTimeoutHint": "How long to wait for the charger to publish. Greencell allows a device up to 30 s to answer; raise this if nothing is found.",
|
||||||
|
"greencellCommandTopic": "QUERY command topic",
|
||||||
|
"greencellCommandTopicHint": "Optional. Greencell documents a QUERY command that makes the charger publish at once, but not the topic it listens on. If you find yours, put it here and reads stop waiting for the charger's own cadence. Use {sn} for the serial."
|
||||||
},
|
},
|
||||||
|
|
||||||
"org": {
|
"org": {
|
||||||
|
|||||||
@@ -300,7 +300,27 @@
|
|||||||
"controlRevoke": "Unieważnij token",
|
"controlRevoke": "Unieważnij token",
|
||||||
"controlRevokeConfirm": "Unieważnić token sterowania tej ładowarki? Rozłączy się i nie połączy ponownie, dopóki nie wygenerujesz nowego.",
|
"controlRevokeConfirm": "Unieważnić token sterowania tej ładowarki? Rozłączy się i nie połączy ponownie, dopóki nie wygenerujesz nowego.",
|
||||||
"controlConnected": "Połączono z backendem sterowania",
|
"controlConnected": "Połączono z backendem sterowania",
|
||||||
"controlDisconnected": "Nie połączono"
|
"controlDisconnected": "Nie połączono",
|
||||||
|
"greencell": "Greencell (ładowarka EV HabuDen)",
|
||||||
|
"greencellDesc": "Odczytuj swoją ładowarkę Greencell przez brokera MQTT, do którego publikuje. Tylko lokalnie — konto w chmurze Greencell nie jest potrzebne.",
|
||||||
|
"greencellBroker": "Broker MQTT",
|
||||||
|
"greencellCharger": "Ładowarka",
|
||||||
|
"greencellHost": "Adres brokera",
|
||||||
|
"greencellHostHint": "Broker, który wskazałeś ładowarce w aplikacji Greencell GC.",
|
||||||
|
"greencellPort": "Port brokera",
|
||||||
|
"greencellPortHint": "Domyślnie 1883, a przy włączonym TLS 8883.",
|
||||||
|
"greencellTls": "Połączenie",
|
||||||
|
"greencellTlsOff": "Zwykłe MQTT",
|
||||||
|
"greencellTlsOn": "TLS (MQTTS)",
|
||||||
|
"greencellUsername": "Użytkownik brokera",
|
||||||
|
"greencellUsernameHint": "Pozostaw puste, jeśli broker dopuszcza klientów anonimowych.",
|
||||||
|
"greencellPassword": "Hasło brokera",
|
||||||
|
"greencellSerial": "Numer seryjny ładowarki",
|
||||||
|
"greencellSerialHint": "Opcjonalne — pozostaw puste, a wykrywanie znajdzie to, co jest na brokerze.",
|
||||||
|
"greencellTimeout": "Okno nasłuchu (sekundy)",
|
||||||
|
"greencellTimeoutHint": "Jak długo czekać, aż ładowarka opublikuje dane. Greencell daje urządzeniu do 30 s na odpowiedź; zwiększ tę wartość, jeśli nic nie zostaje znalezione.",
|
||||||
|
"greencellCommandTopic": "Temat polecenia QUERY",
|
||||||
|
"greencellCommandTopicHint": "Opcjonalne. Greencell opisuje polecenie QUERY, które każe ładowarce natychmiast opublikować dane, ale nie podaje tematu, na którym ona nasłuchuje. Jeśli poznasz swój, wpisz go tutaj, a odczyty przestaną czekać na własny rytm ładowarki. Użyj {sn} zamiast numeru seryjnego."
|
||||||
},
|
},
|
||||||
|
|
||||||
"org": {
|
"org": {
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ watch(tabs, (list) => {
|
|||||||
// list of connectors you expand to configure.
|
// list of connectors you expand to configure.
|
||||||
const toyotaOpen = ref(false);
|
const toyotaOpen = ref(false);
|
||||||
const ankerOpen = ref(false);
|
const ankerOpen = ref(false);
|
||||||
|
const greencellOpen = ref(false);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
@@ -594,6 +595,142 @@ async function testAnkerConnection() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Integrations: Greencell (HabuDen EV charger) ---
|
||||||
|
//
|
||||||
|
// Same cascade once more, but what resolves here is an MQTT *broker*, not a
|
||||||
|
// cloud account: host/port/TLS/credentials describe one endpoint and the server
|
||||||
|
// resolves them together, so the form treats them as a group. The serial, the
|
||||||
|
// QUERY topic and the listen window resolve on their own.
|
||||||
|
//
|
||||||
|
// Only the password and — when inherited — the host and username are masked by
|
||||||
|
// the server; the rest are plain settings, so a locked one shows its effective
|
||||||
|
// value the way Anker's control mode does.
|
||||||
|
|
||||||
|
const GREENCELL_FIELDS = ["host", "port", "tls", "username", "password", "serial", "commandTopic", "timeout"];
|
||||||
|
const GREENCELL_MASKED = ["host", "username"]; // masked by the server when inherited
|
||||||
|
|
||||||
|
const greencell = ref(null); // resolved view from the server
|
||||||
|
const greencellScope = ref("user"); // "user" | "org" (org admins only)
|
||||||
|
const greencellForm = ref({
|
||||||
|
host: "", port: "", tls: "off", username: "", password: "", serial: "", commandTopic: "", timeout: "",
|
||||||
|
});
|
||||||
|
const greencellSaving = ref(false);
|
||||||
|
const greencellSaved = ref(false);
|
||||||
|
const greencellError = ref("");
|
||||||
|
const greencellTesting = ref(false);
|
||||||
|
const greencellHealth = ref(null); // { status, detail } from the last test
|
||||||
|
|
||||||
|
const greencellReadOnly = computed(() => !!greencell.value?.isSuperadmin);
|
||||||
|
const greencellScopeKey = computed(() =>
|
||||||
|
greencell.value?.isSuperadmin ? "user" : greencellScope.value
|
||||||
|
);
|
||||||
|
const greencellScopeData = computed(
|
||||||
|
() => greencell.value?.scopes?.[greencellScopeKey.value] || { editableLayer: "user", fields: {} }
|
||||||
|
);
|
||||||
|
const greencellEditingOrg = computed(() => greencellScopeKey.value === "org");
|
||||||
|
|
||||||
|
function greencellField(k) {
|
||||||
|
return greencellScopeData.value.fields?.[k] || { effective: "", own: "", source: "unset", locked: false };
|
||||||
|
}
|
||||||
|
function greencellLocked(k) {
|
||||||
|
return greencellReadOnly.value || greencellField(k).locked;
|
||||||
|
}
|
||||||
|
const greencellEnabled = computed(() =>
|
||||||
|
greencellEditingOrg.value ? greencell.value?.orgEnabled : greencell.value?.enabled
|
||||||
|
);
|
||||||
|
function greencellSourceLabel(k) {
|
||||||
|
const map = { global: "sourceGlobal", org: "sourceOrg", user: "sourceUser" };
|
||||||
|
const key = map[greencellField(k).source] || "sourceGlobal";
|
||||||
|
return t("settings.integrations.inheritedFrom", { source: t("settings.integrations." + key) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillGreencellForm() {
|
||||||
|
const f = greencellScopeData.value.fields || {};
|
||||||
|
const value = (k, fallback = "") => {
|
||||||
|
const fv = f[k] || {};
|
||||||
|
// A locked field the server masked has nothing useful to show; a locked
|
||||||
|
// plain setting shows what is actually in force.
|
||||||
|
if (fv.locked) return GREENCELL_MASKED.includes(k) ? "" : fv.effective || fallback;
|
||||||
|
return fv.own || fallback;
|
||||||
|
};
|
||||||
|
greencellForm.value = {
|
||||||
|
host: value("host"),
|
||||||
|
port: value("port"),
|
||||||
|
tls: value("tls", "off"),
|
||||||
|
username: value("username"),
|
||||||
|
password: "",
|
||||||
|
serial: value("serial"),
|
||||||
|
commandTopic: value("commandTopic"),
|
||||||
|
timeout: value("timeout"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyGreencellView(body) {
|
||||||
|
greencell.value = body;
|
||||||
|
if (greencellScope.value === "org" && !body.canEditOrg) greencellScope.value = "user";
|
||||||
|
fillGreencellForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadGreencell() {
|
||||||
|
try {
|
||||||
|
applyGreencellView(await api.getGreencell());
|
||||||
|
} catch (e) {
|
||||||
|
greencellError.value = e.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(greencellScope, () => {
|
||||||
|
greencellError.value = "";
|
||||||
|
greencellSaved.value = false;
|
||||||
|
greencellHealth.value = null;
|
||||||
|
fillGreencellForm();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function toggleGreencell(v) {
|
||||||
|
greencellError.value = "";
|
||||||
|
const scope = greencellEditingOrg.value ? "org" : "user";
|
||||||
|
try {
|
||||||
|
applyGreencellView(await api.saveGreencell({ scope, enabled: v }));
|
||||||
|
} catch (e) {
|
||||||
|
greencellError.value = e.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveGreencellSettings() {
|
||||||
|
greencellError.value = "";
|
||||||
|
greencellSaving.value = true;
|
||||||
|
greencellSaved.value = false;
|
||||||
|
const config = {};
|
||||||
|
for (const k of GREENCELL_FIELDS) {
|
||||||
|
if (greencellLocked(k)) continue;
|
||||||
|
if (k === "password" && !greencellForm.value.password) continue;
|
||||||
|
config[k] = greencellForm.value[k];
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
applyGreencellView(await api.saveGreencell({ scope: greencellScopeKey.value, config }));
|
||||||
|
greencellSaved.value = true;
|
||||||
|
setTimeout(() => (greencellSaved.value = false), 2000);
|
||||||
|
} catch (e) {
|
||||||
|
greencellError.value = e.message;
|
||||||
|
} finally {
|
||||||
|
greencellSaving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testGreencellConnection() {
|
||||||
|
greencellError.value = "";
|
||||||
|
greencellHealth.value = null;
|
||||||
|
greencellTesting.value = true;
|
||||||
|
try {
|
||||||
|
const { health } = await api.testGreencell();
|
||||||
|
greencellHealth.value = health;
|
||||||
|
} catch (e) {
|
||||||
|
greencellError.value = e.message;
|
||||||
|
} finally {
|
||||||
|
greencellTesting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function onLogout() {
|
function onLogout() {
|
||||||
logout();
|
logout();
|
||||||
router.replace({ name: "login" });
|
router.replace({ name: "login" });
|
||||||
@@ -729,6 +866,7 @@ onMounted(async () => {
|
|||||||
await loadAvatar();
|
await loadAvatar();
|
||||||
await loadToyota();
|
await loadToyota();
|
||||||
await loadAnkerSolix();
|
await loadAnkerSolix();
|
||||||
|
await loadGreencell();
|
||||||
});
|
});
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
@@ -1018,7 +1156,7 @@ onBeforeUnmount(() => {
|
|||||||
|
|
||||||
<!-- Integrations -->
|
<!-- Integrations -->
|
||||||
<div v-show="activeTab === 'integrations'" class="space-y-6">
|
<div v-show="activeTab === 'integrations'" class="space-y-6">
|
||||||
<section v-if="toyota || anker" class="dh-card p-6">
|
<section v-if="toyota || anker || greencell" class="dh-card p-6">
|
||||||
<h2 class="text-lg font-bold tracking-[-0.02em] text-strong">{{ t("settings.integrations.title") }}</h2>
|
<h2 class="text-lg font-bold tracking-[-0.02em] text-strong">{{ t("settings.integrations.title") }}</h2>
|
||||||
<p class="mb-4 mt-1 text-sm text-muted">{{ t("settings.integrations.subtitle") }}</p>
|
<p class="mb-4 mt-1 text-sm text-muted">{{ t("settings.integrations.subtitle") }}</p>
|
||||||
|
|
||||||
@@ -1348,6 +1486,212 @@ onBeforeUnmount(() => {
|
|||||||
<p v-if="ankerError" class="mt-2 text-sm text-danger">{{ ankerError }}</p>
|
<p v-if="ankerError" class="mt-2 text-sm text-danger">{{ ankerError }}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Greencell (HabuDen EV charger, read over your own MQTT broker) -->
|
||||||
|
<div v-if="greencell" class="mt-4 rounded-control border border-subtle p-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-start justify-between gap-3 text-left"
|
||||||
|
:aria-expanded="greencellOpen"
|
||||||
|
@click="greencellOpen = !greencellOpen"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-semibold text-strong">{{ t("settings.integrations.greencell") }}</p>
|
||||||
|
<p class="mt-0.5 text-xs text-muted">{{ t("settings.integrations.greencellDesc") }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex shrink-0 items-center gap-2">
|
||||||
|
<span
|
||||||
|
v-if="!greencellEditingOrg"
|
||||||
|
class="dh-badge"
|
||||||
|
:class="greencell.enabled ? 'dh-badge-success' : 'dh-badge-warning'"
|
||||||
|
>
|
||||||
|
{{ greencell.enabled ? t("settings.integrations.connected") : t("settings.integrations.notConnected") }}
|
||||||
|
</span>
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||||
|
class="h-4 w-4 text-muted transition-transform" :class="greencellOpen ? 'rotate-180' : ''"
|
||||||
|
><path stroke-linecap="round" stroke-linejoin="round" d="m6 9 6 6 6-6" /></svg>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-show="greencellOpen">
|
||||||
|
<!-- Master / org gates -->
|
||||||
|
<p v-if="!greencell.available" class="mt-3 text-sm text-warning">{{ t("settings.integrations.unavailable") }}</p>
|
||||||
|
<p
|
||||||
|
v-else-if="greencell.orgId && !greencell.orgEnabled && !greencellEditingOrg"
|
||||||
|
class="mt-3 text-sm text-warning"
|
||||||
|
>
|
||||||
|
{{ t("settings.integrations.orgDisabled") }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<!-- Scope switch (org admins) -->
|
||||||
|
<div v-if="greencell.canEditOrg" class="mt-4 flex gap-2">
|
||||||
|
<button
|
||||||
|
v-for="sc in ['user', 'org']"
|
||||||
|
:key="sc"
|
||||||
|
class="rounded-control border px-3 py-1.5 text-sm font-medium transition-colors"
|
||||||
|
:class="greencellScope === sc
|
||||||
|
? 'border-accent bg-accent text-white'
|
||||||
|
: 'border-subtle text-body hover:bg-sunken hover:text-strong'"
|
||||||
|
@click="greencellScope = sc"
|
||||||
|
>
|
||||||
|
{{ sc === 'org' ? t("settings.integrations.scopeOrg") : t("settings.integrations.scopeMy") }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p v-if="greencellEditingOrg" class="mt-2 text-xs text-muted">{{ t("settings.integrations.scopeHint") }}</p>
|
||||||
|
<p v-if="greencellReadOnly" class="mt-3 text-xs text-muted">{{ t("settings.integrations.readOnly") }}</p>
|
||||||
|
|
||||||
|
<!-- Enable toggle -->
|
||||||
|
<label class="mt-4 flex items-center gap-2 text-sm font-medium text-body">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="h-4 w-4 rounded border-subtle text-accent focus:ring-accent"
|
||||||
|
:checked="greencellEnabled"
|
||||||
|
@change="toggleGreencell($event.target.checked)"
|
||||||
|
/>
|
||||||
|
<span>{{ greencellEditingOrg ? t("settings.integrations.enableOrg") : t("settings.integrations.enable") }}</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<!-- Broker: host, port, TLS and credentials resolve together -->
|
||||||
|
<p class="mt-5 text-xs font-semibold uppercase tracking-wide text-muted">
|
||||||
|
{{ t("settings.integrations.greencellBroker") }}
|
||||||
|
</p>
|
||||||
|
<div class="mt-2 grid max-w-sm gap-3">
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellHost") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.host"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('host')"
|
||||||
|
:placeholder="greencellLocked('host') ? '••••••••' : '10.2.1.10'"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('host').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('host') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellHostHint") }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellPort") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.port"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('port')"
|
||||||
|
placeholder="1883"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('port').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('port') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellPortHint") }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellTls") }}</label>
|
||||||
|
<select v-model="greencellForm.tls" class="dh-input" :disabled="greencellLocked('tls')">
|
||||||
|
<option value="off">{{ t("settings.integrations.greencellTlsOff") }}</option>
|
||||||
|
<option value="on">{{ t("settings.integrations.greencellTlsOn") }}</option>
|
||||||
|
</select>
|
||||||
|
<p v-if="greencellField('tls').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('tls') }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellUsername") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.username"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('username')"
|
||||||
|
:placeholder="greencellLocked('username') ? '••••••••' : ''"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('username').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('username') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellUsernameHint") }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellPassword") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.password"
|
||||||
|
type="password"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('password')"
|
||||||
|
:placeholder="greencellField('password').effective ? '••••••••' : ''"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('password').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('password') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.passwordKeep") }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Charger: resolves independently of the broker -->
|
||||||
|
<p class="mt-5 text-xs font-semibold uppercase tracking-wide text-muted">
|
||||||
|
{{ t("settings.integrations.greencellCharger") }}
|
||||||
|
</p>
|
||||||
|
<div class="mt-2 grid max-w-sm gap-3">
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellSerial") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.serial"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('serial')"
|
||||||
|
placeholder="EVGC021B22752405ZM0018"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('serial').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('serial') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellSerialHint") }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellTimeout") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.timeout"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('timeout')"
|
||||||
|
placeholder="12"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('timeout').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('timeout') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellTimeoutHint") }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="dh-label">{{ t("settings.integrations.greencellCommandTopic") }}</label>
|
||||||
|
<input
|
||||||
|
v-model="greencellForm.commandTopic"
|
||||||
|
class="dh-input"
|
||||||
|
:disabled="greencellLocked('commandTopic')"
|
||||||
|
placeholder="/greencell/evse/{sn}/command"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<p v-if="greencellField('commandTopic').locked" class="mt-1 text-xs text-muted">{{ greencellSourceLabel('commandTopic') }}</p>
|
||||||
|
<p v-else class="mt-1 text-xs text-muted">{{ t("settings.integrations.greencellCommandTopicHint") }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
v-if="!greencellReadOnly"
|
||||||
|
class="dh-btn dh-btn-primary"
|
||||||
|
:disabled="greencellSaving"
|
||||||
|
@click="saveGreencellSettings"
|
||||||
|
>
|
||||||
|
{{ greencellSaving ? t("common.saving") : greencellSaved ? t("settings.integrations.saved") : t("settings.integrations.save") }}
|
||||||
|
</button>
|
||||||
|
<button class="dh-btn dh-btn-ghost" :disabled="greencellTesting" @click="testGreencellConnection">
|
||||||
|
{{ greencellTesting ? t("settings.integrations.testing") : t("settings.integrations.test") }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- A reachable broker with no charger on it is "degraded", not down:
|
||||||
|
the half we configure works and the missing half is the device. -->
|
||||||
|
<p
|
||||||
|
v-if="greencellHealth"
|
||||||
|
class="mt-2 text-sm"
|
||||||
|
:class="greencellHealth.status === 'ok'
|
||||||
|
? 'text-success'
|
||||||
|
: greencellHealth.status === 'degraded' ? 'text-warning' : 'text-danger'"
|
||||||
|
>
|
||||||
|
{{ greencellHealth.detail || greencellHealth.status }}
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<p v-if="greencellError" class="mt-2 text-sm text-danger">{{ greencellError }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user