From b6f0dd959cdc75f37b129a0a8ac081f1affe949b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:39:54 +0100 Subject: [PATCH 1/8] fix(sonnen): report battery power with the site sign (2.0.4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sonnen's JSON API v2 reports Pac_total_W positive while discharging. The driver passed it through, so FTW showed charge as discharge. Negate it so battery.w is positive while charging. Measured on a sonnenBatterie with software 1.40.5 on 2026-11-13: in manual mode, a 500 W charge setpoint read back over six reads as Pac_total_W -495 to -504 W, SetPoint_W -500 and BatteryCharging true. The driver stays read-only. battery_pac_w keeps the vendor sign. Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++++ SUPPORT_STATUS.md | 4 +- devices.yaml | 2 +- drivers/lua/sonnen.lua | 13 +++-- .../tests/lua_harness/test_sonnen_sign.lua | 58 +++++++++++++++++++ drivers/tests/test_sonnen_sign.py | 27 +++++++++ index.yaml | 6 +- manifests/sonnen.yaml | 6 +- support-status.json | 2 +- 9 files changed, 113 insertions(+), 16 deletions(-) create mode 100644 drivers/tests/lua_harness/test_sonnen_sign.lua create mode 100644 drivers/tests/test_sonnen_sign.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f4d1e9..fbf51db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,17 @@ driver no longer knows FTW wrote, so that offset stays; today only the operator's control on the heating card writes it. Not yet checked on hardware. +### sonnen 2.0.4 + +Battery power has the site sign. sonnen reports `Pac_total_W` positive while +discharging and negative while charging; the driver passed it through, so +FTW showed every charge as a discharge and the reverse. It now negates the +value: charging is positive. On a sonnenBatterie with software 1.40.5 on +2026-11-13, in manual mode, a 500 W charge setpoint read back over six reads +as `Pac_total_W` -495 to -504 W, `SetPoint_W` -500 and `BatteryCharging` +true. `battery_pac_w` keeps the vendor's own sign. The driver stays +read-only. + ### easee_cloud 1.4.1 The driver says its session energy is coarse, with `session_wh_coarse`. Easee diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 5c50b7c..a5acd79 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -158,8 +158,8 @@ Catalog source is not proof that a target can install or run a driver. | solis | 2.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | solis_string | 1.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | | solis_string | 1.1.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| sonnen | 2.0.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| sonnen | 2.0.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| sonnen | 2.0.4 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| sonnen | 2.0.4 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | sungrow | 1.6.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | sungrow | 1.6.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | tesla_cloud | 0.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index f758c58..4c31d02 100644 --- a/devices.yaml +++ b/devices.yaml @@ -2175,7 +2175,7 @@ manufacturers: protocols: - protocol: http driver: "sonnen" - version: "2.0.3" + version: "2.0.4" ders: [battery, meter] control: false firmware_versions: "" diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index 003cec3..4a3f593 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -19,10 +19,11 @@ -- -- Sign convention (site: positive W flows INTO the site): -- battery.w: positive = charging (sink), negative = discharging (source). --- Sonnen Pac_total_W is reported positive=charging, so it passes through --- unchanged. This is from community-contributed sample code; verify --- on first install by checking that battery.w is positive while the --- site is exporting and the Sonnen is taking the surplus. +-- sonnen reports Pac_total_W positive while DISCHARGING and negative while +-- charging, so the driver negates it. Measured on a sonnenBatterie with +-- software 1.40.5 on 2026-11-13: in manual mode, a 500 W charge setpoint +-- read back over six reads as Pac_total_W -495 to -504 W, SetPoint_W -500 +-- and BatteryCharging true. DRIVER = { host_api_min = 1, @@ -30,7 +31,7 @@ DRIVER = { id = "sonnen", name = "sonnenBatterie (local API)", manufacturer = "sonnen", - version = "2.0.3", + version = "2.0.4", protocols = { "http" }, capabilities = { "battery" }, read_only = true, @@ -182,7 +183,7 @@ function driver_poll() local soc_pct = usoc or rsoc or 0 local battery = { - w = pac_w, + w = -pac_w, -- sonnen: + = discharge; site: + = charge soc = soc_pct / 100.0, } if cap_wh then diff --git a/drivers/tests/lua_harness/test_sonnen_sign.lua b/drivers/tests/lua_harness/test_sonnen_sign.lua new file mode 100644 index 0000000..2091ba8 --- /dev/null +++ b/drivers/tests/lua_harness/test_sonnen_sign.lua @@ -0,0 +1,58 @@ +-- sonnen: battery.w sign. sonnen reports Pac_total_W positive while +-- discharging and negative while charging; FTW's battery.w is positive while +-- charging. Bodies follow /api/v2/latestdata from a sonnenBatterie running +-- software 1.40.5. + +dofile("drivers/tests/lua_harness/host_mock.lua") + +local URL = "http://192.0.2.10:80/api/v2/latestdata" + +local function latest(pac_w, setpoint_w) + return '{"Consumption_W":2259,"FullChargeCapacity":18700,' .. + '"GridFeedIn_W":-2240,"Pac_total_W":' .. tostring(pac_w) .. + ',"Production_W":16,"RSOC":45,"SetPoint_W":' .. tostring(setpoint_w) .. + ',"Timestamp":"2026-11-13 20:03:26","USOC":40,"UTC_Offset":1}' +end + +local function poll_battery_w(body) + host.reset() + dofile("drivers/lua/sonnen.lua") + driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) + host._http_responses[URL] = body + local ok, err = pcall(driver_poll) + if not ok then error("driver_poll failed: " .. tostring(err)) end + local list = host._emitted.battery + if not list or #list == 0 then error("no battery emit") end + return list[#list] +end + +-- Charging: shaped like the readback of a 500 W charge setpoint +-- (measured -495 to -504 W; -500 here). +local charging = poll_battery_w(latest(-500, -500)) +if charging.w ~= 500 then + error("charging must be +500 W in site convention, got " .. tostring(charging.w)) +end +if math.abs(charging.soc - 0.40) > 1e-9 then + error("soc must come from USOC as a fraction, got " .. tostring(charging.soc)) +end +if charging.capacity_wh ~= 18700 then + error("capacity_wh lost: " .. tostring(charging.capacity_wh)) +end + +-- Discharging. +local discharging = poll_battery_w(latest(1200, 0)) +if discharging.w ~= -1200 then + error("discharging must be -1200 W in site convention, got " .. tostring(discharging.w)) +end + +-- The raw vendor value stays available, unconverted, as a metric. +if not host._metrics.battery_pac_w or host._metrics.battery_pac_w.value ~= 1200 then + error("battery_pac_w must keep the vendor sign") +end + +-- Still read-only. +if DRIVER.read_only ~= true or driver_command("battery", 1000, {}) ~= false then + error("sonnen must stay read-only") +end + +print("OK") diff --git a/drivers/tests/test_sonnen_sign.py b/drivers/tests/test_sonnen_sign.py new file mode 100644 index 0000000..c8e4b40 --- /dev/null +++ b/drivers/tests/test_sonnen_sign.py @@ -0,0 +1,27 @@ +"""sonnen: battery.w follows the site convention. + +sonnen reports Pac_total_W positive while discharging; FTW's battery.w is +positive while charging. The harness script polls the driver against +/api/v2/latestdata bodies in the shape a live unit returns. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +LUA = ROOT / "lua55" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + + +def test_sonnen_battery_sign_follows_site_convention(): + result = subprocess.run( + [str(LUA), "drivers/tests/lua_harness/test_sonnen_sign.lua"], + capture_output=True, text=True, cwd=ROOT) + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout diff --git a/index.yaml b/index.yaml index 0fe786c..88fc55e 100644 --- a/index.yaml +++ b/index.yaml @@ -709,15 +709,15 @@ drivers: size_bytes: 5807 sha256: "5669996a562d10fc94ed89748664542ce14e5d965ff0df85d1e7610ff4dda568" - name: "sonnen" - version: "2.0.3" + version: "2.0.4" tier: community protocol: http connectivity: local setup: [device_ui] ders: [battery, meter] control: false - size_bytes: 6631 - sha256: "94ae5e0065f5793051acb89b7ef04a679b2898908dfac6f4ffd6e8deb77fa2c0" + size_bytes: 6734 + sha256: "aee7b5ecf3b7666561084d434664f2df1019425f085ce36c4c4488baebfd1f76" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index d4757fe..7d586f8 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -1,5 +1,5 @@ name: "sonnen" -version: "2.0.3" +version: "2.0.4" tier: community author: "Sourceful Labs AB" protocol: http @@ -16,9 +16,9 @@ tested_devices: notes: "Community driver, untested" min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 6631 +size_bytes: 6734 dkb_id: "" -sha256: "94ae5e0065f5793051acb89b7ef04a679b2898908dfac6f4ffd6e8deb77fa2c0" +sha256: "aee7b5ecf3b7666561084d434664f2df1019425f085ce36c4c4488baebfd1f76" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index c6ee121..f682e59 100644 --- a/support-status.json +++ b/support-status.json @@ -1619,7 +1619,7 @@ }, { "catalog_source": true, - "catalog_version": "2.0.3", + "catalog_version": "2.0.4", "driver_id": "sonnen", "targets": { "blixt-l1": { From 8c7a988159719010769ba8f00cc8dc188d39bbf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:27:19 +0100 Subject: [PATCH 2/8] feat(sonnen): set battery power through the local API (2.1.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sonnen applies setpoints only in manual mode, which it enters through PUT /api/v2/configurations; PATCH and POST there return 404. With FTW's host.http_put and capabilities.http.allow_write, a battery command enters manual mode and posts /setpoint/charge|discharge/, limited to IC_InverterMaxPower_w and an optional owner max_power_w. A manual setpoint holds until replaced, so the driver owns the way back: a 60 s lease in poll, default mode and deinit clear the setpoint and restore the automatic mode the unit ran before (2 or 10), with readback; init clears a manual mode a stopped FTW left behind; three failed handovers stop the unprompted writes. {"error": ...} replies are failed reads instead of w = 0. Without http_put the driver refuses commands and keeps reporting telemetry. Adds http_put to the host API profile and the harness mock. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- CHANGELOG.md | 26 ++ SUPPORT_STATUS.md | 4 +- devices.yaml | 8 +- drivers/lua/sonnen.lua | 341 +++++++++++++++--- drivers/tests/lua_harness/host_mock.lua | 29 ++ .../tests/lua_harness/test_sonnen_control.lua | 222 ++++++++++++ .../tests/lua_harness/test_sonnen_sign.lua | 5 - .../{test_sonnen_sign.py => test_sonnen.py} | 20 +- index.yaml | 8 +- manifests/sonnen.yaml | 12 +- spec/host-api-profile.json | 2 + support-status.json | 2 +- 12 files changed, 608 insertions(+), 71 deletions(-) create mode 100644 drivers/tests/lua_harness/test_sonnen_control.lua rename drivers/tests/{test_sonnen_sign.py => test_sonnen.py} (53%) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbf51db..c817e18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,32 @@ driver no longer knows FTW wrote, so that offset stays; today only the operator's control on the heating card writes it. Not yet checked on hardware. +### sonnen 2.1.0 + +The driver can set sonnenBatterie charge and discharge power. It needs FTW's +`host.http_put`: sonnen changes its operating mode only through +`PUT /api/v2/configurations`, and answers PATCH and POST there with 404. +Without that function, or without `capabilities.http.allow_write`, the +driver refuses commands and keeps reporting telemetry. + +- A battery command puts the unit in manual mode (`EM_OperatingMode` 1) and + posts `/setpoint/charge/` or `/discharge/`, limited to the unit's + `IC_InverterMaxPower_w` and an optional `max_power_w` set by the owner. If the + unit has left manual mode, the driver enters it again once and retries. +- A manual setpoint holds until it is replaced. Without a battery command for + 60 s, the driver clears the setpoint and returns the unit to the automatic + mode it ran before. That mode is self-consumption (2) or time-of-use (10). + Default mode and `deinit` do the same and read the mode back. At start, the + driver clears a manual mode that a stopped FTW left behind. After three + failed handovers, the unprompted paths stop writing. +- `{"error": ...}` replies, such as a wrong token's `Unauthorized`, are failed + reads, not `w = 0`. +- Emits `setpoint_w`, `control_power_w` and `control_power_observed_at` from + `/latestdata` for control feedback. + +None of these safeguards runs when FTW itself is gone. The HIL gate for host +loss while the unit holds a manual setpoint is still open. + ### sonnen 2.0.4 Battery power has the site sign. sonnen reports `Pac_total_W` positive while diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index a5acd79..2edfd09 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -158,8 +158,8 @@ Catalog source is not proof that a target can install or run a driver. | solis | 2.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | solis_string | 1.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | | solis_string | 1.1.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| sonnen | 2.0.4 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| sonnen | 2.0.4 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| sonnen | 2.1.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| sonnen | 2.1.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | sungrow | 1.6.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | sungrow | 1.6.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | tesla_cloud | 0.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 4c31d02..dcd509e 100644 --- a/devices.yaml +++ b/devices.yaml @@ -2175,8 +2175,8 @@ manufacturers: protocols: - protocol: http driver: "sonnen" - version: "2.0.4" + version: "2.1.0" ders: [battery, meter] - control: false - firmware_versions: "" - notes: "Community driver, untested" + control: true + firmware_versions: "1.40.5" + notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index 4a3f593..de41e37 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -1,8 +1,9 @@ --- sonnenBatterie — local JSON API v2 (read-only) +-- sonnenBatterie — local JSON API v2: telemetry and battery setpoints -- Emits: battery --- Protocol: HTTP (local JSON API v2 on the Sonnen unit). Read API must --- be enabled in the Sonnen web UI under Software-Integration → JSON API, --- which also surfaces the Auth-Token to put into config.api_token. +-- Protocol: HTTP (local JSON API v2 on the sonnen unit). Enable the JSON API +-- in the sonnen web UI under Software-Integration, which also shows the +-- Auth-Token for config.api_token. Control needs a token with write access. +-- The unit documents the API at http:///api/doc.html. -- -- Config example (config.yaml): -- drivers: @@ -11,11 +12,14 @@ -- capabilities: -- http: -- allowed_hosts: --- - 192.168.x.y # LAN IP of the Sonnen unit +-- - 192.168.x.y # LAN IP of the sonnen unit +-- allow_write: true # control only; telemetry works without it -- config: -- host: "192.168.x.y" -- port: 80 -- api_token: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +-- # max_power_w: 4000 # optional owner cap for setpoints +-- # default_operating_mode: "2" # "2" self-consumption (default) or "10" time-of-use -- -- Sign convention (site: positive W flows INTO the site): -- battery.w: positive = charging (sink), negative = discharging (source). @@ -24,6 +28,21 @@ -- software 1.40.5 on 2026-11-13: in manual mode, a 500 W charge setpoint -- read back over six reads as Pac_total_W -495 to -504 W, SetPoint_W -500 -- and BatteryCharging true. +-- +-- Control (measured on the same unit): +-- * Setpoints apply only in manual mode, EM_OperatingMode "1". The mode is +-- changed with PUT /api/v2/configurations; PATCH and POST there return +-- 404, so control needs FTW's host.http_put. Without it the driver stays +-- a telemetry driver and refuses commands. +-- * POST /api/v2/setpoint/charge/ or /discharge/ answers "true". +-- * A manual setpoint holds until it is replaced; no device-side timeout +-- has been observed. The driver therefore owns the safe path: +-- - a lease: without a fresh battery command for LEASE_MS, poll clears +-- the setpoint and returns the unit to its automatic mode; +-- - driver_default_mode does the same, and reads the mode back; +-- - init clears a manual mode left behind by a stopped FTW. +-- None of these run if FTW itself is gone. The HIL gate for that case +-- (host loss with a held setpoint) is still open. DRIVER = { host_api_min = 1, @@ -31,43 +50,61 @@ DRIVER = { id = "sonnen", name = "sonnenBatterie (local API)", manufacturer = "sonnen", - version = "2.0.4", + version = "2.1.0", protocols = { "http" }, capabilities = { "battery" }, - read_only = true, - description = "sonnenBatterie local JSON API v2: SoC + charge/discharge power. Read-only.", + description = "sonnenBatterie local JSON API v2: SoC, charge/discharge power and battery setpoints.", homepage = "https://sonnen.de", authors = { "FTW contributors" }, http_hosts = { }, verification_status = "experimental", - verification_notes = "Community-contributed local-API driver; not yet verified against live hardware on a FTW site.", + verification_notes = "Sign and manual-mode setpoints measured on one sonnenBatterie (software 1.40.5); control not yet HIL-accepted.", connection_defaults = { host = "", port = 80, }, -- Secret config keys the wizard / Settings UI should render password - -- inputs for and stuff into config.. Keeps Auth-Token out of - -- yaml-by-hand and lets the operator paste it from the Sonnen web UI - -- (Software-Integration → JSON API). + -- inputs for and stuff into config.. config_secrets = { "api_token" }, } PROTOCOL = "http" +local MODE_MANUAL = "1" +local AUTO_MODES = { ["2"] = true, ["10"] = true } + +-- A battery command must be renewed within this window. FTW's control loop +-- dispatches every few seconds; a minute of silence means nobody is steering. +local LEASE_MS = 60000 + +-- Three failed hand-backs prove the unit will not take them (token without +-- write access, firmware change). The unprompted paths then stop writing; +-- an explicit command still tries, and one success re-arms them. +local DEFAULT_ATTEMPTS = 3 + local sonnen_host = "" local sonnen_port = 80 local api_token = "" +local owner_max_w = nil + +local inverter_max_w = nil -- IC_InverterMaxPower_w, the unit's own rating +local mode = nil -- EM_OperatingMode as last read or written +local auto_mode = "2" -- automatic mode to return to; never "1" +local session = false -- true while this driver holds manual mode +local last_command_ms = 0 +local default_failures = 0 --- Backoff state. Doubles from 2 s to 60 s on consecutive HTTP / decode --- failures so a powered-down or wrong-token unit doesn't pin the poll --- loop hammering the LAN. local last_attempt = 0 local backoff_ms = 0 local BACKOFF_MIN = 2000 local BACKOFF_MAX = 60000 local function base_url() - return "http://" .. sonnen_host .. ":" .. tostring(sonnen_port) + return "http://" .. sonnen_host .. ":" .. tostring(sonnen_port) .. "/api/v2" +end + +local function auth() + return { ["Auth-Token"] = api_token } end local function bump_backoff() @@ -89,29 +126,197 @@ local function in_backoff() return (host.millis() - last_attempt) < backoff_ms end -local function safe_http_get(url, headers) - local ok, resp, err = pcall(host.http_get, url, headers) - if not ok then return nil, tostring(resp) end - return resp, err -end - -local function safe_json_decode(body) +local function decode(body) if body == nil then return nil end local ok, data = pcall(host.json_decode, body) if not ok then return nil end return data end +-- get_json returns the decoded object, or nil and a reason. An +-- {"error": ...} body (a wrong token answers {"error":"Unauthorized"}) is a +-- failed read, never a reading. +local function get_json(path) + local ok, body, err = pcall(host.http_get, base_url() .. path, auth()) + if not ok then return nil, tostring(body) end + if err then return nil, tostring(err) end + local data = decode(body) + if type(data) ~= "table" then return nil, "JSON decode failed" end + if data.error ~= nil then return nil, tostring(data.error) end + return data +end + -- clamp drops obviously-broken values (NaN, sentinel huge numbers from a -- partial JSON parse) so a single bad poll doesn't poison the battery -- model with a 2 GW reading. local function clamp(v, max_abs) local n = tonumber(v) - if n == nil then return nil end + if n == nil or n ~= n then return nil end if max_abs and math.abs(n) > max_abs then return nil end return n end +-- RFC 3339 time of a latestdata sample: Timestamp is local time and +-- UTC_Offset its whole-hour offset. +local function observed_at(data) + local ts = data.Timestamp + local off = tonumber(data.UTC_Offset) + if type(ts) ~= "string" or off == nil or off ~= math.floor(off) then + return nil + end + local d, t = string.match(ts, "^(%d%d%d%d%-%d%d%-%d%d) (%d%d:%d%d:%d%d)$") + if not d then return nil end + local sign = "+" + if off < 0 then sign = "-" end + return string.format("%sT%s%s%02d:00", d, t, sign, math.floor(math.abs(off))) +end + +local function read_configuration() + local cfg, err = get_json("/configurations") + if not cfg then + return false, err + end + local rated = clamp(cfg.IC_InverterMaxPower_w, 100000) + if rated and rated > 0 then + if inverter_max_w ~= rated then host.set_rated_w(rated) end + inverter_max_w = rated + end + if cfg.EM_OperatingMode ~= nil then + mode = tostring(cfg.EM_OperatingMode) + if AUTO_MODES[mode] then auto_mode = mode end + end + if cfg.DE_Software then + host.set_model("sonnenBatterie " .. tostring(cfg.DE_Software)) + end + return true +end + +-- put_mode switches EM_OperatingMode and checks the unit's echo. +local function put_mode(target) + if host.http_put == nil then + return false, "this FTW has no host.http_put; sonnen control needs it" + end + local ok, resp, err = pcall(host.http_put, base_url() .. "/configurations", + "EM_OperatingMode=" .. target, + { ["Auth-Token"] = api_token, + ["Content-Type"] = "application/x-www-form-urlencoded" }) + if not ok then err = tostring(resp) end + if err then + return false, "operating mode " .. target .. ": " .. tostring(err) + end + local data = decode(resp) + if type(data) ~= "table" or tostring(data.EM_OperatingMode) ~= target then + return false, "operating mode " .. target .. " not confirmed: " .. tostring(resp) + end + mode = target + return true +end + +-- post_setpoint sends a manual setpoint in site convention: +W charges, +-- -W discharges, 0 holds the battery idle. +local function post_setpoint(w) + local n = math.floor(math.abs(w) + 0.5) + local dir = "charge" + if w < 0 then dir = "discharge" end + local ok, resp, err = pcall(host.http_post, + base_url() .. "/setpoint/" .. dir .. "/" .. tostring(n), "", auth()) + if not ok then err = tostring(resp) end + if err then + return false, dir .. " " .. n .. " W: " .. tostring(err) + end + if not string.find(tostring(resp), "true", 1, true) then + return false, dir .. " " .. n .. " W refused: " .. tostring(resp) + end + return true +end + +local function power_limit() + local limit = inverter_max_w + if owner_max_w and (limit == nil or owner_max_w < limit) then + limit = owner_max_w + end + return limit +end + +local function set_battery_power(power_w) + if host.http_put == nil then + return "this FTW has no host.http_put; sonnen control needs it" + end + local w = tonumber(power_w) + if w == nil or w ~= w then + return "battery command needs a numeric power_w" + end + if inverter_max_w == nil then + local ok, err = read_configuration() + if not ok then return "sonnen configuration unreadable: " .. tostring(err) end + end + local limit = power_limit() + if limit == nil then + return "sonnen did not report IC_InverterMaxPower_w; refusing an unbounded setpoint" + end + if w > limit then w = limit end + if w < -limit then w = -limit end + + if mode ~= MODE_MANUAL then + local ok, err = put_mode(MODE_MANUAL) + if not ok then return err end + end + session = true + last_command_ms = host.millis() + local ok, err = post_setpoint(w) + if ok then return true end + -- The unit may have left manual mode on its own (app, portal, restart). + -- Re-enter it once and retry before reporting the failure. + local mode_ok, mode_err = put_mode(MODE_MANUAL) + if not mode_ok then return mode_err end + ok, err = post_setpoint(w) + if ok then return true end + return err +end + +-- restore_auto hands the unit back to its automatic mode. It writes only +-- when the unit is (or may be) in manual mode, and reads the result back. +local function restore_auto_once() + local read_ok = read_configuration() + if read_ok and mode ~= MODE_MANUAL then + session = false + return true + end + if not read_ok and not session and mode ~= MODE_MANUAL then + -- Unreachable, and nothing says this driver ever took control: + -- there is nothing to undo, and no state to confirm. + return false + end + -- Clear the setpoint first so a failed mode switch never leaves a + -- charge or discharge request standing. + local cleared, clear_err = post_setpoint(0) + local restored, restore_err = put_mode(auto_mode) + if not restored then + host.log("warn", "sonnen: returning to automatic mode failed: " .. tostring(restore_err)) + return false + end + if not cleared then + host.log("warn", "sonnen: clearing the setpoint failed: " .. tostring(clear_err)) + end + if read_configuration() and mode ~= auto_mode then + host.log("warn", "sonnen: unit reports mode " .. tostring(mode) + .. " after restoring " .. auto_mode) + return false + end + session = false + host.log("info", "sonnen: returned to automatic mode " .. auto_mode) + return true +end + +local function restore_auto() + if restore_auto_once() then + default_failures = 0 + return true + end + default_failures = default_failures + 1 + return false +end + ---------------------------------------------------------------------------- -- Driver interface ---------------------------------------------------------------------------- @@ -129,18 +334,34 @@ function driver_init(config) if type(config.api_token) == "string" and config.api_token ~= "" then api_token = config.api_token end + local cap = tonumber(config.max_power_w) + if cap and cap > 0 then owner_max_w = cap end + local dm = config.default_operating_mode + if dm ~= nil and AUTO_MODES[tostring(dm)] then + auto_mode = tostring(dm) + end end if sonnen_host == "" then - host.log("error", "sonnen: config.host required (LAN IP of the Sonnen unit)") + host.log("error", "sonnen: config.host required (LAN IP of the sonnen unit)") return end if api_token == "" then - host.log("warn", "sonnen: config.api_token is empty — JSON API v2 requires an Auth-Token; enable it in the Sonnen web UI under Software-Integration") + host.log("warn", "sonnen: config.api_token is empty — JSON API v2 requires an Auth-Token; enable it in the sonnen web UI under Software-Integration") + end + + local ok, err = read_configuration() + if not ok then + host.log("warn", "sonnen: reading configurations failed: " .. tostring(err)) + elseif mode == MODE_MANUAL and host.http_put ~= nil then + -- Manual mode with nobody steering: a previous FTW stopped while it + -- held a setpoint. Hand the unit back before anything else. + host.log("warn", "sonnen: unit is in manual mode at start; restoring automatic mode " .. auto_mode) + restore_auto() end host.log("info", "sonnen: driver initialized (host=" .. sonnen_host - .. ":" .. tostring(sonnen_port) .. ")") + .. ":" .. tostring(sonnen_port) .. ", mode=" .. tostring(mode) .. ")") end function driver_poll() @@ -151,64 +372,94 @@ function driver_poll() return 1000 end - local url = base_url() .. "/api/v2/latestdata" - local headers = { ["Auth-Token"] = api_token } - local body, err = safe_http_get(url, headers) - - if err then + local data, err = get_json("/latestdata") + if not data then bump_backoff() host.log("warn", "sonnen: fetch failed: " .. tostring(err) .. " (retry in " .. backoff_ms .. "ms)") return 1000 end + clear_backoff() - local data = safe_json_decode(body) - if not data then - bump_backoff() - host.log("warn", "sonnen: JSON decode failed") + local pac_w = clamp(data.Pac_total_W, 30000) + if pac_w == nil then + host.log("warn", "sonnen: latestdata has no usable Pac_total_W") return 1000 end - - clear_backoff() - - local pac_w = clamp(data.Pac_total_W, 30000) or 0 local rsoc = clamp(data.RSOC, 100) -- USOC is the user-visible SoC the unit clamps usable energy against; -- prefer it over RSOC (raw SoC) so the EMS sees the same headroom the - -- Sonnen will actually deliver / accept. + -- sonnen will actually deliver / accept. local usoc = clamp(data.USOC, 100) local prod_w = clamp(data.Production_W, 30000) or 0 local cons_w = clamp(data.Consumption_W, 30000) or 0 local cap_wh = clamp(data.FullChargeCapacity, 1000000) + local set_w = clamp(data.SetPoint_W, 30000) + local seen_at = observed_at(data) local soc_pct = usoc or rsoc or 0 local battery = { w = -pac_w, -- sonnen: + = discharge; site: + = charge soc = soc_pct / 100.0, + control_power_w = -pac_w, + control_power_available = seen_at ~= nil, } + if seen_at then + battery.control_power_observed_at = seen_at + end + if set_w then + battery.setpoint_w = -set_w + end if cap_wh then battery.capacity_wh = cap_wh end - host.emit("battery", battery) host.emit_metric("battery_rsoc", rsoc or 0) host.emit_metric("battery_usoc", usoc or 0) - host.emit_metric("battery_pac_w", pac_w) + host.emit_metric("battery_pac_w", pac_w) -- vendor sign host.emit_metric("battery_production_w", prod_w) host.emit_metric("battery_consumption_w", cons_w) if cap_wh then host.emit_metric("battery_capacity_wh", cap_wh) end + -- The lease: a held setpoint nobody renews goes back to the unit. + if session and host.millis() - last_command_ms > LEASE_MS + and default_failures < DEFAULT_ATTEMPTS then + host.log("info", "sonnen: no battery command for " + .. math.floor(LEASE_MS / 1000) .. " s; returning to automatic mode") + restore_auto() + end + return 1000 end -function driver_command(...) - return false +function driver_command(action, power_w, cmd) + if sonnen_host == "" then + return "sonnen: config.host is not set" + end + if action == "init" then + return true + elseif action == "battery" then + return set_battery_power(power_w) + elseif action == "deinit" then + if restore_auto() then return true end + return "sonnen: could not return to automatic mode" + end + return "unsupported action: " .. tostring(action) end function driver_default_mode() + if sonnen_host == "" or host.http_put == nil then + return true + end + if default_failures >= DEFAULT_ATTEMPTS then + -- The unit has refused every write; repeating them on each watchdog + -- tick only floods the log. Report the default as held. + return true + end + return restore_auto() end function driver_cleanup() diff --git a/drivers/tests/lua_harness/host_mock.lua b/drivers/tests/lua_harness/host_mock.lua index 609f463..6168fa1 100644 --- a/drivers/tests/lua_harness/host_mock.lua +++ b/drivers/tests/lua_harness/host_mock.lua @@ -47,6 +47,9 @@ host._http_responses = {} -- { [full_url] = response_body_string } host._http_patches = {} -- ordered list of {url=..., body=..., headers=...} host._http_patch_responses = {} -- { [url_or_substring] = response_body_string } host._http_patch_error = nil -- set to an error string to fail PATCHes +host._http_puts = {} -- ordered list of {url=..., body=..., headers=...} +host._http_put_responses = {} -- { [url_or_substring] = body or function(url, body) } +host._http_put_error = nil -- set to an error string to fail PUTs host._poll_interval_ms = nil -- last value passed to set_poll_interval host._mqtt_buffer = {} -- list of {topic=..., payload=...} host._p1_data = nil -- P1 telegram table or nil @@ -99,6 +102,9 @@ function host.reset() host._http_patches = {} host._http_patch_responses = {} host._http_patch_error = nil + host._http_puts = {} + host._http_put_responses = {} + host._http_put_error = nil host._poll_interval_ms = nil host._mqtt_buffer = {} host._p1_data = nil @@ -489,6 +495,29 @@ function host.http_patch(url, body, headers) return '[{"status":"modified"}]' end +-- FTW's host.http_put(url, body, headers) → (body, nil) or (nil, err), with +-- the same recording and response rules as http_patch. Responses come from +-- host._http_put_responses; a function value is called with (url, body). +function host.http_put(url, body, headers) + record_call("http_put", url, body, headers) + table.insert(host._http_puts, {url = url, body = body, headers = headers}) + if host._http_put_error then + return nil, host._http_put_error + end + local resp = host._http_put_responses[url] + if resp == nil then + for pattern_url, r in pairs(host._http_put_responses) do + if string.find(url, pattern_url, 1, true) then + resp = r + break + end + end + end + if type(resp) == "function" then return resp(url, body) end + if resp ~= nil then return resp end + return "{}" +end + --------------------------------------------------------------------------- -- Serial functions --------------------------------------------------------------------------- diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua new file mode 100644 index 0000000..7328f71 --- /dev/null +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -0,0 +1,222 @@ +-- sonnen control: manual setpoints, the driver-side lease, default mode and +-- the refusal paths, against a fake unit that behaves like a sonnenBatterie +-- with software 1.40.5: setpoints only take effect in manual mode ("1"), +-- the mode changes only through PUT /api/v2/configurations, and a manual +-- setpoint holds until it is replaced. + +dofile("drivers/tests/lua_harness/host_mock.lua") + +local BASE = "http://192.0.2.10:80/api/v2" +local unit +local writes + +local function fail(msg) error(msg, 2) end + +local function new_unit(mode) + unit = { mode = mode, setpoint = 0, token = "token", rated = "9900", + refuse_put = nil, unauthorized = false } + writes = {} +end + +local function install_fake_unit(with_put) + host.http_get = function(url, headers) + if (headers or {})["Auth-Token"] ~= unit.token or unit.unauthorized then + return '{"error":"Unauthorized"}' + end + if url == BASE .. "/configurations" then + return '{"EM_OperatingMode":"' .. unit.mode .. '","IC_InverterMaxPower_w":"' + .. unit.rated .. '","DE_Software":"1.40.5"}' + elseif url == BASE .. "/latestdata" then + -- In manual mode the battery follows the setpoint; sonnen sign. + local pac = 0 + if unit.mode == "1" then pac = unit.setpoint end + return '{"FullChargeCapacity":18700,"Pac_total_W":' .. pac .. + ',"RSOC":45,"USOC":40,"SetPoint_W":' .. unit.setpoint .. + ',"Timestamp":"2026-11-13 20:03:26","UTC_Offset":1}' + end + return nil, "HTTP 404" + end + host.http_post = function(url, body, headers) + table.insert(writes, "POST " .. url) + local dir, n = string.match(url, "/setpoint/(%a+)/(%d+)$") + if not dir then return nil, "HTTP 404" end + if unit.mode ~= "1" then return nil, "HTTP 403" end + n = tonumber(n) + if dir == "charge" then unit.setpoint = -n else unit.setpoint = n end + return "true" + end + if with_put then + host.http_put = function(url, body, headers) + table.insert(writes, "PUT " .. url .. " " .. body) + if unit.refuse_put then return nil, unit.refuse_put end + if headers["Auth-Token"] ~= unit.token then return nil, "HTTP 401" end + if headers["Content-Type"] ~= "application/x-www-form-urlencoded" then + return nil, "HTTP 415" + end + local m = string.match(body, "^EM_OperatingMode=(%d+)$") + if url ~= BASE .. "/configurations" or not m then return nil, "HTTP 404" end + unit.mode = m + if m ~= "1" then unit.setpoint = 0 end + return '{"EM_OperatingMode":"' .. m .. '"}' + end + else + host.http_put = nil + end +end + +local function boot(mode, config, with_put) + host.reset() + new_unit(mode) + install_fake_unit(with_put ~= false) + dofile("drivers/lua/sonnen.lua") + local cfg = { host = "192.0.2.10", port = 80, api_token = "token" } + for k, v in pairs(config or {}) do cfg[k] = v end + driver_init(cfg) +end + +local function poll() + local ok, err = pcall(driver_poll) + if not ok then fail("driver_poll failed: " .. tostring(err)) end + local list = host._emitted.battery or {} + return list[#list], #list +end + +local function advance(ms) + host._millis_counter = host._millis_counter + ms +end + +-- ---- Telemetry and control feedback --------------------------------------- + +boot("2") +if #writes ~= 0 then fail("init in self-consumption must not write") end +if DRIVER.read_only then fail("control driver must not declare read_only") end +local b = poll() +if b.w ~= 0 or b.setpoint_w ~= 0 then fail("idle reading wrong") end +if b.control_power_observed_at ~= "2026-11-13T20:03:26+01:00" then + fail("observed_at = " .. tostring(b.control_power_observed_at)) +end +if b.control_power_available ~= true then fail("control power must be available") end + +-- ---- Charge: manual mode, then the setpoint ------------------------------- + +if driver_command("init", 0, {}) ~= true then fail("init action failed") end +if #writes ~= 0 then fail("init action must not write") end +local r = driver_command("battery", 1500, {}) +if r ~= true then fail("charge command failed: " .. tostring(r)) end +if writes[1] ~= "PUT " .. BASE .. "/configurations EM_OperatingMode=1" or + writes[2] ~= "POST " .. BASE .. "/setpoint/charge/1500" then + fail("charge writes: " .. table.concat(writes, " | ")) +end +b = poll() +if b.w ~= 1500 or b.setpoint_w ~= 1500 or b.control_power_w ~= 1500 then + fail("charging must read +1500 in site signs, got w=" .. tostring(b.w) + .. " setpoint_w=" .. tostring(b.setpoint_w)) +end + +-- A second command in manual mode does not switch the mode again. +writes = {} +driver_command("battery", 800, {}) +if #writes ~= 1 or writes[1] ~= "POST " .. BASE .. "/setpoint/charge/800" then + fail("repeat command writes: " .. table.concat(writes, " | ")) +end + +-- ---- Discharge is clamped to the lower of rating and owner cap ------------- + +boot("2", { max_power_w = 4000 }) +driver_command("battery", -20000, {}) +if unit.setpoint ~= 4000 then fail("discharge not clamped to owner cap: " .. unit.setpoint) end +b = poll() +if b.w ~= -4000 then fail("discharging must read -4000, got " .. tostring(b.w)) end +boot("2") +driver_command("battery", 20000, {}) +if unit.setpoint ~= -9900 then fail("charge not clamped to inverter rating: " .. unit.setpoint) end + +-- ---- The unit leaves manual mode behind FTW's back ------------------------- + +boot("2") +driver_command("battery", 500, {}) +unit.mode = "2" +unit.setpoint = 0 +r = driver_command("battery", 700, {}) +if r ~= true or unit.mode ~= "1" or unit.setpoint ~= -700 then + fail("recovery after external mode change failed: " .. tostring(r)) +end + +-- ---- Lease: no command for a minute hands the unit back ------------------- + +boot("2") +driver_command("battery", 1000, {}) +advance(30000) +poll() +if unit.mode ~= "1" then fail("lease expired too early") end +advance(31000) +poll() +if unit.mode ~= "2" or unit.setpoint ~= 0 then + fail("lease expiry must clear the setpoint and restore mode 2, got mode " + .. unit.mode .. " setpoint " .. unit.setpoint) +end +writes = {} +advance(120000) +poll() +if #writes ~= 0 then fail("after the lease the driver must stop writing") end + +-- ---- Default mode ---------------------------------------------------------- + +boot("2") +driver_command("battery", -1200, {}) +if driver_default_mode() ~= true then fail("default mode failed") end +if unit.mode ~= "2" or unit.setpoint ~= 0 then fail("default mode did not restore") end +writes = {} +if driver_default_mode() ~= true or #writes ~= 0 then + fail("default mode on a unit already in automatic mode must not write") +end +if driver_command("deinit", 0, {}) ~= true then fail("deinit failed") end + +-- The automatic mode the unit ran before is the one restored. +boot("10") +driver_command("battery", 300, {}) +driver_default_mode() +if unit.mode ~= "10" then fail("time-of-use was not restored, got " .. unit.mode) end + +-- ---- A manual mode left by a stopped FTW is cleared at start -------------- + +host.reset() +new_unit("1") +unit.setpoint = -2500 +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +if unit.mode ~= "2" or unit.setpoint ~= 0 then + fail("orphan manual mode not cleared at init") +end + +-- ---- A failed read emits nothing ------------------------------------------ + +boot("2") +unit.unauthorized = true +local _, count = poll() +if count ~= 0 then fail("an Unauthorized answer must not become a reading") end + +-- ---- Without host.http_put the driver refuses control --------------------- + +boot("2", nil, false) +r = driver_command("battery", 1000, {}) +if r == true or type(r) ~= "string" then fail("command without http_put must be refused") end +if #writes ~= 0 or unit.mode ~= "2" then fail("command without http_put wrote") end +if driver_default_mode() ~= true or #writes ~= 0 then + fail("default mode without http_put must hold without writing") +end +b = poll() +if b.w ~= 0 then fail("telemetry must still work without http_put") end + +-- ---- Refused writes stop the unprompted path ------------------------------ + +boot("2") +driver_command("battery", 1000, {}) +unit.refuse_put = "HTTP 401" +for _ = 1, 3 do driver_default_mode() end +writes = {} +for _ = 1, 5 do driver_default_mode() end +if #writes ~= 0 then fail("default mode kept writing after refusals: " .. #writes) end + +print("OK") diff --git a/drivers/tests/lua_harness/test_sonnen_sign.lua b/drivers/tests/lua_harness/test_sonnen_sign.lua index 2091ba8..460039d 100644 --- a/drivers/tests/lua_harness/test_sonnen_sign.lua +++ b/drivers/tests/lua_harness/test_sonnen_sign.lua @@ -50,9 +50,4 @@ if not host._metrics.battery_pac_w or host._metrics.battery_pac_w.value ~= 1200 error("battery_pac_w must keep the vendor sign") end --- Still read-only. -if DRIVER.read_only ~= true or driver_command("battery", 1000, {}) ~= false then - error("sonnen must stay read-only") -end - print("OK") diff --git a/drivers/tests/test_sonnen_sign.py b/drivers/tests/test_sonnen.py similarity index 53% rename from drivers/tests/test_sonnen_sign.py rename to drivers/tests/test_sonnen.py index c8e4b40..6ced80a 100644 --- a/drivers/tests/test_sonnen_sign.py +++ b/drivers/tests/test_sonnen.py @@ -1,4 +1,4 @@ -"""sonnen: battery.w follows the site convention. +"""sonnen: battery sign and battery control. sonnen reports Pac_total_W positive while discharging; FTW's battery.w is positive while charging. The harness script polls the driver against @@ -19,9 +19,21 @@ not LUA.exists(), reason="run make check to build ./lua55") -def test_sonnen_battery_sign_follows_site_convention(): - result = subprocess.run( - [str(LUA), "drivers/tests/lua_harness/test_sonnen_sign.lua"], +def run(script: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [str(LUA), f"drivers/tests/lua_harness/{script}"], capture_output=True, text=True, cwd=ROOT) + + +def test_sonnen_battery_sign_follows_site_convention(): + result = run("test_sonnen_sign.lua") + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +def test_sonnen_control_lease_default_mode_and_refusals(): + """Manual setpoints, clamping, the 60 s lease, default mode with + readback, orphan clearing at start, no http_put, and refused writes.""" + result = run("test_sonnen_control.lua") assert result.returncode == 0, result.stdout + result.stderr assert "OK" in result.stdout diff --git a/index.yaml b/index.yaml index 88fc55e..e5ae5a6 100644 --- a/index.yaml +++ b/index.yaml @@ -709,15 +709,15 @@ drivers: size_bytes: 5807 sha256: "5669996a562d10fc94ed89748664542ce14e5d965ff0df85d1e7610ff4dda568" - name: "sonnen" - version: "2.0.4" + version: "2.1.0" tier: community protocol: http connectivity: local setup: [device_ui] ders: [battery, meter] - control: false - size_bytes: 6734 - sha256: "aee7b5ecf3b7666561084d434664f2df1019425f085ce36c4c4488baebfd1f76" + control: true + size_bytes: 16799 + sha256: "19a93b074d7110750652f313c41d7fe1e78caf0b2e351e9a0d2189b430dace9f" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index 7d586f8..fca11ca 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -1,24 +1,24 @@ name: "sonnen" -version: "2.0.4" +version: "2.1.0" tier: community author: "Sourceful Labs AB" protocol: http connectivity: local setup: [device_ui] ders: [battery, meter] -control: false +control: true tested_devices: - manufacturer: "sonnen" model_family: "sonnenBatterie" variants: [sonnenBatterie eco 8.0, sonnenBatterie 10 performance, sonnenBatterie FlexStack] regions: [] - firmware_versions: "" - notes: "Community driver, untested" + firmware_versions: "1.40.5" + notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 6734 +size_bytes: 16799 dkb_id: "" -sha256: "aee7b5ecf3b7666561084d434664f2df1019425f085ce36c4c4488baebfd1f76" +sha256: "19a93b074d7110750652f313c41d7fe1e78caf0b2e351e9a0d2189b430dace9f" signature: "" bytecode_sha256: "" diff --git a/spec/host-api-profile.json b/spec/host-api-profile.json index 92d2e4a..8f530e1 100644 --- a/spec/host-api-profile.json +++ b/spec/host-api-profile.json @@ -62,6 +62,7 @@ "http_get", "http_post", "http_patch", + "http_put", "http_request", "http_cookies_clear", "https_get", @@ -92,6 +93,7 @@ "http_get", "http_post", "http_patch", + "http_put", "http_request", "http_cookies_clear", "mqtt_pub", diff --git a/support-status.json b/support-status.json index f682e59..91ab3f8 100644 --- a/support-status.json +++ b/support-status.json @@ -1619,7 +1619,7 @@ }, { "catalog_source": true, - "catalog_version": "2.0.4", + "catalog_version": "2.1.0", "driver_id": "sonnen", "targets": { "blixt-l1": { From fc5af05d15ae9e7bca1695ce57c08903e6f2aaaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:38:33 +0100 Subject: [PATCH 3/8] fix(sonnen): post no setpoint without a confirmed mode switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit host.http_post is not gated by capabilities.http.allow_write. When the unit already reported manual mode, a battery command skipped the PUT and posted the setpoint directly, so a driver without write permission could still move the battery. Every control session now starts with a confirmed PUT; a refused PUT ends the command before any POST. Also report 0 instead of -0 W when the battery is idle. Found in a dry run of the hardware test protocol against a local fake unit. The new harness case fails on the previous code. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- drivers/lua/sonnen.lua | 14 +++++++++---- .../tests/lua_harness/test_sonnen_control.lua | 20 +++++++++++++++++++ index.yaml | 4 ++-- manifests/sonnen.yaml | 4 ++-- 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index de41e37..44e060b 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -257,7 +257,11 @@ local function set_battery_power(power_w) if w > limit then w = limit end if w < -limit then w = -limit end - if mode ~= MODE_MANUAL then + -- Every session starts with a confirmed PUT, even when the unit already + -- reports manual mode. host.http_post is not gated by allow_write, so + -- this PUT is what keeps a driver without write permission from ever + -- posting a setpoint. + if not session or mode ~= MODE_MANUAL then local ok, err = put_mode(MODE_MANUAL) if not ok then return err end end @@ -398,17 +402,19 @@ function driver_poll() local seen_at = observed_at(data) local soc_pct = usoc or rsoc or 0 + -- sonnen: + = discharge; site: + = charge. Adding 0 turns -0 into 0. + local site_w = -pac_w + 0 local battery = { - w = -pac_w, -- sonnen: + = discharge; site: + = charge + w = site_w, soc = soc_pct / 100.0, - control_power_w = -pac_w, + control_power_w = site_w, control_power_available = seen_at ~= nil, } if seen_at then battery.control_power_observed_at = seen_at end if set_w then - battery.setpoint_w = -set_w + battery.setpoint_w = -set_w + 0 end if cap_wh then battery.capacity_wh = cap_wh diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index 7328f71..7e13014 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -197,6 +197,26 @@ unit.unauthorized = true local _, count = poll() if count ~= 0 then fail("an Unauthorized answer must not become a reading") end +-- ---- No setpoint without a confirmed PUT ---------------------------------- +-- The unit already sits in manual mode (owner, app), and the host refuses +-- the PUT (no allow_write). http_post is not gated by allow_write, so the +-- driver itself must not post a setpoint. + +host.reset() +new_unit("1") +unit.refuse_put = "http: write not granted (set capabilities.http.allow_write)" +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +if unit.mode ~= "1" then fail("setup: unit should still be in manual mode") end +writes = {} +r = driver_command("battery", 900, {}) +if r == true then fail("command must fail when the PUT is refused") end +for _, w in ipairs(writes) do + if string.find(w, "^POST") then fail("posted a setpoint without a confirmed PUT: " .. w) end +end +if unit.setpoint ~= 0 then fail("setpoint changed without a confirmed PUT") end + -- ---- Without host.http_put the driver refuses control --------------------- boot("2", nil, false) diff --git a/index.yaml b/index.yaml index e5ae5a6..ae72c1e 100644 --- a/index.yaml +++ b/index.yaml @@ -716,8 +716,8 @@ drivers: setup: [device_ui] ders: [battery, meter] control: true - size_bytes: 16799 - sha256: "19a93b074d7110750652f313c41d7fe1e78caf0b2e351e9a0d2189b430dace9f" + size_bytes: 17131 + sha256: "714014bb7ea7e026073dde96168f398397d00e59d4284cbe2b516607fe6acd96" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index fca11ca..2c6ccde 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -16,9 +16,9 @@ tested_devices: notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 16799 +size_bytes: 17131 dkb_id: "" -sha256: "19a93b074d7110750652f313c41d7fe1e78caf0b2e351e9a0d2189b430dace9f" +sha256: "714014bb7ea7e026073dde96168f398397d00e59d4284cbe2b516607fe6acd96" signature: "" bytecode_sha256: "" From 322a9f12526918b15015082815ae7349e8232167 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:05 +0100 Subject: [PATCH 4/8] fix(sonnen): an unreachable unit does not use up the hand-back attempts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Default mode counted every failed hand-back toward the three-attempt limit, including calls made while the unit was unreachable, such as FTW's watchdog during a network loss. After three of those it reported the default as held and the lease stopped trying, so the unit kept its manual setpoint after the network returned. Only refusals, where the unit answered the read, now count. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- drivers/lua/sonnen.lua | 24 ++++++++++++------- .../tests/lua_harness/test_sonnen_control.lua | 23 ++++++++++++++++++ index.yaml | 4 ++-- manifests/sonnen.yaml | 4 ++-- 4 files changed, 43 insertions(+), 12 deletions(-) diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index 44e060b..d171779 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -77,7 +77,7 @@ local AUTO_MODES = { ["2"] = true, ["10"] = true } -- dispatches every few seconds; a minute of silence means nobody is steering. local LEASE_MS = 60000 --- Three failed hand-backs prove the unit will not take them (token without +-- Three refused hand-backs prove the unit will not take them (token without -- write access, firmware change). The unprompted paths then stop writing; -- an explicit command still tries, and one success re-arms them. local DEFAULT_ATTEMPTS = 3 @@ -280,16 +280,18 @@ end -- restore_auto hands the unit back to its automatic mode. It writes only -- when the unit is (or may be) in manual mode, and reads the result back. +-- restore_auto_once returns ok, and whether a failure was the unit's +-- refusal (it answered the read) rather than the unit being unreachable. local function restore_auto_once() local read_ok = read_configuration() if read_ok and mode ~= MODE_MANUAL then session = false - return true + return true, false end if not read_ok and not session and mode ~= MODE_MANUAL then -- Unreachable, and nothing says this driver ever took control: -- there is nothing to undo, and no state to confirm. - return false + return false, false end -- Clear the setpoint first so a failed mode switch never leaves a -- charge or discharge request standing. @@ -297,7 +299,7 @@ local function restore_auto_once() local restored, restore_err = put_mode(auto_mode) if not restored then host.log("warn", "sonnen: returning to automatic mode failed: " .. tostring(restore_err)) - return false + return false, read_ok end if not cleared then host.log("warn", "sonnen: clearing the setpoint failed: " .. tostring(clear_err)) @@ -305,19 +307,25 @@ local function restore_auto_once() if read_configuration() and mode ~= auto_mode then host.log("warn", "sonnen: unit reports mode " .. tostring(mode) .. " after restoring " .. auto_mode) - return false + return false, true end session = false host.log("info", "sonnen: returned to automatic mode " .. auto_mode) - return true + return true, false end +-- Only refusals count toward DEFAULT_ATTEMPTS. An unreachable unit (network +-- loss, watchdog standdown) must not use up the attempts, or the lease would +-- never hand the unit back once the network returns. local function restore_auto() - if restore_auto_once() then + local ok, refused = restore_auto_once() + if ok then default_failures = 0 return true end - default_failures = default_failures + 1 + if refused then + default_failures = default_failures + 1 + end return false end diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index 7e13014..523a8df 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -239,4 +239,27 @@ writes = {} for _ = 1, 5 do driver_default_mode() end if #writes ~= 0 then fail("default mode kept writing after refusals: " .. #writes) end +-- ---- Network loss must not use up the hand-back attempts ----------------- +-- FTW's watchdog calls default mode while the unit is unreachable. Those +-- failures are not refusals; once the network returns, the lease must still +-- hand the unit back. + +boot("2") +driver_command("battery", 600, {}) +local real_get, real_post, real_put = host.http_get, host.http_post, host.http_put +host.http_get = function() return nil, "dial tcp 192.0.2.10:80: i/o timeout" end +host.http_post = function() return nil, "dial tcp 192.0.2.10:80: i/o timeout" end +host.http_put = function() return nil, "dial tcp 192.0.2.10:80: i/o timeout" end +for _ = 1, 6 do + if driver_default_mode() == true then fail("default mode cannot succeed while unreachable") end +end +if unit.mode ~= "1" then fail("setup: unit should still hold manual mode") end +host.http_get, host.http_post, host.http_put = real_get, real_post, real_put +advance(61000) +poll() +if unit.mode ~= "2" or unit.setpoint ~= 0 then + fail("after network loss the lease must hand the unit back, got mode " + .. unit.mode .. " setpoint " .. unit.setpoint) +end + print("OK") diff --git a/index.yaml b/index.yaml index ae72c1e..6e8a629 100644 --- a/index.yaml +++ b/index.yaml @@ -716,8 +716,8 @@ drivers: setup: [device_ui] ders: [battery, meter] control: true - size_bytes: 17131 - sha256: "714014bb7ea7e026073dde96168f398397d00e59d4284cbe2b516607fe6acd96" + size_bytes: 17580 + sha256: "c2102a4fd3907db6d01c284a8bacaff267d36fd74326139ecd84df286e815aa7" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index 2c6ccde..1ebacc6 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -16,9 +16,9 @@ tested_devices: notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 17131 +size_bytes: 17580 dkb_id: "" -sha256: "714014bb7ea7e026073dde96168f398397d00e59d4284cbe2b516607fe6acd96" +sha256: "c2102a4fd3907db6d01c284a8bacaff267d36fd74326139ecd84df286e815aa7" signature: "" bytecode_sha256: "" From 0b730b734eca9213e061ce9cfa86b37f02a41a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:02:11 +0100 Subject: [PATCH 5/8] fix(sonnen): undo only manual setpoints this driver or a stopped FTW left MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Init and default mode returned the unit to its automatic mode whenever it reported manual mode. That overrode an owner who keeps the unit in manual mode with setpoint 0 (idle), and without allow_write it still posted setpoint 0, because http_post is not gated by allow_write. Now the driver undoes its own session as before (setpoint 0, then the automatic mode). A manual setpoint other than 0 that it did not set is cleared with a PUT only. A manual mode with setpoint 0 that it did not set is left alone. Without write access nothing is written. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- CHANGELOG.md | 10 +++- drivers/lua/sonnen.lua | 49 +++++++++++++++---- .../tests/lua_harness/test_sonnen_control.lua | 32 ++++++++++++ index.yaml | 4 +- manifests/sonnen.yaml | 4 +- 5 files changed, 83 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c817e18..42e24b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,8 +29,14 @@ driver refuses commands and keeps reporting telemetry. 60 s, the driver clears the setpoint and returns the unit to the automatic mode it ran before. That mode is self-consumption (2) or time-of-use (10). Default mode and `deinit` do the same and read the mode back. At start, the - driver clears a manual mode that a stopped FTW left behind. After three - failed handovers, the unprompted paths stop writing. + driver clears a manual setpoint other than 0 that a stopped FTW left + behind. It leaves a manual mode with setpoint 0 alone, because that may be + the owner's idle and moves no power. After three handovers the unit + refuses, the unprompted paths stop writing; an unreachable unit does not + count toward the three. +- Every control session starts with a confirmed `PUT`. `host.http_post` is + not gated by `allow_write`, so without write access the driver posts + nothing, even when the unit already reports manual mode. - `{"error": ...}` replies, such as a wrong token's `Unauthorized`, are failed reads, not `w = 0`. - Emits `setpoint_w`, `control_power_w` and `control_power_observed_at` from diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index d171779..bd083ee 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -40,7 +40,9 @@ -- - a lease: without a fresh battery command for LEASE_MS, poll clears -- the setpoint and returns the unit to its automatic mode; -- - driver_default_mode does the same, and reads the mode back; --- - init clears a manual mode left behind by a stopped FTW. +-- - init clears a manual setpoint (not 0) left behind by a stopped +-- FTW; a manual mode with setpoint 0 is left alone, since it may be +-- the owner's idle and it moves no power. -- None of these run if FTW itself is gone. The HIL gate for that case -- (host loss with a held setpoint) is still open. @@ -282,19 +284,45 @@ end -- when the unit is (or may be) in manual mode, and reads the result back. -- restore_auto_once returns ok, and whether a failure was the unit's -- refusal (it answered the read) rather than the unit being unreachable. +-- +-- What it undoes depends on who set manual mode: +-- * this driver's own session: clear the setpoint, then restore the +-- automatic mode (the session proved write access with its PUT); +-- * not this process, with a setpoint other than 0 (a stopped FTW left a +-- charge or discharge running): restore the automatic mode with a PUT +-- only, so a driver without write access posts nothing; +-- * not this process, setpoint 0: an owner's manual idle, or an idle hold +-- a stopped FTW left behind. Both are safe; it is left alone. local function restore_auto_once() local read_ok = read_configuration() if read_ok and mode ~= MODE_MANUAL then session = false return true, false end - if not read_ok and not session and mode ~= MODE_MANUAL then - -- Unreachable, and nothing says this driver ever took control: - -- there is nothing to undo, and no state to confirm. - return false, false + if not session then + if not read_ok then + return false, false + end + local data = get_json("/latestdata") + if not data then + return false, false + end + local set_w = clamp(data.SetPoint_W, 30000) + if set_w == 0 then + host.log("info", "sonnen: unit is in manual mode with setpoint 0, not set by this driver; leaving it") + return true, false + end + local restored, restore_err = put_mode(auto_mode) + if not restored then + host.log("warn", "sonnen: returning to automatic mode failed: " .. tostring(restore_err)) + return false, true + end + host.log("info", "sonnen: cleared a manual setpoint of " .. tostring(set_w) + .. " W left by a previous controller; automatic mode " .. auto_mode) + return true, false end - -- Clear the setpoint first so a failed mode switch never leaves a - -- charge or discharge request standing. + -- Our own session. Clear the setpoint first so a failed mode switch + -- never leaves a charge or discharge request standing. local cleared, clear_err = post_setpoint(0) local restored, restore_err = put_mode(auto_mode) if not restored then @@ -366,9 +394,10 @@ function driver_init(config) if not ok then host.log("warn", "sonnen: reading configurations failed: " .. tostring(err)) elseif mode == MODE_MANUAL and host.http_put ~= nil then - -- Manual mode with nobody steering: a previous FTW stopped while it - -- held a setpoint. Hand the unit back before anything else. - host.log("warn", "sonnen: unit is in manual mode at start; restoring automatic mode " .. auto_mode) + -- Manual mode at start. A setpoint other than 0 means a previous FTW + -- stopped while it held one: hand the unit back. Setpoint 0 is left + -- alone (see restore_auto_once). + host.log("warn", "sonnen: unit is in manual mode at start") restore_auto() end diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index 523a8df..c146364 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -190,6 +190,38 @@ if unit.mode ~= "2" or unit.setpoint ~= 0 then fail("orphan manual mode not cleared at init") end +-- ---- An owner's manual idle (setpoint 0) is left alone -------------------- + +host.reset() +new_unit("1") +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +if #writes ~= 0 or unit.mode ~= "1" then fail("init changed an owner's manual idle") end +if driver_default_mode() ~= true or #writes ~= 0 then + fail("default mode must leave an owner's manual idle untouched") +end +-- FTW then takes control; afterwards the unit goes back to self-consumption. +driver_command("battery", 400, {}) +driver_default_mode() +if unit.mode ~= "2" or unit.setpoint ~= 0 then fail("own session was not handed back") end + +-- ---- Without allow_write nothing is written, even from manual mode -------- + +host.reset() +new_unit("1") +unit.setpoint = -1500 -- left by a stopped FTW +unit.refuse_put = "http: write not granted (set capabilities.http.allow_write)" +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +driver_command("battery", 700, {}) +driver_default_mode() +for _, w in ipairs(writes) do + if string.find(w, "^POST") then fail("posted without write access: " .. w) end +end +if unit.setpoint ~= -1500 or unit.mode ~= "1" then fail("unit changed without write access") end + -- ---- A failed read emits nothing ------------------------------------------ boot("2") diff --git a/index.yaml b/index.yaml index 6e8a629..96a0936 100644 --- a/index.yaml +++ b/index.yaml @@ -716,8 +716,8 @@ drivers: setup: [device_ui] ders: [battery, meter] control: true - size_bytes: 17580 - sha256: "c2102a4fd3907db6d01c284a8bacaff267d36fd74326139ecd84df286e815aa7" + size_bytes: 18938 + sha256: "fd4d1f8204ab4097a3e192551aef616cd249bc0aa18367196b460aad9914e8b0" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index 1ebacc6..15104d0 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -16,9 +16,9 @@ tested_devices: notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 17580 +size_bytes: 18938 dkb_id: "" -sha256: "c2102a4fd3907db6d01c284a8bacaff267d36fd74326139ecd84df286e815aa7" +sha256: "fd4d1f8204ab4097a3e192551aef616cd249bc0aa18367196b460aad9914e8b0" signature: "" bytecode_sha256: "" From d5cfeaa9a6fddaedb9a52c787a1a834c91d0a9f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:54:44 +0100 Subject: [PATCH 6/8] fix(sonnen): trust SetPoint_W and the mode only from a fresh manual read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the automatic modes a sonnenBatterie reports its own load-following target in SetPoint_W (1255 W was seen in self-consumption). The driver reported it as setpoint_w in every mode, so FTW would read it as a command it never gave. setpoint_w is now emitted only after a fresh /configurations read confirms manual mode. A /configurations reply without EM_OperatingMode kept the mode from an earlier read, and default mode could then report the unit as automatic while another controller held a manual setpoint. Such a reply is now a failed read. The harness fake now follows the house load in mode 2, as the unit does. Both new cases fail on the previous driver. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- CHANGELOG.md | 8 ++- drivers/lua/sonnen.lua | 21 +++++--- .../tests/lua_harness/test_sonnen_control.lua | 54 ++++++++++++++++--- index.yaml | 4 +- manifests/sonnen.yaml | 4 +- 5 files changed, 71 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42e24b6..25fd6a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,12 @@ driver refuses commands and keeps reporting telemetry. nothing, even when the unit already reports manual mode. - `{"error": ...}` replies, such as a wrong token's `Unauthorized`, are failed reads, not `w = 0`. -- Emits `setpoint_w`, `control_power_w` and `control_power_observed_at` from - `/latestdata` for control feedback. +- Emits `control_power_w` and `control_power_observed_at` from + `/latestdata` for control feedback, and `setpoint_w` only after a fresh read + confirms manual mode. In the automatic modes `SetPoint_W` is the unit's + own load-following target (1255 W was seen in self-consumption), not a + command. A `/configurations` reply without `EM_OperatingMode` is a failed + read, so no decision rests on a mode from an earlier read. None of these safeguards runs when FTW itself is gone. The HIL gate for host loss while the unit holds a manual setpoint is still open. diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index bd083ee..5961f3a 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -173,20 +173,23 @@ local function observed_at(data) return string.format("%sT%s%s%02d:00", d, t, sign, math.floor(math.abs(off))) end +-- read_configuration fails unless the reply carries EM_OperatingMode, so a +-- decision never rests on a mode cached from an earlier read. local function read_configuration() local cfg, err = get_json("/configurations") if not cfg then return false, err end + if cfg.EM_OperatingMode == nil then + return false, "configurations reply has no EM_OperatingMode" + end local rated = clamp(cfg.IC_InverterMaxPower_w, 100000) if rated and rated > 0 then if inverter_max_w ~= rated then host.set_rated_w(rated) end inverter_max_w = rated end - if cfg.EM_OperatingMode ~= nil then - mode = tostring(cfg.EM_OperatingMode) - if AUTO_MODES[mode] then auto_mode = mode end - end + mode = tostring(cfg.EM_OperatingMode) + if AUTO_MODES[mode] then auto_mode = mode end if cfg.DE_Software then host.set_model("sonnenBatterie " .. tostring(cfg.DE_Software)) end @@ -450,8 +453,14 @@ function driver_poll() if seen_at then battery.control_power_observed_at = seen_at end - if set_w then - battery.setpoint_w = -set_w + 0 + -- SetPoint_W is a setpoint only in manual mode. In the automatic modes + -- the unit reports its own load-following target there (1255 W was + -- seen in self-consumption), which is no command FTW gave. Report it + -- only after a fresh read confirms manual mode; a failed read omits it. + if set_w and mode == MODE_MANUAL then + if read_configuration() and mode == MODE_MANUAL then + battery.setpoint_w = -set_w + 0 + end end if cap_wh then battery.capacity_wh = cap_wh diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index c146364..61f0857 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -12,9 +12,14 @@ local writes local function fail(msg) error(msg, 2) end +-- In the automatic modes a real unit reports its own load-following +-- target in SetPoint_W and covers the house load (seen: 1255 W), so the +-- fake does the same instead of reporting 0. +local LOAD_W = 1255 + local function new_unit(mode) unit = { mode = mode, setpoint = 0, token = "token", rated = "9900", - refuse_put = nil, unauthorized = false } + refuse_put = nil, unauthorized = false, omit_mode = false } writes = {} end @@ -24,14 +29,17 @@ local function install_fake_unit(with_put) return '{"error":"Unauthorized"}' end if url == BASE .. "/configurations" then - return '{"EM_OperatingMode":"' .. unit.mode .. '","IC_InverterMaxPower_w":"' + local m = '"EM_OperatingMode":"' .. unit.mode .. '",' + if unit.omit_mode then m = "" end + return '{' .. m .. '"IC_InverterMaxPower_w":"' .. unit.rated .. '","DE_Software":"1.40.5"}' elseif url == BASE .. "/latestdata" then - -- In manual mode the battery follows the setpoint; sonnen sign. - local pac = 0 - if unit.mode == "1" then pac = unit.setpoint end + -- Manual mode: the battery follows FTW's setpoint. Automatic + -- modes: it follows the house load. Sonnen sign. + local pac, sp = LOAD_W, LOAD_W + if unit.mode == "1" then pac, sp = unit.setpoint, unit.setpoint end return '{"FullChargeCapacity":18700,"Pac_total_W":' .. pac .. - ',"RSOC":45,"USOC":40,"SetPoint_W":' .. unit.setpoint .. + ',"RSOC":45,"USOC":40,"SetPoint_W":' .. sp .. ',"Timestamp":"2026-11-13 20:03:26","UTC_Offset":1}' end return nil, "HTTP 404" @@ -91,7 +99,10 @@ boot("2") if #writes ~= 0 then fail("init in self-consumption must not write") end if DRIVER.read_only then fail("control driver must not declare read_only") end local b = poll() -if b.w ~= 0 or b.setpoint_w ~= 0 then fail("idle reading wrong") end +if b.w ~= -LOAD_W then fail("self-consumption reading wrong: " .. tostring(b.w)) end +if b.setpoint_w ~= nil then + fail("setpoint_w must be absent in mode 2, got " .. tostring(b.setpoint_w)) +end if b.control_power_observed_at ~= "2026-11-13T20:03:26+01:00" then fail("observed_at = " .. tostring(b.control_power_observed_at)) end @@ -259,7 +270,7 @@ if driver_default_mode() ~= true or #writes ~= 0 then fail("default mode without http_put must hold without writing") end b = poll() -if b.w ~= 0 then fail("telemetry must still work without http_put") end +if b.w ~= -LOAD_W then fail("telemetry must still work without http_put") end -- ---- Refused writes stop the unprompted path ------------------------------ @@ -294,4 +305,31 @@ if unit.mode ~= "2" or unit.setpoint ~= 0 then .. unit.mode .. " setpoint " .. unit.setpoint) end +-- ---- setpoint_w follows a fresh mode read, not a cached one -------------- +-- FTW put the unit in manual mode; then the app sets self-consumption. The +-- load-following SetPoint_W must not be reported as a setpoint. + +boot("2") +driver_command("battery", 500, {}) +unit.mode = "2" +b = poll() +if b.setpoint_w ~= nil then + fail("setpoint_w reported after the unit left manual mode: " .. tostring(b.setpoint_w)) +end + +-- ---- A configurations reply without EM_OperatingMode is a failed read ----- +-- The driver last saw mode 2. Another controller now holds a manual setpoint +-- and the reply omits the mode. Default mode must not claim the unit is in +-- automatic mode, and must not write blind. + +boot("2") +unit.mode = "1" +unit.setpoint = -2500 +unit.omit_mode = true +writes = {} +if driver_default_mode() == true then + fail("default mode trusted a cached mode when the reply had none") +end +if #writes ~= 0 then fail("wrote without a confirmed mode: " .. table.concat(writes, " | ")) end + print("OK") diff --git a/index.yaml b/index.yaml index 96a0936..2da9b60 100644 --- a/index.yaml +++ b/index.yaml @@ -716,8 +716,8 @@ drivers: setup: [device_ui] ders: [battery, meter] control: true - size_bytes: 18938 - sha256: "fd4d1f8204ab4097a3e192551aef616cd249bc0aa18367196b460aad9914e8b0" + size_bytes: 19538 + sha256: "2ed3b9effd4a56bd2d589da47c07ac82e98be15593121f258637b205a0e0a758" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index 15104d0..d1f5a01 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -16,9 +16,9 @@ tested_devices: notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 18938 +size_bytes: 19538 dkb_id: "" -sha256: "fd4d1f8204ab4097a3e192551aef616cd249bc0aa18367196b460aad9914e8b0" +sha256: "2ed3b9effd4a56bd2d589da47c07ac82e98be15593121f258637b205a0e0a758" signature: "" bytecode_sha256: "" From 174b72d0c43a2d6e774de2d75d508cc1b0d1cd17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:50:09 +0100 Subject: [PATCH 7/8] fix(sonnen): do not report setpoint_w before the own POST is confirmed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the unit was already in manual mode at start, the first poll reported its SetPoint_W as FTW's setpoint, although this driver had not posted one (-1622 and -942 W were seen in the harness log). setpoint_w is now emitted only after this session's own setpoint POST was answered "true" and a fresh read confirms manual mode. A refused POST, a hand-back to automatic mode, or the unit leaving manual mode withdraws it. Mode 2 still never reports SetPoint_W. The max_power_w config example now reads 5000. The new harness case fails on the previous driver with -1622. Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++- drivers/lua/sonnen.lua | 44 ++++++++++--- .../tests/lua_harness/test_sonnen_control.lua | 64 ++++++++++++++++++- index.yaml | 4 +- manifests/sonnen.yaml | 4 +- 5 files changed, 107 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25fd6a4..8c80e38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,11 +40,14 @@ driver refuses commands and keeps reporting telemetry. - `{"error": ...}` replies, such as a wrong token's `Unauthorized`, are failed reads, not `w = 0`. - Emits `control_power_w` and `control_power_observed_at` from - `/latestdata` for control feedback, and `setpoint_w` only after a fresh read + `/latestdata` for control feedback. It emits `setpoint_w` only after the + driver's own setpoint `POST` was confirmed in this session and a fresh read confirms manual mode. In the automatic modes `SetPoint_W` is the unit's own load-following target (1255 W was seen in self-consumption), not a - command. A `/configurations` reply without `EM_OperatingMode` is a failed - read, so no decision rests on a mode from an earlier read. + command. In a manual mode the driver has not yet written, it is what the + unit held before; the first poll after start reported -1622 and -942 W. A + `/configurations` reply without `EM_OperatingMode` is a failed read, so no + decision rests on a mode from an earlier read. None of these safeguards runs when FTW itself is gone. The HIL gate for host loss while the unit holds a manual setpoint is still open. diff --git a/drivers/lua/sonnen.lua b/drivers/lua/sonnen.lua index 5961f3a..4adb457 100644 --- a/drivers/lua/sonnen.lua +++ b/drivers/lua/sonnen.lua @@ -18,7 +18,7 @@ -- host: "192.168.x.y" -- port: 80 -- api_token: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" --- # max_power_w: 4000 # optional owner cap for setpoints +-- # max_power_w: 5000 # optional owner cap for setpoints -- # default_operating_mode: "2" # "2" self-consumption (default) or "10" time-of-use -- -- Sign convention (site: positive W flows INTO the site): @@ -93,6 +93,10 @@ local inverter_max_w = nil -- IC_InverterMaxPower_w, the unit's own rating local mode = nil -- EM_OperatingMode as last read or written local auto_mode = "2" -- automatic mode to return to; never "1" local session = false -- true while this driver holds manual mode +-- true once this session's own setpoint POST was answered "true"; until +-- then SetPoint_W is whatever the unit held before (another controller, a +-- stopped FTW, an owner's idle) and is not reported as FTW's setpoint. +local setpoint_confirmed = false local last_command_ms = 0 local default_failures = 0 @@ -272,14 +276,23 @@ local function set_battery_power(power_w) end session = true last_command_ms = host.millis() + -- Until this POST is confirmed the unit's setpoint is not known to be + -- this one, so setpoint_w stays absent. + setpoint_confirmed = false local ok, err = post_setpoint(w) - if ok then return true end + if ok then + setpoint_confirmed = true + return true + end -- The unit may have left manual mode on its own (app, portal, restart). -- Re-enter it once and retry before reporting the failure. local mode_ok, mode_err = put_mode(MODE_MANUAL) if not mode_ok then return mode_err end ok, err = post_setpoint(w) - if ok then return true end + if ok then + setpoint_confirmed = true + return true + end return err end @@ -300,6 +313,7 @@ local function restore_auto_once() local read_ok = read_configuration() if read_ok and mode ~= MODE_MANUAL then session = false + setpoint_confirmed = false return true, false end if not session then @@ -325,7 +339,9 @@ local function restore_auto_once() return true, false end -- Our own session. Clear the setpoint first so a failed mode switch - -- never leaves a charge or discharge request standing. + -- never leaves a charge or discharge request standing. The commanded + -- setpoint is being withdrawn, so it is no longer reported. + setpoint_confirmed = false local cleared, clear_err = post_setpoint(0) local restored, restore_err = put_mode(auto_mode) if not restored then @@ -453,13 +469,21 @@ function driver_poll() if seen_at then battery.control_power_observed_at = seen_at end - -- SetPoint_W is a setpoint only in manual mode. In the automatic modes - -- the unit reports its own load-following target there (1255 W was - -- seen in self-consumption), which is no command FTW gave. Report it - -- only after a fresh read confirms manual mode; a failed read omits it. - if set_w and mode == MODE_MANUAL then - if read_configuration() and mode == MODE_MANUAL then + -- SetPoint_W is FTW's setpoint only when FTW set it. In the automatic + -- modes the unit reports its own load-following target there (1255 W + -- was seen in self-consumption). In a manual mode this session has not + -- yet written, it is what the unit held before (-1622 and -942 were seen + -- on the first poll after start). Report it only after this session's + -- own POST was confirmed and a fresh read confirms manual mode; a failed + -- read omits it. + if set_w and session and setpoint_confirmed then + local read_ok = read_configuration() + if read_ok and mode == MODE_MANUAL then battery.setpoint_w = -set_w + 0 + elseif read_ok then + -- The unit left manual mode (app, portal, restart): the setpoint + -- this session posted is gone. + setpoint_confirmed = false end end if cap_wh then diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index 61f0857..bd99665 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -19,7 +19,8 @@ local LOAD_W = 1255 local function new_unit(mode) unit = { mode = mode, setpoint = 0, token = "token", rated = "9900", - refuse_put = nil, unauthorized = false, omit_mode = false } + refuse_put = nil, refuse_post = nil, unauthorized = false, + omit_mode = false } writes = {} end @@ -49,6 +50,7 @@ local function install_fake_unit(with_put) local dir, n = string.match(url, "/setpoint/(%a+)/(%d+)$") if not dir then return nil, "HTTP 404" end if unit.mode ~= "1" then return nil, "HTTP 403" end + if unit.refuse_post then return unit.refuse_post end n = tonumber(n) if dir == "charge" then unit.setpoint = -n else unit.setpoint = n end return "true" @@ -332,4 +334,64 @@ if driver_default_mode() == true then end if #writes ~= 0 then fail("wrote without a confirmed mode: " .. table.concat(writes, " | ")) end +-- ---- No setpoint_w before this session's own POST is confirmed ---------- +-- The unit is in manual mode at start with a setpoint this driver did not +-- write. The first poll must not carry it as FTW's setpoint, whether init +-- could not hand the unit back or left an owner's idle alone. + +host.reset() +new_unit("1") +unit.setpoint = 1622 -- left by a stopped FTW; the hand-back is refused +unit.refuse_put = "http: write not granted (set capabilities.http.allow_write)" +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +b = poll() +if b == nil then fail("first poll after start emitted no battery reading") end +if b.setpoint_w ~= nil then + fail("first poll after start reported a setpoint FTW never posted: " + .. tostring(b.setpoint_w)) +end + +host.reset() +new_unit("1") -- owner's manual idle, setpoint 0, left alone by init +install_fake_unit(true) +dofile("drivers/lua/sonnen.lua") +driver_init({ host = "192.0.2.10", port = 80, api_token = "token" }) +b = poll() +if b.setpoint_w ~= nil then + fail("first poll reported the owner's idle as a setpoint: " .. tostring(b.setpoint_w)) +end + +-- The mode switch is confirmed but the unit refuses the setpoint: still none. +unit.refuse_post = "false" +r = driver_command("battery", 900, {}) +if r == true then fail("a refused setpoint POST must fail the command") end +if unit.mode ~= "1" then fail("setup: the PUT to manual mode should have succeeded") end +b = poll() +if b.setpoint_w ~= nil then + fail("setpoint_w reported after the POST was refused: " .. tostring(b.setpoint_w)) +end + +-- Once the POST is confirmed, the read-back setpoint is reported. +unit.refuse_post = nil +r = driver_command("battery", 900, {}) +if r ~= true then fail("charge command failed: " .. tostring(r)) end +b = poll() +if b.setpoint_w ~= 900 then + fail("setpoint_w after a confirmed POST = " .. tostring(b.setpoint_w)) +end + +-- The app moves the unit to self-consumption and back to manual with its +-- own setpoint: the driver's confirmed setpoint is gone. +unit.mode = "2" +poll() +unit.mode = "1" +unit.setpoint = 942 +b = poll() +if b.setpoint_w ~= nil then + fail("setpoint_w reported after the unit left manual mode and returned: " + .. tostring(b.setpoint_w)) +end + print("OK") diff --git a/index.yaml b/index.yaml index 2da9b60..dda93fc 100644 --- a/index.yaml +++ b/index.yaml @@ -716,8 +716,8 @@ drivers: setup: [device_ui] ders: [battery, meter] control: true - size_bytes: 19538 - sha256: "2ed3b9effd4a56bd2d589da47c07ac82e98be15593121f258637b205a0e0a758" + size_bytes: 20590 + sha256: "563440b14f5ad8231a24a6be43d8ad70a110bff25a5e8b9d321e96980042e137" - name: "sungrow" version: "1.6.1" tier: core diff --git a/manifests/sonnen.yaml b/manifests/sonnen.yaml index d1f5a01..eae9cc6 100644 --- a/manifests/sonnen.yaml +++ b/manifests/sonnen.yaml @@ -16,9 +16,9 @@ tested_devices: notes: "Battery sign and manual-mode setpoints measured on one unit (software 1.40.5). Control is not yet HIL-accepted." min_driver_version: "1.0.0" min_host_version: "2.1.0" -size_bytes: 19538 +size_bytes: 20590 dkb_id: "" -sha256: "2ed3b9effd4a56bd2d589da47c07ac82e98be15593121f258637b205a0e0a758" +sha256: "563440b14f5ad8231a24a6be43d8ad70a110bff25a5e8b9d321e96980042e137" signature: "" bytecode_sha256: "" From f4bb865a51bcfc33e549b01a351202cd52e53d6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rgen=20Ohlsson?= <267945958+yogiohlsson-ai@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:29:40 +0100 Subject: [PATCH 8/8] test(sonnen): cover an unclamped discharge setpoint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jörgen Ohlsson <267945958+yogiohlsson-ai@users.noreply.github.com> --- .../tests/lua_harness/test_sonnen_control.lua | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/drivers/tests/lua_harness/test_sonnen_control.lua b/drivers/tests/lua_harness/test_sonnen_control.lua index bd99665..c25e7de 100644 --- a/drivers/tests/lua_harness/test_sonnen_control.lua +++ b/drivers/tests/lua_harness/test_sonnen_control.lua @@ -144,6 +144,28 @@ boot("2") driver_command("battery", 20000, {}) if unit.setpoint ~= -9900 then fail("charge not clamped to inverter rating: " .. unit.setpoint) end +-- ---- Discharge within the rating and with no owner cap is posted as is ----- + +boot("2") +if unit.rated ~= "9900" then fail("setup: rating must be 9900, got " .. unit.rated) end +r = driver_command("battery", -1500, {}) +if r ~= true then fail("discharge command failed: " .. tostring(r)) end +if #writes ~= 2 or + writes[1] ~= "PUT " .. BASE .. "/configurations EM_OperatingMode=1" or + writes[2] ~= "POST " .. BASE .. "/setpoint/discharge/1500" then + fail("discharge writes: " .. table.concat(writes, " | ")) +end +-- The fake stores the vendor sign: discharge is positive. +if unit.mode ~= "1" or unit.setpoint ~= 1500 then + fail("unit did not take a 1500 W discharge: mode=" .. unit.mode + .. " setpoint=" .. tostring(unit.setpoint)) +end +b = poll() +if b.w ~= -1500 or b.setpoint_w ~= -1500 then + fail("discharging must read -1500 in site signs, got w=" .. tostring(b.w) + .. " setpoint_w=" .. tostring(b.setpoint_w)) +end + -- ---- The unit leaves manual mode behind FTW's back ------------------------- boot("2")