Four questions asked of an account that answers twenty-one

The connector called ten endpoints of the read surface the map lists, and
the charger card showed four views. Everything else an EV charger can
reach is now a capability too: the sessions and the history, the savings,
the sharing, the binding, the group, the Wi-Fi, the firmware and its
update log, the tamper records, the site's own detail, price, networks
and energy — plus the vehicle catalogue, dynamic pricing, the currencies
and the notification views. Thirty-eight endpoints, one action each. The
two message views are GET, so the request path grew a GET half that shares
the login retry with the POST one.

The per-charger fan-out asks all of them, six at a time rather than one
after another, and a charger that belongs to a site brings that site's
four views with it once the by-serial lookup has found it. A view that
answers with nothing now says so instead of vanishing: the station record
is empty for a standalone charger because it has no station, which is an
answer worth reading. And "source 0" in the OCPP box carries the address
the account's endpoint list gives it.

Anker's account-level writes stay out, as do the endpoints whose payloads
were only ever read out of the app package.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tajniak81
2026-09-02 22:53:36 +02:00
co-authored by Claude Opus 5
parent fb42791f8d
commit 3f9d5b943f
15 changed files with 839 additions and 70 deletions
@@ -47,6 +47,7 @@ import (
"fmt"
"io"
"net/http"
neturl "net/url"
"sort"
"strings"
"sync"
@@ -88,6 +89,69 @@ const (
epUserVehicles = "power_service/v1/app/vehicle/get_vehicle_list" // vehicles registered for smart charging
epVehicleDetail = "power_service/v1/app/vehicle/get_vehicle_detail" // details for one registered vehicle
// The rest of the read surface an EV charger can reach, from the same source
// as the endpoints above (anker-solix-api's apitypes.py, filtered to what a
// charger touches) and catalogued in anker-api-map.html. Every one of these
// reads; the account-level writes the app makes — vehicles, site prices,
// sharing invites, quiet hours, auto-upgrade — are deliberately not here, and
// neither is any endpoint whose payload was only ever read out of the app
// package rather than called ("unmapped" in the map).
// Finding and identifying a charger.
epSiteDetailBySN = "power_service/v1/site/get_site_detail_by_sn" // the site a charger belongs to, from its serial alone
epSiteDetail = "power_service/v1/site/get_site_detail" // site detail; answers for shared accounts too
epSiteHomepage = "power_service/v1/site/get_site_homepage" // the app home screen's own view of every site
epUserDevices = "power_service/v1/site/list_user_devices" // owned devices, lighter than the bound-device view
epDeviceBindDetails = "power_service/v1/app/get_device_bind_details" // binding details for a list of serials
epGroupDevices = "power_service/v1/app/group/get_group_devices" // whether a charger is grouped with sub-devices
epSiteWifiList = "power_service/v1/site/get_wifi_info_list" // networks the site can see
epDeviceProductInfo = "charging_hes_svc/get_device_product_info" // product info for HES-family devices
epInstallInfo = "charging_hes_svc/get_install_info" // where the system was installed
epChargerWifiInfo = "charging_hes_svc/get_wifi_info" // the charger's own Wi-Fi details
// Charging sessions — where the completed history lives.
epChargingOrders = "power_service/v1/app/order/get_charging_order_list" // every session in a date range
epChargingOrder = "power_service/v1/app/order/get_charging_order_detail" // one session, with its chart points and vehicle
epOrderSecDetail = "power_service/v1/app/order/get_charging_order_sec_detail" // second-resolution detail for a session
epOrderSecPreview = "power_service/v1/app/order/get_charging_order_sec_preview" // preview of the same
// Energy, price and what it cost.
epEnergyStatistics = "charging_hes_svc/get_energy_statistics" // energy stats with the EV charger as its own source
epDeviceIncome = "power_service/v1/app/device/get_device_income" // income / savings figures per device
epSitePrice = "power_service/v1/site/get_site_price" // the site's power price and CO2 factor
epCurrencyList = "power_service/v1/currency/get_list" // supported currencies
epSiteDataExport = "power_service/v1/site/site_data_exported" // filename and URL for a CSV export
epDynPriceCheck = "power_service/v1/dynamic_price/check_available" // which sites have dynamic pricing at all
epDynPriceOptions = "power_service/v1/dynamic_price/support_option" // price providers for a product code
epDynPriceDetail = "power_service/v1/dynamic_price/price_detail" // the actual price curve
// The vehicle catalogue behind smart charging.
epVehicleBrands = "power_service/v1/app/get_brand_list" // vehicle brands
epVehicleModels = "power_service/v1/app/get_models" // models for a brand
epVehicleYears = "power_service/v1/app/get_model_years" // production years for a model
epVehicleSpecs = "power_service/v1/app/get_model_list" // what Anker knows about that exact car
// Sharing.
epSharedDevice = "app/devicerelation/get_shared_device" // who a charger is currently shared with
// Firmware.
epOtaBatchCheck = "app/ota/batch/check_update" // latest available version per serial
epOtaInfo = "power_service/v1/app/compatible/get_ota_info" // current OTA status
epOtaUpdate = "power_service/v1/app/compatible/get_ota_update" // details of an available update
epUpgradeRecords = "power_service/v1/app/get_upgrade_record" // firmware update history
epUpgradeRecord = "power_service/v1/app/check_upgrade_record" // one update record, three views of it
epAutoUpgrade = "power_service/v1/app/get_auto_upgrade" // which devices auto-update
// Notifications, and the charging events behind them. The first two are the
// only endpoints in this connector Anker serves over GET.
epMessageUnread = "power_service/v1/get_message_unread" // whether anything is waiting (GET)
epMessages = "power_service/v1/get_message" // the messages themselves (GET, last_time)
epMessageNotDisturb = "power_service/v1/get_message_not_disturb" // current quiet-hours settings
epMessageSNList = "power_service/v1/get_message_sn_list" // which devices produce messages at all
// Health and faults.
epTamperRecords = "power_service/v1/device/get_tamper_records" // tamper records for a device
// The cloud MQTT broker's own credentials endpoint is epMqttInfo, declared in
// cloudmqtt.go next to the transport that uses it.
)
@@ -181,7 +245,7 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
AuthType: plugins.AuthBasic,
Capabilities: []plugins.Capability{
{ID: "chargers", Method: "POST", Endpoint: epStandaloneChargers, Description: "Every EV charger on the account, merged from the standalone, per-site, bound-device and per-charger station views, each charger carrying every field those views reported (see chargers.go)."},
{ID: "charger-details", Method: "POST", Endpoint: epStationInfo, Description: "Every per-charger view the account holds — the station record, the charging totals, the OCPP backend and the RFID cards — each relayed as the fields it sent (needs sn)."},
{ID: "charger-details", Method: "POST", Endpoint: epStationInfo, Description: "Every view the account holds about one charger — the station record, the totals, the history and sessions, the savings, the OCPP backend and the endpoints that name its source, the cards, the sharing, the binding, the group, the Wi-Fi, the firmware, the tamper log, and the site's own views when it belongs to one — each relayed as the fields it sent (needs sn)."},
{ID: "charger-status", Method: "POST", Endpoint: epStationInfo, Description: "Live station/status info for one charger (needs sn; optional featuretype 1 or 2)."},
{ID: "charger-state", Method: "POST", Endpoint: epSceneInfo, Description: "Normalized live state of a site's EV chargers: status, operational mode and the modes it can be switched to (needs siteId; optional sn)."},
{ID: "site-status", Method: "POST", Endpoint: epSceneInfo, Description: "Live site view; EV chargers appear under charging_pile_info (needs siteId)."},
@@ -195,6 +259,49 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
{ID: "sites", Method: "POST", Endpoint: epSiteList, Description: "Sites (systems) registered to the account."},
{ID: "vehicles", Method: "POST", Endpoint: epUserVehicles, Description: "Vehicles registered for smart charging."},
{ID: "vehicle", Method: "POST", Endpoint: epVehicleDetail, Description: "Details for one registered vehicle (needs vehicleId)."},
// The rest of the read surface an EV charger can reach, one action per
// endpoint, so anything the account will say can be asked for without
// a new capability being invented for it first. The account-level
// writes the app makes and the endpoints nobody has ever called stay
// out (see the endpoint block above).
{ID: "site-by-sn", Method: "POST", Endpoint: epSiteDetailBySN, Description: "The site a charger belongs to, from its serial alone (needs sn)."},
{ID: "site-detail", Method: "POST", Endpoint: epSiteDetail, Description: "Site detail; answers for shared accounts too (needs siteId)."},
{ID: "site-homepage", Method: "POST", Endpoint: epSiteHomepage, Description: "The app home screen's own view of every site."},
{ID: "user-devices", Method: "POST", Endpoint: epUserDevices, Description: "Owned devices, a lighter list than the bound-device view."},
{ID: "bind-details", Method: "POST", Endpoint: epDeviceBindDetails, Description: "Binding details for one or more serials (needs sn, or sns)."},
{ID: "group-devices", Method: "POST", Endpoint: epGroupDevices, Description: "Whether a charger is grouped with sub-devices (needs sn)."},
{ID: "site-wifi", Method: "POST", Endpoint: epSiteWifiList, Description: "The networks a site can see (needs siteId)."},
{ID: "charger-wifi", Method: "POST", Endpoint: epChargerWifiInfo, Description: "The charger's own Wi-Fi details (needs sn)."},
{ID: "product-info", Method: "POST", Endpoint: epDeviceProductInfo, Description: "Product info for HES-family devices (optional sn)."},
{ID: "install-info", Method: "POST", Endpoint: epInstallInfo, Description: "Where the system was installed (optional sn, siteId)."},
{ID: "charging-orders", Method: "POST", Endpoint: epChargingOrders, Description: "Every charging session in a date range - a plainer list than the paged stats one (needs sn; optional startTime)."},
{ID: "charging-order", Method: "POST", Endpoint: epChargingOrder, Description: "One session with its chart points and the vehicle it charged (needs sn and orderId)."},
{ID: "order-seconds", Method: "POST", Endpoint: epOrderSecDetail, Description: "Second-resolution detail for one session (needs orderId; optional startTime)."},
{ID: "order-seconds-preview", Method: "POST", Endpoint: epOrderSecPreview, Description: "Preview of the second-resolution session detail (needs orderId)."},
{ID: "energy-statistics", Method: "POST", Endpoint: epEnergyStatistics, Description: "Energy statistics with the EV charger as its own source (optional sn, siteId)."},
{ID: "device-income", Method: "POST", Endpoint: epDeviceIncome, Description: "Income / savings figures for one charger (needs sn; optional startTime)."},
{ID: "site-price", Method: "POST", Endpoint: epSitePrice, Description: "A site's power price and CO2 factor (needs siteId)."},
{ID: "currencies", Method: "POST", Endpoint: epCurrencyList, Description: "The currencies the cloud supports."},
{ID: "site-export", Method: "POST", Endpoint: epSiteDataExport, Description: "Filename and URL for a site's CSV export, where the system supports one (needs siteId; optional startTime, endTime)."},
{ID: "dynamic-price-available", Method: "POST", Endpoint: epDynPriceCheck, Description: "Which sites have dynamic pricing at all."},
{ID: "dynamic-price-options", Method: "POST", Endpoint: epDynPriceOptions, Description: "Price providers for a product code and the login country (needs devicePn)."},
{ID: "dynamic-price", Method: "POST", Endpoint: epDynPriceDetail, Description: "The dynamic price curve smart charging would schedule against (needs area and company; optional date, sn)."},
{ID: "vehicle-brands", Method: "POST", Endpoint: epVehicleBrands, Description: "Vehicle brands - the first picker behind adding a car."},
{ID: "vehicle-models", Method: "POST", Endpoint: epVehicleModels, Description: "Models for a brand (needs brand)."},
{ID: "vehicle-years", Method: "POST", Endpoint: epVehicleYears, Description: "Production years for a model (needs brand and model)."},
{ID: "vehicle-specs", Method: "POST", Endpoint: epVehicleSpecs, Description: "What Anker knows about one exact car (needs brand, model and year)."},
{ID: "shared-with", Method: "POST", Endpoint: epSharedDevice, Description: "Who a charger is currently shared with (needs sn)."},
{ID: "ota-check", Method: "POST", Endpoint: epOtaBatchCheck, Description: "The latest firmware available per serial (needs sn, or sns)."},
{ID: "ota-info", Method: "POST", Endpoint: epOtaInfo, Description: "Current OTA status for one or more serials (needs sn, or sns)."},
{ID: "ota-update", Method: "POST", Endpoint: epOtaUpdate, Description: "Details of an available update (needs sn, or sns)."},
{ID: "upgrade-records", Method: "POST", Endpoint: epUpgradeRecords, Description: "Firmware update history (optional sn)."},
{ID: "upgrade-record", Method: "POST", Endpoint: epUpgradeRecord, Description: "One update record, in one of three views (needs sn; optional type 1-3)."},
{ID: "auto-upgrade", Method: "POST", Endpoint: epAutoUpgrade, Description: "Which devices update themselves."},
{ID: "messages-unread", Method: "GET", Endpoint: epMessageUnread, Description: "Whether any notification is waiting."},
{ID: "messages", Method: "GET", Endpoint: epMessages, Description: "The notifications themselves (optional lastTime cursor)."},
{ID: "quiet-hours", Method: "POST", Endpoint: epMessageNotDisturb, Description: "The account's quiet-hours settings, and the charging events they cover."},
{ID: "message-devices", Method: "POST", Endpoint: epMessageSNList, Description: "Which devices produce notifications at all."},
{ID: "tamper-records", Method: "POST", Endpoint: epTamperRecords, Description: "Tamper records for one device (needs sn; optional page, pageSize)."},
{ID: "mqtt-status", Method: "POST", Endpoint: epMqttInfo, Description: "Live state of one charger over Anker's cloud MQTT broker — the path to a charger the server cannot reach (needs sn)."},
{ID: "mqtt-command", Method: "POST", Endpoint: epMqttInfo, Description: "Control one charger over Anker's cloud MQTT broker: start, stop, boost, skip-delay, limit (with amps) or trigger (needs sn and command)."},
{ID: "mqtt-settings", Method: "POST", Endpoint: epMqttInfo, Description: "Write one charger's settings over Anker's cloud MQTT broker — current ceiling, switches, schedules, load balancing and solar charging (needs sn and settings)."},
@@ -294,6 +401,26 @@ type invokeParams struct {
StartDate string `json:"startDate"` // YYYY-MM-DD, or YYYY-MM / YYYY for month / year
EndDate string `json:"endDate"`
// The wider read surface. Session history addresses a session by id, the
// vehicle catalogue walks brand -> model -> year, dynamic pricing is asked
// per area and provider, and a few views take several serials at once. Each
// field is read only by the actions that name it.
SNs []string `json:"sns"` // several serials at once (binding details, OTA)
OrderID string `json:"orderId"` // one charging session
StartTime string `json:"startTime"` // upstream's own epoch/date field, passed through
EndTime string `json:"endTime"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
Type int `json:"type"` // upgrade-record view, 1-3
LastTime string `json:"lastTime"` // message cursor, format undocumented upstream
Brand string `json:"brand"`
Model string `json:"model"`
Year string `json:"year"`
DevicePN string `json:"devicePn"` // product code, for dynamic-price providers
Area string `json:"area"`
Company string `json:"company"`
Date string `json:"date"`
// The cloud MQTT actions: which command to send, the current ceiling "limit"
// carries, and the settings "mqtt-settings" writes, by the names the snapshot
// reports them under.
@@ -352,6 +479,7 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
var (
endpoint string
payload map[string]any
query map[string]string // set instead of payload for the two GET views
needSN bool
needSite bool
)
@@ -403,6 +531,147 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
}
endpoint = epVehicleDetail
payload = map[string]any{"vehicle_id": pp.VehicleID}
// --- the rest of the read surface ---------------------------------------
// Bodies are upstream's own field names, taken from the endpoint map; a
// field the caller left empty is still sent, because the cloud treats an
// empty string as "no filter" on every one of these.
case "site-by-sn":
endpoint, needSN = epSiteDetailBySN, true
payload = map[string]any{"device_sn": pp.SN}
case "site-detail":
endpoint, needSite = epSiteDetail, true
payload = map[string]any{"site_id": pp.SiteID}
case "site-homepage":
endpoint, payload = epSiteHomepage, map[string]any{}
case "user-devices":
endpoint, payload = epUserDevices, map[string]any{}
case "bind-details", "ota-check", "ota-info", "ota-update":
// The four views that ask about a list of serials rather than one. Both
// spellings are accepted: sns for several, sn for the usual one.
sns := serialList(pp)
if len(sns) == 0 {
return nil, fmt.Errorf("anker-solix: action %q requires an sn (or sns)", action)
}
switch action {
case "bind-details":
endpoint = epDeviceBindDetails
case "ota-check":
endpoint = epOtaBatchCheck
case "ota-info":
endpoint = epOtaInfo
default:
endpoint = epOtaUpdate
}
payload = map[string]any{"device_sn_list": sns}
case "group-devices":
endpoint, needSN = epGroupDevices, true
payload = map[string]any{"device_sn": pp.SN}
case "site-wifi":
endpoint, needSite = epSiteWifiList, true
payload = map[string]any{"site_id": pp.SiteID}
case "charger-wifi":
endpoint, needSN = epChargerWifiInfo, true
payload = map[string]any{"evChargerSn": pp.SN}
case "product-info":
endpoint = epDeviceProductInfo
payload = map[string]any{"evChargerSn": pp.SN}
case "install-info":
endpoint = epInstallInfo
payload = map[string]any{"evChargerSn": pp.SN, "siteId": pp.SiteID}
case "charging-orders":
endpoint, needSN = epChargingOrders, true
payload = map[string]any{"device_sn": pp.SN, "start_time": pp.StartTime}
case "charging-order":
if pp.OrderID == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an orderId", action)
}
endpoint, needSN = epChargingOrder, true
payload = map[string]any{"device_sn": pp.SN, "order_id": pp.OrderID}
case "order-seconds", "order-seconds-preview":
if pp.OrderID == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an orderId", action)
}
if action == "order-seconds" {
endpoint = epOrderSecDetail
payload = map[string]any{"order_id": pp.OrderID, "start_time": pp.StartTime}
} else {
endpoint = epOrderSecPreview
payload = map[string]any{"order_id": pp.OrderID}
}
case "energy-statistics":
endpoint = epEnergyStatistics
payload = map[string]any{"sourceType": "evCharger", "evChargerSn": pp.SN, "siteId": pp.SiteID}
case "device-income":
endpoint, needSN = epDeviceIncome, true
payload = map[string]any{"device_sn": pp.SN, "start_time": pp.StartTime}
case "site-price":
endpoint, needSite = epSitePrice, true
payload = map[string]any{"site_id": pp.SiteID}
case "currencies":
endpoint, payload = epCurrencyList, map[string]any{}
case "site-export":
endpoint, needSite = epSiteDataExport, true
payload = map[string]any{"site_id": pp.SiteID, "start_time": pp.StartTime, "end_time": pp.EndTime}
case "dynamic-price-available":
endpoint, payload = epDynPriceCheck, map[string]any{}
case "dynamic-price-options":
if pp.DevicePN == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a devicePn (the charger's product code)", action)
}
endpoint = epDynPriceOptions
payload = map[string]any{"device_pn": pp.DevicePN}
case "dynamic-price":
if pp.Area == "" || pp.Company == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an area and a company (from dynamic-price-options)", action)
}
endpoint = epDynPriceDetail
payload = map[string]any{"area": pp.Area, "company": pp.Company, "date": pp.Date, "device_sn": pp.SN}
case "vehicle-brands":
endpoint, payload = epVehicleBrands, map[string]any{}
case "vehicle-models":
if pp.Brand == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand", action)
}
endpoint = epVehicleModels
payload = map[string]any{"brand_name": pp.Brand}
case "vehicle-years":
if pp.Brand == "" || pp.Model == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand and a model", action)
}
endpoint = epVehicleYears
payload = map[string]any{"brand_name": pp.Brand, "model_name": pp.Model}
case "vehicle-specs":
if pp.Brand == "" || pp.Model == "" || pp.Year == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand, a model and a year", action)
}
endpoint = epVehicleSpecs
payload = map[string]any{"brand_name": pp.Brand, "model_name": pp.Model, "productive_year": pp.Year}
case "shared-with":
endpoint, needSN = epSharedDevice, true
payload = map[string]any{"device_sn": pp.SN}
case "upgrade-records":
endpoint = epUpgradeRecords
payload = map[string]any{"device_sn": pp.SN}
case "upgrade-record":
endpoint, needSN = epUpgradeRecord, true
payload = map[string]any{"device_sn": pp.SN, "type": upgradeRecordView(pp.Type)}
case "auto-upgrade":
endpoint, payload = epAutoUpgrade, map[string]any{}
case "messages-unread":
endpoint, query = epMessageUnread, map[string]string{}
case "messages":
endpoint, query = epMessages, map[string]string{}
if pp.LastTime != "" {
query["last_time"] = pp.LastTime
}
case "quiet-hours":
endpoint, payload = epMessageNotDisturb, map[string]any{}
case "message-devices":
endpoint, payload = epMessageSNList, map[string]any{}
case "tamper-records":
endpoint, needSN = epTamperRecords, true
payload = map[string]any{"device_sn": pp.SN, "page_num": pageNum(pp.Page), "page_size": pageSize(pp.PageSize)}
default:
return nil, fmt.Errorf("anker-solix: unknown action %q", action)
}
@@ -413,6 +682,14 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
return nil, fmt.Errorf("anker-solix: action %q requires a siteId", action)
}
// Two of these are GET views; everything else is a POST with a JSON body.
if query != nil {
body, err := p.apiGet(ctx, endpoint, query)
if err != nil {
return nil, err
}
return json.RawMessage(body), nil
}
body, err := p.apiRequest(ctx, endpoint, payload)
if err != nil {
return nil, err
@@ -420,6 +697,48 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
return json.RawMessage(body), nil
}
// serialList is the serials a multi-serial view is asked about: the several it
// was given, or the single one every other action takes, so a caller never has
// to know which spelling an endpoint wanted.
func serialList(pp invokeParams) []string {
out := make([]string, 0, len(pp.SNs)+1)
for _, sn := range pp.SNs {
if sn = strings.TrimSpace(sn); sn != "" {
out = append(out, sn)
}
}
if len(out) == 0 && pp.SN != "" {
out = append(out, pp.SN)
}
return out
}
// upgradeRecordView clamps check_upgrade_record's view selector, which upstream
// documents as 1-3 and nothing more; 1 is what the app asks for.
func upgradeRecordView(t int) int {
if t < 1 || t > 3 {
return 1
}
return t
}
// pageNum and pageSize give the paged views a first page and a readable page
// when the caller does not care, rather than sending a zero the cloud reads as
// "no page at all".
func pageNum(n int) int {
if n < 1 {
return 1
}
return n
}
func pageSize(n int) int {
if n < 1 || n > 100 {
return 20
}
return n
}
// energyRange normalizes the energy_analysis period, defaulting to a week like
// the reference implementation's EV-charger poll.
func energyRange(r string) string {
@@ -844,13 +1163,31 @@ func (p *Plugin) storeToken(body []byte) error {
// is rejected. It returns the raw response body; a non-zero API code or non-2xx
// status is returned as an error.
func (p *Plugin) apiRequest(ctx context.Context, endpoint string, payload map[string]any) ([]byte, error) {
return p.apiCall(ctx, endpoint, func(tok tokenInfo, gmt string) ([]byte, int, error) {
return p.doRequest(ctx, endpoint, payload, tok.authToken, tok.gtoken, gmt)
})
}
// apiGet is apiRequest for the two message views, the only endpoints in this
// connector Anker serves over GET: same headers, same credential, same one
// retry after a fresh login — a query string instead of a body.
func (p *Plugin) apiGet(ctx context.Context, endpoint string, query map[string]string) ([]byte, error) {
return p.apiCall(ctx, endpoint, func(tok tokenInfo, gmt string) ([]byte, int, error) {
return p.doGet(ctx, endpoint, query, tok.authToken, tok.gtoken, gmt)
})
}
// apiCall is what both of those share: a token, one attempt, and — when the
// cloud rejects the token — a fresh login and exactly one more. There is no
// refresh token, so a rejected token can only be answered with a new login.
func (p *Plugin) apiCall(ctx context.Context, endpoint string, send func(tokenInfo, string) ([]byte, int, error)) ([]byte, error) {
tok, err := p.ensureToken(ctx)
if err != nil {
return nil, err
}
gmt, _ := timezone()
body, status, err := p.doRequest(ctx, endpoint, payload, tok.authToken, tok.gtoken, gmt)
body, status, err := send(tok, gmt)
if err != nil {
return nil, err
}
@@ -869,7 +1206,7 @@ func (p *Plugin) apiRequest(ctx context.Context, endpoint string, payload map[st
if lerr != nil {
return nil, lerr
}
body, status, err = p.doRequest(ctx, endpoint, payload, newTok.authToken, newTok.gtoken, gmt)
body, status, err = send(newTok, gmt)
if err != nil {
return nil, err
}
@@ -896,16 +1233,7 @@ func (p *Plugin) doRequest(ctx context.Context, endpoint string, payload map[str
if err != nil {
return nil, 0, err
}
req.Header.Set("content-type", "application/json")
req.Header.Set("model-type", "DESKTOP")
req.Header.Set("app-name", "anker_power")
req.Header.Set("os-type", "android")
req.Header.Set("country", p.countryId)
req.Header.Set("timezone", gmt)
if authToken != "" {
req.Header.Set("x-auth-token", authToken)
req.Header.Set("gtoken", gtoken)
}
ankerHeaders(req, p.countryId, authToken, gtoken, gmt)
resp, err := p.client.Do(req)
if err != nil {
@@ -916,6 +1244,47 @@ func (p *Plugin) doRequest(ctx context.Context, endpoint string, payload map[str
return respBody, resp.StatusCode, nil
}
// doGet issues a single GET with the same headers a POST carries. Only the two
// message views are served this way.
func (p *Plugin) doGet(ctx context.Context, endpoint string, query map[string]string, authToken, gtoken, gmt string) ([]byte, int, error) {
url := p.apiBase + "/" + endpoint
if len(query) > 0 {
vals := neturl.Values{}
for k, v := range query {
vals.Set(k, v)
}
url += "?" + vals.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, 0, err
}
ankerHeaders(req, p.countryId, authToken, gtoken, gmt)
resp, err := p.client.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("anker-solix: request %s: %w", endpoint, err)
}
defer drain(resp)
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
return respBody, resp.StatusCode, nil
}
// ankerHeaders sets the identity every request carries. When authToken is empty
// the credential headers are omitted (the login request).
func ankerHeaders(req *http.Request, countryId, authToken, gtoken, gmt string) {
req.Header.Set("content-type", "application/json")
req.Header.Set("model-type", "DESKTOP")
req.Header.Set("app-name", "anker_power")
req.Header.Set("os-type", "android")
req.Header.Set("country", countryId)
req.Header.Set("timezone", gmt)
if authToken != "" {
req.Header.Set("x-auth-token", authToken)
req.Header.Set("gtoken", gtoken)
}
}
// ---- crypto & small helpers --------------------------------------------------
// encryptPassword AES-256-CBC encrypts the password under the ECDH shared secret
@@ -3,11 +3,18 @@ package ankersolix
// The account's other views of one charger.
//
// The merged inventory (chargers.go) answers "what chargers are there", and it
// asks the views that list them. Four more endpoints answer only when a serial
// is named: the station record the app opens on a charger, its cumulative
// charging totals, which OCPP backend it is pointed at, and the RFID cards
// authorised on it. None of them lists a charger, so none belongs in the merge —
// and none of them was reachable from the app at all until this capability.
// asks the views that list them. Everything else the cloud will say about one
// charger answers only when a serial is named the station record, the
// charging totals and the completed sessions, the OCPP backend, the RFID cards,
// the binding, the sharing, the firmware, the Wi-Fi, the tamper log — so none of
// them can be part of the merge, and none of them was reachable from the app at
// all until this capability.
//
// Every read the endpoint map lists for one charger is asked here, rather than a
// chosen few: which of them an account can answer is itself the finding, and a
// view nobody asks for is a field nobody can see. A charger that belongs to a
// site brings four more with it — the site is only known once the first pass has
// asked for it, so the site's own views are a second pass.
//
// What they answer with is not documented, by Anker or by the reference: the
// endpoints are known, their payloads are not. So each view is relayed as the
@@ -19,15 +26,24 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
)
// chargerDetailView is one endpoint's answer about one charger. A view that
// fails carries its reason instead of its fields: an account that is not the
// owner cannot read the cards, which is a fact about the account rather than an
// error in the read.
// error in the read. A view that answers with nothing carries neither, and says
// so by being empty — a standalone charger has no station record, and that is
// worth seeing too.
//
// Note is the one thing said in DriverVault's own words rather than the cloud's:
// a number the account elsewhere gives a meaning to, resolved. It never replaces
// a field, so the cloud's own keys stay exactly as they arrived.
type chargerDetailView struct {
ID string `json:"id"`
Attrs map[string]string `json:"attrs,omitempty"`
Note string `json:"note,omitempty"`
Error string `json:"error,omitempty"`
}
@@ -36,6 +52,20 @@ type chargerDetailsDoc struct {
Views []chargerDetailView `json:"views"`
}
// detailRequest is one view to ask for: the id it is reported under, the
// endpoint, and the body it takes.
type detailRequest struct {
id string
endpoint string
payload map[string]any
}
// detailFanout is how many of these are in flight at once. The cloud is a
// stranger's API being asked twenty questions about one charger; a handful at a
// time keeps the whole card under a couple of seconds without arriving as a
// burst that looks like something to rate-limit.
const detailFanout = 6
// chargerDetails asks every per-charger endpoint and returns what each answered.
// One failing view is reported in place; only losing all of them is an error,
// for the same reason the inventory works that way — a charger the cloud will
@@ -45,35 +75,162 @@ func (p *Plugin) chargerDetails(ctx context.Context, sn string) (json.RawMessage
return nil, err
}
views := []struct {
id string
endpoint string
payload map[string]any
}{
// Everything that needs only the serial. Ordered as the card reads them:
// what it is doing, what it has done, who may use it, what it is, and the
// housekeeping the account keeps about it.
views := []detailRequest{
{"station", epStationInfo, map[string]any{"evChargerSn": sn, "featuretype": 1}},
{"stationFeature", epStationInfo, map[string]any{"evChargerSn": sn, "featuretype": 2}},
{"totals", epChargeStats, map[string]any{
"device_sn": sn, "date_type": "all", "start_date": "", "end_date": ""}},
{"orders", epChargeStatsList, map[string]any{
"device_sn": sn, "order_status": 1, "date_type": "all",
"start_date": "", "end_date": "", "page": 0, "page_size": 10}},
{"sessions", epChargingOrders, map[string]any{"device_sn": sn, "start_time": ""}},
{"income", epDeviceIncome, map[string]any{"device_sn": sn, "start_time": ""}},
{"ocpp", epOcppInfo, map[string]any{"device_sn": sn}},
{"ocppEndpoints", epOcppEndpoints, map[string]any{}},
{"rfid", epRfidCards, map[string]any{"device_sn": sn}},
{"shared", epSharedDevice, map[string]any{"device_sn": sn}},
{"binding", epDeviceBindDetails, map[string]any{"device_sn_list": []string{sn}}},
{"group", epGroupDevices, map[string]any{"device_sn": sn}},
{"wifi", epChargerWifiInfo, map[string]any{"evChargerSn": sn}},
{"ota", epOtaInfo, map[string]any{"device_sn_list": []string{sn}}},
{"upgrades", epUpgradeRecords, map[string]any{"device_sn": sn}},
{"tamper", epTamperRecords, map[string]any{"device_sn": sn, "page_num": 1, "page_size": 20}},
{"siteBySn", epSiteDetailBySN, map[string]any{"device_sn": sn}},
}
doc := chargerDetailsDoc{SN: sn, Views: make([]chargerDetailView, 0, len(views))}
failed := 0
for _, v := range views {
out := chargerDetailView{ID: v.id}
body, err := p.apiRequest(ctx, v.endpoint, v.payload)
if err != nil {
out.Error, failed = shorten(err.Error()), failed+1
} else {
out.Attrs = map[string]string{}
flattenInto(out.Attrs, "", dataValue(body))
}
doc.Views = append(doc.Views, out)
out := p.askViews(ctx, views)
// The site's own views, once the first pass has found which site this is.
// A standalone charger has none, and asking anyway would be four errors
// about a site that does not exist.
if siteID := siteIDFrom(out); siteID != "" {
out = append(out, p.askViews(ctx, []detailRequest{
{"site", epSiteDetail, map[string]any{"site_id": siteID}},
{"sitePrice", epSitePrice, map[string]any{"site_id": siteID}},
{"siteWifi", epSiteWifiList, map[string]any{"site_id": siteID}},
{"energy", epEnergyAnalysis, map[string]any{
"site_id": siteID, "device_sn": sn, "device_type": "ev_charger",
"type": energyRange(""), "start_time": "", "end_time": ""}},
})...)
}
if failed == len(views) {
// Which OCPP backend "source 0" actually is, from the list the account
// publishes for exactly that purpose.
noteOcppSource(out)
failed := 0
for _, v := range out {
if v.Error != "" {
failed++
}
}
if failed == len(out) {
return nil, fmt.Errorf("anker-solix: charger %s: no per-charger view answered", sn)
}
return json.Marshal(doc)
return json.Marshal(chargerDetailsDoc{SN: sn, Views: out})
}
// askViews asks a batch of views at once and returns them in the order given —
// concurrency is for the waiting, not for the reading, and a card whose boxes
// reorder between refreshes is a card nobody can read against itself.
func (p *Plugin) askViews(ctx context.Context, reqs []detailRequest) []chargerDetailView {
out := make([]chargerDetailView, len(reqs))
sem := make(chan struct{}, detailFanout)
var wg sync.WaitGroup
for i, req := range reqs {
wg.Add(1)
go func(i int, req detailRequest) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
view := chargerDetailView{ID: req.id}
body, err := p.apiRequest(ctx, req.endpoint, req.payload)
if err != nil {
view.Error = shorten(err.Error())
} else {
attrs := map[string]string{}
flattenInto(attrs, "", dataValue(body))
if len(attrs) > 0 {
view.Attrs = attrs
}
}
out[i] = view
}(i, req)
}
wg.Wait()
return out
}
// siteIDFrom reads the site this charger belongs to out of the by-serial lookup,
// under whichever key that view used for it.
func siteIDFrom(views []chargerDetailView) string {
for _, v := range views {
if v.ID != "siteBySn" {
continue
}
for _, key := range []string{"site_id", "siteId", "station_id", "site_info.site_id"} {
if id := strings.TrimSpace(v.Attrs[key]); id != "" {
return id
}
}
}
return ""
}
// noteOcppSource names the OCPP backend the charger is pointed at. The per-
// charger view reports it as a bare number ("source 0"); the account's endpoint
// list is where those numbers have addresses, so the two are read together and
// the answer is said once, as the view's note. When the list does not carry the
// number, nothing is said — a guessed backend is worse than a plain number.
func noteOcppSource(views []chargerDetailView) {
var ocpp *chargerDetailView
var endpoints map[string]string
for i := range views {
switch views[i].ID {
case "ocpp":
ocpp = &views[i]
case "ocppEndpoints":
endpoints = views[i].Attrs
}
}
if ocpp == nil || len(ocpp.Attrs) == 0 || len(endpoints) == 0 {
return
}
source := strings.TrimSpace(ocpp.Attrs["source"])
if source == "" {
return
}
if url := endpointForSource(endpoints, source); url != "" {
ocpp.Note = "source " + source + " = " + url
}
}
// endpointForSource finds the address listed under a source number. The list
// arrives flattened — list[0].source, list[0].url and whatever else it carries —
// so the entry whose source matches is found first, and its address taken from
// that same entry.
func endpointForSource(endpoints map[string]string, source string) string {
prefix := ""
for key, val := range endpoints {
if !strings.HasSuffix(key, ".source") || strings.TrimSpace(val) != source {
continue
}
prefix = strings.TrimSuffix(key, ".source")
break
}
if prefix == "" {
return ""
}
for _, field := range []string{".url", ".endpoint", ".address", ".ocpp_url", ".server_url", ".name"} {
if v := strings.TrimSpace(endpoints[prefix+field]); v != "" {
return v
}
}
return ""
}
// dataValue returns a response's "data", whatever shape it came in: these views
@@ -0,0 +1,97 @@
package ankersolix
import "testing"
// The site views are only worth asking for once the by-serial lookup has found a
// site, and that lookup names it differently depending on which shape answered.
func TestSiteIDFromReadsWhicheverKeyTheLookupUsed(t *testing.T) {
cases := []struct {
name string
attrs map[string]string
want string
}{
{"snake case", map[string]string{"site_id": "s-1"}, "s-1"},
{"camel case", map[string]string{"siteId": "s-2"}, "s-2"},
{"nested", map[string]string{"site_info.site_id": "s-3"}, "s-3"},
{"standalone charger", map[string]string{"device_sn": "AT1"}, ""},
{"blank is not an answer", map[string]string{"site_id": " "}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
views := []chargerDetailView{{ID: "ocpp", Attrs: map[string]string{"site_id": "wrong"}}, {ID: "siteBySn", Attrs: tc.attrs}}
if got := siteIDFrom(views); got != tc.want {
t.Fatalf("siteIDFrom = %q, want %q", got, tc.want)
}
})
}
}
// "source 0" is a number until the account's endpoint list gives it an address.
func TestNoteOcppSourceNamesTheBackend(t *testing.T) {
views := []chargerDetailView{
{ID: "ocpp", Attrs: map[string]string{"source": "1"}},
{ID: "ocppEndpoints", Attrs: map[string]string{
"list[0].source": "0", "list[0].url": "wss://ocpp.anker.example/0",
"list[1].source": "1", "list[1].url": "wss://ocpp.anker.example/1",
}},
}
noteOcppSource(views)
if want := "source 1 = wss://ocpp.anker.example/1"; views[0].Note != want {
t.Fatalf("note = %q, want %q", views[0].Note, want)
}
}
// A number the list does not carry stays a number: a guessed backend would be
// worse than saying nothing.
func TestNoteOcppSourceSaysNothingWhenTheListCannotAnswer(t *testing.T) {
views := []chargerDetailView{
{ID: "ocpp", Attrs: map[string]string{"source": "7"}},
{ID: "ocppEndpoints", Attrs: map[string]string{"list[0].source": "0", "list[0].url": "wss://x/0"}},
}
noteOcppSource(views)
if views[0].Note != "" {
t.Fatalf("note = %q, want none", views[0].Note)
}
}
// The entry's own address, not a neighbour's.
func TestEndpointForSourceStaysWithinItsEntry(t *testing.T) {
endpoints := map[string]string{
"list[0].source": "0", "list[0].endpoint": "wss://a",
"list[1].source": "2", "list[1].endpoint": "wss://b",
}
if got := endpointForSource(endpoints, "2"); got != "wss://b" {
t.Fatalf("endpointForSource = %q, want wss://b", got)
}
if got := endpointForSource(endpoints, "3"); got != "" {
t.Fatalf("endpointForSource = %q, want empty", got)
}
}
// The multi-serial views accept either spelling, and reject neither silently.
func TestSerialList(t *testing.T) {
if got := serialList(invokeParams{SN: "AT1"}); len(got) != 1 || got[0] != "AT1" {
t.Fatalf("single serial = %v", got)
}
got := serialList(invokeParams{SN: "AT1", SNs: []string{"AT2", " ", "AT3"}})
if len(got) != 2 || got[0] != "AT2" || got[1] != "AT3" {
t.Fatalf("several serials = %v", got)
}
if got := serialList(invokeParams{}); len(got) != 0 {
t.Fatalf("nothing given = %v", got)
}
}
// The paged and multi-view endpoints get a sane ask when the caller does not
// care, rather than a zero the cloud reads as "no page at all".
func TestPagingAndViewDefaults(t *testing.T) {
if pageNum(0) != 1 || pageNum(3) != 3 {
t.Fatalf("pageNum: %d %d", pageNum(0), pageNum(3))
}
if pageSize(0) != 20 || pageSize(500) != 20 || pageSize(50) != 50 {
t.Fatalf("pageSize: %d %d %d", pageSize(0), pageSize(500), pageSize(50))
}
if upgradeRecordView(0) != 1 || upgradeRecordView(4) != 1 || upgradeRecordView(2) != 2 {
t.Fatalf("upgradeRecordView: %d %d %d", upgradeRecordView(0), upgradeRecordView(4), upgradeRecordView(2))
}
}