From 46b28a1cb968bb81cf30df9290cfca816d1d91b9 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 11:29:38 +0100 Subject: [PATCH 1/8] fix(sungrow): an outage no longer drops registers or the release (1.6.1) (#202) Count a failed read or EMS write only when the device answers with a Modbus exception. A failed read also counts when another read in the same poll returned data. Transport errors, reconnect backoff and gateway or busy exceptions never count. The first poll that reads data after a poll that read nothing clears the read misses and the EMS write count. Once forced mode has landed, set_self_consumption always writes the release and never reports the default as held until the inverter takes it. FTW's random site rig (27 October 2026, master 83c2b24c) found both: 13000 dropped after an outage flipped the battery sign (207539, 207534), and the release was skipped while the inverter held its last forced command for up to 5 minutes (8 of 10 seeds). Signed-off-by: Fredrik Ahlgren Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 26 +++ SUPPORT_STATUS.md | 4 +- devices.yaml | 10 +- drivers/lua/sungrow.lua | 123 +++++++++-- drivers/tests/test_sungrow_outage.py | 297 +++++++++++++++++++++++++++ index.yaml | 6 +- manifests/sungrow.yaml | 6 +- support-status.json | 2 +- 8 files changed, 443 insertions(+), 31 deletions(-) create mode 100644 drivers/tests/test_sungrow_outage.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 52a8522..399f8d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ ## [Unreleased] +### sungrow 1.6.1 + +An inverter that drops off the network no longer loses registers or its +release. FTW's random site rig takes the inverter offline for 20 to 90 s. +Every read and write then fails, and the driver counted those failures as the +device refusing them. + +- Reads: 12999, 13000 and the PV registers were dropped for the session after + three failed polls. 13000 signs the battery, so FTW read a discharge as a + charge for the rest of the run. A failed read now counts only when the + device answers with a Modbus exception, or when another read in the same + poll returned data. The first poll that reads data after a poll that read + nothing starts every count over. +- Writes: three failed writes marked the EMS block absent, so the watchdog's + release was reported as held without being written. The inverter kept its + last forced command for up to five minutes. Only a Modbus exception now + counts toward that, and a reconnect resets the count. Once this driver has + put the inverter in forced mode, the release is always written, and is never + reported as held, until the inverter takes it. + +Gateway exceptions 0x0A and 0x0B and the busy exception 0x06 do not count: +they say the device could not answer, not that the register is missing. + +FTW's bundled copy does not move with this commit. Bump the pin and run +`scripts/sync-bundled-drivers.sh`. + ### easee_cloud 1.4.0 Read Easee's SignalR stream when the host grants a WebSocket. Easee diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 3cff62e..2285c99 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_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 | -| sungrow | 1.6.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| sungrow | 1.6.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 | | tesla_cloud | 0.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | tesla_vehicle | 0.2.6 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 478a570..723fd8b 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1762,7 +1762,7 @@ manufacturers: protocols: - protocol: modbus driver: "sungrow" - version: "1.6.0" + version: "1.6.1" ders: [battery, meter, pv] control: true firmware_versions: "" @@ -1773,7 +1773,7 @@ manufacturers: protocols: - protocol: modbus driver: "sungrow" - version: "1.6.0" + version: "1.6.1" ders: [battery, meter, pv] control: true firmware_versions: "" @@ -1784,7 +1784,7 @@ manufacturers: protocols: - protocol: modbus driver: "sungrow" - version: "1.6.0" + version: "1.6.1" ders: [battery, meter, pv] control: true firmware_versions: "" @@ -1795,7 +1795,7 @@ manufacturers: protocols: - protocol: modbus driver: "sungrow" - version: "1.6.0" + version: "1.6.1" ders: [battery, meter, pv] control: true firmware_versions: "" @@ -1806,7 +1806,7 @@ manufacturers: protocols: - protocol: modbus driver: "sungrow" - version: "1.6.0" + version: "1.6.1" ders: [battery, meter, pv] control: true firmware_versions: "" diff --git a/drivers/lua/sungrow.lua b/drivers/lua/sungrow.lua index 36efb80..b035dc8 100644 --- a/drivers/lua/sungrow.lua +++ b/drivers/lua/sungrow.lua @@ -9,7 +9,7 @@ DRIVER = { id = "sungrow", name = "Sungrow SH Hybrid Inverter", manufacturer = "Sungrow", - version = "1.6.0", + version = "1.6.1", protocols = { "modbus" }, capabilities = { "meter", "pv", "battery", "pv-curtail" }, description = "Sungrow SH-series hybrid inverters with LFP battery, via Modbus TCP.", @@ -150,6 +150,37 @@ local function known_to_have_no_battery() return model_family == "string" end +---------------------------------------------------------------------------- +-- What a failure proves +-- +-- A Modbus exception is the device itself saying no: it is up, and it does +-- not take that register. Anything else -- a refused or reset connection, a +-- timeout, FTW's reconnect backoff -- says only that the link is down, and +-- proves nothing about the register. +-- +-- FTW's random site rig showed what counting both costs (27 October 2026). +-- An inverter offline for 20 to 90 s failed every read and every write. The +-- driver counted those as refusals: it dropped 12999, 13000 and the PV +-- registers for the rest of the session, so FTW read the battery with the +-- wrong sign, and it stopped writing the EMS block, so the watchdog heard +-- that the default held while the inverter kept its last forced discharge. +-- +-- Codes 0x0A and 0x0B mean a gateway could not reach the device, and 0x06 +-- means it was busy. None of them says the register is absent. +local LINK_EXCEPTION_CODES = { [0x06] = true, [0x0A] = true, [0x0B] = true } + +local function device_refused(why) + if type(why) ~= "string" then return false end + local text = why:lower() + if text:find("gateway", 1, true) or text:find("busy", 1, true) then + return false + end + local code = text:match("exception.-code=0x(%x+)") + if code then return not LINK_EXCEPTION_CODES[tonumber(code, 16)] end + return text:find("modbus exception", 1, true) ~= nil + or text:find("illegal", 1, true) ~= nil +end + ---------------------------------------------------------------------------- -- The EMS control block, 13049-13051 -- @@ -186,19 +217,26 @@ end local EMS_WRITE_ATTEMPTS = 3 local ems_write_failures = 0 +-- Set once the device has taken forced mode from this driver, cleared once it +-- has taken the release. While set, the device may be holding a forced state, +-- so the release is always written and never reported as held unwritten. +local forced_mode_written = false + -- True while the EMS block is still worth writing unprompted. local function ems_block_worth_writing() - return ems_write_failures < EMS_WRITE_ATTEMPTS + return ems_write_failures < EMS_WRITE_ATTEMPTS or forced_mode_written end -- Record what the device did with one EMS operation. Counts the operation, -- not each of its three registers: the trio goes out together and fails --- together, so one rejected trio is one piece of evidence. +-- together, so one rejected trio is one piece of evidence. Only a refusal +-- from the device counts; a write that never reached it proves nothing. local function note_ems_write(write_err) if write_err == nil then ems_write_failures = 0 return end + if not device_refused(write_err) then return end ems_write_failures = ems_write_failures + 1 if ems_write_failures == EMS_WRITE_ATTEMPTS then host.log("info", "Sungrow: the EMS control block rejected " @@ -233,6 +271,44 @@ local function never_sent(ok, first, second) return type(why) == "string" and why:find("reconnect backoff", 1, true) ~= nil end +-- A failure that is not a refusal counts only if another read in the same +-- poll returned data: then the link was up and this register still did not +-- answer. A poll that read nothing is an outage, and the first poll that reads +-- again after one is a reconnect, which starts every count over. +local poll_read_data = false +local poll_unproved = {} +local link_down = false + +local function count_miss(address) + local misses = (miss_counts[address] or 0) + 1 + miss_counts[address] = misses + if misses >= MISSES_BEFORE_SKIP then + host.log("info", "Sungrow: register " .. address .. " failed " + .. misses .. " reads in a row; treating it as absent") + end +end + +local function begin_poll() + poll_read_data = false + poll_unproved = {} +end + +local function settle_poll() + if not poll_read_data then + link_down = true + return + end + if link_down then + link_down = false + miss_counts = {} + ems_write_failures = 0 + host.log("info", "Sungrow: the device answers again; " + .. "every register and the EMS block start over") + return + end + for _, address in ipairs(poll_unproved) do count_miss(address) end +end + local function optional_read(address, count, kind) if (miss_counts[address] or 0) >= MISSES_BEFORE_SKIP then return nil @@ -240,21 +316,24 @@ local function optional_read(address, count, kind) local ok, registers, err = pcall(host.modbus_read, address, count, kind) if never_sent(ok, registers, err) then return nil end -- Check every register asked for, not just the first. A short reply leaves - -- the rest nil, and arithmetic on nil ends the whole poll. + -- the rest nil, and arithmetic on nil ends the whole poll. The device did + -- reply, so a short reply counts like a refusal. + local short = false if ok and registers ~= nil then for i = 1, count do - if registers[i] == nil then ok = false break end + if registers[i] == nil then ok = false short = true break end end end if ok and registers ~= nil then miss_counts[address] = nil + poll_read_data = true return registers end - local misses = (miss_counts[address] or 0) + 1 - miss_counts[address] = misses - if misses >= MISSES_BEFORE_SKIP then - host.log("info", "Sungrow: register " .. address .. " failed " - .. misses .. " reads in a row; treating it as absent") + local why = ok and err or registers + if short or device_refused(why) then + count_miss(address) + else + poll_unproved[#poll_unproved + 1] = address end return nil end @@ -436,7 +515,7 @@ local function full_read_due(now_ms) or now_ms - last_full_read_ms >= FULL_READ_MS - POLL_MS / 2 end -function driver_poll() +local function read_and_emit() local now_ms = host.millis() local full = full_read_due(now_ms) if full then last_full_read_ms = now_ms end @@ -849,6 +928,13 @@ function driver_poll() return POLL_MS end +function driver_poll() + begin_poll() + local interval = read_and_emit() + settle_poll() + return interval +end + ---------------------------------------------------------------------------- -- Battery control ---------------------------------------------------------------------------- @@ -943,6 +1029,7 @@ function set_battery_power(power_w) local mode_err = host.modbus_write(13049, 2) -- 1. forced mode local cmd_err = host.modbus_write(13050, want_cmd) -- 2. charge/discharge cmd local power_err = host.modbus_write(13051, watts) -- 3. power setpoint + if mode_err == nil then forced_mode_written = true end local write_err = first_write_error(mode_err, cmd_err, power_err) -- A command always attempts, however many times the block has refused -- before: only the unprompted paths give up. But the outcome still counts, @@ -987,6 +1074,7 @@ function set_battery_idle() local mode_err = host.modbus_write(13049, 2) -- forced mode local cmd_err = host.modbus_write(13050, 0xCC) -- stop forced charge/discharge local power_err = host.modbus_write(13051, 0) -- zero power setpoint + if mode_err == nil then forced_mode_written = true end local write_err = first_write_error(mode_err, cmd_err, power_err) -- Reached by a zero-watt command, which 1.5.4 accepts on every family. -- It still attempts; the count only decides the unprompted paths. @@ -1020,10 +1108,11 @@ end -- write has to be let go of. function set_self_consumption() -- Nothing to hand back on a device that has refused this block three - -- times: a write it rejects cannot have latched a forced state. Report the - -- default as held rather than failed -- the watchdog reads a false as the - -- safe state being unreachable and escalates, which is the wrong answer - -- for an inverter that was never under control to begin with. + -- times and never took forced mode from this driver. Report the default + -- as held rather than failed -- the watchdog reads a false as the safe + -- state being unreachable and escalates, which is the wrong answer for an + -- inverter that was never under control to begin with. Once forced mode + -- has landed, ems_block_worth_writing stays true until the release lands. if not ems_block_worth_writing() then return true end @@ -1043,13 +1132,13 @@ function set_self_consumption() host.log("debug", "Sungrow: self-consumption mode") local ok, ems = pcall(host.modbus_read, 13049, 3, "holding") - if not ok or not ems then return true end - if ems[1] ~= 0 or ems[2] ~= 0xCC or ems[3] ~= 0 then + if ok and ems and (ems[1] ~= 0 or ems[2] ~= 0xCC or ems[3] ~= 0) then host.log("warn", string.format( "Sungrow: self-consumption reset not latched (mode=%d cmd=0x%02x power=%dW)", ems[1] or -1, ems[2] or -1, ems[3] or -1)) return false end + forced_mode_written = false return true end diff --git a/drivers/tests/test_sungrow_outage.py b/drivers/tests/test_sungrow_outage.py new file mode 100644 index 0000000..09157a5 --- /dev/null +++ b/drivers/tests/test_sungrow_outage.py @@ -0,0 +1,297 @@ +"""An inverter that drops off the network is not an inverter without registers. + +FTW's random site rig takes the Sungrow offline for 20 to 90 s and brings it +back (srcfl/ftw nightly, 27 October 2026). Every read and write fails while it +is gone, and none of those failures came from the device. Before 1.6.1 the +driver counted them as if they had: + +- reads: 12999, 13000 and the PV registers were dropped for the session. 13000 + signs the battery, so FTW read a discharge as a charge for the rest of the + run (seed 207539: 105 samples). +- writes: three failed EMS writes marked the block absent, so the release was + reported as held without being written, while the inverter kept the last + forced discharge (seed 207534: 5000 W for up to five minutes). + +Only a Modbus exception, the device's own refusal, proves a register absent. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +LUA = ROOT / "lua55" +HARNESS = ROOT / "drivers" / "tests" / "lua_harness" +DRIVER = ROOT / "drivers" / "lua" / "sungrow.lua" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + +HEALTHY_HYBRID = ''' +host._modbus_registers.input[4999] = {0x0E0E} +host._modbus_registers.input[5000] = {100} +host._modbus_registers.input[5016] = {4000, 0} +host._modbus_registers.input[12999] = {0x0000} +host._modbus_registers.input[13000] = {0x0004} -- bit 2 set: discharging +host._modbus_registers.input[13002] = {5000, 0} +host._modbus_registers.input[13019] = {4800, 120, 900, 550} +host._modbus_registers.input[13026] = {1000, 0} +host._modbus_registers.input[13036] = {2000, 0} +host._modbus_registers.input[13040] = {3000, 0} +host._modbus_registers.input[13045] = {4000, 0} +host._modbus_registers.input[5600] = {1500, 0} +''' + +# What FTW's host hands the driver while the device is gone. The first is the +# dial error the rig logged; the last two are what a Modbus gateway answers +# when it cannot reach the device behind it. +LINK_ERRORS = [ + "dial tcp 127.0.0.1:502: connect: connection refused", + "read after reconnect: modbus reconnect backoff active for 1.243s " + "(original: EOF)", + "modbus transport failure: i/o timeout", + "modbus exception function=0x03 code=0x0b", + "modbus exception function=0x06 code=0x0a", +] + +REFUSAL = "modbus exception function=0x06 code=0x02" + + +def run_lua(body: str) -> dict[str, str]: + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() +host._millis_step = 1000 -- one poll a second, a full read every five +{HEALTHY_HYBRID} +dofile("{DRIVER}") +driver_init({{}}) +for _ = 1, 3 do driver_poll() end +{body} +''' + result = subprocess.run([str(LUA), "-e", script], + capture_output=True, text=True, cwd=ROOT) + assert result.returncode == 0, result.stdout + result.stderr + return dict(line.split(" ", 1) + for line in result.stdout.strip().splitlines() if " " in line) + + +def offline(err: str, polls: int = 5, defaults: int = 5) -> str: + return f''' +host._modbus_read_error = "{err}" +host._modbus_write_error = "{err}" +for _ = 1, {polls} do driver_poll() end +for _ = 1, {defaults} do driver_default_mode() end +host._modbus_read_error = nil +host._modbus_write_error = nil +''' + + +def reads_on_next_poll() -> str: + return ''' +local before = #host._calls +driver_poll() +local read = {} +for i = before + 1, #host._calls do + local call = host._calls[i] + if call.func == "modbus_read" then read[call.args[1]] = true end +end +for _, addr in ipairs({12999, 13000, 5016, 5010}) do + print("READ_" .. addr .. " " .. tostring(read[addr] == true)) +end +local emits = host._emitted.battery +print("BATTERY_W " .. tostring(emits[#emits].w)) +''' + + +@pytest.mark.parametrize("err", LINK_ERRORS) +def test_an_outage_does_not_drop_registers(err: str) -> None: + """The device comes back; so must 13000 and the PV registers.""" + # Five polls: one full read lands every five, so 12999 is read too. + out = run_lua(offline(err, polls=12, defaults=0) + + "for _ = 1, 4 do driver_poll() end\n" + + reads_on_next_poll()) + + for addr in (13000, 5016, 5010): + assert out[f"READ_{addr}"] == "true", ( + f"register {addr} was not read after the device came back: the " + f"outage ({err!r}) was counted as proof it is absent. {out}") + assert out["BATTERY_W"] == "-900", ( + f"the battery discharges at 900 W but reads {out['BATTERY_W']}: " + f"13000, which signs it, was dropped during the outage") + + +def test_an_outage_does_not_drop_the_running_state() -> None: + """12999 is read on full polls only, so check it across five.""" + out = run_lua(offline(LINK_ERRORS[0], polls=20, defaults=0) + ''' +local before = #host._calls +for _ = 1, 6 do driver_poll() end +local seen = false +for i = before + 1, #host._calls do + local call = host._calls[i] + if call.func == "modbus_read" and call.args[1] == 12999 then seen = true end +end +print("READ_12999 " .. tostring(seen)) +''') + assert out["READ_12999"] == "true", out + + +def test_a_refused_register_is_still_given_up_while_others_answer() -> None: + """The bound still works: an exception is the device saying no.""" + out = run_lua(''' +host._modbus_read_fail_addresses[5743] = "Illegal Data Address" +for _ = 1, 4 do driver_poll() end +''' + ''' +local before = #host._calls +driver_poll() +local read = false +for i = before + 1, #host._calls do + if host._calls[i].func == "modbus_read" and host._calls[i].args[1] == 5743 then + read = true + end +end +print("READ_5743 " .. tostring(read)) +''') + assert out["READ_5743"] == "false", "a refused register was read forever" + + +def test_a_timeout_on_one_register_counts_while_the_rest_answer() -> None: + """A transport-shaped failure still counts when the link is plainly up.""" + out = run_lua(''' +host._modbus_read_fail_addresses[5743] = "i/o timeout" +for _ = 1, 4 do driver_poll() end +local before = #host._calls +driver_poll() +local read = false +for i = before + 1, #host._calls do + if host._calls[i].func == "modbus_read" and host._calls[i].args[1] == 5743 then + read = true + end +end +print("READ_5743 " .. tostring(read)) +''') + assert out["READ_5743"] == "false", ( + "a register that times out while every other read answers was read " + "forever") + + +def test_a_reconnect_starts_the_read_count_over() -> None: + """Two refusals, an outage, then one more refusal: not yet three.""" + out = run_lua(''' +host._modbus_read_fail_addresses[5743] = "Illegal Data Address" +driver_poll() +driver_poll() +host._modbus_read_error = "dial tcp 127.0.0.1:502: connect: connection refused" +driver_poll() +host._modbus_read_error = nil +driver_poll() +local before = #host._calls +driver_poll() +local read = false +for i = before + 1, #host._calls do + if host._calls[i].func == "modbus_read" and host._calls[i].args[1] == 5743 then + read = true + end +end +print("READ_5743 " .. tostring(read)) +''') + assert out["READ_5743"] == "true", ( + "misses counted before an outage carried over the reconnect") + + +def forced_then(body: str) -> str: + return ''' +print("FORCED " .. tostring(driver_command("battery", -3000, {}) == true)) +''' + body + ''' +host._modbus_write_attempts = 0 +local held = driver_default_mode() +print("RELEASE_WRITES " .. tostring(host._modbus_write_attempts)) +print("RELEASED " .. tostring(held == true)) +print("MODE " .. tostring(host._modbus_registers.holding[13049])) +''' + + +@pytest.mark.parametrize("err", LINK_ERRORS) +def test_the_release_is_written_when_the_device_returns(err: str) -> None: + """Seeds 207533-207539: a forced discharge outlived the outage.""" + out = run_lua(forced_then(offline(err))) + + assert out["FORCED"] == "true" + assert int(out["RELEASE_WRITES"]) >= 3, ( + f"the inverter came back holding forced discharge and the watchdog's " + f"release wrote {out['RELEASE_WRITES']} registers. The outage " + f"({err!r}) was counted as the device refusing the EMS block.") + assert out["MODE"] == "0", f"EMS mode left at {out['MODE']}, not 0" + assert out["RELEASED"] == "true" + + +def test_the_release_is_never_reported_held_while_forced_mode_may_be_latched() -> None: + """Even three real refusals do not excuse it once forced mode landed.""" + out = run_lua(forced_then(f''' +host._modbus_write_error = "{REFUSAL}" +local answers = {{}} +for _ = 1, 5 do answers[#answers + 1] = tostring(driver_default_mode()) end +print("DURING " .. table.concat(answers, ",")) +host._modbus_write_error = nil +''')) + + assert "true" not in out["DURING"].split(","), ( + f"driver_default_mode reported the default held without writing it: " + f"{out['DURING']}. This driver put the inverter in forced mode, so " + f"the inverter may still be holding it.") + assert int(out["RELEASE_WRITES"]) >= 3 + assert out["MODE"] == "0" + + +def test_failures_during_an_outage_report_the_release_as_failed() -> None: + """While nothing reaches the device, the honest answer is false.""" + out = run_lua(forced_then(''' +host._modbus_read_error = "dial tcp 127.0.0.1:502: connect: connection refused" +host._modbus_write_error = host._modbus_read_error +local answers = {} +for _ = 1, 5 do answers[#answers + 1] = tostring(driver_default_mode()) end +print("DURING " .. table.concat(answers, ",")) +host._modbus_read_error = nil +host._modbus_write_error = nil +''')) + assert out["DURING"] == ",".join(["false"] * 5), out["DURING"] + + +def test_a_reconnect_starts_the_write_count_over() -> None: + """Two refusals, an outage, then two more: not yet three in a row.""" + out = run_lua(f''' +host._modbus_write_error = "{REFUSAL}" +driver_default_mode() +driver_default_mode() +host._modbus_write_error = nil +host._modbus_read_error = "dial tcp 127.0.0.1:502: connect: connection refused" +driver_poll() +host._modbus_read_error = nil +driver_poll() +host._modbus_write_error = "{REFUSAL}" +driver_default_mode() +driver_default_mode() +host._modbus_write_attempts = 0 +driver_default_mode() +print("WRITES " .. tostring(host._modbus_write_attempts)) +''') + assert int(out["WRITES"]) >= 3, ( + "refusals counted before an outage carried over the reconnect") + + +def test_a_device_that_refuses_the_block_still_settles() -> None: + """The SG12RT rule from 1.5.7 holds: never forced, three refusals, stop.""" + out = run_lua(f''' +host._modbus_write_error = "{REFUSAL}" +local writes = {{}} +for _ = 1, 6 do + host._modbus_write_attempts = 0 + driver_default_mode() + writes[#writes + 1] = host._modbus_write_attempts +end +print("WRITES " .. table.concat(writes, ",")) +''') + assert out["WRITES"].split(",")[-3:] == ["0", "0", "0"], out["WRITES"] diff --git a/index.yaml b/index.yaml index e2744f1..b701ed6 100644 --- a/index.yaml +++ b/index.yaml @@ -710,14 +710,14 @@ drivers: size_bytes: 6631 sha256: "94ae5e0065f5793051acb89b7ef04a679b2898908dfac6f4ffd6e8deb77fa2c0" - name: "sungrow" - version: "1.6.0" + version: "1.6.1" tier: core protocol: modbus connectivity: local ders: [battery, meter, pv] control: true - size_bytes: 52811 - sha256: "db4e378f49f6421c93621e0f101f00c64e5459a38190171003476f9f2b2cc4c1" + size_bytes: 56325 + sha256: "b89fd9cd70ea67be3c7f0089a3c6d5552d8bbc994e39b8720dbd8d4d9892261b" - name: "tesla_cloud" version: "0.2.0" tier: community diff --git a/manifests/sungrow.yaml b/manifests/sungrow.yaml index 0f32ba3..cfe3857 100644 --- a/manifests/sungrow.yaml +++ b/manifests/sungrow.yaml @@ -1,5 +1,5 @@ name: "sungrow" -version: "1.6.0" +version: "1.6.1" tier: core author: "Sourceful Labs AB" protocol: modbus @@ -43,9 +43,9 @@ tested_devices: notes: "Commercial/industrial three-phase string inverter. Needs 1.5.3: 1.2.1 stopped polling the SH battery registers this family does not answer, and 1.5.3 refuses a battery dispatch instead of writing them. A zero-watt command is still written on every family from 1.5.4 -- it is the release, and on a model without the registers it fails harmlessly." min_driver_version: "1.5.3" min_host_version: "2.0.0" -size_bytes: 52811 +size_bytes: 56325 dkb_id: "sungrow_sh_rt" -sha256: "db4e378f49f6421c93621e0f101f00c64e5459a38190171003476f9f2b2cc4c1" +sha256: "b89fd9cd70ea67be3c7f0089a3c6d5552d8bbc994e39b8720dbd8d4d9892261b" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index 054edf7..4f61ce4 100644 --- a/support-status.json +++ b/support-status.json @@ -1619,7 +1619,7 @@ }, { "catalog_source": true, - "catalog_version": "1.6.0", + "catalog_version": "1.6.1", "driver_id": "sungrow", "targets": { "blixt-l1": { From 107eb609e38eced5f88af383107733a28993554b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Mon, 2 Nov 2026 11:08:55 +0100 Subject: [PATCH 2/8] fix(tesla_wall_connector): no charge power through an open contactor (0.1.2) (#204) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(tesla_wall_connector): idle unit must report 0 W The vitals of an idle Gen 3 (no car, contactor open, 0 V on every leg, 0.8 A and 0.6 A of sensor offset) give 184 W today: the same number a field connection test showed. Adds the idle, car-waiting and charging cases. Fails on 0.1.1. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren * fix(tesla_wall_connector): no charge power through an open contactor (0.1.2) With the contactor open the output legs read 0 V, the leg sum was 0, and the driver fell back to grid_v × vehicle_current_a. That multiplied the grid-side voltage by the sensor offset of an idle unit and reported about 180-290 W to a car that was not there. Charge power and charging now need a closed contactor and a car on the cable. A reply without contactor_closed falls back to the EVSE charging states. Power through a closed contactor is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren * fix(tesla_wall_connector): contactor field first, grid_v only with no leg voltage From review. An explicit contactor_closed now goes before vehicle_connected: the contactor is the physical switch, and a status flag should not cancel volts and amps measured through it. With that order, a closed contactor with every leg at 0 V would still have reached the grid_v fallback, so the fallback now runs only when the reply has no leg voltage at all. A leg that reads 0 V carries no power, as in Home Assistant's own calculation. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --------- Signed-off-by: Fredrik Ahlgren Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 21 +++ SUPPORT_STATUS.md | 4 +- devices.yaml | 2 +- drivers/lua/tesla_wall_connector.lua | 46 ++++--- .../lua_harness/test_tesla_wall_connector.lua | 130 ++++++++++++++++++ drivers/tests/test_tesla_wall_connector.py | 12 ++ index.yaml | 6 +- manifests/tesla_wall_connector.yaml | 6 +- support-status.json | 2 +- 9 files changed, 199 insertions(+), 30 deletions(-) create mode 100644 drivers/tests/lua_harness/test_tesla_wall_connector.lua create mode 100644 drivers/tests/test_tesla_wall_connector.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 399f8d4..f50a0d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ ## [Unreleased] +### tesla_wall_connector 0.1.2 + +An idle Wall Connector no longer shows charge power. With no car on the +cable and the contactor open, the unit reads 0 V on its output legs and +about 0.5–1 A of sensor offset. The leg sum was 0, so the driver fell back to +`grid_v × vehicle_current_a`: the voltage on the grid side of the open +contactor times the offset. One field report showed 184 W, and 284 W in the +flow diagram, with no car present. That fallback is the only path in 0.1.1 +that gives power with every leg at 0 V. + +- Charge power and `charging` now need a closed contactor. A reply without + `contactor_closed` falls back to `vehicle_connected` and then the EVSE + charging states. +- The `grid_v` fallback now runs only when the reply has no leg voltage at + all. A leg that reads 0 V carries no power. +- Split-phase installs and measured leg power through a closed contactor do + not change. + +FTW's bundled copy does not move with this commit. Bump the pin and run +`scripts/sync-bundled-drivers.sh`. + ### sungrow 1.6.1 An inverter that drops off the network no longer loses registers or its diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 2285c99..21ef6ad 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -164,8 +164,8 @@ Catalog source is not proof that a target can install or run a driver. | tesla_cloud | 0.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | tesla_vehicle | 0.2.6 | ftw-core | not_assessed | — | not_recorded | not_assessed | | tesla_vehicle | 0.2.6 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| tesla_wall_connector | 0.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| tesla_wall_connector | 0.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| tesla_wall_connector | 0.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| tesla_wall_connector | 0.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | teslamate_vehicle | 0.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | teslamate_vehicle | 0.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | tibber | 1.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 723fd8b..cb0dd99 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1852,7 +1852,7 @@ manufacturers: protocols: - protocol: http driver: "tesla_wall_connector" - version: "0.1.1" + version: "0.1.2" ders: [ev] control: false firmware_versions: "" diff --git a/drivers/lua/tesla_wall_connector.lua b/drivers/lua/tesla_wall_connector.lua index 985895e..85e67b7 100644 --- a/drivers/lua/tesla_wall_connector.lua +++ b/drivers/lua/tesla_wall_connector.lua @@ -26,7 +26,7 @@ DRIVER = { id = "tesla_wall_connector", name = "Tesla Wall Connector", manufacturer = "Tesla", - version = "0.1.1", + version = "0.1.2", protocols = { "http" }, capabilities = { "ev" }, read_only = true, @@ -131,20 +131,31 @@ local function phase_power(v, a) return v * a end -local function charge_power(vitals) - if split_phase then - local w = (as_number(vitals.grid_v) or 0) * (as_number(vitals.vehicle_current_a) or 0) - if w < 0 then w = 0 end - return w +-- The contactor joins the car to the grid and closes only with a car on +-- the cable. While it is open no current reaches a car: an idle unit still +-- reads about 0.5–1 A of sensor offset on its legs, and that is not load. +-- A reply without contactor_closed falls back to vehicle_connected and +-- the EVSE state. +local function contactor_closed(state, vitals) + if vitals.contactor_closed ~= nil then return vitals.contactor_closed == true end + if vitals.vehicle_connected == false then return false end + return state == EVSE_CHARGE_LOW or state == EVSE_CHARGE_FULL +end + +local function charge_power(state, vitals) + if not contactor_closed(state, vitals) then return 0 end + local grid_w = (as_number(vitals.grid_v) or 0) * (as_number(vitals.vehicle_current_a) or 0) + if grid_w < 0 then grid_w = 0 end + if split_phase then return grid_w end + -- The legs are measured on the car side of the contactor. Only a reply + -- with no leg voltage at all falls back to the grid voltage; a leg that + -- reads 0 V carries no power. + if vitals.voltageA_v == nil and vitals.voltageB_v == nil and vitals.voltageC_v == nil then + return grid_w end - local w = phase_power(vitals.voltageA_v, vitals.currentA_a) + return phase_power(vitals.voltageA_v, vitals.currentA_a) + phase_power(vitals.voltageB_v, vitals.currentB_a) + phase_power(vitals.voltageC_v, vitals.currentC_a) - if w <= 0 then - local fallback = (as_number(vitals.grid_v) or 0) * (as_number(vitals.vehicle_current_a) or 0) - if fallback > 0 then w = fallback end - end - return w end local function active_phases(vitals) @@ -156,16 +167,11 @@ local function active_phases(vitals) return n end -local function is_charging(state, vitals) - if state == EVSE_CHARGE_LOW or state == EVSE_CHARGE_FULL then return true end - return vitals.contactor_closed == true -end - local function is_connected(state, vitals) if vitals.vehicle_connected == true then return true end return state == EVSE_CONNECTED or state == EVSE_READY or state == EVSE_HANDSHAKE or state == EVSE_FINISHED - or state == EVSE_WAIT_CAR or is_charging(state, vitals) + or state == EVSE_WAIT_CAR or contactor_closed(state, vitals) end function driver_init(config) @@ -209,10 +215,10 @@ function driver_poll() end local state = as_number(vitals.evse_state) or EVSE_IDLE - local power_w = charge_power(vitals) + local power_w = charge_power(state, vitals) local session_wh = as_number(vitals.session_energy_wh) or 0 local connected = is_connected(state, vitals) - local charging = is_charging(state, vitals) + local charging = contactor_closed(state, vitals) local phases = active_phases(vitals) host.emit("ev", { diff --git a/drivers/tests/lua_harness/test_tesla_wall_connector.lua b/drivers/tests/lua_harness/test_tesla_wall_connector.lua new file mode 100644 index 0000000..1831c39 --- /dev/null +++ b/drivers/tests/lua_harness/test_tesla_wall_connector.lua @@ -0,0 +1,130 @@ +-- Tesla Wall Connector Gen 3: charge power comes only through a closed +-- contactor with a car on the cable, from measured volts and amps. +dofile("drivers/tests/lua_harness/host_mock.lua") + +local BASE = "http://wc.test" + +local function poll(vitals, config) + host.reset() + host._http_responses[BASE .. "/api/1/version"] = + '{"serial_number":"TWC-SN-1","part_number":"1529455-02-J","firmware_version":"24.36.3"}' + host._http_responses[BASE .. "/api/1/vitals"] = vitals + dofile("drivers/lua/tesla_wall_connector.lua") + config = config or {} + config.base_url = BASE + driver_init(config) + assert(driver_poll() == 5000) + local ev = host._emitted.ev + assert(ev and #ev == 1, "one ev reading per poll") + return ev[1] +end + +local function near(got, want, tol, label) + assert(math.abs(got - want) <= tol, + string.format("%s: got %.1f W, want %.1f W", label, got, want)) +end + +-- A real idle unit: no car, contactor open, 0 V on every output leg, and +-- 0.8 A and 0.6 A of sensor offset on legs A and B. The connection test +-- read EV 184 W, which is grid_v × vehicle_current_a (230 V × 0.8 A). +-- The report did not show those two fields; these are the values that +-- give 184 W. +local idle = [[{"contactor_closed":false,"vehicle_connected":false,"session_s":0, +"grid_v":230.0,"grid_hz":50.01,"vehicle_current_a":0.8, +"currentA_a":0.8,"currentB_a":0.6,"currentC_a":0.0,"currentN_a":0.0, +"voltageA_v":0.0,"voltageB_v":0.0,"voltageC_v":0.0, +"relay_coil_v":11.9,"pcba_temp_c":21.3,"handle_temp_c":14.2,"mcu_temp_c":27.5, +"uptime_s":86400,"input_thermopile_uv":-210,"prox_v":0.0, +"pilot_high_v":11.9,"pilot_low_v":11.9,"session_energy_wh":0.0, +"config_status":5,"evse_state":1,"current_alerts":[]}]] +local r = poll(idle) +assert(r.w == 0, "idle unit with open contactor reported " .. tostring(r.w) .. " W") +assert(r.connected == false and r.charging == false) +assert(host._metrics.ev_power_w.value == 0, "ev_power_w must match w") +-- The raw sensor reading stays visible as a diagnostic. +assert(host._metrics.ev_l1_a.value == 0.8 and host._metrics.ev_l1_v.value == 0) + +-- A larger offset sample is still no load. The same report's flow +-- diagram showed 284 W; 1.2 A × 236.7 V is one pair that gives it. +r = poll((idle:gsub('"vehicle_current_a":0.8', '"vehicle_current_a":1.2') + :gsub('"grid_v":230.0', '"grid_v":236.7'))) +assert(r.w == 0, "offset sample reported " .. tostring(r.w) .. " W") + +-- A reply without contactor_closed: no car means no charge power. +r = poll('{"vehicle_connected":false,"evse_state":1,"grid_v":230,"vehicle_current_a":0.8,' + .. '"currentA_a":0.8,"currentB_a":0.6,"voltageA_v":0,"voltageB_v":0,"voltageC_v":0}') +assert(r.w == 0 and r.charging == false) + +-- Car on the cable, contactor open (waiting or finished): still no load. +r = poll((idle:gsub('"vehicle_connected":false', '"vehicle_connected":true') + :gsub('"evse_state":1', '"evse_state":9'))) +assert(r.w == 0, "open contactor with car reported " .. tostring(r.w) .. " W") +assert(r.connected == true and r.charging == false) + +-- The EVSE state alone does not close the contactor. +r = poll((idle:gsub('"vehicle_connected":false', '"vehicle_connected":true') + :gsub('"evse_state":1', '"evse_state":11'))) +assert(r.w == 0 and r.charging == false, "state 11 with open contactor") + +-- A contactor that says closed while every leg reads 0 V: the grid +-- voltage must not stand in for the 0 V the charger measured. +r = poll((idle:gsub('"contactor_closed":false', '"contactor_closed":true'))) +assert(r.w == 0, "closed contactor at 0 V reported " .. tostring(r.w) .. " W") + +-- Split-phase installs use grid_v × vehicle_current_a: the same gate holds. +r = poll(idle, { split_phase = true }) +assert(r.w == 0, "split-phase idle reported " .. tostring(r.w) .. " W") + +-- Three-phase charging: the sum of measured V × A on each leg, positive. +local charging3 = [[{"contactor_closed":true,"vehicle_connected":true,"session_s":1800, +"grid_v":230.0,"grid_hz":50.0,"vehicle_current_a":16.0, +"currentA_a":16.1,"currentB_a":16.0,"currentC_a":16.2,"currentN_a":0.3, +"voltageA_v":230.0,"voltageB_v":229.5,"voltageC_v":230.4, +"session_energy_wh":4200.0,"config_status":5,"evse_state":11,"current_alerts":[]}]] +r = poll(charging3) +-- 230×16.1 + 229.5×16.0 + 230.4×16.2 = 11107.48 +near(r.w, 11107.48, 0.01, "three-phase charging") +assert(r.connected == true and r.charging == true and r.phases == 3) +assert(r.session_wh == 4200) +assert(host._metrics.ev_power_w.value == r.w) + +-- One-phase car: unused legs sit at a few volts and do not count. +r = poll([[{"contactor_closed":true,"vehicle_connected":true,"grid_v":230, +"vehicle_current_a":16,"currentA_a":16,"currentB_a":0.2,"currentC_a":0.1, +"voltageA_v":230,"voltageB_v":2.4,"voltageC_v":1.8,"session_energy_wh":100,"evse_state":11}]]) +near(r.w, 3680, 0.01, "one-phase charging") +assert(r.phases == 1 and r.charging == true) + +-- Power measured through a closed contactor counts even if the cable +-- flag disagrees: a status flag does not cancel measured volts and amps. +r = poll([[{"contactor_closed":true,"vehicle_connected":false,"grid_v":230, +"vehicle_current_a":16,"currentA_a":16,"voltageA_v":230,"voltageB_v":0,"voltageC_v":0, +"session_energy_wh":1,"evse_state":11}]]) +near(r.w, 3680, 0.01, "closed contactor, measured leg") + +-- Contactor closed, legs read about 0 V: no power from grid_v. +r = poll([[{"contactor_closed":true,"vehicle_connected":true,"grid_v":230, +"vehicle_current_a":10,"voltageA_v":2,"voltageB_v":1,"voltageC_v":0, +"session_energy_wh":1,"evse_state":11}]]) +assert(r.w == 0, "legs at 0 V reported " .. tostring(r.w) .. " W") + +-- A reply with no leg voltage at all: the car sees the measured grid +-- voltage through the closed contactor. +r = poll([[{"contactor_closed":true,"vehicle_connected":true,"grid_v":230, +"vehicle_current_a":10,"session_energy_wh":1,"evse_state":11}]]) +near(r.w, 2300, 0.01, "no leg voltages, grid voltage") + +-- Split-phase charging: grid_v × vehicle_current_a. +r = poll([[{"contactor_closed":true,"vehicle_connected":true,"grid_v":240, +"vehicle_current_a":32,"currentA_a":40,"currentB_a":40, +"voltageA_v":120,"voltageB_v":120,"session_energy_wh":50,"evse_state":11}]], + { split_phase = true }) +near(r.w, 7680, 0.01, "split-phase charging") + +-- A reply without contactor_closed falls back to the EVSE state. +r = poll([[{"vehicle_connected":true,"evse_state":11,"grid_v":230,"vehicle_current_a":16, +"currentA_a":16,"voltageA_v":230,"voltageB_v":0,"voltageC_v":0}]]) +near(r.w, 3680, 0.01, "no contactor field, charging state") +assert(r.charging == true) + +print("tesla_wall_connector: all cases pass") diff --git a/drivers/tests/test_tesla_wall_connector.py b/drivers/tests/test_tesla_wall_connector.py new file mode 100644 index 0000000..e697309 --- /dev/null +++ b/drivers/tests/test_tesla_wall_connector.py @@ -0,0 +1,12 @@ +"""Tesla Wall Connector reports charge power only through a closed contactor.""" +from pathlib import Path +import subprocess + + +def test_tesla_wall_connector_charge_power(): + root = Path(__file__).resolve().parents[2] + result = subprocess.run( + [str(root / "lua55"), "drivers/tests/lua_harness/test_tesla_wall_connector.lua"], + cwd=root, text=True, capture_output=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/index.yaml b/index.yaml index b701ed6..e66f04c 100644 --- a/index.yaml +++ b/index.yaml @@ -739,14 +739,14 @@ drivers: size_bytes: 10096 sha256: "d1b8a2cbea20630dcab3cb306df0f6924b0f9ad7f31bcf367fb1d41ca7833350" - name: "tesla_wall_connector" - version: "0.1.1" + version: "0.1.2" tier: community protocol: http connectivity: local ders: [ev] control: false - size_bytes: 8162 - sha256: "66b6313eda4f68a92a7cc55931baa2408cb6cbb249145f7e6005456fb821d284" + size_bytes: 8786 + sha256: "c365aad2a1216fad870b7dadb32e87feed75627714eeb8160f22cec4db651a80" - name: "teslamate_vehicle" version: "0.2.0" tier: community diff --git a/manifests/tesla_wall_connector.yaml b/manifests/tesla_wall_connector.yaml index f037d4f..a2870a1 100644 --- a/manifests/tesla_wall_connector.yaml +++ b/manifests/tesla_wall_connector.yaml @@ -1,5 +1,5 @@ name: "tesla_wall_connector" -version: "0.1.1" +version: "0.1.2" tier: community author: "Sourceful Labs AB" protocol: http @@ -15,9 +15,9 @@ tested_devices: notes: "Tesla Wall Connector Gen 3 on the LAN. Observation only; no local current setpoint." min_driver_version: "0.1.0" min_host_version: "2.0.0" -size_bytes: 8162 +size_bytes: 8786 dkb_id: "tesla_wall_connector" -sha256: "66b6313eda4f68a92a7cc55931baa2408cb6cbb249145f7e6005456fb821d284" +sha256: "c365aad2a1216fad870b7dadb32e87feed75627714eeb8160f22cec4db651a80" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index 4f61ce4..aa17b7b 100644 --- a/support-status.json +++ b/support-status.json @@ -1682,7 +1682,7 @@ }, { "catalog_source": true, - "catalog_version": "0.1.1", + "catalog_version": "0.1.2", "driver_id": "tesla_wall_connector", "targets": { "blixt-l1": { From d662c3eb1910b999b2ad6aa4a1275e789c6897b3 Mon Sep 17 00:00:00 2001 From: murwall Date: Wed, 4 Nov 2026 11:01:08 +0100 Subject: [PATCH 3/8] fix(zap): read the meter DER under data model v2 (#208) Some Zap gateway firmware serves the local API in data model v2 (srcful-data-models 2.3.0): every meter field gets an "_ac" suffix and the L1/L2/L3 phase prefix is lowercased (W -> W_ac, L1_V -> l1_V_ac; Hz is unchanged). emit_meter read the v1 names unconditionally, so a Zap on v2 firmware gave FTW no meter reading at all. Add raw_field(), which tries the v1 name, then the _ac suffix, then the lowercased-prefix _ac variant -- no explicit version branch needed. Scoped to the meter DER only; pv/battery have the identical assumption against v2's _ac/_dc split and are left to #170, since this site runs read_pv/read_battery both false and I have no v2 hardware with those enabled to verify against. Fixes (partially) #170. Signed-off-by: Marcus Murwall --- CHANGELOG.md | 21 +++++ SUPPORT_STATUS.md | 4 +- devices.yaml | 2 +- drivers/lua/zap.lua | 29 +++++- .../lua_harness/test_zap_meter_schema.lua | 93 +++++++++++++++++++ drivers/tests/test_zap_meter_schema.py | 46 +++++++++ index.yaml | 6 +- manifests/zap.yaml | 6 +- support-status.json | 2 +- 9 files changed, 196 insertions(+), 13 deletions(-) create mode 100644 drivers/tests/lua_harness/test_zap_meter_schema.lua create mode 100644 drivers/tests/test_zap_meter_schema.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f50a0d9..b8194d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ ## [Unreleased] +### zap 3.1.2 + +The P1/HAN site meter reads again on Zap firmware serving the data model v2 +local API. That firmware renames every meter field with an `_ac` suffix and +lowercases the `L1`/`L2`/`L3` phase prefix (`W` → `W_ac`, `L1_V` → `l1_V_ac`; +`Hz` is unchanged). `emit_meter` read the v1 names unconditionally, so a Zap +on v2 firmware gave FTW no meter reading at all — `driver_poll` logged +`Zap: site-meter payload unavailable` every cycle and FTW lost its site +meter, with no site meter data for the home's grid import/export. + +- `emit_meter` now tries the v1 field name first, then the `_ac` suffix, + then the lowercased-phase-prefix `_ac` variant, so it reads either + firmware generation without checking `version` explicitly. +- Scoped to the meter DER only. `pv`/`battery` (`emit_pv`/`emit_battery`) + have the identical `.W`-style field assumption against v2 and are not + covered here — see #170 for that broader scope (`pv` → `solar` rename, + `_dc`/`_ac` split, `null`-vs-`0` handling). + +FTW's bundled copy does not move with this commit. Bump the pin and run +`scripts/sync-bundled-drivers.sh`. + ### tesla_wall_connector 0.1.2 An idle Wall Connector no longer shows charge power. With no car on the diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 21ef6ad..ec9152b 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -180,8 +180,8 @@ Catalog source is not proof that a target can install or run a driver. | victron_mqtt | 1.0.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.0.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.0.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| zap | 3.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| zap | 3.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| zap | 3.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| zap | 3.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | zaptec | 1.0.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | zaptec | 1.0.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | zaptec_cloud | 0.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index cb0dd99..f1df6c2 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1749,7 +1749,7 @@ manufacturers: protocols: - protocol: http driver: "zap" - version: "3.1.1" + version: "3.1.2" ders: [meter, pv, battery] control: false firmware_versions: "" diff --git a/drivers/lua/zap.lua b/drivers/lua/zap.lua index 721c010..06dec0b 100644 --- a/drivers/lua/zap.lua +++ b/drivers/lua/zap.lua @@ -31,6 +31,14 @@ -- meter: +W import, -W export -- pv: -W generation -- battery:+W charge, -W discharge +-- +-- Meter schema compatibility: some Zap firmware serves the local data model +-- v2 (srcful-data-models 2.3.0, "version":"v2" in /data/json), which renames +-- every meter field with an "_ac" suffix and lowercases the L1/L2/L3 phase +-- prefix (e.g. "L1_V" -> "l1_V_ac", "W" -> "W_ac"; "Hz" is unchanged either +-- way). This driver reads both v1 and v2 field names for the meter DER; see +-- https://github.com/srcfl/device-drivers/issues/170 for the full v2 scope +-- (pv -> solar, battery, DC/AC split), which is not yet covered here. DRIVER = { host_api_min = 1, @@ -38,7 +46,7 @@ DRIVER = { id = "zap", name = "Sourceful Zap (P1/HAN meter)", manufacturer = "Sourceful", - version = "3.1.1", + version = "3.1.2", protocols = { "http" }, capabilities = { "meter", "pv", "battery" }, read_only = true, @@ -377,15 +385,30 @@ local meter_fields = { { "total_export_wh", "total_export_Wh", "Wh" }, } +-- Data model v2 renames every meter field with an "_ac" suffix and +-- lowercases the L1/L2/L3 phase prefix (e.g. "L1_V" -> "l1_V_ac"); "Hz" is +-- unchanged. Try the v1 name first, then the v2 variants, so this driver +-- reads either firmware generation without needing to branch on "version". +local function raw_field(raw, name) + if raw[name] ~= nil then return raw[name] end + if raw[name .. "_ac"] ~= nil then return raw[name .. "_ac"] end + local lowered = name:gsub("^L(%d)_", "l%1_") + if lowered ~= name then + if raw[lowered] ~= nil then return raw[lowered] end + if raw[lowered .. "_ac"] ~= nil then return raw[lowered .. "_ac"] end + end + return nil +end + local function emit_meter(data) if type(data) ~= "table" or type(data.meter) ~= "table" then return false end local raw = data.meter - local w = number(raw.W) + local w = number(raw_field(raw, "W")) if w == nil then return false end local meter_reading = { w = w } for _, mapping in ipairs(meter_fields) do - local value = number(raw[mapping[2]]) + local value = number(raw_field(raw, mapping[2])) if value ~= nil then meter_reading[mapping[1]] = value host.emit_metric("meter_" .. mapping[1], value, mapping[3]) diff --git a/drivers/tests/lua_harness/test_zap_meter_schema.lua b/drivers/tests/lua_harness/test_zap_meter_schema.lua new file mode 100644 index 0000000..4dc7e87 --- /dev/null +++ b/drivers/tests/lua_harness/test_zap_meter_schema.lua @@ -0,0 +1,93 @@ +-- Exercise zap.lua's meter field reading against both the v1 and v2 Zap +-- local API field names. Run with the scenario as arg[1]: "v1" or "v2". +-- +-- This file is a draft for drivers/tests/lua_harness/test_zap_meter_schema.lua +-- in srcfl/device-drivers — see pr-drafts/README.md for how this fits that +-- repo's `make test-driver ID=zap` harness. Not run against the real harness +-- yet (no local checkout with lua55/pytest); matches the structure of the +-- existing drivers/tests/lua_harness/test_esphome_dsmr_aliases.lua, which +-- solves the same kind of field-name-aliasing problem. + +local scenario = arg[1] +if scenario ~= "v1" and scenario ~= "v2" then + error("schema scenario must be v1 or v2") +end + +dofile("drivers/tests/lua_harness/host_mock.lua") +host.reset() + +local function respond(path, body) + host._http_responses["http://127.0.0.1" .. path] = body +end + +-- The device list is unaffected by the v2 meter-field rename (see +-- https://github.com/srcfl/device-drivers/issues/170 — only `ders[].type` +-- for pv/battery changes, not for the P1 meter), so both scenarios use the +-- same /api/devices response. +respond("/api/devices", [[ +{"devices":[{"sn":"TESTZAP-P1-1","type":"p1_uart","device_type":"energy_meter", + "ders":[{"type":"meter","enabled":true}]}]} +]]) + +if scenario == "v1" then + respond("/api/devices/TESTZAP-P1-1/data/json", [[ +{"meter":{"W":1850,"Hz":50.0, + "L1_W":600,"L1_V":230.1,"L1_A":2.61, + "L2_W":600,"L2_V":230.4,"L2_A":2.60, + "L3_W":650,"L3_V":229.8,"L3_A":2.83, + "total_import_Wh":58000000,"total_export_Wh":9000000}} +]]) +else + respond("/api/devices/TESTZAP-P1-1/data/json", [[ +{"meter":{"W_ac":1850,"Hz":50.0, + "l1_W_ac":600,"l1_V_ac":230.1,"l1_A_ac":2.61, + "l2_W_ac":600,"l2_V_ac":230.4,"l2_A_ac":2.60, + "l3_W_ac":650,"l3_V_ac":229.8,"l3_A_ac":2.83, + "total_import_Wh_ac":58000000,"total_export_Wh_ac":9000000}, + "version":"v2","format":"p1_uart"} +]]) +end + +dofile("drivers/lua/zap.lua") + +if DRIVER.id ~= "zap" or DRIVER.version ~= "3.1.2" then + error("Zap identity metadata is wrong or version was not bumped") +end +if DRIVER.host_api_min ~= 1 or DRIVER.host_api_max ~= 1 or DRIVER.read_only ~= true then + error("Zap host API or read-only metadata is wrong") +end + +driver_init({ host = "127.0.0.1" }) +local ok, err = pcall(driver_poll) +if not ok then error("driver_poll failed: " .. tostring(err)) end + +local samples = host._emitted.meter +if not samples or #samples ~= 1 then + error("expected exactly one meter sample for scenario " .. scenario + .. ", got " .. tostring(samples and #samples or 0)) +end + +local meter = samples[1] +local function near(actual, expected) + return type(actual) == "number" and math.abs(actual - expected) < 0.001 +end + +if not near(meter.w, 1850) then error(scenario .. ": meter.w wrong: " .. tostring(meter.w)) end +if not near(meter.l1_w, 600) or not near(meter.l2_w, 600) or not near(meter.l3_w, 650) then + error(scenario .. ": phase power wrong") +end +if not near(meter.l1_v, 230.1) or not near(meter.l2_v, 230.4) or not near(meter.l3_v, 229.8) then + error(scenario .. ": phase voltage wrong") +end +if not near(meter.l1_a, 2.61) or not near(meter.l2_a, 2.60) or not near(meter.l3_a, 2.83) then + error(scenario .. ": phase current wrong") +end +if not near(meter.freq_hz, 50.0) then error(scenario .. ": Hz wrong (unsuffixed in both schemas)") end +if not near(meter.total_import_wh, 58000000) or not near(meter.import_wh, 58000000) then + error(scenario .. ": total_import_Wh / import_wh alias wrong") +end +if not near(meter.total_export_wh, 9000000) or not near(meter.export_wh, 9000000) then + error(scenario .. ": total_export_Wh / export_wh alias wrong") +end + +driver_cleanup() diff --git a/drivers/tests/test_zap_meter_schema.py b/drivers/tests/test_zap_meter_schema.py new file mode 100644 index 0000000..994af2e --- /dev/null +++ b/drivers/tests/test_zap_meter_schema.py @@ -0,0 +1,46 @@ +"""Exercise zap.lua's meter reading against the v1 and v2 Zap local API schemas. + +Draft for drivers/tests/test_zap_meter_schema.py in srcfl/device-drivers, +paired with drivers/tests/lua_harness/test_zap_meter_schema.lua. Modeled on +the existing test_esphome_dsmr_aliases.py, which runs the equivalent +field-aliasing check for a different driver through the same lua55 harness. +""" + +from pathlib import Path +import re +import subprocess + +import pytest + + +ROOT = Path(__file__).resolve().parents[2] + + +def test_zap_source_has_ftw_read_only_contract(): + source = (ROOT / "drivers/lua/zap.lua").read_text(encoding="utf-8") + for entrypoint in ("driver_init", "driver_poll", "driver_command", + "driver_default_mode"): + assert re.search(rf"\bfunction\s+{entrypoint}\s*\(", source), entrypoint + assert re.search(r"\bhost_api_min\s*=", source) + assert re.search(r"\bhost_api_max\s*=", source) + assert re.search(r"\bread_only\s*=\s*true\b", source) + assert not re.search( + r"\bhost\.(?:http_post|modbus_write(?:_multi)?|mqtt_publish|serial_write)\s*\(", + source, + ), "a read-only driver calls a write-capable host function" + + +@pytest.mark.parametrize("scenario", ["v1", "v2"]) +def test_zap_meter_schema(scenario): + result = subprocess.run( + [ + str(ROOT / "lua55"), + "drivers/tests/lua_harness/test_zap_meter_schema.lua", + scenario, + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/index.yaml b/index.yaml index e66f04c..602079c 100644 --- a/index.yaml +++ b/index.yaml @@ -814,14 +814,14 @@ drivers: size_bytes: 2842 sha256: "1c0362e0a25f1fe297de838a85089eb7676b25e78a7d6d1d03ccea1258b94403" - name: "zap" - version: "3.1.1" + version: "3.1.2" tier: core protocol: http connectivity: local ders: [meter, pv, battery] control: false - size_bytes: 26911 - sha256: "dbbef0e614162219c3774292c647f944d0210c752688165afb9a491244700c19" + size_bytes: 28162 + sha256: "5be6d7793a9daa074557182e4333443b382a7a34427dd07143d90f27a8cf01b6" - name: "zaptec" version: "1.0.1" tier: community diff --git a/manifests/zap.yaml b/manifests/zap.yaml index 77aeb9d..4a6e823 100644 --- a/manifests/zap.yaml +++ b/manifests/zap.yaml @@ -1,5 +1,5 @@ name: "zap" -version: "3.1.1" +version: "3.1.2" tier: core author: "Sourceful Labs AB" protocol: http @@ -15,9 +15,9 @@ tested_devices: notes: "P1/HAN site meter from a Sourceful Zap. PV and battery telemetry from devices on Zap are opt-in (read_pv / read_battery) and read-only. Prefer a native FTW driver; use Zap as the reader only when it already owns the bus." min_driver_version: "3.1.0" min_host_version: "2.0.0" -size_bytes: 26911 +size_bytes: 28162 dkb_id: "zap" -sha256: "dbbef0e614162219c3774292c647f944d0210c752688165afb9a491244700c19" +sha256: "5be6d7793a9daa074557182e4333443b382a7a34427dd07143d90f27a8cf01b6" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index aa17b7b..24ec8f7 100644 --- a/support-status.json +++ b/support-status.json @@ -1850,7 +1850,7 @@ }, { "catalog_source": true, - "catalog_version": "3.1.1", + "catalog_version": "3.1.2", "driver_id": "zap", "targets": { "blixt-l1": { From e463c653763d5e5c7d28af97bd381eed4fafa47c Mon Sep 17 00:00:00 2001 From: David Mozart Date: Wed, 4 Nov 2026 11:53:41 +0100 Subject: [PATCH 4/8] fix(zap): read PV and battery under data model v2 (3.1.3) (#209) Zap firmware 7.x calls the PV DER solar, sends power and energy on one side, _ac or _dc, and moves the ratings to /api/devices. read_pv and read_battery therefore read nothing on 7.x. The driver now reads the 1.x and the v2 names, and a value v2 sends as null stays unknown. An AC-side voltage or current is not reported as the battery's own. The inverter DER is not counted as another resource. Also removes draft comments and a pinned version from the meter schema test. Signed-off-by: David Mozart Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 19 ++ SUPPORT_STATUS.md | 4 +- devices.yaml | 2 +- drivers/lua/zap.lua | 102 +++++++--- .../lua_harness/test_zap_meter_schema.lua | 11 +- .../test_zap_pv_battery_schema.lua | 188 ++++++++++++++++++ drivers/tests/test_zap_meter_schema.py | 8 +- drivers/tests/test_zap_pv_battery_schema.py | 36 ++++ index.yaml | 6 +- manifests/zap.yaml | 6 +- support-status.json | 2 +- 11 files changed, 325 insertions(+), 59 deletions(-) create mode 100644 drivers/tests/lua_harness/test_zap_pv_battery_schema.lua create mode 100644 drivers/tests/test_zap_pv_battery_schema.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b8194d3..b1affa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## [Unreleased] +### zap 3.1.3 + +`read_pv` and `read_battery` read again on Zap firmware 7.x. Data model v2 calls +the PV DER `solar`, puts power and energy on one side (`_ac` or `_dc`), and moves +the ratings to `/api/devices`, so 3.1.2 found no PV and no battery power there. + +- PV and battery read on both the 1.x and the v2 names. A value v2 sends as + `null` stays unknown. +- An AC-side voltage or current is not reported as the battery's own. +- The `inverter` DER is not counted as another resource, and `ev_charger_port` + counts as a charger. + +Checked through FTW's Lua host on firmware 7.0.3, against a real Zap-P1 with a +simulated Solis. Not checked against a real inverter. Without `read_pv` and +`read_battery` the driver still reads the meter and nothing else. + +FTW's bundled copy does not move with this commit. Bump the pin and run +`scripts/sync-bundled-drivers.sh`. + ### zap 3.1.2 The P1/HAN site meter reads again on Zap firmware serving the data model v2 diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index ec9152b..72c770c 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -180,8 +180,8 @@ Catalog source is not proof that a target can install or run a driver. | victron_mqtt | 1.0.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.0.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.0.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| zap | 3.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| zap | 3.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| zap | 3.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| zap | 3.1.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | zaptec | 1.0.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | zaptec | 1.0.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | zaptec_cloud | 0.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index f1df6c2..7936061 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1749,7 +1749,7 @@ manufacturers: protocols: - protocol: http driver: "zap" - version: "3.1.2" + version: "3.1.3" ders: [meter, pv, battery] control: false firmware_versions: "" diff --git a/drivers/lua/zap.lua b/drivers/lua/zap.lua index 06dec0b..7b7922f 100644 --- a/drivers/lua/zap.lua +++ b/drivers/lua/zap.lua @@ -32,13 +32,17 @@ -- pv: -W generation -- battery:+W charge, -W discharge -- --- Meter schema compatibility: some Zap firmware serves the local data model --- v2 (srcful-data-models 2.3.0, "version":"v2" in /data/json), which renames --- every meter field with an "_ac" suffix and lowercases the L1/L2/L3 phase --- prefix (e.g. "L1_V" -> "l1_V_ac", "W" -> "W_ac"; "Hz" is unchanged either --- way). This driver reads both v1 and v2 field names for the meter DER; see --- https://github.com/srcfl/device-drivers/issues/170 for the full v2 scope --- (pv -> solar, battery, DC/AC split), which is not yet covered here. +-- Data model v2: Zap firmware 7.x serves the local API in data model v2 +-- ("version":"v2" in /data/json). Older firmware uses the 1.x names. This +-- driver reads both, and a value v2 sends as null stays unknown. v2 moved: +-- meter: W -> W_ac, L1_V -> l1_V_ac, total_import_Wh -> total_import_Wh_ac +-- pv: the DER is "solar"; power and energy are on one side, _ac or _dc; +-- mppt1_V -> mppt[1].V_dc; heatsink_C -> inverter.temperature_C +-- battery: power and energy likewise; V -> V_dc, A -> A_dc; +-- SoC_nom_fract -> soc_nom_fract; heatsink_C -> temperature_C +-- ratings: from /api/devices: rated_power_W_ac on the "inverter" DER, +-- installed_power_W_dc on "solar", rated_power_W_dc and +-- capacity_Wh_dc on "battery" DRIVER = { host_api_min = 1, @@ -46,7 +50,7 @@ DRIVER = { id = "zap", name = "Sourceful Zap (P1/HAN meter)", manufacturer = "Sourceful", - version = "3.1.2", + version = "3.1.3", protocols = { "http" }, capabilities = { "meter", "pv", "battery" }, read_only = true, @@ -57,7 +61,7 @@ DRIVER = { verification_status = "production", verified_by = { "erikarenhill@fortytwo:3d" }, verified_at = "2026-07-17", - verification_notes = "P1/HAN live-hardware verified against the official Zap Local API (srcful-zap-x-firmware 96e0258). PV aggregation was live-hardware verified on the same API before the 3.0 meter-only cut; it returns as an operator opt-in. Battery payloads are contract-tested against the firmware serializers. Inverters, batteries and chargers found on Zap are not ingested unless read_pv / read_battery is set.", + verification_notes = "P1/HAN live-hardware verified against the official Zap Local API (srcful-zap-x-firmware 96e0258). PV aggregation was live-hardware verified on the same API before the 3.0 meter-only cut; it returns as an operator opt-in. Battery payloads are contract-tested against the firmware serializers. Inverters, batteries and chargers found on Zap are not ingested unless read_pv / read_battery is set. Data model v2 checked 2026-11-04 on firmware 7.0.3: the meter on a Zap-HAN with a real meter; PV and battery on a Zap-P1 with a simulated Solis, not on a real inverter.", tested_models = { "Sourceful Zap (ESP32-C3 controller firmware)" }, connection_defaults = { host = "zap.local", @@ -98,6 +102,24 @@ local function number(v) return n end +local function positive(v) + local n = number(v) + if n ~= nil and n > 0 then return n end + return nil +end + +-- Data model v2 sends a power or energy value on one side, _ac or _dc, and the +-- other side null. A 1.x payload has the plain name. +local function sided(raw, name) + return number(raw[name]) or number(raw[name .. "_ac"]) or number(raw[name .. "_dc"]) +end + +-- A battery's or a string's own voltage and current. An AC-side value is the +-- grid's, not theirs. +local function dc_side(raw, name) + return number(raw[name]) or number(raw[name .. "_dc"]) +end + local function cfg_true(v) return v == true or v == "true" or v == 1 or v == "1" end @@ -252,22 +274,29 @@ local function discover_devices() if der.type == "meter" then rec.meter = true if not first_meter then first_meter = sn end - elseif der.type == "pv" then + elseif der.type == "pv" or der.type == "solar" then if read_pv then rec.pv = true - rec.pv_rated_w = number(der.rated_power) or number(der.installed_power) or rec.pv_rated_w + rec.pv_rated_w = number(der.rated_power) or number(der.installed_power) + or number(der.installed_power_W_dc) or rec.pv_rated_w else add_other(extras, seen, "PV inverter") end elseif der.type == "battery" then if read_battery then rec.battery = true - rec.battery_rated_w = number(der.rated_power) or rec.battery_rated_w - rec.battery_capacity_wh = number(der.capacity) or rec.battery_capacity_wh + rec.battery_rated_w = number(der.rated_power) or number(der.rated_power_W_dc) + or rec.battery_rated_w + rec.battery_capacity_wh = number(der.capacity) or number(der.capacity_Wh_dc) + or rec.battery_capacity_wh else add_other(extras, seen, "battery") end - elseif der.type == "v2x_charger" or der.type == "ev" then + elseif der.type == "inverter" then + -- The AC stage and rating of a device already + -- listed, not a resource of its own. + rec.inverter_rated_w = positive(der.rated_power_W_ac) or rec.inverter_rated_w + elseif der.type == "v2x_charger" or der.type == "ev" or der.type == "ev_charger_port" then add_other(extras, seen, "charger") elseif der.type ~= nil and der.type ~= "" and der.type ~= "meter" then add_other(extras, seen, tostring(der.type)) @@ -454,6 +483,11 @@ local function snapshot_map() return out end +local function mppt_input(pv, index) + local inputs = type(pv.mppt) == "table" and pv.mppt or {} + return type(inputs[index]) == "table" and inputs[index] or {} +end + local function emit_pv(snapshots) local source_count = count_kind("pv") if source_count == 0 then return end @@ -467,14 +501,14 @@ local function emit_pv(snapshots) for _, rec in ipairs(tracked) do local data = snapshots[rec.sn] - local pv = data and data.pv + local pv = data and (data.pv or data.solar) if rec.pv and type(pv) == "table" then - local rated = number(pv.rated_power_W) or rec.pv_rated_w + local rated = number(pv.rated_power_W) or rec.inverter_rated_w or rec.pv_rated_w if rated and rated > 0 then total_rated_w = total_rated_w + rated any_rating = true end - local w = sane_power(pv.W, rated) + local w = sane_power(sided(pv, "W"), rated) if w ~= nil and w <= 0 then total_w = total_w + w any_power = true @@ -485,18 +519,20 @@ local function emit_pv(snapshots) host.log("warn", "Zap: rejected positive PV power for " .. rec.sn .. ": " .. w .. "W") end - local generation = bounded(pv.total_generation_Wh, 0, nil) + local generation = bounded(sided(pv, "total_generation_Wh"), 0, nil) if generation ~= nil then total_generation_wh = total_generation_wh + generation any_generation = true end local tag = source_count > 1 and ("_" .. metric_tag(rec.sn)) or "" - emit_optional_metric("pv_heatsink_c" .. tag, number(pv.heatsink_C), "°C") - emit_optional_metric("pv_mppt1_v" .. tag, number(pv.mppt1_V), "V") - emit_optional_metric("pv_mppt1_a" .. tag, number(pv.mppt1_A), "A") - emit_optional_metric("pv_mppt2_v" .. tag, number(pv.mppt2_V), "V") - emit_optional_metric("pv_mppt2_a" .. tag, number(pv.mppt2_A), "A") + local inverter = type(data.inverter) == "table" and data.inverter or {} + local mppt1, mppt2 = mppt_input(pv, 1), mppt_input(pv, 2) + emit_optional_metric("pv_heatsink_c" .. tag, number(pv.heatsink_C) or number(inverter.temperature_C), "°C") + emit_optional_metric("pv_mppt1_v" .. tag, number(pv.mppt1_V) or number(mppt1.V_dc), "V") + emit_optional_metric("pv_mppt1_a" .. tag, number(pv.mppt1_A) or number(mppt1.A_dc), "A") + emit_optional_metric("pv_mppt2_v" .. tag, number(pv.mppt2_V) or number(mppt2.V_dc), "V") + emit_optional_metric("pv_mppt2_a" .. tag, number(pv.mppt2_A) or number(mppt2.A_dc), "A") end end @@ -544,7 +580,7 @@ local function emit_battery(snapshots) total_rated_w = total_rated_w + rated any_rating = true end - local w = sane_power(battery.W, rated) + local w = sane_power(sided(battery, "W"), rated) if w ~= nil then total_w = total_w + w any_power = true @@ -552,7 +588,7 @@ local function emit_battery(snapshots) -- Firmware SoC_nom_fract is 0-1. Identifier keeps the -- catalog check that soc is already a fraction, not percent. - local soc_already_fract = bounded(battery.SoC_nom_fract, 0, 1) + local soc_already_fract = bounded(number(battery.SoC_nom_fract) or number(battery.soc_nom_fract), 0, 1) local soc = soc_already_fract if soc ~= nil then soc_sum = soc_sum + soc @@ -565,17 +601,17 @@ local function emit_battery(snapshots) end end - local charge = bounded(battery.total_charge_Wh, 0, nil) + local charge = bounded(sided(battery, "total_charge_Wh"), 0, nil) if charge ~= nil then total_charge_wh = total_charge_wh + charge; any_charge_energy = true end - local discharge = bounded(battery.total_discharge_Wh, 0, nil) + local discharge = bounded(sided(battery, "total_discharge_Wh"), 0, nil) if discharge ~= nil then total_discharge_wh = total_discharge_wh + discharge; any_discharge_energy = true end local tag = source_count > 1 and ("_" .. metric_tag(rec.sn)) or "" if source_count > 1 and w ~= nil then host.emit_metric("battery_w" .. tag, w, "W") end if source_count > 1 and soc ~= nil then host.emit_metric("battery_soc" .. tag, soc, "fraction") end - emit_optional_metric("battery_dc_v" .. tag, number(battery.V), "V") - emit_optional_metric("battery_dc_a" .. tag, number(battery.A), "A") - emit_optional_metric("battery_temp_c" .. tag, number(battery.heatsink_C), "°C") + emit_optional_metric("battery_dc_v" .. tag, dc_side(battery, "V"), "V") + emit_optional_metric("battery_dc_a" .. tag, dc_side(battery, "A"), "A") + emit_optional_metric("battery_temp_c" .. tag, number(battery.heatsink_C) or number(battery.temperature_C), "°C") end end @@ -600,9 +636,9 @@ local function emit_battery(snapshots) if any_rating then battery_reading.rated_w = total_rated_w end if source_count == 1 and single then - battery_reading.v = number(single.V) - battery_reading.a = number(single.A) - battery_reading.temp_c = number(single.heatsink_C) + battery_reading.v = dc_side(single, "V") + battery_reading.a = dc_side(single, "A") + battery_reading.temp_c = number(single.heatsink_C) or number(single.temperature_C) end host.emit("battery", battery_reading) diff --git a/drivers/tests/lua_harness/test_zap_meter_schema.lua b/drivers/tests/lua_harness/test_zap_meter_schema.lua index 4dc7e87..97cb564 100644 --- a/drivers/tests/lua_harness/test_zap_meter_schema.lua +++ b/drivers/tests/lua_harness/test_zap_meter_schema.lua @@ -1,12 +1,5 @@ -- Exercise zap.lua's meter field reading against both the v1 and v2 Zap -- local API field names. Run with the scenario as arg[1]: "v1" or "v2". --- --- This file is a draft for drivers/tests/lua_harness/test_zap_meter_schema.lua --- in srcfl/device-drivers — see pr-drafts/README.md for how this fits that --- repo's `make test-driver ID=zap` harness. Not run against the real harness --- yet (no local checkout with lua55/pytest); matches the structure of the --- existing drivers/tests/lua_harness/test_esphome_dsmr_aliases.lua, which --- solves the same kind of field-name-aliasing problem. local scenario = arg[1] if scenario ~= "v1" and scenario ~= "v2" then @@ -50,8 +43,8 @@ end dofile("drivers/lua/zap.lua") -if DRIVER.id ~= "zap" or DRIVER.version ~= "3.1.2" then - error("Zap identity metadata is wrong or version was not bumped") +if DRIVER.id ~= "zap" then + error("Zap identity metadata is wrong") end if DRIVER.host_api_min ~= 1 or DRIVER.host_api_max ~= 1 or DRIVER.read_only ~= true then error("Zap host API or read-only metadata is wrong") diff --git a/drivers/tests/lua_harness/test_zap_pv_battery_schema.lua b/drivers/tests/lua_harness/test_zap_pv_battery_schema.lua new file mode 100644 index 0000000..b165fbd --- /dev/null +++ b/drivers/tests/lua_harness/test_zap_pv_battery_schema.lua @@ -0,0 +1,188 @@ +-- Exercise zap.lua's read_pv and read_battery on the 1.x and the data model v2 +-- local API. Run with the scenario as arg[1]. The v2 payload is what a Zap on +-- firmware 7.0.3 sent for a simulated Solis, with the serial replaced. + +local scenario = arg[1] + +dofile("drivers/tests/lua_harness/host_mock.lua") +host.reset() + +local function respond(path, body) + host._http_responses["http://127.0.0.1" .. path] = body +end + +local V1_DEVICES = [[ +{"devices":[{"sn":"INV-1","type":"modbus_tcp","device_type":"inverter","ders":[ + {"type":"pv","enabled":false,"rated_power":20000}, + {"type":"battery","enabled":false,"rated_power":5000,"capacity":15000}]}]} +]] + +local V1_DATA = [[ +{"pv":{"type":"pv","W":-3000,"rated_power_W":20000,"total_generation_Wh":150000, + "mppt1_V":300,"mppt1_A":-5,"mppt2_V":290,"mppt2_A":-4.8,"heatsink_C":45}, + "battery":{"type":"battery","W":5000,"V":52,"A":10,"SoC_nom_fract":0.75, + "rated_power_W":5000,"capacity_Wh":15000, + "total_charge_Wh":4200000,"total_discharge_Wh":1800000,"heatsink_C":24}, + "version":"v1","format":"json"} +]] + +local V2_DEVICES = [[ +{"count":1,"devices":[{"type":"modbus_tcp","profile":"solis","device_type":"inverter","sn":"INV-1","ders":[ + {"type":"solar","enabled":true,"installed_power_W_dc":8000}, + {"type":"battery","enabled":true,"rated_power_W_dc":5000,"capacity_Wh_dc":15000}, + {"type":"inverter","enabled":true,"rated_power_W_ac":20000}]}]} +]] + +local V2_DATA = [[ +{"solar":{"type":"solar","make":"solis","W_ac":null,"W_dc":-3000, + "mppt":[{"V_dc":300,"A_dc":-5,"W_dc":-1500},{"V_dc":290,"A_dc":-4.8,"W_dc":-1392}], + "total_generation_Wh_ac":null,"total_generation_Wh_dc":150000, + "lower_limit_W_ac":null,"lower_limit_W_dc":null}, + "battery":{"type":"battery","make":"solis","W_ac":null,"W_dc":5000,"V_ac":null,"V_dc":52, + "A_ac":null,"A_dc":10,"soc_nom_fract":0.75,"soh_fract":null,"temperature_C":24, + "total_charge_Wh_ac":null,"total_charge_Wh_dc":4200000, + "total_discharge_Wh_ac":null,"total_discharge_Wh_dc":1800000, + "upper_limit_W_ac":null,"upper_limit_W_dc":5000,"setpoint_W_ac":null,"setpoint_W_dc":5000}, + "inverter":{"type":"inverter","make":"solis","W_ac":-2400,"temperature_C":45,"rated_power_W_ac":20000}, + "version":"v2","format":"json"} +]] + +local function near(actual, expected) + return type(actual) == "number" and math.abs(actual - expected) < 0.001 +end + +local function want(name, actual, expected) + if not near(actual, expected) then + error(scenario .. ": " .. name .. " = " .. tostring(actual) .. ", want " .. tostring(expected)) + end +end + +local function metric(name) + local entry = host._metrics[name] + return entry and entry.value +end + +local function poll(config) + dofile("drivers/lua/zap.lua") + config.host = "127.0.0.1" + driver_init(config) + local ok, err = pcall(driver_poll) + if not ok then error("driver_poll failed: " .. tostring(err)) end +end + +local function assert_full_reading() + local pv = host._emitted.pv and host._emitted.pv[1] + if not pv then error(scenario .. ": no pv reading") end + want("pv.w", pv.w, -3000) + want("pv.total_generation_wh", pv.total_generation_wh, 150000) + want("pv.rated_w", pv.rated_w or pv.rated_power_w, 20000) + + local battery = host._emitted.battery and host._emitted.battery[1] + if not battery then error(scenario .. ": no battery reading") end + want("battery.w", battery.w, 5000) + want("battery.soc", battery.soc, 0.75) + want("battery.v", battery.v, 52) + want("battery.a", battery.a, 10) + want("battery.temp_c", battery.temp_c, 24) + want("battery.total_charge_wh", battery.total_charge_wh, 4200000) + want("battery.total_discharge_wh", battery.total_discharge_wh, 1800000) + want("battery.rated_w", battery.rated_w or battery.rated_power_w, 5000) + + want("pv_heatsink_c", metric("pv_heatsink_c"), 45) + want("pv_mppt1_v", metric("pv_mppt1_v"), 300) + want("pv_mppt1_a", metric("pv_mppt1_a"), -5) + want("pv_mppt2_v", metric("pv_mppt2_v"), 290) + want("pv_mppt2_a", metric("pv_mppt2_a"), -4.8) + want("battery_dc_v", metric("battery_dc_v"), 52) + want("battery_dc_a", metric("battery_dc_a"), 10) +end + +if scenario == "v1" then + respond("/api/devices", V1_DEVICES) + respond("/api/devices/INV-1/data/json", V1_DATA) + poll({ read_pv = true, read_battery = true }) + assert_full_reading() + +elseif scenario == "v2" then + respond("/api/devices", V2_DEVICES) + respond("/api/devices/INV-1/data/json", V2_DATA) + poll({ read_pv = true, read_battery = true }) + assert_full_reading() + +elseif scenario == "v2_panels_rating" then + -- No inverter rating set: the rating falls back on the installed panels. + respond("/api/devices", [[ +{"devices":[{"type":"modbus_tcp","device_type":"inverter","sn":"INV-1","ders":[ + {"type":"solar","installed_power_W_dc":8000}, + {"type":"inverter","rated_power_W_ac":0}]}]} +]]) + respond("/api/devices/INV-1/data/json", [[{"solar":{"W_ac":null,"W_dc":-3000},"version":"v2"}]]) + poll({ read_pv = true }) + want("pv.rated_w", host._emitted.pv[1].rated_w or host._emitted.pv[1].rated_power_w, 8000) + +elseif scenario == "v2_ac_side" then + -- An AC-side power and energy count. An AC-side voltage and current are the + -- grid's, so they are not the battery's. + respond("/api/devices", V2_DEVICES) + respond("/api/devices/INV-1/data/json", [[ +{"solar":{"W_ac":-1000,"W_dc":null,"total_generation_Wh_ac":700,"total_generation_Wh_dc":null}, + "battery":{"W_ac":-400,"W_dc":null,"V_ac":230,"V_dc":null,"A_ac":-1.7,"A_dc":null, + "soc_nom_fract":0.5,"total_charge_Wh_ac":90,"total_charge_Wh_dc":null}, + "version":"v2"} +]]) + poll({ read_pv = true, read_battery = true }) + want("pv.w", host._emitted.pv[1].w, -1000) + want("pv.total_generation_wh", host._emitted.pv[1].total_generation_wh, 700) + local battery = host._emitted.battery[1] + want("battery.w", battery.w, -400) + want("battery.total_charge_wh", battery.total_charge_wh, 90) + if battery.v ~= nil or battery.a ~= nil then + error("v2_ac_side: an AC voltage or current became the battery's") + end + if metric("battery_dc_v") ~= nil or metric("battery_dc_a") ~= nil then + error("v2_ac_side: an AC voltage or current became a DC metric") + end + +elseif scenario == "v2_null" then + -- What was not read stays unknown, never 0. + respond("/api/devices", V2_DEVICES) + respond("/api/devices/INV-1/data/json", [[ +{"solar":{"W_ac":null,"W_dc":null,"mppt":null,"total_generation_Wh_ac":null,"total_generation_Wh_dc":null}, + "battery":{"W_ac":null,"W_dc":null,"V_dc":null,"soc_nom_fract":null}, + "version":"v2"} +]]) + poll({ read_pv = true, read_battery = true }) + if host._emitted.pv then error("v2_null: null power became a pv reading") end + if host._emitted.battery then error("v2_null: null power became a battery reading") end + +elseif scenario == "v2_null_soc" then + respond("/api/devices", V2_DEVICES) + respond("/api/devices/INV-1/data/json", [[ +{"battery":{"W_dc":100,"soc_nom_fract":null,"total_charge_Wh_dc":null},"version":"v2"} +]]) + poll({ read_battery = true }) + local battery = host._emitted.battery[1] + if battery.soc ~= nil or battery.total_charge_wh ~= nil then + error("v2_null_soc: an unread value was invented") + end + +elseif scenario == "v2_not_opted_in" then + -- The defaults are unchanged: nothing but the meter is read, and the v2 + -- inverter DER is not a resource of its own. + respond("/api/devices", [[ +{"devices":[{"type":"modbus_tcp","device_type":"inverter","sn":"INV-1","ders":[ + {"type":"solar"},{"type":"battery"},{"type":"inverter","rated_power_W_ac":20000}]}, + {"type":"mqtt","device_type":"v2x_charger","sn":"EV-1","ders":[{"type":"ev_charger_port"}]}]} +]]) + respond("/api/devices/INV-1/data/json", V2_DATA) + poll({}) + if host._emitted.pv or host._emitted.battery then + error("v2_not_opted_in: read a resource that was not opted in") + end + want("other_resources", metric("other_resources"), 3) + +else + error("unknown scenario: " .. tostring(scenario)) +end + +driver_cleanup() diff --git a/drivers/tests/test_zap_meter_schema.py b/drivers/tests/test_zap_meter_schema.py index 994af2e..ecb7401 100644 --- a/drivers/tests/test_zap_meter_schema.py +++ b/drivers/tests/test_zap_meter_schema.py @@ -1,10 +1,4 @@ -"""Exercise zap.lua's meter reading against the v1 and v2 Zap local API schemas. - -Draft for drivers/tests/test_zap_meter_schema.py in srcfl/device-drivers, -paired with drivers/tests/lua_harness/test_zap_meter_schema.lua. Modeled on -the existing test_esphome_dsmr_aliases.py, which runs the equivalent -field-aliasing check for a different driver through the same lua55 harness. -""" +"""Exercise zap.lua's meter reading against the v1 and v2 Zap local API schemas.""" from pathlib import Path import re diff --git a/drivers/tests/test_zap_pv_battery_schema.py b/drivers/tests/test_zap_pv_battery_schema.py new file mode 100644 index 0000000..7bfc636 --- /dev/null +++ b/drivers/tests/test_zap_pv_battery_schema.py @@ -0,0 +1,36 @@ +"""Exercise zap.lua's read_pv and read_battery on the 1.x and data model v2 APIs.""" + +from pathlib import Path +import subprocess + +import pytest + + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize( + "scenario", + [ + "v1", + "v2", + "v2_panels_rating", + "v2_ac_side", + "v2_null", + "v2_null_soc", + "v2_not_opted_in", + ], +) +def test_zap_pv_battery_schema(scenario): + result = subprocess.run( + [ + str(ROOT / "lua55"), + "drivers/tests/lua_harness/test_zap_pv_battery_schema.lua", + scenario, + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/index.yaml b/index.yaml index 602079c..a0bdde4 100644 --- a/index.yaml +++ b/index.yaml @@ -814,14 +814,14 @@ drivers: size_bytes: 2842 sha256: "1c0362e0a25f1fe297de838a85089eb7676b25e78a7d6d1d03ccea1258b94403" - name: "zap" - version: "3.1.2" + version: "3.1.3" tier: core protocol: http connectivity: local ders: [meter, pv, battery] control: false - size_bytes: 28162 - sha256: "5be6d7793a9daa074557182e4333443b382a7a34427dd07143d90f27a8cf01b6" + size_bytes: 30379 + sha256: "b11198e45d761599939b8201c0969514bbbbc6c2571dcf56d12959cf9ade2b5d" - name: "zaptec" version: "1.0.1" tier: community diff --git a/manifests/zap.yaml b/manifests/zap.yaml index 4a6e823..91c3258 100644 --- a/manifests/zap.yaml +++ b/manifests/zap.yaml @@ -1,5 +1,5 @@ name: "zap" -version: "3.1.2" +version: "3.1.3" tier: core author: "Sourceful Labs AB" protocol: http @@ -15,9 +15,9 @@ tested_devices: notes: "P1/HAN site meter from a Sourceful Zap. PV and battery telemetry from devices on Zap are opt-in (read_pv / read_battery) and read-only. Prefer a native FTW driver; use Zap as the reader only when it already owns the bus." min_driver_version: "3.1.0" min_host_version: "2.0.0" -size_bytes: 28162 +size_bytes: 30379 dkb_id: "zap" -sha256: "5be6d7793a9daa074557182e4333443b382a7a34427dd07143d90f27a8cf01b6" +sha256: "b11198e45d761599939b8201c0969514bbbbc6c2571dcf56d12959cf9ade2b5d" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index 24ec8f7..403c1de 100644 --- a/support-status.json +++ b/support-status.json @@ -1850,7 +1850,7 @@ }, { "catalog_source": true, - "catalog_version": "3.1.2", + "catalog_version": "3.1.3", "driver_id": "zap", "targets": { "blixt-l1": { From d1c6a2e3dd85ae4f60d29cd5826e6163ab8c2051 Mon Sep 17 00:00:00 2001 From: David Mozart Date: Wed, 4 Nov 2026 12:42:30 +0100 Subject: [PATCH 5/8] Add read-only SAJ eManager C1 Pro driver (#210) * feat(saj-emanager): add read-only eManager telemetry The community register sheet does not state sign, word order, or whether phase voltage and frequency are summed. Control stays off until a named eManager proves a held zero. Signed-off-by: Cursor Agent Co-authored-by: David Mozart * fix(saj-emanager): state site signs on every watt Generation stays negative. Battery charge is positive and discharge is negative; the H2 wire is the other way round, so 0x8491 is negated. Grid import stays positive. Vendor-only words are not DER fields. Signed-off-by: Cursor Agent Co-authored-by: David Mozart --------- Signed-off-by: Cursor Agent Co-authored-by: Cursor Agent Co-authored-by: David Mozart --- CHANGELOG.md | 37 ++ SUPPORT_STATUS.md | 2 + devices.yaml | 11 + drivers/lua/saj-emanager.lua | 607 +++++++++++++++++++++++++++++ drivers/tests/test_saj-emanager.py | 581 +++++++++++++++++++++++++++ index.yaml | 9 + manifests/saj-emanager.yaml | 38 ++ support-status.json | 21 + 8 files changed, 1306 insertions(+) create mode 100644 drivers/lua/saj-emanager.lua create mode 100644 drivers/tests/test_saj-emanager.py create mode 100644 manifests/saj-emanager.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index b1affa6..9d21e65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,43 @@ ## [Unreleased] +### saj-emanager 0.1.1 + +Emitted power uses the same signs as the other drivers. Generation is +negative. Battery power is positive when charging and negative when +discharging. Grid power is positive on import and negative on export. + +The H2 wire is discharge-positive on the battery, so `0x8491` is negated +once at the boundary. The H2 grid word is already import-positive, so +`0x8496` and the phase watts are not. Inverter, load and generator words +have no stated sign and stay on `*_vendor` metrics, off the DER streams. +Still unverified on an eManager. + +### saj-emanager 0.1.0 + +Read-only telemetry for a SAJ eManager C1 Pro in front of one or more CHS2/CH2 +hybrids. Modbus TCP only, port 502. The register sheet marks RTU as not supported. + +- PV, grid and battery come from the aggregate block at `0x848A`. Battery + telemetry is emitted only when capacity, SoC or battery power says a pack + is there. A failed or short read is left out; it is not reported as 0 W. +- Phase voltage and frequency are divided by `DeviceNum` only when the scaled + value cannot be one phase and the quotient can. The register sheet does not + say those registers are summed. Eniris does, and only for voltage and + frequency. Power is never divided. +- Emitted signs match the rest of the catalog. Generation is negative. + Battery power is positive when charging and negative when discharging + (the H2 wire is discharge-positive, so `0x8491` is negated). Grid power is + positive on import and negative on export (the H2 wire already is, so + `0x8496` is not negated). Word order is high word first. The eManager + sheet states none of this. All three are unverified. +- `0x8400`–`0x8405` are documented, including the ±11000 setpoint scaling and + the SEC-C map that reuses the same addresses, and are not written. +- Not run on hardware. The first site to check is Castellum Örebro. + +FTW's bundled copy does not move with this commit. Bump the pin and run +`scripts/sync-bundled-drivers.sh`. + ### zap 3.1.3 `read_pv` and `read_battery` read again on Zap firmware 7.x. Data model v2 calls diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 72c770c..5339321 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -120,6 +120,8 @@ Catalog source is not proof that a target can install or run a driver. | pixii_pv | 0.3.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | remne_p1ib | 0.1.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | remne_p1ib | 0.1.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| saj-emanager | 0.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| saj-emanager | 0.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | saj | 1.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | saj | 1.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | schneider_meter | 1.0.5 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 7936061..31e9414 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1098,6 +1098,17 @@ manufacturers: control: false firmware_versions: "" notes: "Same H2-Protocol map as the three-phase hybrid. Ampere.StoragePro / EKD-Solar is a rebadged HS2. Telemetry only." + - name: "eManager C1 Pro" + variants: [eManager C1 Pro] + regions: [] + protocols: + - protocol: modbus + driver: "saj-emanager" + version: "0.1.1" + ders: [pv, battery, meter] + control: false + firmware_versions: "" + notes: "Site controller in front of 1..N CHS2/CH2 C&I hybrids. Modbus TCP only, port 502; the register sheet marks RTU as not supported. Telemetry only, decoded from the community eManager/SEC-C workbook. Not tested on hardware. First check is Castellum Örebro (3x CHS2 50 kW). Control 0x8400-0x8405 is documented and not written." - name: "SMA" model_families: - name: "SMA Home Manager 2.0" diff --git a/drivers/lua/saj-emanager.lua b/drivers/lua/saj-emanager.lua new file mode 100644 index 0000000..f6d9f20 --- /dev/null +++ b/drivers/lua/saj-emanager.lua @@ -0,0 +1,607 @@ +-- SAJ eManager C1 Pro site controller. +-- Emits: PV, Battery (only when the aggregate says a pack is there), Meter +-- Protocol: Modbus TCP only, HOLDING registers (FC 0x03), port 502, unit 1 +-- +-- The interface sheet marks Modbus RTU as "Not supported". This driver has +-- no serial settings and does not speak RTU. The catalog protocol field is +-- still "modbus" because that is the only Modbus value the manifest allows. +-- +-- Register map (community, not an official SAJ publication): +-- Modbus_registers_eManager.xlsx, posted by remkoteselle on +-- github.com/stanus74/home-assistant-saj-h2-modbus discussion #182. +-- Sheets: Interface spec, EMS Mapping table, Real-time Data Table, +-- EMS Energy Dispatch Control, sec-c Anti-Backflow Control. +-- A text dump of that workbook is what this file was decoded from. +-- SAJ's own portal copies are not linked here; a document behind a login +-- cannot be watched. +-- +-- Cross-checks, not the map this driver reads: +-- * Eniris SmartgridOne, "SAJ eManager-C1 Pro" (still marked in testing): +-- docs.eniris.com — TCP 502, unit 1, and the voltage/frequency note below. +-- * OpenEMS io.openems.edge.saj (xeno27/openems pull 2), the CH2 PCS +-- map from SAJ "Protocol for CH2 remote EMS control". Same 0x8400-0x8405 +-- control block. Direct CH2 realtime is 0x7B04-0x7C88, which this +-- controller map does not use. Not hardware-validated there either. +-- * The H2 holding map in drivers/lua/saj.lua, for sign and word order. +-- +-- This build is read-only and has not been run on hardware. The first site +-- to check is Castellum Örebro (3x CHS2 50 kW behind one eManager). +-- +-- ═══ Addresses (holding, hex is the sheet's number) ═══════════════════════ +-- +-- 0x4A00 DeviceNum U16 connected devices, 0..21 +-- 0x4A01 per device, stride 12 words, up to 21: +-- SN 10 words, ASCII, high byte first +-- ID U16 Modbus unit id of that inverter +-- reserved U16 +-- The ID15 reserved row prints decimal 19234 next to hex 4AB4. +-- 0x4AB4 is 19124. The stride above follows the hex and the other +-- twenty rows, not that one decimal. +-- 0x848A system realtime, see the block layout below +-- 0x849E grid phase R, then S, then T. 8 words each. +-- 0x8500 energy counters, U32, magnification -2, unit kWh +-- 0x8550 parallInvPower is length 2 and the next row says reserve at +-- 0x8551. Those overlap. This driver stops at 0x854F. +-- +-- There is no eManager serial in this sheet. Identity is the first connected +-- inverter SN, plus DeviceNum. A blank first SN falls through to the next. +-- +-- ═══ Scaling (sheet "Magnification" column) ═══════════════════════════════ +-- +-- -1 × 0.1 grid voltage (V), grid current (A) +-- -2 × 0.01 frequency (Hz), SoC (%), energy (kWh) +-- -3 × 0.001 power factor (not emitted; no DER field) +-- blank on a watt register means the word is already watts +-- +-- int32 / uint32 are two words. The sheet does not state the word order. +-- ASSUMPTION: high word first, same as the H2 driver in this repository and +-- the SAJ Modbus PDFs. UNVERIFIED on an eManager. A swapped pair of a +-- negative power would be a huge value, not a sign flip of the real watts. +-- +-- ═══ Signs ═════════════════════════════════════════════════════════════════ +-- +-- Positive watts flow INTO the site. Same rule as every other driver here +-- (docs/WRITING-A-DRIVER.md, drivers/lua/saj.lua): +-- pv.W always negative — generation +-- battery.W positive = charging, negative = discharging +-- meter.W positive = import, negative = export +-- +-- The realtime sheet never says which direction is positive on the wire. +-- The conversion, in one place each: +-- TotalPVPower (0x848F) is uint32, a magnitude. Negated. +-- TotalBatteryPower (0x8491) is assumed discharge-positive, which is the +-- H2 register and what the 0x8405 setpoint text describes. Negated, so +-- a charging pack is positive here. UNVERIFIED on this aggregate word. +-- TotalGridPowerWatt (0x8496) and the per-phase watts are assumed +-- import-positive, which is the H2 grid word and already the site rule. +-- Not negated. Phase current follows that (positive into the site). +-- UNVERIFIED on this aggregate word. +-- CH2's own map does not trust the power word; it uses direction registers +-- this sheet does not have. +-- +-- Load (0x8493), inverter (0x848D) and generator (0x8498) power are int32 +-- with no stated sign. They are metrics named *_vendor and are not DER +-- fields, so a positive word there is not a site-signed watt. +-- +-- ═══ Voltage and frequency may be summed — the sheet does not say so ═════ +-- +-- Eniris, for this exact product, says the eManager returns phase voltage +-- and frequency as the SUM across connected inverters (4 inverters can read +-- 200 Hz) and that the controller divides by the inverter count. Power is +-- the combined total and must not be divided. Current is not mentioned. +-- +-- The register sheet describes those cells as ordinary phase quantities +-- (magnification -1 V, -2 Hz). It does not mention a sum. Dividing every +-- site by DeviceNum would turn a true 230 V into 77 V on a 3-inverter plant. +-- +-- So this driver divides voltage or frequency only when both are true: +-- the sheet's own scale is implausible for one phase, and +-- DeviceNum was read (2..21) and the quotient lands in a normal band +-- (about 180..280 V, 45..65 Hz). +-- A 230 V / 50 Hz reading is left alone, even when three inverters are +-- connected. A 690 V / 150 Hz reading with DeviceNum = 3 becomes 230 V / +-- 50 Hz. Power, current, energy and rated power are never divided. +-- Confirm at Castellum which of the two a 3x CHS2 plant actually returns. +-- +-- ═══ Battery presence ═════════════════════════════════════════════════════ +-- +-- A hybrid plant and a PV-only plant (the home manual also lists R5/R6) +-- share this map. paralltotalcap / parallUsercap at 0, SoC at 0 and battery +-- power at 0 do not mean an empty pack: nothing on the map has said a pack +-- exists. Emitting SoC 0 in that case is an empty battery the planner can +-- charge. The battery DER is emitted only when capacity is non-zero, SoC is +-- in 0.01%..100.00%, or battery power is non-zero. A real 0% pack that still +-- reports capacity is emitted, SoC and all. +-- +-- The capacity unit on the sheet is "K", not kWh and not Wh. The raw word +-- is a presence signal and a metric. It is not converted. +-- +-- ═══ Energy direction ═════════════════════════════════════════════════════ +-- +-- PV generation, battery charge and battery discharge totals are named on +-- the sheet and are copied onto the DER. FeedIn (0x852E) and Sell (0x8536) +-- are not: SAJ uses both words for both directions in different PDFs. They +-- are metrics under the vendor names, not meter import/export. +-- +-- ═══ Control 0x8400-0x8405 — NOT IMPLEMENTED ══════════════════════════════ +-- +-- EMS sheet (eManager), R/W: +-- 0x8400 EMSEnable U16 +-- 0 invalid / inverter's own mode +-- 1 inverter-power dispatch, follows 0x8402 +-- 2 battery-power dispatch, follows 0x8405 +-- (the sheet says SEC-C does not support 2) +-- 0x8401 EMSKeepTime U16 seconds, default 10, range 0..60000. +-- Heartbeat. On timeout the machine outputs 0. +-- 0x8402 EMSINVPRef I16 magnification -4 unit % range -11000..11000 +-- Positive: discharge / export toward the target. +-- Negative: import and charge toward the target. +-- 0x8403 EMSBATChargCurrentLimit U16 magnification -1 A +-- 0x8404 EMSBATDisChargCurrentLimit U16 magnification -1 A +-- Both marked "Temporarily Closed" on the sheet. +-- 0x8405 EMSBATPRef I16 same scaling and sign as 0x8402, battery target. +-- +-- Scaling is unverified. Magnification -4 means ×10^-4, so raw 10000 = 1.00 +-- and raw 11000 = 1.10. Read as a fraction of rated power, that is 100% and +-- 110%, i.e. 0.01 percentage points per step. The unit column says "%" +-- which would be the same limit if the step were 0.01% (magnification -2). +-- Both readings of the sheet put the documented stop at ±110% of rated. +-- OpenEMS CH2 states the same numbers from the unpublished CH2 EMS protocol +-- (10000 = 100%, ±110%, positive discharges) and was not run on hardware. +-- +-- SEC-C anti-backflow reuses 0x8400-0x8404 with different meanings (0 off, +-- 1 phase power limit, 2 phase current limit, 3 total power limit; 0x8402 +-- is then a ±110% grid limit at magnification -2). Writing the EMS encoding +-- to a SEC-C, or the reverse, would select the wrong mode. This driver +-- targets the eManager EMS sheet and writes neither block. +-- +-- A future control path has to prove, on a named eManager and firmware: +-- held zero, charge, discharge, heartbeat refresh, and a release back to +-- EMSEnable 0. Until then driver_command refuses and driver_default_mode +-- does not write. + +DRIVER = { + id = "saj-emanager", + name = "SAJ eManager C1 Pro", + manufacturer = "SAJ", + version = "0.1.1", + host_api_min = 1, + host_api_max = 1, + protocols = { "modbus" }, + capabilities = { "pv", "battery", "meter" }, + read_only = true, + description = "SAJ eManager C1 Pro site controller (Modbus TCP only, port 502; RTU is not supported) in front of CHS2/CH2 hybrids. Aggregate PV, battery and grid telemetry. Read-only. Not tested on hardware.", + homepage = "https://www.saj-electric.com", + authors = { "Sourceful Labs AB" }, + tested_models = { "eManager C1 Pro" }, + verification_status = "experimental", + verification_notes = "Decoded from the community eManager/SEC-C register workbook on home-assistant-saj-h2-modbus discussion 182, cross-checked against Eniris and the OpenEMS CH2 module. Not tested on hardware. Control registers 0x8400-0x8405 are documented and not written. First site to check: Castellum Örebro.", + connection_defaults = { + port = 502, + unit_id = 1, + }, +} + +PROTOCOL = "modbus" + +---------------------------------------------------------------------------- +-- Register map +---------------------------------------------------------------------------- + +local REG_DEVICE_NUM = 0x4A00 +local REG_SLOT0 = 0x4A01 +local SLOT_STRIDE = 12 +local SN_WORDS = 10 +local MAX_DEVICES = 21 +-- Stay under the usual 125-word Modbus ceiling. 10 slots = 120 words. +local SLOTS_PER_READ = 10 + +-- 0x848A .. 0x849D. One read, 20 words. Layout is 1-based in the block. +local REG_SUMMARY = 0x848A +local SUMMARY_WORDS = 20 +local IDX_MODE = 1 +local IDX_RATED = 2 -- uint32 +local IDX_INV = 4 -- int32 TotalInvPowerWatt +local IDX_PV = 6 -- uint32 TotalPVPower +local IDX_BAT = 8 -- int32 TotalBatteryPower +local IDX_LOAD = 10 -- int32 +local IDX_SOC = 12 -- uint16 × 0.01 % +local IDX_GRID = 13 -- int32 TotalGridPowerWatt +local IDX_GEN = 15 -- int32 +local IDX_CAP = 17 -- uint32 paralltotalcap, unit "K" +local IDX_USERCAP = 19 -- uint32 parallUsercap, unit "K" + +-- 0x849E .. 0x84B5. R, S, T. 8 words: V, I, f, P, S, PF. +local REG_PHASES = 0x849E +local PHASES_WORDS = 24 +local PHASE_WORDS = 8 + +-- 0x8500 .. 0x854F. Pairs of uint32 × 0.01 kWh. Pair 0 is 0x8500. +local REG_ENERGY = 0x8500 +local ENERGY_WORDS = 80 +local PAIR_TOTAL_PV = 3 -- 0x8506 +local PAIR_TOTAL_BAT_CHG = 7 -- 0x850E +local PAIR_TOTAL_BAT_DIS = 11 -- 0x8516 +local PAIR_TOTAL_FEED_IN = 23 -- 0x852E +local PAIR_TOTAL_SELL = 27 -- 0x8536 + +-- MPVMode 5 is "Fault" on the sheet. +local MODE_FAULT = 5 + +-- One-phase bands for the Eniris sum heuristic. See the header. +local VOLT_SUSPECT = 320 +local VOLT_OK_LO = 180 +local VOLT_OK_HI = 280 +local HZ_SUSPECT = 70 +local HZ_OK_LO = 45 +local HZ_OK_HI = 65 + +local PHASE_NAMES = { "L1", "L2", "L3" } + +---------------------------------------------------------------------------- +-- Decoding +---------------------------------------------------------------------------- + +local function finite(value) + if value ~= value then return nil end + if value == math.huge or value == -math.huge then return nil end + return value +end + +local function scaled(raw, factor) + if raw == nil then return nil end + return finite(raw * factor) +end + +-- 0xFFFFFFFF is not a capacity or an energy total. Leave it out. +local function u32_at(regs, index) + local hi, lo = regs[index], regs[index + 1] + if hi == nil or lo == nil then return nil end + if hi == 0xFFFF and lo == 0xFFFF then return nil end + return host.decode_u32_be(hi, lo) +end + +-- 0x7FFFFFFF and 0x80000000 are not a site power. The sheet does not name +-- them as sentinels; they are rejected because they are not a measurement. +local function i32_at(regs, index) + local hi, lo = regs[index], regs[index + 1] + if hi == nil or lo == nil then return nil end + local raw = host.decode_i32_be(hi, lo) + if raw == 2147483647 or raw == -2147483648 then return nil end + return raw +end + +-- 0.01 kWh → Wh. A decoded 0 stays 0: the device said zero. +local function u32_wh(regs, index) + local raw = u32_at(regs, index) + if raw == nil then return nil end + return finite(raw * 10) +end + +local function pair_wh(regs, pair) + return u32_wh(regs, pair * 2 + 1) +end + +-- SoC: uint16 × 0.01 percent → fraction 0..1. 0xFFFF and anything above +-- 100.00% are not a state of charge. +local function soc_fraction(raw) + if raw == nil or raw == 0xFFFF or raw > 10000 then return nil end + return raw / 10000 +end + +-- Site meter watts: positive imports, negative exports. +-- Wire assumption (H2, unverified here): already import-positive, so no flip. +local function grid_watts(vendor) + return vendor +end + +-- Site battery watts: positive charges, negative discharges. +-- Wire assumption (H2 and the 0x8405 text, unverified here): positive on +-- 0x8491 is discharge, so negate once. +local function battery_watts(vendor) + if vendor == nil then return nil end + return -vendor +end + +-- Divide only when the sheet scale is implausible AND DeviceNum explains it. +-- Returns the value to publish, and whether a divide was applied. +local function unsum_if_indicated(value, device_count, suspect_above, ok_lo, ok_hi) + if value == nil then return nil, false end + if value == 0 then return 0, false end + if device_count ~= nil and device_count >= 2 and device_count <= MAX_DEVICES + and value > suspect_above then + local corrected = finite(value / device_count) + if corrected ~= nil and corrected >= ok_lo and corrected <= ok_hi then + return corrected, true + end + end + return value, false +end + +---------------------------------------------------------------------------- +-- Reading registers that may not exist +-- +-- The host counts every failed host.modbus_read against the poll whether or +-- not this driver caught the error. Three misses, then stop until restart. +-- A short reply is a miss: the missing words are nil, never a filled-in 0. +-- +-- The summary block does not go through here. When it fails the driver +-- emits no DER at all, so a blip cannot silence the plant for the session +-- and a permanent failure does not claim the device is fine. +---------------------------------------------------------------------------- + +local GIVE_UP_AFTER = 3 +local read_failures = {} +local announced = false + +local function complete(regs, count) + if regs == nil then return false end + for i = 1, count do + if regs[i] == nil then return false end + end + return true +end + +local function probe_read(addr, count, kind) + if (read_failures[addr] or 0) >= GIVE_UP_AFTER then return nil end + local ok, regs = pcall(host.modbus_read, addr, count, kind) + if ok and complete(regs, count) then + read_failures[addr] = nil + return regs + end + local failures = (read_failures[addr] or 0) + 1 + read_failures[addr] = failures + if failures == GIVE_UP_AFTER then + host.log("info", string.format( + "SAJ eManager: register %d did not answer %d times; leaving it " .. + "alone until restart", addr, GIVE_UP_AFTER)) + end + return nil +end + +local function required_read(addr, count, kind) + local ok, regs = pcall(host.modbus_read, addr, count, kind) + if ok and complete(regs, count) then return regs end + return nil +end + +---------------------------------------------------------------------------- +-- Identity. DeviceNum decides how many slots exist; we do not scan 21. +---------------------------------------------------------------------------- + +local function read_device_count() + local regs = probe_read(REG_DEVICE_NUM, 1, "holding") + if not regs then return nil end + local n = regs[1] + if n == nil or n == 0xFFFF or n > MAX_DEVICES then return nil end + return n +end + +local function decode_slots(regs, n) + local devices = {} + for i = 0, n - 1 do + local base = i * SLOT_STRIDE + local sn = host.decode_string(regs, base + 1, SN_WORDS) + if sn == "" then sn = nil end + devices[#devices + 1] = { + sn = sn, + id = regs[base + SN_WORDS + 1], + } + end + return devices +end + +local function read_slots(count) + if count == nil or count < 1 then return nil end + local devices = {} + local done = 0 + while done < count do + local n = math.min(count - done, SLOTS_PER_READ) + local addr = REG_SLOT0 + done * SLOT_STRIDE + local regs = probe_read(addr, n * SLOT_STRIDE, "holding") + if not regs then return nil end + local part = decode_slots(regs, n) + for _, device in ipairs(part) do + devices[#devices + 1] = device + end + done = done + n + end + return devices +end + +local function first_sn(devices) + if not devices then return nil end + for _, device in ipairs(devices) do + if device.sn then return device.sn end + end + return nil +end + +local function note_identity(device_count, devices) + local sn = first_sn(devices) + if sn then host.set_sn(sn) end + if device_count ~= nil then + host.emit_metric("saj_emanager_device_count", device_count) + end + if announced or device_count == nil then return end + announced = true + host.log("info", string.format( + "SAJ eManager: DeviceNum=%d first SN=%s", + device_count, sn or "(none)")) +end + +---------------------------------------------------------------------------- +-- Summary block → DER fields. Nil means the word did not decode. +---------------------------------------------------------------------------- + +local function battery_indicated(cap, user, soc_raw, bat_w) + if cap ~= nil and cap > 0 then return true end + if user ~= nil and user > 0 then return true end + if soc_raw ~= nil and soc_raw > 0 and soc_raw <= 10000 then return true end + if bat_w ~= nil and bat_w ~= 0 then return true end + return false +end + +local function decode_summary(regs) + local mode = regs[IDX_MODE] + if mode ~= nil and mode ~= 0xFFFF then + host.emit_metric("saj_emanager_mpv_mode", mode) + if mode == MODE_FAULT then + host.set_device_fault(true, "MPVMode 5 fault") + else + host.set_device_fault(false, "") + end + end + + local rated = u32_at(regs, IDX_RATED) + if rated ~= nil and rated > 0 then host.set_rated_w(rated) end + + local pv_w = u32_at(regs, IDX_PV) + local bat_w = i32_at(regs, IDX_BAT) + local grid_w = i32_at(regs, IDX_GRID) + local cap = u32_at(regs, IDX_CAP) + local user = u32_at(regs, IDX_USERCAP) + local soc_raw = regs[IDX_SOC] + + -- No stated sign on these three. Keep the raw word off the DER streams. + local inv_w = i32_at(regs, IDX_INV) + if inv_w ~= nil then host.emit_metric("saj_emanager_inv_w_vendor", inv_w) end + local load_w = i32_at(regs, IDX_LOAD) + if load_w ~= nil then host.emit_metric("saj_emanager_load_w_vendor", load_w) end + local gen_w = i32_at(regs, IDX_GEN) + if gen_w ~= nil and gen_w ~= 0 then + host.emit_metric("saj_emanager_gen_w_vendor", gen_w) + end + + local pv = {} + -- Generation is negative in every driver in this repository. + if pv_w ~= nil then pv.W = -pv_w end + + local meter = {} + if grid_w ~= nil then meter.W = grid_watts(grid_w) end + + local battery = nil + if battery_indicated(cap, user, soc_raw, bat_w) then + battery = {} + local site_bat = battery_watts(bat_w) + if site_bat ~= nil then battery.W = site_bat end + local soc = soc_fraction(soc_raw) + if soc ~= nil then battery.SoC_nom_fract = soc end + if cap ~= nil then + host.emit_metric("saj_emanager_battery_capacity_raw", cap) + end + if user ~= nil then + host.emit_metric("saj_emanager_battery_available_raw", user) + end + end + + return pv, meter, battery +end + +local function apply_phases(meter, regs, device_count) + local divided = false + local hz + for i, name in ipairs(PHASE_NAMES) do + local b = (i - 1) * PHASE_WORDS + local volts = scaled(regs[b + 1], 0.1) + local amps = nil + if regs[b + 2] ~= nil then + amps = scaled(host.decode_i16(regs[b + 2]), 0.1) + end + local freq = scaled(regs[b + 3], 0.01) + local watts = i32_at(regs, b + 4) + local v_out, v_div = unsum_if_indicated( + volts, device_count, VOLT_SUSPECT, VOLT_OK_LO, VOLT_OK_HI) + local f_out, f_div = unsum_if_indicated( + freq, device_count, HZ_SUSPECT, HZ_OK_LO, HZ_OK_HI) + if v_div or f_div then divided = true end + if v_out ~= nil then meter[name .. "_V"] = v_out end + if amps ~= nil then meter[name .. "_A"] = amps end + local site_w = grid_watts(watts) + if site_w ~= nil then meter[name .. "_W"] = site_w end + if i == 1 then hz = f_out end + end + if hz ~= nil then meter.Hz = hz end + return divided +end + +local function apply_energy(pv, battery, regs) + local pv_wh = pair_wh(regs, PAIR_TOTAL_PV) + if pv_wh ~= nil then pv.lifetime_wh = pv_wh end + if battery then + local chg = pair_wh(regs, PAIR_TOTAL_BAT_CHG) + local dis = pair_wh(regs, PAIR_TOTAL_BAT_DIS) + if chg ~= nil then battery.total_charge_Wh = chg end + if dis ~= nil then battery.total_discharge_Wh = dis end + end + -- Vendor names, deliberately not import_wh / export_wh. + local feed = pair_wh(regs, PAIR_TOTAL_FEED_IN) + local sell = pair_wh(regs, PAIR_TOTAL_SELL) + if feed ~= nil then host.emit_metric("saj_emanager_vendor_feed_in_wh", feed) end + if sell ~= nil then host.emit_metric("saj_emanager_vendor_sell_wh", sell) end +end + +local function emit_der(kind, fields) + if next(fields) ~= nil then host.emit(kind, fields) end +end + +---------------------------------------------------------------------------- +-- Entry points +---------------------------------------------------------------------------- + +function driver_init(config) + host.set_make("SAJ") + host.set_model("eManager C1 Pro") +end + +function driver_poll() + local device_count = read_device_count() + local devices = read_slots(device_count) + note_identity(device_count, devices) + + local summary = required_read(REG_SUMMARY, SUMMARY_WORDS, "holding") + if not summary then return 5000 end + + local pv, meter, battery = decode_summary(summary) + + local phases = probe_read(REG_PHASES, PHASES_WORDS, "holding") + local divided = false + if phases then + divided = apply_phases(meter, phases, device_count) + end + if divided and device_count ~= nil then + host.emit_metric("saj_emanager_phase_scale_divisor", device_count) + elseif phases and device_count ~= nil and device_count >= 1 then + host.emit_metric("saj_emanager_phase_scale_divisor", 1) + end + + local energy = probe_read(REG_ENERGY, ENERGY_WORDS, "holding") + if energy then + apply_energy(pv, battery, energy) + end + + emit_der("pv", pv) + emit_der("meter", meter) + if battery then emit_der("battery", battery) end + + return 5000 +end + +function driver_command(action, power_w, cmd) + if action == "init" or action == "deinit" then + return true + end + host.log("warn", "SAJ eManager: control is not enabled (action=" .. + tostring(action) .. ")") + return false +end + +function driver_default_mode() + -- Read-only: nothing was taken, so there is nothing to release. + -- 0x8400 is not written back to 0 from here. +end + +function driver_cleanup() + announced = false + read_failures = {} +end diff --git a/drivers/tests/test_saj-emanager.py b/drivers/tests/test_saj-emanager.py new file mode 100644 index 0000000..a8f79fb --- /dev/null +++ b/drivers/tests/test_saj-emanager.py @@ -0,0 +1,581 @@ +"""SAJ eManager C1 Pro: aggregate Modbus TCP telemetry, no fabricated zeros. + +The register sheet is the community workbook on +stanus74/home-assistant-saj-h2-modbus discussion 182. Nothing here was read +off a live controller. + +Site signs, same as the other drivers: generation is negative, battery +charge and grid import are positive, battery discharge and grid export are +negative. The H2 wire is the other way round on the battery only, so the +fixture's battery word is discharge-positive and the assertions are the +site watts. 32-bit values are high word first. +""" + +from __future__ import annotations + +import math +import re +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +LUA = ROOT / "lua55" +HARNESS = ROOT / "drivers" / "tests" / "lua_harness" +DRIVER = ROOT / "drivers" / "lua" / "saj-emanager.lua" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + +REG_DEVICE_NUM = 0x4A00 +REG_SLOT0 = 0x4A01 +REG_SUMMARY = 0x848A +REG_PHASES = 0x849E +REG_ENERGY = 0x8500 +REG_CONTROL = 0x8400 + +SERIALS = ( + "CHS2TEST0000000001", + "CHS2TEST0000000002", + "CHS2TEST0000000003", +) + +# Sheet scales, raw register units. Signs are the vendor's, not the site's. +PV_W = 123456 # uint32 magnitude, high word first +BAT_W_VENDOR = -6000 # discharge-positive: negative means charging +GRID_W_VENDOR = -2500 # import-positive: negative means export +INV_W_VENDOR = 42000 +LOAD_W_VENDOR = 9000 +SOC_RAW = 7325 # 0.01 % → 73.25 % +RATED_W = 150000 +CAP_RAW = 200 # unit on the sheet is "K", not Wh +USER_RAW = 146 +PV_ENERGY_RAW = 123456 # 0.01 kWh +BAT_CHARGE_RAW = 50000 +BAT_DISCHARGE_RAW = 40000 +FEED_IN_RAW = 111 +SELL_RAW = 222 +DEVICE_COUNT = 3 + +# One phase, already on the sheet's scale. Must NOT be divided by 3. +L1_V_RAW = 2304 # 230.4 V +L1_A_RAW = 105 # 10.5 A +L2_A_RAW = -15 # -1.5 A +L1_HZ_RAW = 5002 # 50.02 Hz +L1_W = -800 +L2_W = -700 +L3_W = -1000 + + +def _ascii_regs(text: str, width: int) -> list[int]: + padded = text.encode("ascii").ljust(width * 2, b"\x00") + return [padded[i] << 8 | padded[i + 1] for i in range(0, width * 2, 2)] + + +def _u32_regs(value: int) -> list[int]: + return [(value >> 16) & 0xFFFF, value & 0xFFFF] + + +def _i32_regs(value: int) -> list[int]: + raw = value & 0xFFFFFFFF + return [(raw >> 16) & 0xFFFF, raw & 0xFFFF] + + +def _i16(value: int) -> int: + return value & 0xFFFF + + +def _lua_list(values) -> str: + return "{" + ", ".join(str(int(v)) for v in values) + "}" + + +def _put_pair(buf: list[int], pair: int, value: int) -> None: + hi, lo = _u32_regs(value) + buf[pair * 2] = hi + buf[pair * 2 + 1] = lo + + +def fixture_registers(*, pack: str = "yes", summed: bool = False, + count: int = DEVICE_COUNT) -> str: + """Three CHS2s behind one eManager, unless count says otherwise. + + pack: "yes" (capacity + SoC + power), "no" (all zero), "power" (only + battery watts), "soc_sentinel" (capacity, SoC word 0xFFFF). + summed: phase volts and hertz are DeviceNum times a normal phase, which + is the Eniris observation the sheet itself does not document. + """ + slots: list[int] = [] + n_slots = count if 1 <= count <= 21 else 0 + for i in range(n_slots): + slots.extend(_ascii_regs(SERIALS[i], 10)) + slots.append(i + 1) # inverter Modbus id + slots.append(0) # reserved + + summary = [0] * 20 + summary[0] = 2 # MPVMode grid-connected + summary[1:3] = _u32_regs(RATED_W) + summary[3:5] = _i32_regs(INV_W_VENDOR) + summary[5:7] = _u32_regs(PV_W) + summary[9:11] = _i32_regs(LOAD_W_VENDOR) + summary[12:14] = _i32_regs(GRID_W_VENDOR) + # generator stays 0: no metric + if pack == "no": + summary[7:9] = _i32_regs(0) + summary[11] = 0 + summary[16:18] = _u32_regs(0) + summary[18:20] = _u32_regs(0) + elif pack == "power": + summary[7:9] = _i32_regs(BAT_W_VENDOR) + summary[11] = 0 + summary[16:18] = _u32_regs(0) + summary[18:20] = _u32_regs(0) + elif pack == "soc_sentinel": + summary[7:9] = _i32_regs(BAT_W_VENDOR) + summary[11] = 0xFFFF + summary[16:18] = _u32_regs(CAP_RAW) + summary[18:20] = _u32_regs(USER_RAW) + else: + summary[7:9] = _i32_regs(BAT_W_VENDOR) + summary[11] = SOC_RAW + summary[16:18] = _u32_regs(CAP_RAW) + summary[18:20] = _u32_regs(USER_RAW) + + hz_raw = L1_HZ_RAW * count if summed and count > 1 else L1_HZ_RAW + phases: list[int] = [] + for phase, watts in enumerate((L1_W, L2_W, L3_W)): + amps = (L1_A_RAW, L2_A_RAW, 200)[phase] + # Each phase's own voltage, summed across inverters when `summed`. + volts = L1_V_RAW + phase + if summed and count > 1: + volts *= count + phases.extend([ + volts, + _i16(amps), + hz_raw, + *_i32_regs(watts), + 0, 0, # apparent power, unused + 1000, # power factor × 0.001, unused + ]) + + energy = [0] * 80 + _put_pair(energy, 3, PV_ENERGY_RAW) # 0x8506 total PV + _put_pair(energy, 7, BAT_CHARGE_RAW) # 0x850E + _put_pair(energy, 11, BAT_DISCHARGE_RAW) # 0x8516 + _put_pair(energy, 23, FEED_IN_RAW) # 0x852E + _put_pair(energy, 27, SELL_RAW) # 0x8536 + + lines = [ + f"host._modbus_registers.holding[{REG_DEVICE_NUM}] = {{{count}}}", + f"host._modbus_registers.holding[{REG_SUMMARY}] = {_lua_list(summary)}", + f"host._modbus_registers.holding[{REG_PHASES}] = {_lua_list(phases)}", + f"host._modbus_registers.holding[{REG_ENERGY}] = {_lua_list(energy)}", + ] + if slots: + lines.append( + f"host._modbus_registers.holding[{REG_SLOT0}] = {_lua_list(slots)}") + return "\n".join(lines) + + +def run_lua(body: str) -> dict[str, str]: + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() +{body} +''' + result = subprocess.run([str(LUA), "-e", script], + capture_output=True, text=True, cwd=ROOT) + assert result.returncode == 0, result.stdout + result.stderr + return dict(line.split(" ", 1) + for line in result.stdout.strip().splitlines() if " " in line) + + +REPORT = f''' +local function last(t) return t and t[#t] or nil end +local function field(obj, key) + if obj == nil or obj[key] == nil then return "nil" end + return tostring(obj[key]) +end +local function metric(name) + local m = host._metrics[name] + if m == nil or m.value == nil then return "nil" end + return tostring(m.value) +end +local pv = last(host._emitted["pv"]) +local bat = last(host._emitted["battery"]) +local met = last(host._emitted["meter"]) +print("PV_EMITS " .. tostring(host._emitted["pv"] and #host._emitted["pv"] or 0)) +print("BAT_EMITS " .. tostring(host._emitted["battery"] and #host._emitted["battery"] or 0)) +print("MET_EMITS " .. tostring(host._emitted["meter"] and #host._emitted["meter"] or 0)) +print("PV_W " .. field(pv, "W")) +print("PV_WH " .. field(pv, "lifetime_wh")) +print("BAT_W " .. field(bat, "W")) +print("BAT_SOC " .. field(bat, "SoC_nom_fract")) +print("BAT_CHG " .. field(bat, "total_charge_Wh")) +print("BAT_DIS " .. field(bat, "total_discharge_Wh")) +print("MET_W " .. field(met, "W")) +print("MET_HZ " .. field(met, "Hz")) +print("MET_L1V " .. field(met, "L1_V")) +print("MET_L1A " .. field(met, "L1_A")) +print("MET_L1W " .. field(met, "L1_W")) +print("MET_L2A " .. field(met, "L2_A")) +print("MET_L2W " .. field(met, "L2_W")) +print("MET_L3V " .. field(met, "L3_V")) +print("MET_L3W " .. field(met, "L3_W")) +print("MET_IMPORT " .. field(met, "total_import_Wh")) +print("MET_EXPORT " .. field(met, "total_export_Wh")) +print("MAKE " .. tostring(host._make)) +print("MODEL " .. tostring(host._model)) +print("SN " .. tostring(host._sn)) +print("RATED " .. tostring(host._rated_w)) +print("FAULT " .. tostring(host._faulted)) +print("COUNT " .. metric("saj_emanager_device_count")) +print("DIVISOR " .. metric("saj_emanager_phase_scale_divisor")) +print("LOAD " .. metric("saj_emanager_load_w_vendor")) +print("INV " .. metric("saj_emanager_inv_w_vendor")) +print("GEN " .. metric("saj_emanager_gen_w_vendor")) +print("CAP " .. metric("saj_emanager_battery_capacity_raw")) +print("FEED " .. metric("saj_emanager_vendor_feed_in_wh")) +print("SELL " .. metric("saj_emanager_vendor_sell_wh")) +local slot_reads, slot_count, control_reads, bad_kind = 0, 0, 0, 0 +for _, call in ipairs(host._calls) do + if call.func == "modbus_read" then + if call.args[1] == {REG_SLOT0} then + slot_reads = slot_reads + 1 + slot_count = call.args[2] + end + if call.args[1] == {REG_CONTROL} then + control_reads = control_reads + 1 + end + if call.args[3] ~= "holding" then bad_kind = bad_kind + 1 end + end +end +print("SLOT_READS " .. tostring(slot_reads)) +print("SLOT_COUNT " .. tostring(slot_count)) +print("CONTROL_READS " .. tostring(control_reads)) +print("BAD_KIND " .. tostring(bad_kind)) +print("WRITES " .. tostring(host._modbus_write_attempts)) +''' + + +def poll_once(extra: str = "", **fixture) -> dict[str, str]: + return run_lua(f''' +{fixture_registers(**fixture)} +{extra} +dofile("{DRIVER}") +driver_init({{}}) +local interval = driver_poll() +print("INTERVAL " .. tostring(interval)) +{REPORT} +''') + + +def test_three_inverter_plant_in_site_convention(): + out = poll_once() + + assert out["INTERVAL"] == "5000" + assert out["MAKE"] == "SAJ" + assert out["MODEL"] == "eManager C1 Pro" + assert out["SN"] == SERIALS[0] + assert out["COUNT"] == "3" + assert out["RATED"] == str(RATED_W) + assert out["FAULT"] == "false" + assert out["BAD_KIND"] == "0" + assert out["CONTROL_READS"] == "0" + assert out["WRITES"] == "0" + # One read of the three slots, not a scan of all 21. + assert out["SLOT_READS"] == "1" + assert out["SLOT_COUNT"] == str(DEVICE_COUNT * 12) + + assert out["PV_EMITS"] == "1" + # Generation is negative, same as the other drivers. + assert float(out["PV_W"]) == -PV_W + assert float(out["PV_W"]) < 0 + assert float(out["PV_WH"]) == PV_ENERGY_RAW * 10 + + # Wire -6000 is charging on a discharge-positive register. Site charge is +. + assert out["BAT_EMITS"] == "1" + assert float(out["BAT_W"]) == 6000 + assert math.isclose(float(out["BAT_SOC"]), SOC_RAW / 10000, rel_tol=1e-6) + assert float(out["BAT_CHG"]) == BAT_CHARGE_RAW * 10 + assert float(out["BAT_DIS"]) == BAT_DISCHARGE_RAW * 10 + assert out["CAP"] == str(CAP_RAW) + + # Wire -2500 is export on an import-positive register. Site export is −. + assert out["MET_EMITS"] == "1" + assert float(out["MET_W"]) == -2500 + assert math.isclose(float(out["MET_HZ"]), L1_HZ_RAW / 100, rel_tol=1e-6) + assert math.isclose(float(out["MET_L1V"]), L1_V_RAW / 10, rel_tol=1e-6) + assert math.isclose(float(out["MET_L1A"]), L1_A_RAW / 10, rel_tol=1e-6) + assert math.isclose(float(out["MET_L2A"]), L2_A_RAW / 10, rel_tol=1e-6) + assert float(out["MET_L1W"]) == L1_W + assert float(out["MET_L2W"]) == L2_W + assert float(out["MET_L3W"]) == L3_W + assert math.isclose(float(out["MET_L3V"]), (L1_V_RAW + 2) / 10, rel_tol=1e-6) + # Sheet scale was already one phase, so the divisor stays 1. + assert out["DIVISOR"] == "1" + # FeedIn / Sell stay vendor metrics. They are not import and export. + assert out["MET_IMPORT"] == "nil" + assert out["MET_EXPORT"] == "nil" + assert float(out["FEED"]) == FEED_IN_RAW * 10 + assert float(out["SELL"]) == SELL_RAW * 10 + assert float(out["LOAD"]) == LOAD_W_VENDOR + assert float(out["INV"]) == INV_W_VENDOR + assert out["GEN"] == "nil" + + +def _i32_words(value: int) -> tuple[int, int]: + hi, lo = _i32_regs(value) + return hi, lo + + +def test_site_signs_both_directions(): + """Sourceful: charge/import positive, discharge/export/generation negative. + + Same boundary as drivers/lua/saj.lua. The H2 wire is discharge-positive + on the battery and import-positive on the grid; this driver flips only + the battery. + """ + charging = poll_once() + assert float(charging["BAT_W"]) == 6000 + assert float(charging["MET_W"]) == -2500 + assert float(charging["MET_L1W"]) == -800 + assert float(charging["PV_W"]) == -PV_W + + discharge_hi, discharge_lo = _i32_words(4500) # wire: discharging + import_hi, import_lo = _i32_words(1800) # wire: importing + phase_hi, phase_lo = _i32_words(400) # wire: L1 importing + out = poll_once( + f"host._modbus_registers.holding[{REG_SUMMARY}][8] = {discharge_hi}\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][9] = {discharge_lo}\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][13] = {import_hi}\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][14] = {import_lo}\n" + f"host._modbus_registers.holding[{REG_PHASES}][4] = {phase_hi}\n" + f"host._modbus_registers.holding[{REG_PHASES}][5] = {phase_lo}") + assert float(out["BAT_W"]) == -4500 + assert float(out["MET_W"]) == 1800 + assert float(out["MET_L1W"]) == 400 + assert float(out["PV_W"]) < 0 + + +def test_summed_voltage_and_frequency_are_divided_power_is_not(): + """Eniris: 3 inverters can report 3×230 V and 3×50 Hz. Watts stay summed.""" + out = poll_once(summed=True) + + assert math.isclose(float(out["MET_L1V"]), L1_V_RAW / 10, rel_tol=1e-6) + assert math.isclose(float(out["MET_HZ"]), L1_HZ_RAW / 100, rel_tol=1e-6) + assert math.isclose(float(out["MET_L3V"]), (L1_V_RAW + 2) / 10, rel_tol=1e-6) + assert out["DIVISOR"] == "3" + # Current and power are not part of that correction. + assert math.isclose(float(out["MET_L1A"]), L1_A_RAW / 10, rel_tol=1e-6) + assert float(out["MET_L1W"]) == L1_W + assert float(out["PV_W"]) == -PV_W + assert float(out["MET_W"]) == GRID_W_VENDOR + + +def test_implausible_voltage_that_does_not_divide_cleanly_is_left_alone(): + """400 V / 3 is not a phase voltage, so the sheet scale is published.""" + out = poll_once( + f"host._modbus_registers.holding[{REG_PHASES}][1] = 4000") + assert math.isclose(float(out["MET_L1V"]), 400.0, rel_tol=1e-6) + assert out["DIVISOR"] == "1" + + +def test_sum_is_not_guessed_when_device_count_did_not_answer(): + out = poll_once( + f'host._modbus_read_fail_addresses[{REG_DEVICE_NUM}] = "timeout"\n' + f"host._modbus_registers.holding[{REG_PHASES}][3] = 15000") + assert out["COUNT"] == "nil" + assert out["DIVISOR"] == "nil" + assert out["SN"] == "nil" + assert out["SLOT_READS"] == "0" + # 150.00 Hz stays 150.00 Hz. Inventing a divisor of 3 would hide that. + assert math.isclose(float(out["MET_HZ"]), 150.0, rel_tol=1e-6) + assert out["PV_EMITS"] == "1" + + +def test_no_battery_when_capacity_soc_and_power_are_zero(): + out = poll_once(pack="no") + assert out["BAT_EMITS"] == "0" + assert out["CAP"] == "nil" + assert out["PV_EMITS"] == "1" + assert out["MET_EMITS"] == "1" + assert float(out["PV_W"]) == -PV_W + + +def test_battery_from_power_alone(): + """A non-zero battery watt is a pack, even when SoC and capacity read 0.""" + out = poll_once(pack="power") + assert out["BAT_EMITS"] == "1" + assert float(out["BAT_W"]) == 6000 + assert float(out["BAT_SOC"]) == 0.0 + + +def test_soc_sentinel_is_omitted(): + out = poll_once(pack="soc_sentinel") + assert out["BAT_EMITS"] == "1" + assert out["BAT_SOC"] == "nil" + assert float(out["BAT_W"]) == 6000 + + +def test_device_zero_is_emitted_a_failed_read_is_not(): + """Night-time 0 W is the device. A missed summary is silence, not 0 W.""" + zeros = poll_once( + f"host._modbus_registers.holding[{REG_SUMMARY}][6] = 0\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][7] = 0\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][13] = 0\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][14] = 0") + assert zeros["PV_EMITS"] == "1" + assert float(zeros["PV_W"]) == 0 + assert zeros["MET_EMITS"] == "1" + assert float(zeros["MET_W"]) == 0 + assert zeros["BAT_EMITS"] == "1" + + failed = poll_once( + f'host._modbus_read_fail_addresses[{REG_SUMMARY}] = "timeout"') + assert failed["PV_EMITS"] == "0" + assert failed["MET_EMITS"] == "0" + assert failed["BAT_EMITS"] == "0" + assert failed["PV_W"] == "nil" + assert failed["MET_W"] == "nil" + + +def test_short_summary_emits_nothing(): + out = poll_once( + f"host._modbus_read_short_counts[{REG_SUMMARY}] = 10") + assert out["PV_EMITS"] == "0" + assert out["MET_EMITS"] == "0" + assert out["BAT_EMITS"] == "0" + assert out["PV_W"] == "nil" + assert out["RATED"] == "nil" + + +def test_short_phase_block_does_not_zero_fill(): + out = poll_once( + f"host._modbus_read_short_counts[{REG_PHASES}] = 8") + assert out["MET_EMITS"] == "1" + assert float(out["MET_W"]) == GRID_W_VENDOR + assert out["MET_L1V"] == "nil" + assert out["MET_L1W"] == "nil" + assert out["MET_HZ"] == "nil" + assert out["DIVISOR"] == "nil" + + +def test_phase_failure_keeps_the_totals(): + out = poll_once( + f'host._modbus_read_fail_addresses[{REG_PHASES}] = "Illegal Data Address"') + assert float(out["MET_W"]) == GRID_W_VENDOR + assert out["MET_L1V"] == "nil" + assert float(out["PV_W"]) == -PV_W + + +def test_energy_failure_omits_counters(): + out = poll_once( + f'host._modbus_read_fail_addresses[{REG_ENERGY}] = "Illegal Data Address"') + assert float(out["PV_W"]) == -PV_W + assert out["PV_WH"] == "nil" + assert float(out["BAT_W"]) == 6000 + assert out["BAT_CHG"] == "nil" + assert out["BAT_DIS"] == "nil" + assert out["FEED"] == "nil" + assert out["SELL"] == "nil" + + +def test_int32_sentinel_is_not_a_power(): + out = poll_once( + f"host._modbus_registers.holding[{REG_SUMMARY}][13] = 0x7FFF\n" + f"host._modbus_registers.holding[{REG_SUMMARY}][14] = 0xFFFF") + assert out["MET_W"] == "nil" + assert float(out["MET_L1W"]) == L1_W + assert out["MET_EMITS"] == "1" + + +def test_zero_devices_does_not_scan_slots(): + out = poll_once(count=0) + assert out["COUNT"] == "0" + assert out["SLOT_READS"] == "0" + assert out["SN"] == "nil" + assert out["PV_EMITS"] == "1" + + +def test_sentinel_device_count_does_not_scan_slots(): + out = poll_once(count=0xFFFF) + assert out["COUNT"] == "nil" + assert out["SLOT_READS"] == "0" + + +def test_fault_mode_is_reported(): + out = poll_once( + f"host._modbus_registers.holding[{REG_SUMMARY}][1] = 5") + assert out["FAULT"] == "true" + assert out["PV_EMITS"] == "1" + + +def test_phase_absence_settles_and_keeps_pv(): + out = run_lua(f''' +{fixture_registers()} +host._modbus_read_fail_addresses[{REG_PHASES}] = "Illegal Data Address" +dofile("{DRIVER}") +driver_init({{}}) +for i = 1, 10 do + host._emitted = {{}} + pcall(driver_poll) +end +local reads = 0 +for _, call in ipairs(host._calls) do + if call.func == "modbus_read" and call.args[1] == {REG_PHASES} then + reads = reads + 1 + end +end +print("PHASE_READS " .. tostring(reads)) +print("PV_EMITS " .. tostring(host._emitted["pv"] and #host._emitted["pv"] or 0)) +''') + assert out["PHASE_READS"] == "3" + assert out["PV_EMITS"] == "1" + + +def test_command_and_default_mode_do_not_write(): + out = run_lua(f''' +{fixture_registers()} +dofile("{DRIVER}") +driver_init({{}}) +driver_poll() +local ret = driver_command("battery", 1000, {{}}) +local init_ret = driver_command("init", 0, {{}}) +local deinit_ret = driver_command("deinit", 0, {{}}) +driver_default_mode() +print("RET " .. tostring(ret)) +print("INIT " .. tostring(init_ret)) +print("DEINIT " .. tostring(deinit_ret)) +print("WRITES " .. tostring(host._modbus_write_attempts)) +''') + assert out["RET"] == "false" + assert out["INIT"] == "true" + assert out["DEINIT"] == "true" + assert out["WRITES"] == "0" + + +def _code_without_comments() -> str: + lines = [] + for line in DRIVER.read_text(encoding="utf-8").splitlines(): + lines.append(line.split("--", 1)[0]) + return "\n".join(lines) + + +def test_source_is_tcp_only_and_does_not_read_or_write_control(): + """The executable code never touches 0x8400. The comments do, on purpose.""" + text = DRIVER.read_text(encoding="utf-8") + code = _code_without_comments() + assert "RTU is not supported" in text + assert re.search(r"port\s*=\s*502", text) + # Mentioning the block in a string is the documentation. Reading or + # writing it is the bug. + assert not re.search(r"modbus_read\s*\([^)]*0x8400", code) + assert "modbus_write" not in code + assert "write_registers" not in code + assert "host.write" not in code + manifest = (ROOT / "manifests" / "saj-emanager.yaml").read_text(encoding="utf-8") + assert 'tier: community' in manifest + assert "control: false" in manifest + assert "RTU" in manifest diff --git a/index.yaml b/index.yaml index a0bdde4..5bdfa73 100644 --- a/index.yaml +++ b/index.yaml @@ -535,6 +535,15 @@ drivers: control: false size_bytes: 10858 sha256: "38749fb157e0929c26c31ccb9e8013e3ee81f584349be1dd7cc60792b9e3adeb" + - name: "saj-emanager" + version: "0.1.1" + tier: community + protocol: modbus + connectivity: local + ders: [pv, battery, meter] + control: false + size_bytes: 25082 + sha256: "4efc62ef56d5736e24895929d478a78788586796bb2d45be64acdd5051df640f" - name: "saj" version: "1.2.0" tier: community diff --git a/manifests/saj-emanager.yaml b/manifests/saj-emanager.yaml new file mode 100644 index 0000000..d9b5030 --- /dev/null +++ b/manifests/saj-emanager.yaml @@ -0,0 +1,38 @@ +name: "saj-emanager" +version: "0.1.1" +tier: community +author: "Sourceful Labs AB" +protocol: modbus +connectivity: local +ders: [pv, battery, meter] +control: false +tested_devices: + - manufacturer: "SAJ" + model_family: "eManager C1 Pro" + variants: ["eManager C1 Pro"] + regions: [] + firmware_versions: "" + notes: "Site controller in front of 1..N CHS2/CH2 C&I hybrids. Modbus TCP only, port 502; the register sheet marks RTU as not supported. Telemetry only, decoded from the community eManager/SEC-C workbook. Not tested on hardware. First check is Castellum Örebro (3x CHS2 50 kW). Control 0x8400-0x8405 is documented and not written." + min_driver_version: "0.1.0" +upstream_docs: + - url: "https://github.com/stanus74/home-assistant-saj-h2-modbus/discussions/182" + title: "Community eManager/SEC-C Modbus workbook (discussion attachment, not an official SAJ map)" + kind: register_map + url_stability: volatile + - url: "https://docs.eniris.com/en/Controller/Devices/PV-hybrid-and-battery-inverters/SAJ" + title: "Eniris SmartgridOne SAJ eManager-C1 Pro connection notes" + kind: other + url_stability: stable + - url: "https://www.saj-electric.com/hubfs/Guides%20and%20Manuals/eManager/eManager_User_Manual_V3_en.pdf" + title: "SAJ eManager user manual V3 (home controller; LAN Modbus, not the C&I register map)" + kind: manual + url_stability: stable +min_host_version: "2.0.0" +size_bytes: 25082 +dkb_id: "" +sha256: "4efc62ef56d5736e24895929d478a78788586796bb2d45be64acdd5051df640f" +signature: "" +bytecode_sha256: "" +bytecode_signature: "" +bytecode_size: 0 +changelog: "Site signs match the catalog: PV negative, battery positive when charging, grid positive on import. Still read-only and untested on hardware." diff --git a/support-status.json b/support-status.json index 403c1de..228c835 100644 --- a/support-status.json +++ b/support-status.json @@ -1218,6 +1218,27 @@ } } }, + { + "catalog_source": true, + "catalog_version": "0.1.1", + "driver_id": "saj-emanager", + "targets": { + "blixt-l1": { + "hil": "not_recorded", + "historical_signed_beta_version": null, + "legacy_parity": "not_assessed", + "note": "", + "target_conformance": "not_assessed" + }, + "ftw-core": { + "hil": "not_recorded", + "historical_signed_beta_version": null, + "legacy_parity": "not_assessed", + "note": "", + "target_conformance": "not_assessed" + } + } + }, { "catalog_source": true, "catalog_version": "1.2.0", From 87473782f886a6bc731fce7097d968f7368b37bf Mon Sep 17 00:00:00 2001 From: David Mozart Date: Wed, 4 Nov 2026 12:52:21 +0100 Subject: [PATCH 6/8] fix(saj-emanager): use the saj brand key (#212) NovaCore rejects set_make("SAJ") and does not provide emit_metric. Device count and the phase divisor are logged once instead. Signed-off-by: Cursor Agent Co-authored-by: Cursor Agent Co-authored-by: David Mozart --- CHANGELOG.md | 12 ++++++ SUPPORT_STATUS.md | 4 +- devices.yaml | 2 +- drivers/lua/saj-emanager.lua | 66 +++++++++++------------------- drivers/tests/test_saj-emanager.py | 49 +++++++--------------- index.yaml | 6 +-- manifests/saj-emanager.yaml | 8 ++-- support-status.json | 2 +- 8 files changed, 63 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d21e65..352b581 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## [Unreleased] +### saj-emanager 0.1.2 + +The NovaCore device-support registry accepts this driver. + +- `host.set_make` is the brand key `saj`. `SAJ` is not a key in `/brands`. + Same correction the SAJ H2 driver took in 1.0.2. +- `host.emit_metric` is not a host function in that registry. Device count + and the phase-scale divisor are one log line each. Inverter, load, + generator, raw capacity, and the FeedIn/Sell counters are not published: + the first three have no stated sign, capacity is not a known Wh unit, and + FeedIn versus Sell is still an open direction question. + ### saj-emanager 0.1.1 Emitted power uses the same signs as the other drivers. Generation is diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 5339321..4fec4ef 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -120,8 +120,8 @@ Catalog source is not proof that a target can install or run a driver. | pixii_pv | 0.3.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | remne_p1ib | 0.1.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | remne_p1ib | 0.1.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| saj-emanager | 0.1.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| saj-emanager | 0.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| saj-emanager | 0.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| saj-emanager | 0.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | saj | 1.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | saj | 1.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | schneider_meter | 1.0.5 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 31e9414..2701aa6 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1104,7 +1104,7 @@ manufacturers: protocols: - protocol: modbus driver: "saj-emanager" - version: "0.1.1" + version: "0.1.2" ders: [pv, battery, meter] control: false firmware_versions: "" diff --git a/drivers/lua/saj-emanager.lua b/drivers/lua/saj-emanager.lua index f6d9f20..8233329 100644 --- a/drivers/lua/saj-emanager.lua +++ b/drivers/lua/saj-emanager.lua @@ -79,9 +79,9 @@ -- CH2's own map does not trust the power word; it uses direction registers -- this sheet does not have. -- --- Load (0x8493), inverter (0x848D) and generator (0x8498) power are int32 --- with no stated sign. They are metrics named *_vendor and are not DER --- fields, so a positive word there is not a site-signed watt. +-- Load (0x8493), inverter (0x848D) and generator (0x8498) are int32 with +-- no stated sign. They are left unpublished: a DER field would invent a +-- sign, and the NovaCore registry host does not provide emit_metric. -- -- ═══ Voltage and frequency may be summed — the sheet does not say so ═════ -- @@ -113,15 +113,15 @@ -- in 0.01%..100.00%, or battery power is non-zero. A real 0% pack that still -- reports capacity is emitted, SoC and all. -- --- The capacity unit on the sheet is "K", not kWh and not Wh. The raw word --- is a presence signal and a metric. It is not converted. +-- The capacity unit on the sheet is "K", not kWh and not Wh. A non-zero +-- word means a pack is present. It is not converted and not published. -- -- ═══ Energy direction ═════════════════════════════════════════════════════ -- -- PV generation, battery charge and battery discharge totals are named on -- the sheet and are copied onto the DER. FeedIn (0x852E) and Sell (0x8536) --- are not: SAJ uses both words for both directions in different PDFs. They --- are metrics under the vendor names, not meter import/export. +-- are not published: SAJ uses both words for both directions in different +-- PDFs, so neither is meter import or export. -- -- ═══ Control 0x8400-0x8405 — NOT IMPLEMENTED ══════════════════════════════ -- @@ -164,7 +164,7 @@ DRIVER = { id = "saj-emanager", name = "SAJ eManager C1 Pro", manufacturer = "SAJ", - version = "0.1.1", + version = "0.1.2", host_api_min = 1, host_api_max = 1, protocols = { "modbus" }, @@ -222,8 +222,6 @@ local ENERGY_WORDS = 80 local PAIR_TOTAL_PV = 3 -- 0x8506 local PAIR_TOTAL_BAT_CHG = 7 -- 0x850E local PAIR_TOTAL_BAT_DIS = 11 -- 0x8516 -local PAIR_TOTAL_FEED_IN = 23 -- 0x852E -local PAIR_TOTAL_SELL = 27 -- 0x8536 -- MPVMode 5 is "Fault" on the sheet. local MODE_FAULT = 5 @@ -333,6 +331,7 @@ end local GIVE_UP_AFTER = 3 local read_failures = {} local announced = false +local scale_logged = false local function complete(regs, count) if regs == nil then return false end @@ -420,9 +419,6 @@ end local function note_identity(device_count, devices) local sn = first_sn(devices) if sn then host.set_sn(sn) end - if device_count ~= nil then - host.emit_metric("saj_emanager_device_count", device_count) - end if announced or device_count == nil then return end announced = true host.log("info", string.format( @@ -430,6 +426,18 @@ local function note_identity(device_count, devices) device_count, sn or "(none)")) end +-- One line, once. The registry host has no emit_metric, and the voltage +-- check at Castellum needs to see whether the sum was divided. +local function note_phase_scale(divided, device_count, phases_ok) + if scale_logged or not phases_ok then return end + if device_count == nil or device_count < 1 then return end + scale_logged = true + local divisor = 1 + if divided then divisor = device_count end + host.log("info", string.format( + "SAJ eManager: phase voltage/frequency divisor %d", divisor)) +end + ---------------------------------------------------------------------------- -- Summary block → DER fields. Nil means the word did not decode. ---------------------------------------------------------------------------- @@ -445,7 +453,6 @@ end local function decode_summary(regs) local mode = regs[IDX_MODE] if mode ~= nil and mode ~= 0xFFFF then - host.emit_metric("saj_emanager_mpv_mode", mode) if mode == MODE_FAULT then host.set_device_fault(true, "MPVMode 5 fault") else @@ -463,16 +470,6 @@ local function decode_summary(regs) local user = u32_at(regs, IDX_USERCAP) local soc_raw = regs[IDX_SOC] - -- No stated sign on these three. Keep the raw word off the DER streams. - local inv_w = i32_at(regs, IDX_INV) - if inv_w ~= nil then host.emit_metric("saj_emanager_inv_w_vendor", inv_w) end - local load_w = i32_at(regs, IDX_LOAD) - if load_w ~= nil then host.emit_metric("saj_emanager_load_w_vendor", load_w) end - local gen_w = i32_at(regs, IDX_GEN) - if gen_w ~= nil and gen_w ~= 0 then - host.emit_metric("saj_emanager_gen_w_vendor", gen_w) - end - local pv = {} -- Generation is negative in every driver in this repository. if pv_w ~= nil then pv.W = -pv_w end @@ -487,12 +484,6 @@ local function decode_summary(regs) if site_bat ~= nil then battery.W = site_bat end local soc = soc_fraction(soc_raw) if soc ~= nil then battery.SoC_nom_fract = soc end - if cap ~= nil then - host.emit_metric("saj_emanager_battery_capacity_raw", cap) - end - if user ~= nil then - host.emit_metric("saj_emanager_battery_available_raw", user) - end end return pv, meter, battery @@ -534,11 +525,6 @@ local function apply_energy(pv, battery, regs) if chg ~= nil then battery.total_charge_Wh = chg end if dis ~= nil then battery.total_discharge_Wh = dis end end - -- Vendor names, deliberately not import_wh / export_wh. - local feed = pair_wh(regs, PAIR_TOTAL_FEED_IN) - local sell = pair_wh(regs, PAIR_TOTAL_SELL) - if feed ~= nil then host.emit_metric("saj_emanager_vendor_feed_in_wh", feed) end - if sell ~= nil then host.emit_metric("saj_emanager_vendor_sell_wh", sell) end end local function emit_der(kind, fields) @@ -550,7 +536,8 @@ end ---------------------------------------------------------------------------- function driver_init(config) - host.set_make("SAJ") + -- NovaCore brand key from /brands. "SAJ" is rejected. + host.set_make("saj") host.set_model("eManager C1 Pro") end @@ -569,11 +556,7 @@ function driver_poll() if phases then divided = apply_phases(meter, phases, device_count) end - if divided and device_count ~= nil then - host.emit_metric("saj_emanager_phase_scale_divisor", device_count) - elseif phases and device_count ~= nil and device_count >= 1 then - host.emit_metric("saj_emanager_phase_scale_divisor", 1) - end + note_phase_scale(divided, device_count, phases ~= nil) local energy = probe_read(REG_ENERGY, ENERGY_WORDS, "holding") if energy then @@ -603,5 +586,6 @@ end function driver_cleanup() announced = false + scale_logged = false read_failures = {} end diff --git a/drivers/tests/test_saj-emanager.py b/drivers/tests/test_saj-emanager.py index a8f79fb..d047e74 100644 --- a/drivers/tests/test_saj-emanager.py +++ b/drivers/tests/test_saj-emanager.py @@ -197,11 +197,6 @@ def run_lua(body: str) -> dict[str, str]: if obj == nil or obj[key] == nil then return "nil" end return tostring(obj[key]) end -local function metric(name) - local m = host._metrics[name] - if m == nil or m.value == nil then return "nil" end - return tostring(m.value) -end local pv = last(host._emitted["pv"]) local bat = last(host._emitted["battery"]) local met = last(host._emitted["meter"]) @@ -230,14 +225,7 @@ def run_lua(body: str) -> dict[str, str]: print("SN " .. tostring(host._sn)) print("RATED " .. tostring(host._rated_w)) print("FAULT " .. tostring(host._faulted)) -print("COUNT " .. metric("saj_emanager_device_count")) -print("DIVISOR " .. metric("saj_emanager_phase_scale_divisor")) -print("LOAD " .. metric("saj_emanager_load_w_vendor")) -print("INV " .. metric("saj_emanager_inv_w_vendor")) -print("GEN " .. metric("saj_emanager_gen_w_vendor")) -print("CAP " .. metric("saj_emanager_battery_capacity_raw")) -print("FEED " .. metric("saj_emanager_vendor_feed_in_wh")) -print("SELL " .. metric("saj_emanager_vendor_sell_wh")) +print("LOGS " .. table.concat(host._logs, " || ")) local slot_reads, slot_count, control_reads, bad_kind = 0, 0, 0, 0 for _, call in ipairs(host._calls) do if call.func == "modbus_read" then @@ -275,10 +263,10 @@ def test_three_inverter_plant_in_site_convention(): out = poll_once() assert out["INTERVAL"] == "5000" - assert out["MAKE"] == "SAJ" + assert out["MAKE"] == "saj" assert out["MODEL"] == "eManager C1 Pro" assert out["SN"] == SERIALS[0] - assert out["COUNT"] == "3" + assert "DeviceNum=3" in out["LOGS"] assert out["RATED"] == str(RATED_W) assert out["FAULT"] == "false" assert out["BAD_KIND"] == "0" @@ -300,7 +288,6 @@ def test_three_inverter_plant_in_site_convention(): assert math.isclose(float(out["BAT_SOC"]), SOC_RAW / 10000, rel_tol=1e-6) assert float(out["BAT_CHG"]) == BAT_CHARGE_RAW * 10 assert float(out["BAT_DIS"]) == BAT_DISCHARGE_RAW * 10 - assert out["CAP"] == str(CAP_RAW) # Wire -2500 is export on an import-positive register. Site export is −. assert out["MET_EMITS"] == "1" @@ -313,16 +300,11 @@ def test_three_inverter_plant_in_site_convention(): assert float(out["MET_L2W"]) == L2_W assert float(out["MET_L3W"]) == L3_W assert math.isclose(float(out["MET_L3V"]), (L1_V_RAW + 2) / 10, rel_tol=1e-6) - # Sheet scale was already one phase, so the divisor stays 1. - assert out["DIVISOR"] == "1" - # FeedIn / Sell stay vendor metrics. They are not import and export. + # Sheet scale was already one phase, so the logged divisor stays 1. + assert "divisor 1" in out["LOGS"] + # FeedIn / Sell are not import and export. Direction is unconfirmed. assert out["MET_IMPORT"] == "nil" assert out["MET_EXPORT"] == "nil" - assert float(out["FEED"]) == FEED_IN_RAW * 10 - assert float(out["SELL"]) == SELL_RAW * 10 - assert float(out["LOAD"]) == LOAD_W_VENDOR - assert float(out["INV"]) == INV_W_VENDOR - assert out["GEN"] == "nil" def _i32_words(value: int) -> tuple[int, int]: @@ -366,7 +348,7 @@ def test_summed_voltage_and_frequency_are_divided_power_is_not(): assert math.isclose(float(out["MET_L1V"]), L1_V_RAW / 10, rel_tol=1e-6) assert math.isclose(float(out["MET_HZ"]), L1_HZ_RAW / 100, rel_tol=1e-6) assert math.isclose(float(out["MET_L3V"]), (L1_V_RAW + 2) / 10, rel_tol=1e-6) - assert out["DIVISOR"] == "3" + assert "divisor 3" in out["LOGS"] # Current and power are not part of that correction. assert math.isclose(float(out["MET_L1A"]), L1_A_RAW / 10, rel_tol=1e-6) assert float(out["MET_L1W"]) == L1_W @@ -379,15 +361,15 @@ def test_implausible_voltage_that_does_not_divide_cleanly_is_left_alone(): out = poll_once( f"host._modbus_registers.holding[{REG_PHASES}][1] = 4000") assert math.isclose(float(out["MET_L1V"]), 400.0, rel_tol=1e-6) - assert out["DIVISOR"] == "1" + assert "divisor 1" in out["LOGS"] def test_sum_is_not_guessed_when_device_count_did_not_answer(): out = poll_once( f'host._modbus_read_fail_addresses[{REG_DEVICE_NUM}] = "timeout"\n' f"host._modbus_registers.holding[{REG_PHASES}][3] = 15000") - assert out["COUNT"] == "nil" - assert out["DIVISOR"] == "nil" + assert "DeviceNum=" not in out["LOGS"] + assert "divisor" not in out["LOGS"] assert out["SN"] == "nil" assert out["SLOT_READS"] == "0" # 150.00 Hz stays 150.00 Hz. Inventing a divisor of 3 would hide that. @@ -398,7 +380,6 @@ def test_sum_is_not_guessed_when_device_count_did_not_answer(): def test_no_battery_when_capacity_soc_and_power_are_zero(): out = poll_once(pack="no") assert out["BAT_EMITS"] == "0" - assert out["CAP"] == "nil" assert out["PV_EMITS"] == "1" assert out["MET_EMITS"] == "1" assert float(out["PV_W"]) == -PV_W @@ -459,7 +440,7 @@ def test_short_phase_block_does_not_zero_fill(): assert out["MET_L1V"] == "nil" assert out["MET_L1W"] == "nil" assert out["MET_HZ"] == "nil" - assert out["DIVISOR"] == "nil" + assert "divisor" not in out["LOGS"] def test_phase_failure_keeps_the_totals(): @@ -478,8 +459,6 @@ def test_energy_failure_omits_counters(): assert float(out["BAT_W"]) == 6000 assert out["BAT_CHG"] == "nil" assert out["BAT_DIS"] == "nil" - assert out["FEED"] == "nil" - assert out["SELL"] == "nil" def test_int32_sentinel_is_not_a_power(): @@ -493,7 +472,7 @@ def test_int32_sentinel_is_not_a_power(): def test_zero_devices_does_not_scan_slots(): out = poll_once(count=0) - assert out["COUNT"] == "0" + assert "DeviceNum=0" in out["LOGS"] assert out["SLOT_READS"] == "0" assert out["SN"] == "nil" assert out["PV_EMITS"] == "1" @@ -501,7 +480,7 @@ def test_zero_devices_does_not_scan_slots(): def test_sentinel_device_count_does_not_scan_slots(): out = poll_once(count=0xFFFF) - assert out["COUNT"] == "nil" + assert "DeviceNum=" not in out["LOGS"] assert out["SLOT_READS"] == "0" @@ -569,6 +548,8 @@ def test_source_is_tcp_only_and_does_not_read_or_write_control(): code = _code_without_comments() assert "RTU is not supported" in text assert re.search(r"port\s*=\s*502", text) + assert 'set_make("saj")' in code + assert "host.emit_metric" not in code # Mentioning the block in a string is the documentation. Reading or # writing it is the bug. assert not re.search(r"modbus_read\s*\([^)]*0x8400", code) diff --git a/index.yaml b/index.yaml index 5bdfa73..ebee215 100644 --- a/index.yaml +++ b/index.yaml @@ -536,14 +536,14 @@ drivers: size_bytes: 10858 sha256: "38749fb157e0929c26c31ccb9e8013e3ee81f584349be1dd7cc60792b9e3adeb" - name: "saj-emanager" - version: "0.1.1" + version: "0.1.2" tier: community protocol: modbus connectivity: local ders: [pv, battery, meter] control: false - size_bytes: 25082 - sha256: "4efc62ef56d5736e24895929d478a78788586796bb2d45be64acdd5051df640f" + size_bytes: 24245 + sha256: "db7692001df4fcd19130c1a7e5b0f61f425f519bf2ba92be4ae1371c345da792" - name: "saj" version: "1.2.0" tier: community diff --git a/manifests/saj-emanager.yaml b/manifests/saj-emanager.yaml index d9b5030..0348b11 100644 --- a/manifests/saj-emanager.yaml +++ b/manifests/saj-emanager.yaml @@ -1,5 +1,5 @@ name: "saj-emanager" -version: "0.1.1" +version: "0.1.2" tier: community author: "Sourceful Labs AB" protocol: modbus @@ -28,11 +28,11 @@ upstream_docs: kind: manual url_stability: stable min_host_version: "2.0.0" -size_bytes: 25082 +size_bytes: 24245 dkb_id: "" -sha256: "4efc62ef56d5736e24895929d478a78788586796bb2d45be64acdd5051df640f" +sha256: "db7692001df4fcd19130c1a7e5b0f61f425f519bf2ba92be4ae1371c345da792" signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "Site signs match the catalog: PV negative, battery positive when charging, grid positive on import. Still read-only and untested on hardware." +changelog: "Brand key saj. Drop emit_metric; the NovaCore registry does not provide it. Still read-only and untested on hardware." diff --git a/support-status.json b/support-status.json index 228c835..fd82e8f 100644 --- a/support-status.json +++ b/support-status.json @@ -1220,7 +1220,7 @@ }, { "catalog_source": true, - "catalog_version": "0.1.1", + "catalog_version": "0.1.2", "driver_id": "saj-emanager", "targets": { "blixt-l1": { From e07d27038e83e431cc01c1cd988ffcb1997355c0 Mon Sep 17 00:00:00 2001 From: huangkongsheng <59566679+huangkongsheng@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:03:08 -0500 Subject: [PATCH 7/8] fix(growatt): skip battery telemetry when no battery is connected (2.1.3) (#203) * fix(growatt): skip battery telemetry when no battery is connected PV-only Growatt still answers the battery registers with 0, so Overview rendered a phantom Battery node. Only emit battery telemetry when voltage/SoC/power indicate a real battery. Fixes srcfl/ftw#1669. Signed-off-by: huangkongsheng <59566679+huangkongsheng@users.noreply.github.com> * chore(growatt): lower the invented-number baseline and regenerate for 2.1.3 The battery gate removes four invented numbers from growatt (20 to 16), so the ratchet needs its baseline lowered. index.yaml, devices.yaml and the support status are regenerated for the 2.1.3 manifest. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --------- Signed-off-by: huangkongsheng <59566679+huangkongsheng@users.noreply.github.com> Signed-off-by: Fredrik Ahlgren Co-authored-by: Fredrik Ahlgren Co-authored-by: Claude Opus 5.5 --- SUPPORT_STATUS.md | 4 +- devices.yaml | 12 +- drivers/lua/growatt.lua | 27 +++-- drivers/tests/invented-number-baseline.json | 2 +- drivers/tests/test_growatt_pv_only_battery.py | 107 ++++++++++++++++++ index.yaml | 6 +- manifests/growatt.yaml | 8 +- support-status.json | 2 +- 8 files changed, 142 insertions(+), 26 deletions(-) create mode 100644 drivers/tests/test_growatt_pv_only_battery.py diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 4fec4ef..f602598 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -72,8 +72,8 @@ Catalog source is not proof that a target can install or run a driver. | goe_http | 1.0.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | goodwe | 2.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | | goodwe | 2.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| growatt | 2.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| growatt | 2.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| growatt | 2.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| growatt | 2.1.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | hardybarth | 1.0.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | hardybarth | 1.0.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | heishamon | 0.8.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 2701aa6..7dfd711 100644 --- a/devices.yaml +++ b/devices.yaml @@ -533,7 +533,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -544,7 +544,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -555,7 +555,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -566,7 +566,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -577,7 +577,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -588,7 +588,7 @@ manufacturers: protocols: - protocol: modbus driver: "growatt" - version: "2.1.2" + version: "2.1.3" ders: [pv, battery, meter] control: false firmware_versions: "" diff --git a/drivers/lua/growatt.lua b/drivers/lua/growatt.lua index afc8789..5abd5ba 100644 --- a/drivers/lua/growatt.lua +++ b/drivers/lua/growatt.lua @@ -21,7 +21,7 @@ DRIVER = { id = "growatt", name = "Growatt hybrid inverter", manufacturer = "Growatt", - version = "2.1.2", + version = "2.1.3", protocols = { "modbus" }, capabilities = { "meter", "pv", "battery" }, read_only = true, @@ -181,14 +181,23 @@ function driver_poll() bat_temp = btemp_regs[1] * 0.1 end - host.emit("battery", { - w = bat_w, - v = bat_v, - soc = bat_soc, - temp_c = bat_temp, - }) - host.emit_metric("battery_dc_v", bat_v) - host.emit_metric("battery_temp_c", bat_temp) + -- A PV-only Growatt (no battery connected) still answers the battery + -- registers with 0, which made FTW render a phantom "Battery" node on + -- Overview even though no battery exists. A real battery reports a + -- terminal voltage and/or SoC above 0 even at rest, so treat all-zero + -- battery readings as "no battery present" and skip the emit. + -- see srcfl/ftw#1669 + local has_battery = bat_v > 0 or bat_soc > 0 or bat_charge_w > 0 or bat_discharge_w > 0 + if has_battery then + host.emit("battery", { + w = bat_w, + v = bat_v, + soc = bat_soc, + temp_c = bat_temp, + }) + host.emit_metric("battery_dc_v", bat_v) + host.emit_metric("battery_temp_c", bat_temp) + end -- ---- Meter ---- diff --git a/drivers/tests/invented-number-baseline.json b/drivers/tests/invented-number-baseline.json index 3cb282b..2c0de0f 100644 --- a/drivers/tests/invented-number-baseline.json +++ b/drivers/tests/invented-number-baseline.json @@ -31,7 +31,7 @@ "fronius": 11, "goe": 8, "goodwe": 24, - "growatt": 20, + "growatt": 16, "hello": 3, "janitza": 13, "keba": 8, diff --git a/drivers/tests/test_growatt_pv_only_battery.py b/drivers/tests/test_growatt_pv_only_battery.py new file mode 100644 index 0000000..42a7fbe --- /dev/null +++ b/drivers/tests/test_growatt_pv_only_battery.py @@ -0,0 +1,107 @@ +"""A PV-only Growatt must not emit a phantom Battery stream. + +A Growatt with no battery connected still answers the battery Modbus +registers with 0. The driver used to emit a `battery` stream on every poll +regardless, which made FTW render a "Battery Growatt" node on Overview even +though no battery exists (srcfl/ftw#1669). The driver now only emits battery +telemetry when a battery is actually present. + +CI builds ./lua55 (see tools/build_luac.sh) and runs this through the host +mock, so the guard holds in the pipeline. pytest skips it locally when the +interpreter is absent. +""" + +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +LUA = ROOT / "lua55" +HARNESS = ROOT / "drivers" / "tests" / "lua_harness" +GROWATT = ROOT / "drivers" / "lua" / "growatt.lua" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + + +def _run(body: str) -> dict[str, str]: + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() + +{body} +''' + result = subprocess.run([str(LUA), "-e", script], + capture_output=True, text=True, cwd=ROOT) + assert result.returncode == 0, result.stdout + result.stderr + return dict(line.split(" ", 1) + for line in result.stdout.strip().splitlines() if " " in line) + + +def _poll(registers: dict[str, int]) -> dict[str, str]: + setup = "\n".join( + f"host._modbus_registers.input[{addr}] = {val}" + for addr, val in registers.items() + ) + return _run(f''' +{setup} +dofile("{GROWATT}") +driver_init({{host = '127.0.0.1', port = 502, unit_id = 1}}) +local ok, err = pcall(driver_poll) +if not ok then print("POLL_ERROR " .. tostring(err)) os.exit(1) end +local bat = host._emitted.battery +if bat and #bat > 0 then + print("BATTERY_EMITTED 1") + print("BAT_V " .. tostring(bat[1].v)) + print("BAT_SOC " .. tostring(bat[1].soc)) + print("BAT_W " .. tostring(bat[1].w)) +else + print("BATTERY_EMITTED 0") +end +''') + + +def test_pv_only_install_emits_no_battery_node(): + """A Growatt answering all-zero battery registers must not emit battery.""" + out = _poll({}) # every register unmapped -> the mock returns 0 + assert out["BATTERY_EMITTED"] == "0", ( + "PV-only Growatt emitted a battery stream; Overview would show a " + "phantom Battery node (srcfl/ftw#1669)." + ) + + +def test_hybrid_install_with_battery_emits_battery(): + """A real battery (voltage + SoC + charge power) must still be reported.""" + out = _poll({ + 1009: 0, 1010: 100, # charge power 10 W + 1011: 0, 1012: 0, # discharge power 0 W + 1013: 480, # terminal voltage 48.0 V + 1014: 50, # SoC 50 % + }) + assert out["BATTERY_EMITTED"] == "1", ( + "Hybrid Growatt with a battery present did not emit battery telemetry." + ) + assert float(out["BAT_V"]) == 48.0 + assert float(out["BAT_SOC"]) == 0.5 + assert float(out["BAT_W"]) == 10.0 # charge - discharge + + +def test_battery_at_rest_with_zero_soc_still_emits(): + """A present battery reads a terminal voltage even at 0 % SoC. + + Guards against an over-strict gate that would drop a real battery just + because its SoC register reads 0. + """ + out = _poll({ + 1009: 0, 1010: 0, + 1011: 0, 1012: 0, + 1013: 520, # 52.0 V present + 1014: 0, # SoC 0 % + }) + assert out["BATTERY_EMITTED"] == "1", ( + "A battery at 0 % SoC but with terminal voltage was dropped; the gate " + "must key off voltage/power, not SoC alone." + ) + assert float(out["BAT_V"]) == 52.0 diff --git a/index.yaml b/index.yaml index ebee215..1a99d9a 100644 --- a/index.yaml +++ b/index.yaml @@ -313,14 +313,14 @@ drivers: size_bytes: 9566 sha256: "148d36d25fa630dd11ab1f697c46dde60863dcd3a2a9944e78e322dba55bde49" - name: "growatt" - version: "2.1.2" + version: "2.1.3" tier: community protocol: modbus connectivity: local ders: [pv, battery, meter] control: false - size_bytes: 9376 - sha256: "1e9623cbf3453697f0fba429a5b8dab7d61cf9507587e616d0cd9de3cc3594c8" + size_bytes: 9923 + sha256: "684c788e989c6f90b7a64fd79521f913104486f2c939bf13d4aaa2fbfddd9dad" - name: "hardybarth" version: "1.0.1" tier: community diff --git a/manifests/growatt.yaml b/manifests/growatt.yaml index 2ec89bd..1e1121c 100644 --- a/manifests/growatt.yaml +++ b/manifests/growatt.yaml @@ -1,5 +1,5 @@ name: "growatt" -version: "2.1.2" +version: "2.1.3" tier: community author: "Sourceful Labs AB" protocol: modbus @@ -50,12 +50,12 @@ tested_devices: notes: "Community driver, untested" min_driver_version: "1.0.0" min_host_version: "2.0.0" -size_bytes: 9376 +size_bytes: 9923 dkb_id: "" -sha256: "1e9623cbf3453697f0fba429a5b8dab7d61cf9507587e616d0cd9de3cc3594c8" +sha256: "684c788e989c6f90b7a64fd79521f913104486f2c939bf13d4aaa2fbfddd9dad" signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "" +changelog: "2.1.3: skip battery telemetry when no battery is connected (PV-only installs), fixes phantom Battery node on Overview (srcfl/ftw#1669)" diff --git a/support-status.json b/support-status.json index fd82e8f..309845d 100644 --- a/support-status.json +++ b/support-status.json @@ -716,7 +716,7 @@ }, { "catalog_source": true, - "catalog_version": "2.1.2", + "catalog_version": "2.1.3", "driver_id": "growatt", "targets": { "blixt-l1": { From 1e4b5de7c055885481a8ba4a56476bd1bc1b7bbb Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 8 Nov 2026 15:10:06 +0100 Subject: [PATCH 8/8] fix(easee_cloud): declare the coarse session counter (1.4.1) (#214) Easee moves session energy in steps of about 1 kWh. FTW's energy record judged each step against the time since the last reading, and rejected those that landed moments later. On one home box it kept 10 of 24.3 kWh. The driver now says so with session_wh_coarse. Measured power came within 0.1 % of Easee's own total on three charges. Signed-off-by: Fredrik Ahlgren Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++++ SUPPORT_STATUS.md | 4 ++-- devices.yaml | 2 +- drivers/lua/easee_cloud.lua | 6 ++++- .../test_easee_cloud_session_counter.lua | 23 +++++++++++++++++++ .../tests/test_easee_cloud_session_counter.py | 12 ++++++++++ index.yaml | 6 ++--- manifests/easee_cloud.yaml | 6 ++--- support-status.json | 2 +- 9 files changed, 59 insertions(+), 11 deletions(-) create mode 100644 drivers/tests/lua_harness/test_easee_cloud_session_counter.lua create mode 100644 drivers/tests/test_easee_cloud_session_counter.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 352b581..aaf58aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## [Unreleased] +### easee_cloud 1.4.1 + +The driver says its session energy is coarse, with `session_wh_coarse`. Easee +moves that figure in steps of about 1 kWh, and FTW's energy record rejected +steps that landed moments after the last reading. On one home box that kept +10 of 24.3 kWh. FTW now uses measured power for this charger's energy, which +came within 0.1 % of Easee's own session total on three charges (6.6, 24.3 and +31.7 kWh). + ### saj-emanager 0.1.2 The NovaCore device-support registry accepts this driver. diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index f602598..1574553 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -46,8 +46,8 @@ Catalog source is not proof that a target can install or run a driver. | deye | 2.1.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | easee | 1.0.4 | ftw-core | not_assessed | — | not_recorded | not_assessed | | easee | 1.0.4 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| easee_cloud | 1.4.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| easee_cloud | 1.4.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| easee_cloud | 1.4.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| easee_cloud | 1.4.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | esphome_dsmr | 1.0.7 | ftw-core | not_assessed | — | not_recorded | not_assessed | | esphome_dsmr | 1.0.7 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | etrel | 1.0.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 7dfd711..317220b 100644 --- a/devices.yaml +++ b/devices.yaml @@ -338,7 +338,7 @@ manufacturers: protocols: - protocol: http driver: "easee_cloud" - version: "1.4.0" + version: "1.4.1" ders: [ev] control: true firmware_versions: "" diff --git a/drivers/lua/easee_cloud.lua b/drivers/lua/easee_cloud.lua index 8ff13ef..fd123f9 100644 --- a/drivers/lua/easee_cloud.lua +++ b/drivers/lua/easee_cloud.lua @@ -29,7 +29,7 @@ DRIVER = { id = "easee_cloud", name = "Easee Cloud", manufacturer = "Easee", - version = "1.4.0", + version = "1.4.1", protocols = { "http" }, capabilities = { "ev" }, description = "Easee Home/Charge via Cloud REST API. No local protocol needed.", @@ -1100,6 +1100,10 @@ function driver_poll() charging = charging, request_active = request_active, session_wh = session_wh, + -- Easee moves session energy in steps of about 1 kWh, in its own + -- time. It is right for what a session delivered, and too coarse to + -- say when the energy flowed, so Core's energy record uses power. + session_wh_coarse = true, power_observed_at = power_observed_at, -- Control verification needs distinct source samples. A fresh cloud -- reply alone does not establish a new physical power measurement. diff --git a/drivers/tests/lua_harness/test_easee_cloud_session_counter.lua b/drivers/tests/lua_harness/test_easee_cloud_session_counter.lua new file mode 100644 index 0000000..b86fe22 --- /dev/null +++ b/drivers/tests/lua_harness/test_easee_cloud_session_counter.lua @@ -0,0 +1,23 @@ +dofile("drivers/tests/lua_harness/host_mock.lua") +-- Easee's session energy moves in steps of about 1 kWh, so the driver says +-- so and FTW's energy record uses power. The figure itself stays. +local driver = "drivers/lua/easee_cloud.lua" +host.reset() +host._millis_step = 0 +host._http_responses["/accounts/login"] = '{"accessToken":"test","expiresIn":3600}' +host._http_responses["/config"] = '{"maxChargerCurrent":16}' +host._http_responses["/sessions/ongoing"] = '{}' +dofile(driver) +driver_init({email="test@example.invalid",password="test",serial="TEST123"}) +host._http_responses["/observations?ids="] = host.json_encode({ + {id=109,value=3,timestamp="2026-11-08T02:00:00Z"}, + {id=120,value=9.6,timestamp="2026-11-08T02:00:00Z"}, + {id=121,value=12.0,timestamp="2026-11-08T02:00:00Z"}, +}) +driver_poll() +local rows = host._emitted.ev +assert(rows and #rows > 0, "no EV sample") +local sample = rows[#rows] +assert(sample.session_wh_coarse == true, "the coarse session counter was not declared") +assert(sample.session_wh == 12000, "session energy lost: " .. tostring(sample.session_wh)) +print("Easee session counter: passed") diff --git a/drivers/tests/test_easee_cloud_session_counter.py b/drivers/tests/test_easee_cloud_session_counter.py new file mode 100644 index 0000000..23a330e --- /dev/null +++ b/drivers/tests/test_easee_cloud_session_counter.py @@ -0,0 +1,12 @@ +"""Easee's coarse session counter must be declared, and stay reported.""" +from pathlib import Path +import subprocess + + +def test_easee_cloud_declares_its_coarse_session_counter(): + root = Path(__file__).resolve().parents[2] + result = subprocess.run( + [str(root / "lua55"), "drivers/tests/lua_harness/test_easee_cloud_session_counter.lua"], + cwd=root, text=True, capture_output=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/index.yaml b/index.yaml index 1a99d9a..0f09d7f 100644 --- a/index.yaml +++ b/index.yaml @@ -193,15 +193,15 @@ drivers: size_bytes: 4054 sha256: "4a2cd1efb4a5583468ce897ebd88a000e348917295c40210e86ecf834c0ba543" - name: "easee_cloud" - version: "1.4.0" + version: "1.4.1" tier: core protocol: http connectivity: cloud setup: [vendor_portal] ders: [ev] control: true - size_bytes: 64126 - sha256: "94653989702cb805c56db296be0651886b4b685a0d407bd69089450b86571abe" + size_bytes: 64392 + sha256: "de954b416dcab6d9d7af06075056dce30a1e9d8dbba80223d78a1cdb806101cd" - name: "esphome_dsmr" version: "1.0.7" tier: core diff --git a/manifests/easee_cloud.yaml b/manifests/easee_cloud.yaml index 3b55ee8..8ab261a 100644 --- a/manifests/easee_cloud.yaml +++ b/manifests/easee_cloud.yaml @@ -1,5 +1,5 @@ name: "easee_cloud" -version: "1.4.0" +version: "1.4.1" tier: core author: "Sourceful Labs AB" protocol: http @@ -16,9 +16,9 @@ tested_devices: notes: "Easee Home/Charge via Cloud REST API. No local protocol needed." min_driver_version: "1.0.1" min_host_version: "2.0.0" -size_bytes: 64126 +size_bytes: 64392 dkb_id: "easee_cloud" -sha256: "94653989702cb805c56db296be0651886b4b685a0d407bd69089450b86571abe" +sha256: "de954b416dcab6d9d7af06075056dce30a1e9d8dbba80223d78a1cdb806101cd" signature: "" bytecode_sha256: "" diff --git a/support-status.json b/support-status.json index 309845d..65543b7 100644 --- a/support-status.json +++ b/support-status.json @@ -443,7 +443,7 @@ }, { "catalog_source": true, - "catalog_version": "1.4.0", + "catalog_version": "1.4.1", "driver_id": "easee_cloud", "targets": { "blixt-l1": {