Files
DriverVault/API Server/internal/api/integrations_ankersolix_mqtt.go
T
tajniak81andClaude Opus 5 90558d60b2 What the app can set, the cloud connection can set
The broker transport could move a session along — start, stop, boost, skip the
delay, cap the current — and nothing else. Everything the charger is actually
configured with sat one field away in the same messages we were already
decoding: the schedule it charges on, the plug lock, auto-start, the LED, load
balancing, solar charging, and the Modbus server the local transport depends on.
Readable, and unreachable.

The obstacle was never the cloud, it was the shape of the protocol. A setting is
not a register write. It is a *command*, and a command owns a set of fields
inside a message type — mostly one, but five own several, and the charger reads
the whole command as the new truth. A light-off schedule sent carrying only its
switch is a schedule whose start and end have just been set to midnight. So a
grouped write resends the siblings the caller did not name, using the values the
charger itself last reported, and refuses when it has never reported them. That
last part is not caution for its own sake: load balancing and solar charging
carry the serial of the meter they watch, and nothing outside the charger knows
it. An empty one would be adopted.

Those values do not arrive with the telemetry, either. The fast 0410 stream a
realtime trigger turns on carries none of them — the settings come on 0405, 0840
and 0900, which the charger sends when it has something to acknowledge. So a
grouped write may have to send a trigger first purely to make the charger talk
about itself, and says so plainly when even that produces nothing.

Everything a caller supplies is encoded before the cloud is touched at all. A
request naming one bad value changes nothing rather than half of what it asked
for, and a mistyped setting costs a validation error instead of a sign-in, a
certificate fetch and a broker connection to be told no.

mqttsettings.go holds one table and it is the only place a setting is defined:
the wire field, the name a caller uses, the state key its current value comes
from, and how a value becomes bytes. The names are the snapshot's own, so a
caller can read a status, change one entry and send it back. The existing limit
command now builds its frame from that table too rather than encoding field a8 a
second time.

Reading grew to match. The frame decoder gains the fields the grouped writes must
carry back — the two load-balance settings, both monitor serials, the solar
monitoring mode — plus the swipe gestures, and the snapshot exposes the rest of
what is now writable. One name was wrong and is corrected: field d9 was called
chargingMode after the Modbus register at 20088, but the reference has it as the
solar charging mode, so it becomes solarChargeMode and moves in beside the solar
settings. A mislabelled reading is bad; a mislabelled writable field is worse.

Over HTTP it is one action rather than a dozen, because the charger groups the
fields anyway: POST .../settings with a settings object, and settings sharing a
command travel in one frame instead of overwriting each other. The other two
transports refuse it by name and say which one has it, the way they already
refuse each other's commands. The audit trail records the values, not just that
a write happened — a setting that changes what the charger will draw, or whether
it answers on the LAN at all, is worth being able to trace afterwards.

Two things worth saying plainly. This is built from the reference project's
message maps and checked against its own frame layout, not against hardware —
there is no charger on this end to point it at. And modbusEnabled is a loaded
gun: writing it off stops the charger serving the register map, and the way back
is this transport, or the app.

The ignore rule for the local Modbus map artifact widens to the protocol maps
that now sit beside it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 18:28:45 +02:00

184 lines
7.2 KiB
Go

package api
// The remote half of the Anker Solix control plane.
//
// The other two transports each assume a route that a customer's charger usually
// does not have. OCPP (integrations_ankersolix_control.go) waits for the charger
// to dial in to us, which needs a public endpoint the charger can reach and a
// firmware willing to talk to our CSMS. Modbus TCP
// (integrations_ankersolix_modbus.go) dials the charger, which needs the server
// on the charger's own network. Between them they cover a charger we host and a
// charger we stand next to — and neither covers the ordinary case: a charger
// behind a customer's router, somewhere else entirely.
//
// This one goes the way the owner's phone already does. The charger holds a
// connection open to Anker's MQTT broker (it is the mqttStatus register the
// Modbus snapshot reports), and the account's own certificate lets us publish on
// the same topics the app publishes on. Nothing has to be reachable, forwarded
// or certificated on the customer's side; what it costs instead is a dependency
// on Anker's cloud being up, and on an unofficial protocol.
//
// The command set is the charger's, not OCPP's: start, stop, boost, skip-delay
// and a current limit, plus the one thing neither other transport can do at all
// — writing the charger's own configuration, which is what "settings" is for.
// Everything the register map or the CSMS can do that this cannot is refused by
// name rather than as an unknown action.
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"drivervault/apiserver/internal/plugins/builtin/ankersolix"
)
// ankerMqttTimeout bounds one command or status read end to end. It is generous
// because the path is: our broker connection, Anker's cloud, the customer's
// link, the charger — and back again for the confirmation. The plugin's own
// waits are shorter, so this only catches a request that is going nowhere.
const ankerMqttTimeout = 45 * time.Second
// ankerCloudConfig is the plugin config one caller's resolved credentials make.
// The cloud transport signs in as the account, so unlike Modbus it needs them.
func ankerCloudConfig(res ankerResolution) map[string]string {
return map[string]string{
"email": res.eff.Email,
"password": res.eff.Password,
"country": res.eff.Country,
}
}
// ankerMqttAction issues one control command over Anker's cloud broker. The
// gate, rate limit, destructive-action confirmation and audit have already run
// in handleAnkerControlAction; this decides what to send and reports the result.
func (s *Server) ankerMqttAction(w http.ResponseWriter, r *http.Request, who *callerIdentity,
res ankerResolution, sn, action string, body ankerControlBody) {
// Actions this transport has no equivalent for. Naming the transport that
// does have them beats a bare "unknown action" the caller cannot act on.
switch action {
case "reset", "unlock", "availability", "trigger", "config":
writeError(w, http.StatusBadRequest,
"\""+action+"\" is an OCPP command; the Anker cloud connection cannot send it. Switch the control mode to a CSMS mode to use it.")
return
case "phase", "timeout":
writeError(w, http.StatusBadRequest,
"\""+action+"\" is set through the charger's Modbus registers; the Anker cloud connection cannot send it. Switch the control mode to Modbus TCP to use it.")
return
case "clear-limit":
// As over Modbus: "no limit" would mean writing a ceiling we would have to
// invent, and the charger clamps to its own rating anyway.
writeError(w, http.StatusBadRequest,
"the Anker cloud connection has no \"clear limit\" command; send \"limit\" with the amps you want instead")
return
}
ctx, cancel := context.WithTimeout(r.Context(), ankerMqttTimeout)
defer cancel()
var (
capability = "mqtt-command"
params = map[string]any{"transport": "mqtt"}
payload = map[string]any{"sn": sn}
)
switch action {
case "start", "stop", "boost", "skip-delay":
payload["command"] = action
if action == "boost" && body.On != nil && !*body.On {
// Boost is a one-way command on this transport: the charger clears it
// when the session ends, and there is no message to cancel it early.
writeError(w, http.StatusBadRequest,
"boost cannot be switched off over the Anker cloud; it ends with the charging session, or stop the session to end it now")
return
}
case "limit":
params["amps"] = body.Amps
payload["command"], payload["amps"] = "limit", body.Amps
case "settings":
// The values themselves are audited, not just the fact of a write: a
// setting that changes what the charger will draw, or whether it answers on
// the LAN at all, is worth being able to trace afterwards.
if len(body.Settings) == 0 {
writeError(w, http.StatusBadRequest,
"settings requires a \"settings\" object, e.g. {\"settings\":{\"ledBrightness\":50}}")
return
}
capability = "mqtt-settings"
params["settings"] = body.Settings
payload["settings"] = body.Settings
case "status":
capability = "mqtt-status"
default:
writeError(w, http.StatusBadRequest, "unknown control action: "+action)
return
}
raw, err := s.plugins.InvokeWith(ctx, ankerPlugin, ankerCloudConfig(res), capability, mustJSON(payload))
outcome := "accepted"
if err != nil {
outcome = "error"
}
s.auditControl(who, sn, action, params, outcome, err)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return
}
if action == "status" {
writeJSON(w, http.StatusOK, map[string]any{"status": outcome, "result": json.RawMessage(raw)})
return
}
// The plugin answers {serial, command|applied, status, confirmed, detail?};
// relay it so the caller sees whether the charger acknowledged, not just that
// we sent.
writeJSON(w, http.StatusOK, json.RawMessage(raw))
}
// ankerMqttSnapshot reads a charger's live state for the status endpoint. Like
// its Modbus counterpart it is best effort: a charger that is offline, or an
// account the cloud will not hand a broker certificate for, simply has no
// snapshot — which is a fact to report, not an error to fail on.
func (s *Server) ankerMqttSnapshot(ctx context.Context, res ankerResolution, sn string) (ankersolix.MqttSnapshot, string, bool) {
var snap ankersolix.MqttSnapshot
if strings.TrimSpace(sn) == "" {
return snap, "", false
}
ctx, cancel := context.WithTimeout(ctx, ankerMqttTimeout)
defer cancel()
raw, err := s.plugins.InvokeWith(ctx, ankerPlugin, ankerCloudConfig(res), "mqtt-status", mustJSON(map[string]any{"sn": sn}))
if err != nil {
return snap, err.Error(), false
}
if err := json.Unmarshal(raw, &snap); err != nil {
return snap, err.Error(), false
}
return snap, "", true
}
// mustJSON encodes a small, known-good map for a plugin call. The values are
// built here from typed fields, so an encoding failure is not a runtime case.
func mustJSON(v map[string]any) json.RawMessage {
b, err := json.Marshal(v)
if err != nil {
return json.RawMessage(`{}`)
}
return b
}
// shortenDetail trims an upstream failure to something that fits in a status
// card without hiding what went wrong.
func shortenDetail(s string) string {
s = strings.TrimSpace(strings.ReplaceAll(s, "\n", " "))
if s == "" {
return "no detail"
}
if len(s) > 200 {
return s[:200] + "…"
}
return s
}