Reach the charger where it is, instead of waiting for it to call
OCPP asks the charger to dial us: a public endpoint, a TLS certificate, and a route in through the customer's router. Our own handler then demanded two more things the V1 does not offer — TLS on a charger that connects over ws://, and Basic auth credentials the Anker app has no field for — so every connection was turned away before the upgrade. Anker publishes a Modbus TCP register map for this charger, and it inverts the problem: we dial the charger, on its own network, with no inbound reachability to arrange. That works for a charger behind a router that OCPP cannot reach at all. internal/modbus is the protocol, hand-rolled against the spec like the MQTT and WebSocket clients beside it. The plugin's modbus.go is the V1's map: the same 0-8 status enum the cloud already reports, per-phase measurements, and the writable registers behind start, stop, current limit, boost and phase mode. A new "modbus" control mode routes the existing control endpoints down it, so the REST surface, the rate limit, the confirmation step and the audit trail are the ones already there. The commands the register map has no equivalent for say so by name rather than failing as unknown, and a current below the charger's 6 A floor is refused because it pauses the charge rather than slowing it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
e9a82a1cca
commit
f7472bada3
@@ -28,10 +28,14 @@ const (
|
||||
ankerPlugin = "anker-solix"
|
||||
ankerSecretMask = "••••••••"
|
||||
|
||||
// OCPP control modes for the Anker Solix charger (see internal/ocpp).
|
||||
ankerControlOff = "off" // monitoring only (default)
|
||||
ankerControlOwn = "own" // DriverVault is the charger's Central System
|
||||
ankerControlProxy = "proxy" // DriverVault relays to Anker's cloud and injects
|
||||
// Control modes for the Anker Solix charger. The first three are OCPP paths
|
||||
// (see internal/ocpp) and need the charger to dial in to us; modbus is the
|
||||
// local path (see the ankersolix plugin's modbus.go), where we dial the
|
||||
// charger instead — the only one that works when the charger cannot reach us.
|
||||
ankerControlOff = "off" // monitoring only (default)
|
||||
ankerControlOwn = "own" // DriverVault is the charger's Central System
|
||||
ankerControlProxy = "proxy" // DriverVault relays to Anker's cloud and injects
|
||||
ankerControlModbus = "modbus" // DriverVault talks Modbus TCP to the charger on the LAN
|
||||
)
|
||||
|
||||
// normalizeControlMode maps a raw control-mode value to a recognized mode, or ""
|
||||
@@ -43,6 +47,8 @@ func normalizeControlMode(v string) string {
|
||||
return ankerControlOwn
|
||||
case ankerControlProxy:
|
||||
return ankerControlProxy
|
||||
case ankerControlModbus:
|
||||
return ankerControlModbus
|
||||
case ankerControlOff:
|
||||
return ankerControlOff
|
||||
default:
|
||||
@@ -60,7 +66,8 @@ type ankerConfig struct {
|
||||
ControlMode string `json:"controlMode"`
|
||||
}
|
||||
|
||||
// ankerChargerBinding records a per-charger OCPP control token. The operator
|
||||
// ankerChargerBinding is what we know about one charger the caller controls:
|
||||
// its OCPP control token, its local Modbus address, or both. The operator
|
||||
// installs the token into the charger (as its OCPP Basic-auth password); we keep
|
||||
// only its SHA-256 hash and a short hint, never the plaintext — the token is
|
||||
// shown to the owner exactly once, at generation. User-layer only, not a cascade
|
||||
@@ -69,6 +76,14 @@ type ankerChargerBinding struct {
|
||||
TokenHash string `json:"tokenHash,omitempty"` // sha256(token), lowercase hex
|
||||
TokenHint string `json:"tokenHint,omitempty"` // last 4 chars, for the UI
|
||||
AddedAt string `json:"addedAt,omitempty"`
|
||||
|
||||
// ModbusHost and ModbusPort address the charger's local Modbus TCP server,
|
||||
// which the owner enables in the Anker app (Settings > Integrations > Modbus
|
||||
// TCP; the app then shows this address). They are per charger rather than per
|
||||
// account because they are a LAN address, not a credential — and unlike the
|
||||
// OCPP token they are not a secret, so they are stored and shown verbatim.
|
||||
ModbusHost string `json:"modbusHost,omitempty"`
|
||||
ModbusPort int `json:"modbusPort,omitempty"` // 0 means the standard 502
|
||||
}
|
||||
|
||||
// ankerStored is what we persist per user/org under pluginSettings.ankerSolix.
|
||||
|
||||
@@ -377,7 +377,26 @@ func (s *Server) handleAnkerControlStatus(w http.ResponseWriter, r *http.Request
|
||||
"endpoint": s.ocppEndpoint(r, sn),
|
||||
"hasToken": binding.TokenHash != "",
|
||||
"tokenHint": binding.TokenHint, // last-4 only; the token is shown once at generation
|
||||
"modbusHost": binding.ModbusHost,
|
||||
"modbusPort": binding.ModbusPort,
|
||||
}
|
||||
|
||||
// In Modbus mode "connected" is something we find out by asking, not by
|
||||
// having been dialled: the charger holds no session with us between commands.
|
||||
if res.eff.ControlMode == ankerControlModbus {
|
||||
snap, ok := s.ankerModbusSnapshot(r.Context(), binding)
|
||||
body["connected"] = ok
|
||||
if ok {
|
||||
body["status"] = snap
|
||||
} else if strings.TrimSpace(binding.ModbusHost) == "" {
|
||||
body["detail"] = "No local address saved yet. Enable Modbus TCP in the Anker app under Settings > Integrations, then save the address it shows."
|
||||
} else {
|
||||
body["detail"] = "The charger did not answer on " + ankerModbusConfig(binding).Address() + ". Check that it is powered on, on this network, and that Modbus TCP is still enabled in the Anker app."
|
||||
}
|
||||
writeJSON(w, http.StatusOK, body)
|
||||
return
|
||||
}
|
||||
|
||||
if sess, ok := s.ocpp.SessionFor(sn); ok {
|
||||
body["connected"] = true
|
||||
body["status"] = sess.Snapshot()
|
||||
@@ -470,13 +489,33 @@ func (s *Server) handleAnkerControlRevoke(w http.ResponseWriter, r *http.Request
|
||||
writeJSON(w, http.StatusOK, map[string]any{"serial": sn, "revoked": true})
|
||||
}
|
||||
|
||||
// handleAnkerControlAction issues one OCPP command to a connected charger.
|
||||
// ankerControlBody is the union of everything a control action may be given.
|
||||
// Which fields matter depends on the action, and on the transport: the OCPP
|
||||
// actions take connector ids and transaction ids, the Modbus ones do not.
|
||||
type ankerControlBody struct {
|
||||
IdTag string `json:"idTag"`
|
||||
ConnectorID int `json:"connectorId"`
|
||||
TransactionID int `json:"transactionId"`
|
||||
Amps float64 `json:"amps"`
|
||||
Operative *bool `json:"operative"`
|
||||
Hard bool `json:"hard"`
|
||||
RequestedMessage string `json:"requestedMessage"`
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Confirm bool `json:"confirm"`
|
||||
Password string `json:"password"`
|
||||
On *bool `json:"on"` // boost
|
||||
PhaseMode *int `json:"phase"` // 0 automatic, 1 single, 2 three
|
||||
Seconds int `json:"seconds"` // Modbus control timeout
|
||||
}
|
||||
|
||||
// handleAnkerControlAction issues one command to a charger, over whichever
|
||||
// transport the resolved control mode selects.
|
||||
func (s *Server) handleAnkerControlAction(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.ankerControlSession(w, r)
|
||||
who, res, binding, ok := s.ankerControlGate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
who := caller(r)
|
||||
sn := r.PathValue("sn")
|
||||
action := r.PathValue("action")
|
||||
|
||||
@@ -487,19 +526,7 @@ func (s *Server) handleAnkerControlAction(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
IdTag string `json:"idTag"`
|
||||
ConnectorID int `json:"connectorId"`
|
||||
TransactionID int `json:"transactionId"`
|
||||
Amps float64 `json:"amps"`
|
||||
Operative *bool `json:"operative"`
|
||||
Hard bool `json:"hard"`
|
||||
RequestedMessage string `json:"requestedMessage"`
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Confirm bool `json:"confirm"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
var body ankerControlBody
|
||||
if r.Body != nil {
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
}
|
||||
@@ -521,6 +548,17 @@ func (s *Server) handleAnkerControlAction(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
}
|
||||
|
||||
if res.eff.ControlMode == ankerControlModbus {
|
||||
s.ankerModbusAction(w, r, who, binding, sn, action, body)
|
||||
return
|
||||
}
|
||||
|
||||
sess, ok := s.ocpp.SessionFor(sn)
|
||||
if !ok {
|
||||
writeError(w, http.StatusConflict, "charger is not connected to the control backend")
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
var (
|
||||
status string
|
||||
@@ -623,40 +661,67 @@ func controlAuditParams(action string, connectorID int, amps float64, hard bool,
|
||||
return p
|
||||
}
|
||||
|
||||
// ankerControlSession applies the full gate (cascade + control mode + a live
|
||||
// session the caller actually owns) and returns the charger's session.
|
||||
func (s *Server) ankerControlSession(w http.ResponseWriter, r *http.Request) (*ocpp.Session, bool) {
|
||||
// ankerControlGate applies everything a control request must satisfy before any
|
||||
// transport is chosen: the cascade, a control mode that is not off, and a
|
||||
// charger the caller actually owns. It answers the request itself on refusal.
|
||||
//
|
||||
// What "owns" means depends on the mode, because the two transports bind a
|
||||
// charger differently: OCPP by the control token the charger authenticates
|
||||
// with, Modbus by the local address we dial. Requiring a token in Modbus mode
|
||||
// would demand a credential that path never uses.
|
||||
func (s *Server) ankerControlGate(w http.ResponseWriter, r *http.Request) (*callerIdentity, ankerResolution, ankerChargerBinding, bool) {
|
||||
var (
|
||||
res ankerResolution
|
||||
binding ankerChargerBinding
|
||||
)
|
||||
who := caller(r)
|
||||
if who == nil {
|
||||
writeError(w, http.StatusUnauthorized, "not authenticated")
|
||||
return nil, false
|
||||
return nil, res, binding, false
|
||||
}
|
||||
sn := r.PathValue("sn")
|
||||
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||
res := s.resolveAnker(r.Context(), who, userRaw)
|
||||
res = s.resolveAnker(r.Context(), who, userRaw)
|
||||
|
||||
switch {
|
||||
case !res.available:
|
||||
writeError(w, http.StatusForbidden, "the Anker Solix integration is disabled by the administrator")
|
||||
return nil, false
|
||||
return nil, res, binding, false
|
||||
case !res.orgEnabled:
|
||||
writeError(w, http.StatusForbidden, "the Anker Solix integration is disabled for your organization")
|
||||
return nil, false
|
||||
return nil, res, binding, false
|
||||
case !res.enabled:
|
||||
writeError(w, http.StatusForbidden, "enable the Anker Solix integration in Settings first")
|
||||
return nil, false
|
||||
return nil, res, binding, false
|
||||
}
|
||||
if res.eff.ControlMode == ankerControlOff {
|
||||
writeError(w, http.StatusConflict, "control mode is off; choose Own or Proxy CSMS to send commands")
|
||||
return nil, false
|
||||
writeError(w, http.StatusConflict, "control mode is off; choose Modbus TCP or a CSMS mode to send commands")
|
||||
return nil, res, binding, false
|
||||
}
|
||||
// The caller must own this charger (have a token bound to it), so a serial
|
||||
// alone can't be used to reach someone else's charger.
|
||||
if ankerBindingFor(userRaw, sn).TokenHash == "" {
|
||||
|
||||
binding = ankerBindingFor(userRaw, sn)
|
||||
if res.eff.ControlMode == ankerControlModbus {
|
||||
if strings.TrimSpace(binding.ModbusHost) == "" {
|
||||
writeError(w, http.StatusNotFound, "no local address for this charger; enable Modbus TCP in the Anker app and save the address it shows")
|
||||
return nil, res, binding, false
|
||||
}
|
||||
return who, res, binding, true
|
||||
}
|
||||
// A serial alone can't be used to reach someone else's charger.
|
||||
if binding.TokenHash == "" {
|
||||
writeError(w, http.StatusNotFound, "no control token for this charger; generate one first")
|
||||
return nil, res, binding, false
|
||||
}
|
||||
return who, res, binding, true
|
||||
}
|
||||
|
||||
// ankerControlSession applies the gate and returns the charger's live OCPP
|
||||
// session.
|
||||
func (s *Server) ankerControlSession(w http.ResponseWriter, r *http.Request) (*ocpp.Session, bool) {
|
||||
if _, _, _, ok := s.ankerControlGate(w, r); !ok {
|
||||
return nil, false
|
||||
}
|
||||
sess, ok := s.ocpp.SessionFor(sn)
|
||||
sess, ok := s.ocpp.SessionFor(r.PathValue("sn"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusConflict, "charger is not connected to the control backend")
|
||||
return nil, false
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
package api
|
||||
|
||||
// The local half of the Anker Solix control plane. Where the OCPP path in
|
||||
// integrations_ankersolix_control.go waits for the charger to dial in to us,
|
||||
// this one dials the charger: Modbus TCP on its own network, using the register
|
||||
// map Anker publishes for the V1 (see the plugin's modbus.go). That inversion is
|
||||
// the whole point — a charger behind a customer's router can be controlled this
|
||||
// way without any inbound reachability, a public endpoint or a TLS certificate.
|
||||
//
|
||||
// The trade-off is that the server must share a network with the charger, so
|
||||
// this mode is selectable per user rather than assumed.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drivervault/apiserver/internal/modbus"
|
||||
"drivervault/apiserver/internal/plugins/builtin/ankersolix"
|
||||
)
|
||||
|
||||
// modbusActionTimeout bounds one dial-plus-exchange. The charger is on the LAN,
|
||||
// so this is generous; it exists so an unreachable address fails the request
|
||||
// rather than holding it open.
|
||||
const modbusActionTimeout = 10 * time.Second
|
||||
|
||||
// ankerModbusConfig reads a charger's local address out of its stored binding.
|
||||
func ankerModbusConfig(b ankerChargerBinding) ankersolix.ModbusConfig {
|
||||
return ankersolix.ModbusConfig{Host: strings.TrimSpace(b.ModbusHost), Port: b.ModbusPort}
|
||||
}
|
||||
|
||||
// ankerModbusAction issues one control command over Modbus TCP. The gate,
|
||||
// rate limit, destructive-action confirmation and audit have already run in
|
||||
// handleAnkerControlAction; this decides what to write and reports the outcome.
|
||||
func (s *Server) ankerModbusAction(w http.ResponseWriter, r *http.Request, who *callerIdentity,
|
||||
binding ankerChargerBinding, sn, action string, body ankerControlBody) {
|
||||
|
||||
// Actions the register map has no equivalent for. Saying which transport is
|
||||
// missing 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 local Modbus connection cannot send it. Switch the control mode to a CSMS mode to use it.")
|
||||
return
|
||||
case "clear-limit":
|
||||
// The register takes an explicit ceiling and the charger clamps anything
|
||||
// above its rating, so "no limit" would mean writing a value we would have
|
||||
// to guess. Asking for the real one is better than guessing wrong.
|
||||
writeError(w, http.StatusBadRequest,
|
||||
"the local connection has no \"clear limit\" command; send \"limit\" with the amps you want instead")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), modbusActionTimeout)
|
||||
defer cancel()
|
||||
|
||||
client, err := ankersolix.ModbusDial(ctx, ankerModbusConfig(binding))
|
||||
if err != nil {
|
||||
s.auditControl(who, sn, action, nil, "error", err)
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
var (
|
||||
result any
|
||||
params = map[string]any{"transport": "modbus"}
|
||||
)
|
||||
switch action {
|
||||
case "start":
|
||||
err = ankersolix.ModbusStartCharging(ctx, client)
|
||||
case "stop":
|
||||
err = ankersolix.ModbusStopCharging(ctx, client)
|
||||
case "limit":
|
||||
params["amps"] = body.Amps
|
||||
err = ankersolix.ModbusSetMaxCurrent(ctx, client, body.Amps)
|
||||
case "boost":
|
||||
on := body.On == nil || *body.On
|
||||
params["on"] = on
|
||||
err = ankersolix.ModbusSetBoost(ctx, client, on)
|
||||
case "phase":
|
||||
if body.PhaseMode == nil {
|
||||
writeError(w, http.StatusBadRequest, "phase requires \"phase\": 0 (automatic), 1 (single) or 2 (three)")
|
||||
return
|
||||
}
|
||||
params["phase"] = *body.PhaseMode
|
||||
err = ankersolix.ModbusSetPhaseMode(ctx, client, *body.PhaseMode)
|
||||
case "timeout":
|
||||
params["seconds"] = body.Seconds
|
||||
err = ankersolix.ModbusSetTimeout(ctx, client, body.Seconds)
|
||||
case "status":
|
||||
var snap ankersolix.ModbusSnapshot
|
||||
snap, err = ankersolix.ModbusRead(ctx, client, true)
|
||||
result = snap
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "unknown control action: "+action)
|
||||
return
|
||||
}
|
||||
|
||||
outcome := "accepted"
|
||||
if err != nil {
|
||||
outcome = "error"
|
||||
}
|
||||
s.auditControl(who, sn, action, params, outcome, err)
|
||||
|
||||
if err != nil {
|
||||
// A register the charger refused is a bad request, not a bad gateway: the
|
||||
// link worked and the charger said no.
|
||||
status := http.StatusBadGateway
|
||||
var mbErr *modbus.Error
|
||||
if errors.As(err, &mbErr) {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp := map[string]any{"status": outcome}
|
||||
if result != nil {
|
||||
resp["result"] = result
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handleAnkerControlAddress saves (or clears, on DELETE) the local address of one
|
||||
// charger's Modbus TCP server — the address the Anker app shows once Modbus is
|
||||
// enabled on the device.
|
||||
func (s *Server) handleAnkerControlAddress(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
|
||||
}
|
||||
sn := strings.TrimSpace(r.PathValue("sn"))
|
||||
if sn == "" {
|
||||
writeError(w, http.StatusBadRequest, "missing charger serial")
|
||||
return
|
||||
}
|
||||
|
||||
var host string
|
||||
var port int
|
||||
if r.Method != http.MethodDelete {
|
||||
var body struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
}
|
||||
if r.Body != nil {
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
}
|
||||
host = strings.TrimSpace(body.Host)
|
||||
port = body.Port
|
||||
if err := validateModbusAddress(host, port); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
userRaw := s.userPluginSettings(r.Context(), who.ID)
|
||||
newDoc := mergeAnker(userRaw, func(as *ankerStored) {
|
||||
if as.ControlChargers == nil {
|
||||
as.ControlChargers = map[string]ankerChargerBinding{}
|
||||
}
|
||||
// Keep whatever else the binding holds: a charger may carry both an OCPP
|
||||
// token and a local address, and switching control mode must not discard
|
||||
// the other one.
|
||||
b := as.ControlChargers[sn]
|
||||
b.ModbusHost, b.ModbusPort = host, port
|
||||
if b.AddedAt == "" {
|
||||
b.AddedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
as.ControlChargers[sn] = b
|
||||
})
|
||||
if err := s.pb.Update(r.Context(), s.usersCollection(), who.ID,
|
||||
map[string]any{"pluginSettings": newDoc}, nil); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
action := "address.set"
|
||||
if host == "" {
|
||||
action = "address.clear"
|
||||
}
|
||||
s.auditControl(who, sn, action, map[string]any{"host": host, "port": port}, "ok", nil)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"serial": sn, "modbusHost": host, "modbusPort": port})
|
||||
}
|
||||
|
||||
// validateModbusAddress checks a user-supplied charger address. Loopback is
|
||||
// refused because this address is one the server dials on the caller's behalf,
|
||||
// and 127.0.0.1 would point it at services running on the server itself rather
|
||||
// than at a charger. Other addresses are allowed: the charger is expected on a
|
||||
// private LAN, but a routed or VPN deployment is legitimate too.
|
||||
func validateModbusAddress(host string, port int) error {
|
||||
if host == "" {
|
||||
return errors.New("the charger's local address is required")
|
||||
}
|
||||
if port < 0 || port > 65535 {
|
||||
return fmt.Errorf("%d is not a valid port", port)
|
||||
}
|
||||
if strings.ContainsAny(host, " /\\?#@") {
|
||||
return errors.New("the address should be just a hostname or IP, with no scheme or path")
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip.IsLoopback() || ip.IsUnspecified() {
|
||||
return errors.New("that address points at the server itself, not at a charger")
|
||||
}
|
||||
} else if strings.EqualFold(host, "localhost") {
|
||||
return errors.New("that address points at the server itself, not at a charger")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ankerModbusSnapshot reads a charger's live state for the status endpoint. It
|
||||
// is best effort: a charger that is switched off or on another network simply
|
||||
// has no snapshot, which is not an error in a status report.
|
||||
func (s *Server) ankerModbusSnapshot(ctx context.Context, binding ankerChargerBinding) (ankersolix.ModbusSnapshot, bool) {
|
||||
if strings.TrimSpace(binding.ModbusHost) == "" {
|
||||
return ankersolix.ModbusSnapshot{}, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, modbusActionTimeout)
|
||||
defer cancel()
|
||||
|
||||
client, err := ankersolix.ModbusDial(ctx, ankerModbusConfig(binding))
|
||||
if err != nil {
|
||||
return ankersolix.ModbusSnapshot{}, false
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
snap, err := ankersolix.ModbusRead(ctx, client, true)
|
||||
if err != nil {
|
||||
return ankersolix.ModbusSnapshot{}, false
|
||||
}
|
||||
return snap, true
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateModbusAddressAcceptsLANAddresses(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
host string
|
||||
port int
|
||||
}{
|
||||
{"10.2.1.55", 502},
|
||||
{"192.168.1.40", 0}, // 0 means the standard port
|
||||
{"charger.local", 502},
|
||||
{"fd00::1", 502},
|
||||
} {
|
||||
if err := validateModbusAddress(tc.host, tc.port); err != nil {
|
||||
t.Errorf("validateModbusAddress(%q, %d) = %v, want nil", tc.host, tc.port, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The server dials this address on the caller's behalf, so an address that
|
||||
// resolves back to the server would point it at its own services.
|
||||
func TestValidateModbusAddressRefusesLoopback(t *testing.T) {
|
||||
for _, host := range []string{"127.0.0.1", "::1", "localhost", "LocalHost", "0.0.0.0"} {
|
||||
err := validateModbusAddress(host, 502)
|
||||
if err == nil {
|
||||
t.Errorf("validateModbusAddress(%q) was accepted", host)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), "server itself") {
|
||||
t.Errorf("validateModbusAddress(%q) = %v, want it to say why", host, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateModbusAddressRejectsMalformed(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
host string
|
||||
port int
|
||||
}{
|
||||
{"empty host", "", 502},
|
||||
{"a URL rather than a host", "http://10.2.1.55/", 502},
|
||||
{"host with a path", "10.2.1.55/modbus", 502},
|
||||
{"port above the range", "10.2.1.55", 70000},
|
||||
{"negative port", "10.2.1.55", -1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if err := validateModbusAddress(tc.host, tc.port); err == nil {
|
||||
t.Errorf("%s was accepted", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnkerModbusConfigTrimsAndDefaults(t *testing.T) {
|
||||
cfg := ankerModbusConfig(ankerChargerBinding{ModbusHost: " 10.2.1.55 "})
|
||||
if cfg.Host != "10.2.1.55" {
|
||||
t.Errorf("Host = %q, want it trimmed", cfg.Host)
|
||||
}
|
||||
if got := cfg.Address(); got != "10.2.1.55:502" {
|
||||
t.Errorf("Address = %q, want the standard port filled in", got)
|
||||
}
|
||||
|
||||
cfg = ankerModbusConfig(ankerChargerBinding{ModbusHost: "10.2.1.55", ModbusPort: 1502})
|
||||
if got := cfg.Address(); got != "10.2.1.55:1502" {
|
||||
t.Errorf("Address = %q, want 10.2.1.55:1502", got)
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,10 @@ func TestNormalizeControlMode(t *testing.T) {
|
||||
"off": "off",
|
||||
"own": "own",
|
||||
"proxy": "proxy",
|
||||
"modbus": "modbus",
|
||||
"OWN": "own",
|
||||
" Proxy": "proxy",
|
||||
"Modbus ": "modbus",
|
||||
"": "", // unset — cascade continues to the next layer
|
||||
"bogus": "", // unknown — treated as unset
|
||||
}
|
||||
|
||||
@@ -451,6 +451,8 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/integrations/anker-solix/chargers/{sn}/control", s.handleAnkerControlStatus)
|
||||
mux.HandleFunc("POST /api/integrations/anker-solix/chargers/{sn}/control/token", s.handleAnkerControlToken)
|
||||
mux.HandleFunc("DELETE /api/integrations/anker-solix/chargers/{sn}/control/token", s.handleAnkerControlRevoke)
|
||||
mux.HandleFunc("PUT /api/integrations/anker-solix/chargers/{sn}/control/address", s.handleAnkerControlAddress)
|
||||
mux.HandleFunc("DELETE /api/integrations/anker-solix/chargers/{sn}/control/address", s.handleAnkerControlAddress)
|
||||
mux.HandleFunc("POST /api/integrations/anker-solix/chargers/{sn}/{action}", s.handleAnkerControlAction)
|
||||
|
||||
// OCPP WebSocket endpoint the charger dials out to (own/proxy modes). It sits
|
||||
|
||||
Reference in New Issue
Block a user