diff --git a/.changeset/bundle-zaptec-control.md b/.changeset/bundle-zaptec-control.md new file mode 100644 index 000000000..5bd828790 --- /dev/null +++ b/.changeset/bundle-zaptec-control.md @@ -0,0 +1,15 @@ +--- +"ftw": minor +--- + +FTW now controls a Zaptec Go, Go 2 or Pro through Zaptec Cloud. The bundled +`zaptec_cloud` driver used to be read-only, so a Zaptec charger on a +loadpoint charged at whatever the Zaptec app set, and the car could overload +a phase next to the battery. FTW now sets the charging current within the +fuse budget, pauses and resumes. When FTW stands down, for example on a +restart or a stale meter, it sets the charger to 0 A and pauses it until the +next order, and tells Core when the charger refused; the setting is stored +on the charger, so if you stop using FTW, +set the current again in the Zaptec app. Experimental: not yet confirmed on a +real charger. Tesla Wall Connector, TeslaMate, Home Assistant cars and Tesla +Cloud now say why FTW can only read them. diff --git a/docs/ocpp.md b/docs/ocpp.md index 9955b75b5..a791e082a 100644 --- a/docs/ocpp.md +++ b/docs/ocpp.md @@ -453,8 +453,10 @@ car; without it, profiles and `vehicle_capacity_wh` remain the whole story. handshake instead, so the port stays open on every interface even when only one is served. - Chargers that also have a native protocol may work better through a driver. - Easee over Modbus and Zaptec over its cloud API already have drivers; OCPP is - the option when you want the cloud out of the loop. + Easee and Zaptec have cloud drivers (`easee_cloud`, `zaptec_cloud`) that set + the current, pause and resume; Zaptec's control is experimental until a + real charger confirms it. OCPP is the option when you want the cloud out of + the loop. FTW has no local driver for either. ## When you still need a driver diff --git a/drivers/BUNDLED_SOURCE.json b/drivers/BUNDLED_SOURCE.json index f69bb7349..f17a382a1 100644 --- a/drivers/BUNDLED_SOURCE.json +++ b/drivers/BUNDLED_SOURCE.json @@ -16,7 +16,7 @@ "from the signed channel. Run scripts/sync-bundled-drivers.sh to update." ], "repository": "srcfl/device-drivers", - "commit": "940a9136e4e08410f9f2a759438f13559f80f09b", + "commit": "504b0ddf7831e4b6e97ff8438c92970e4ac39c1d", "source_dir": "drivers/lua", "drivers": [ "ambibox_v2x", "ctek", "ctek_hybrid", "ctek_v2", "deye", "easee_cloud", diff --git a/go/internal/drivers/testdata/zaptec_cloud.lua b/go/internal/drivers/testdata/zaptec_cloud.lua deleted file mode 100644 index cfd1d09d5..000000000 --- a/go/internal/drivers/testdata/zaptec_cloud.lua +++ /dev/null @@ -1,421 +0,0 @@ --- Zaptec Cloud EV charger driver (Go / Go 2 / Pro). --- --- Protocol: HTTPS against the Zaptec Cloud REST API (api.zaptec.com). --- Canonical copy belongs in srcfl/device-drivers as zaptec_cloud.lua; --- this testdata file is the in-tree source until that pin lands. Operators --- can drop the same file in the user-drivers directory in the meantime. --- --- Auth: POST /oauth/token (OAuth2 password grant, form-encoded) --- Telemetry: GET /api/chargers/{id}/state --- Control: POST /api/chargers/{id}/update (current / phases) --- POST /api/chargers/{id}/sendCommand/506 (pause) --- POST /api/chargers/{id}/sendCommand/507 (resume; 528 = already running) --- --- Sign convention: positive W is charging (power into the vehicle / site load). --- Minimum offered current is 6 A (IEC 61851); below that we pause. --- --- Config: --- email / username Zaptec account email --- password Zaptec account password (secret) --- serial optional charger Id (UUID) or SerialNo --- phases 1 or 3 (default 3) --- min_a minimum current, default 6 --- max_a maximum current, default 32 --- base_url optional origin override (tests / staging) --- --- verification_status is experimental until a live charger has been --- exercised end-to-end. - -DRIVER = { - host_api_min = 1, - host_api_max = 1, - id = "zaptec-cloud", - name = "Zaptec Cloud", - manufacturer = "Zaptec", - version = "0.1.0", - protocols = { "http" }, - capabilities = { "ev" }, - description = "Zaptec Go / Go 2 / Pro via Zaptec Cloud. Email + password; optional charger serial.", - homepage = "https://zaptec.com", - http_hosts = { "api.zaptec.com" }, - authors = { "FTW contributors" }, - tested_models = { "Go", "Go 2", "Pro" }, - verification_status = "experimental", - config_secrets = { "password" }, -} - -PROTOCOL = "http" - -local BASE_URL = "https://api.zaptec.com" - --- Observation IDs from the Zaptec Cloud charger state document. -local OBS_VOLTAGE_L1 = 501 -local OBS_CURRENT_L1 = 507 -local OBS_MAX_CURRENT = 510 -local OBS_ACTIVE_PHASES = 512 -local OBS_CHARGE_POWER = 513 -local OBS_SESSION_ENERGY = 553 -local OBS_OP_MODE = 710 - --- Operating modes (observation 710). -local OP_DISCONNECTED = 1 -local OP_CONNECTED = 2 -local OP_CHARGING = 3 -local OP_FINISHED = 5 - --- sendCommand codes. -local CMD_STOP = 506 -local CMD_RESUME = 507 - -local email = nil -local password = nil -local serial_want = nil -local charger_id = nil -local phases = 3 -local min_a = 6 -local max_a = 32 -local access_token = nil -local refresh_token = nil -local token_expiry = 0 -local paused_state = false - -local function pick(t, ...) - if type(t) ~= "table" then return nil end - for i = 1, select("#", ...) do - local v = t[select(i, ...)] - if v ~= nil then return v end - end - return nil -end - -local function as_number(v) - if type(v) == "number" then return v end - if v == nil then return nil end - return tonumber(v) -end - --- Keep HTTP error strings to a status prefix so a 4xx body that echoes --- credentials or a bearer token never lands in the driver log. -local function redact_http_err(err) - if err == nil then return "request failed" end - local s = tostring(err) - return s:match("^(HTTP %d+)") or "request failed" -end - -local function url_encode(s) - s = tostring(s or "") - return (s:gsub("[^%w%-%.%_%~]", function(c) - return string.format("%%%02X", string.byte(c)) - end)) -end - -local function auth_headers() - return { Authorization = "Bearer " .. (access_token or "") } -end - -local function decode_json(raw) - if raw == nil or raw == "" then return nil, "empty body" end - local data, err = host.json_decode(raw) - if data == nil then return nil, tostring(err or "decode failed") end - return data, nil -end - -local function login() - local body = "grant_type=password" - .. "&username=" .. url_encode(email) - .. "&password=" .. url_encode(password) - local resp, err = host.http_post( - BASE_URL .. "/oauth/token", - body, - { ["Content-Type"] = "application/x-www-form-urlencoded" }) - if err then - return false, err - end - local data, derr = decode_json(resp) - if derr or not data then - return false, derr or "invalid JSON" - end - local token = pick(data, "access_token", "accessToken") - if not token or token == "" then - return false, "no access_token" - end - access_token = token - refresh_token = pick(data, "refresh_token", "refreshToken") or refresh_token - local expires_in = as_number(pick(data, "expires_in", "expiresIn")) or 3600 - token_expiry = host.millis() + (expires_in * 1000) - 60000 - host.log("info", "Zaptec: logged in") - return true -end - -local function refresh() - if not refresh_token or refresh_token == "" then return false end - local body = "grant_type=refresh_token" - .. "&refresh_token=" .. url_encode(refresh_token) - local resp, err = host.http_post( - BASE_URL .. "/oauth/token", - body, - { ["Content-Type"] = "application/x-www-form-urlencoded" }) - if err then - host.log("warn", "Zaptec token refresh failed: " .. redact_http_err(err)) - return false - end - local data, derr = decode_json(resp) - if derr or not data then return false end - local token = pick(data, "access_token", "accessToken") - if not token or token == "" then return false end - access_token = token - local rotated = pick(data, "refresh_token", "refreshToken") - if rotated and rotated ~= "" then refresh_token = rotated end - local expires_in = as_number(pick(data, "expires_in", "expiresIn")) or 3600 - token_expiry = host.millis() + (expires_in * 1000) - 60000 - return true -end - -local function ensure_auth() - if access_token and host.millis() < token_expiry then return true end - if refresh() then return true end - local ok = login() - return ok -end - -local function charger_rows(data) - if type(data) ~= "table" then return nil end - local rows = pick(data, "Data", "data") - if type(rows) == "table" then return rows end - if data[1] ~= nil then return data end - return nil -end - -local function charger_matches(ch, want) - if not want or want == "" then return true end - local id = tostring(pick(ch, "Id", "id") or "") - local serial = tostring(pick(ch, "SerialNo", "serialNo", "Serial") or "") - local device = tostring(pick(ch, "DeviceId", "deviceId") or "") - return id == want or serial == want or device == want -end - -local function resolve_charger() - local resp, err = host.http_get(BASE_URL .. "/api/chargers", auth_headers()) - if err then return nil, err end - local data, derr = decode_json(resp) - if derr then return nil, derr end - local rows = charger_rows(data) - if not rows or #rows == 0 then - return nil, "no chargers on account" - end - if serial_want and serial_want ~= "" then - for i = 1, #rows do - if charger_matches(rows[i], serial_want) then - return tostring(pick(rows[i], "Id", "id")), nil - end - end - return nil, "charger not found" - end - return tostring(pick(rows[1], "Id", "id")), nil -end - -local function observation_map(raw) - local data, err = decode_json(raw) - if err then return nil, err end - local rows = data - if type(data) == "table" and data[1] == nil then - rows = pick(data, "Data", "data") or data - end - local obs = {} - if type(rows) ~= "table" then return obs, nil end - for i = 1, #rows do - local item = rows[i] - local id = as_number(pick(item, "StateId", "stateId", "ObservationId", "observationId")) - if id then - obs[id] = pick(item, "ValueAsString", "valueAsString", "Value", "value") - end - end - return obs, nil -end - -local function send_command(code) - local url = BASE_URL .. "/api/chargers/" .. charger_id .. "/sendCommand/" .. tostring(code) - local _, err = host.http_post(url, "{}", auth_headers()) - if err then - -- 528: not paused, cannot resume — treat as success so a resume - -- issued while already running does not fail the command. - if code == CMD_RESUME and tostring(err):match("528") then - return true - end - host.log("warn", "Zaptec sendCommand " .. tostring(code) .. " failed: " .. redact_http_err(err)) - return false - end - return true -end - -local function update_charger(fields) - local body = host.json_encode(fields) - local _, err = host.http_post( - BASE_URL .. "/api/chargers/" .. charger_id .. "/update", - body, - auth_headers()) - if err then - host.log("warn", "Zaptec update failed: " .. redact_http_err(err)) - return false - end - return true -end - -local function watts_to_amps(power_w) - local p = phases - if p < 1 then p = 1 end - local amps = math.floor((tonumber(power_w) or 0) / (230 * p) + 0.5) - if amps < 0 then amps = 0 end - if amps > max_a then amps = max_a end - return amps -end - -function driver_init(config) - host.set_make("Zaptec") - config = config or {} - email = config.email or config.username - password = config.password - serial_want = config.serial - if serial_want == "" then serial_want = nil end - if email == "" then email = nil end - if password == "" then password = nil end - if config.base_url and tostring(config.base_url) ~= "" then - BASE_URL = tostring(config.base_url):gsub("/$", "") - end - local p = as_number(config.phases) - if p == 1 or p == 3 then phases = p end - local mn = as_number(config.min_a) - if mn and mn > 0 then min_a = mn end - local mx = as_number(config.max_a) - if mx and mx > 0 then max_a = mx end - - if not email or not password then - error("Zaptec: email/username and password required") - end - local ok, lerr = login() - if not ok then - error("Zaptec: initial login failed: " .. redact_http_err(lerr)) - end - local id, rerr = resolve_charger() - if not id then - error("Zaptec: could not list chargers: " .. redact_http_err(rerr)) - end - charger_id = id - host.set_sn(charger_id) - host.log("info", "Zaptec: driver initialized for " .. charger_id) -end - -function driver_poll() - if not charger_id or not email then - return 10000 - end - if not ensure_auth() then - host.log("warn", "Zaptec: auth failed, skipping poll") - return 10000 - end - local resp, err = host.http_get( - BASE_URL .. "/api/chargers/" .. charger_id .. "/state", - auth_headers()) - if err then - host.log("warn", "Zaptec: state poll failed: " .. redact_http_err(err)) - return 10000 - end - local obs, oerr = observation_map(resp) - if oerr or not obs then - host.log("warn", "Zaptec: state decode failed") - return 10000 - end - - local op_mode = as_number(obs[OBS_OP_MODE]) or OP_DISCONNECTED - local power_w = as_number(obs[OBS_CHARGE_POWER]) or 0 - if power_w < 0 then power_w = 0 end - local session_kwh = as_number(obs[OBS_SESSION_ENERGY]) or 0 - local session_wh = session_kwh * 1000 - local connected = (op_mode == OP_CONNECTED or op_mode == OP_CHARGING or op_mode == OP_FINISHED) - local charging = (op_mode == OP_CHARGING) - local max_current = as_number(obs[OBS_MAX_CURRENT]) - local active_phases = as_number(obs[OBS_ACTIVE_PHASES]) or phases - - host.emit("ev", { - w = power_w, - connected = connected, - charging = charging, - session_wh = session_wh, - max_a = max_current, - phases = active_phases, - op_mode = op_mode, - }) - - local i1 = as_number(obs[OBS_CURRENT_L1]) - if i1 then host.emit_metric("ev_l1_a", i1) end - local v1 = as_number(obs[OBS_VOLTAGE_L1]) - if v1 then host.emit_metric("ev_l1_v", v1) end - host.emit_metric("ev_power_w", power_w) - - return 5000 -end - -function driver_command(action, power_w, cmd) - if action == "init" or action == "deinit" then - return true - end - if not charger_id then - host.log("warn", "Zaptec: command before charger resolved") - return false - end - if not ensure_auth() then return false end - - if action == "ev_pause" then - local ok = send_command(CMD_STOP) - if ok then paused_state = true end - return ok - end - - if action == "ev_start" or action == "ev_resume" then - local ok = send_command(CMD_RESUME) - if ok then paused_state = false end - return ok - end - - if action == "ev_set_current" then - local amps = watts_to_amps(power_w) - if cmd and type(cmd) == "table" then - local req_phases = as_number(cmd.phases) - if req_phases == 1 or req_phases == 3 then - phases = req_phases - if not update_charger({ maxChargePhases = phases }) then - return false - end - end - end - if amps > 0 and amps < min_a then - amps = 0 - end - if amps <= 0 then - local ok = send_command(CMD_STOP) - if ok then paused_state = true end - return ok - end - if not update_charger({ maxChargeCurrent = amps }) then - return false - end - if paused_state then - if send_command(CMD_RESUME) then - paused_state = false - end - end - return true - end - - host.log("warn", "Zaptec: unknown action " .. tostring(action)) - return false -end - -function driver_default_mode() - -- Cloud charger keeps its last setpoint when FTW goes away. -end - -function driver_cleanup() - access_token = nil - refresh_token = nil -end diff --git a/go/internal/drivers/zaptec_cloud_bundled_test.go b/go/internal/drivers/zaptec_cloud_bundled_test.go new file mode 100644 index 000000000..2a8d88fa9 --- /dev/null +++ b/go/internal/drivers/zaptec_cloud_bundled_test.go @@ -0,0 +1,132 @@ +package drivers + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// bundledZaptecCloudPath resolves the bundled drivers/zaptec_cloud.lua, the +// file a release ships, from the repo root. +func bundledZaptecCloudPath(t *testing.T) string { + t.Helper() + _, thisFile, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + return filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "drivers", "zaptec_cloud.lua") +} + +// TestZaptecCloudControlsThroughFTWHost runs the bundled Zaptec Cloud driver in +// Core's Lua host against a fake Zaptec API. It pins the exact writes: the +// current goes to maxChargeCurrent, a pause is 0 A plus command 506, a resume +// offers 6 A and sends 507, and the stand-down after FTW wrote is 0 A plus 506 +// once. Every request names FTW in its User-Agent. +func TestZaptecCloudControlsThroughFTWHost(t *testing.T) { + path := bundledZaptecCloudPath(t) + var mu sync.Mutex + var posts []string + state := `[{"StateId":710,"ValueAsString":"3"},{"StateId":718,"ValueAsString":"0"},{"StateId":712,"ValueAsString":"0"}, +{"StateId":507,"ValueAsString":"15.9"},{"StateId":508,"ValueAsString":"16.1"},{"StateId":509,"ValueAsString":"15.8"}, +{"StateId":510,"ValueAsString":"16"},{"StateId":513,"ValueAsString":"11000"},{"StateId":553,"ValueAsString":"2.5"}, +{"StateId":100,"ValueAsString":"{\"ProductVariant\":\"Go2\"}"}]` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + if !strings.HasPrefix(r.Header.Get("User-Agent"), "FTW-zaptec_cloud/") { + t.Errorf("%s %s without FTW User-Agent: %q", r.Method, r.URL.Path, r.Header.Get("User-Agent")) + } + switch { + case r.URL.Path == "/oauth/token": + _, _ = w.Write([]byte(`{"access_token":"tok","refresh_token":"ref","expires_in":3600}`)) + case r.URL.Path == "/api/chargers" && r.Method == http.MethodGet: + _, _ = w.Write([]byte(`{"Data":[{"Id":"c-1","SerialNo":"ZAP1"}]}`)) + case r.URL.Path == "/api/chargers/c-1/state": + _, _ = w.Write([]byte(state)) + case r.Method == http.MethodPost: + if r.Header.Get("Authorization") != "Bearer tok" { + t.Errorf("POST %s without bearer token", r.URL.Path) + } + mu.Lock() + posts = append(posts, r.URL.Path+" "+string(body)) + mu.Unlock() + w.WriteHeader(http.StatusOK) + default: + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + tel := telemetry.NewStore() + d, err := NewLuaDriver(path, NewHostEnv("zaptec", tel).WithHTTP()) + if err != nil { + t.Fatalf("load: %v", err) + } + defer d.Cleanup() + if err := d.Init(context.Background(), map[string]any{"email": "o@example.invalid", "password": "pw", "base_url": srv.URL}); err != nil { + t.Fatalf("init: %v", err) + } + if _, err := d.Poll(context.Background()); err != nil { + t.Fatalf("poll: %v", err) + } + r := tel.Get("zaptec", telemetry.DerEV) + if r == nil { + t.Fatal("no ev reading") + } + raw, _ := json.Marshal(r) + t.Logf("ev reading: %s", raw) + if r.RawW != 11000 { + t.Errorf("EV W=%v, want 11000 (charging, positive)", r.RawW) + } + cmd := func(m map[string]any) error { + b, _ := json.Marshal(m) + return d.Command(context.Background(), b) + } + if err := cmd(map[string]any{"action": "ev_set_current", "power_w": 11040, "phase_mode": "3p", "voltage": 230, "max_amps_per_phase": 13.5}); err != nil { + t.Fatalf("set current: %v", err) + } + if err := cmd(map[string]any{"action": "ev_pause"}); err != nil { + t.Fatalf("pause: %v", err) + } + if err := cmd(map[string]any{"action": "ev_resume"}); err != nil { + t.Fatalf("resume: %v", err) + } + if err := d.DefaultMode(); err != nil { + t.Fatalf("default mode: %v", err) + } + if err := d.DefaultMode(); err != nil { + t.Fatalf("second default mode: %v", err) + } + mu.Lock() + defer mu.Unlock() + for _, p := range posts { + t.Logf("POST %s", p) + } + want := []string{ + `/api/chargers/c-1/update {"maxChargeCurrent":13.5}`, + `/api/chargers/c-1/update {"maxChargeCurrent":0}`, + `/api/chargers/c-1/sendCommand/506 `, + `/api/chargers/c-1/update {"maxChargeCurrent":6}`, + `/api/chargers/c-1/sendCommand/507 `, + `/api/chargers/c-1/update {"maxChargeCurrent":0}`, + `/api/chargers/c-1/sendCommand/506 `, + } + got := posts + if len(got) != len(want) { + t.Fatalf("posts = %d, want %d", len(got), len(want)) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("post %d = %q, want %q", i, got[i], want[i]) + } + } +} diff --git a/go/internal/drivers/zaptec_cloud_test.go b/go/internal/drivers/zaptec_cloud_test.go index 325c90dc3..fc7b6cf94 100644 --- a/go/internal/drivers/zaptec_cloud_test.go +++ b/go/internal/drivers/zaptec_cloud_test.go @@ -21,7 +21,7 @@ func zaptecCloudDriverPath(t *testing.T) string { if !ok { t.Fatal("runtime.Caller failed") } - return filepath.Join(filepath.Dir(thisFile), "testdata", "zaptec_cloud.lua") + return filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "drivers", "zaptec_cloud.lua") } func zaptecStateJSON(opMode int, powerW, sessionKWh float64) []byte { diff --git a/go/internal/evcloud/zaptec.go b/go/internal/evcloud/zaptec.go index c7c8caac5..e37276f6b 100644 --- a/go/internal/evcloud/zaptec.go +++ b/go/internal/evcloud/zaptec.go @@ -70,7 +70,7 @@ func (z *Zaptec) Describe() Descriptor { NeedsAuth: true, UsernameLabel: "Email", // Installed from the device-drivers pin as drivers/zaptec_cloud.lua. - // Tests load the in-tree copy at go/internal/drivers/testdata/. + // Tests in go/internal/drivers load that bundled file. LuaDriver: "drivers/zaptec_cloud.lua", } }