From c941646e4a2a5906d7ca8f46845ac909896337c1 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 22 Nov 2026 13:30:41 +0100 Subject: [PATCH 1/2] fix(fronius): read the battery where the GEN24 storage maps put it (2.3.0) Earlier releases read model 124 at fixed addresses that assume a model 160 with two inputs. With storage, Fronius's model 160 has two more blocks for the battery, so those reads landed inside them. Battery power also came from the OutWRte / InWRte setpoints times WChaMax, not a measurement. The driver now reads model 160's header, finds model 124 right after it, and takes battery power from the StCha / StDisCha blocks (charge minus discharge, positive charging), voltage from the same blocks, and SoC from ChaState with its scale factor. Without model 124 it sends no battery. The float decoder works on the 16-bit halves, so floats keep their sign on 32-bit Lua, and NaN is left out instead of sent as 0. Failed PV reads are left out too; fronius leaves the invented-number baseline. Source: Fronius register map bundle 1.2.7-2 (GEN24 and Verto float maps with storage) and the GEN24 Modbus manual 42,0410,2649; evcc's fronius-gen24 template agrees. Not verified on hardware. Refs srcfl/device-drivers#260 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- CHANGELOG.md | 34 ++ SUPPORT_STATUS.md | 4 +- devices.yaml | 12 +- drivers/lua/fronius.lua | 390 ++++++++++++-------- drivers/tests/invented-number-baseline.json | 1 - drivers/tests/test_fronius_storage_map.py | 293 +++++++++++++++ index.yaml | 6 +- manifests/fronius.yaml | 8 +- support-status.json | 2 +- 9 files changed, 571 insertions(+), 179 deletions(-) create mode 100644 drivers/tests/test_fronius_storage_map.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 96e328c..dd68d6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,40 @@ ## [Unreleased] +### fronius 2.3.0 + +Battery power, voltage and SoC now come from the registers Fronius's GEN24 +and Verto storage maps give them (register map bundle 1.2.7-2, float maps). +Not yet checked on hardware (srcfl/device-drivers#260). + +- **Where the battery is.** Earlier releases read model 124 at fixed + addresses that assume a model 160 with two inputs. With storage, Fronius's + model 160 has two more, for the battery, so those reads landed inside + model 160's battery blocks. The driver now reads model 160's header, + learns its length, and finds model 124 directly after it. +- **Battery power** is the charge input's DC power minus the discharge + input's (the last two blocks of model 160, "StCha" and "StDisCha"), + positive when charging. Earlier releases took it from OutWRte and InWRte + times WChaMax, which are rate setpoints and a rating, not a measurement. +- **Voltage** is the larger of the two inputs' DC voltage (before firmware + 1.31 only the active input carries it), and is left out when both read 0. + **SoC** is model 124's ChaState with its scale factor. +- **No storage, no battery.** Model 124 exists only with storage. Without it + the driver sends no battery, where earlier releases sent 0 W, 0 V and 0 %. +- **Floats.** The float decoder works on the 16-bit halves. It joined the + words into one 32-bit number first, so on 32-bit Lua every float came out + negative (FTW and Blixt L1 use 64-bit integers and were not affected). NaN + and infinity are now left out instead of sent as 0. +- **Failed reads are left out.** PV is sent only when DC power answered, and + each other PV field and metric only when its own read did. The MPPT values + come from one read of model 160, with the scale factors that go with them. + `fronius` leaves `invented-number-baseline.json` (10 to 0). +- **Not changed.** PV power still comes from model 113's DC power. evcc's + GEN24 template sums the MPPT inputs instead, and Fronius's map does not + say whether model 113 includes the battery input. In the int+SF setting + model 160 starts at 40254; the driver reads only the float maps, so it + now sends no DC input or battery values there rather than wrong ones. + ### ferroamp_modbus 2.2.2 A float that answers NaN or infinity is now left out instead of sent as 0 diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 2948ba6..d020626 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -58,8 +58,8 @@ Catalog source is not proof that a target can install or run a driver. | ferroamp_modbus | 2.2.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | foxess_h3_smart | 0.10.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | foxess_h3_smart | 0.10.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| fronius | 2.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| fronius | 2.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| fronius | 2.3.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| fronius | 2.3.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | fronius_api | 1.0.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | | fronius_api | 1.0.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | fronius_smart_meter | 2.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 346a0c4..75cee1c 100644 --- a/devices.yaml +++ b/devices.yaml @@ -419,7 +419,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -430,7 +430,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -441,7 +441,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -452,7 +452,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -463,7 +463,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -496,7 +496,7 @@ manufacturers: protocols: - protocol: modbus driver: "fronius" - version: "2.2.0" + version: "2.3.0" ders: [battery, meter, pv] control: false firmware_versions: "" diff --git a/drivers/lua/fronius.lua b/drivers/lua/fronius.lua index 23ca3a4..71efc6d 100644 --- a/drivers/lua/fronius.lua +++ b/drivers/lua/fronius.lua @@ -15,7 +15,7 @@ DRIVER = { id = "fronius", name = "Fronius GEN24", manufacturer = "Fronius", - version = "2.2.0", + version = "2.3.0", protocols = { "modbus" }, capabilities = { "pv", "battery" }, read_only = true, @@ -65,50 +65,63 @@ end -- Decode IEEE 754 single-precision float from two u16 registers, -- big-endian word order: hi = first register, lo = second. --- Treats NaN / ±Inf (SunSpec "not implemented" sentinel 0x7FC00000) as 0. +-- +-- Works on the 16-bit halves (docs/WRITING-A-DRIVER.md, "Numbers"). Earlier +-- versions joined the words into one 32-bit number and compared it with +-- 0x80000000, which is negative where Lua integers are 32 bits, so every +-- float came out negative there (the harness, and any 32-bit host). FTW and +-- Blixt L1 use 64-bit integers and were not affected. ferroamp_modbus had the +-- same fault (srcfl/device-drivers#254). +-- +-- NaN and infinity give nil. Fronius answers NaN (0x7FC00000) for a point it +-- does not support, and earlier versions turned that into 0, a reading +-- nobody took. local function decode_f32_be(hi, lo) - local bits = (hi % 0x10000) * 0x10000 + (lo % 0x10000) - if bits == 0 then return 0 end - local sign = (bits >= 0x80000000) and -1 or 1 - local exp = math.floor(bits / 0x800000) % 0x100 - local frac = bits % 0x800000 - if exp == 0xFF then return 0 end - if exp == 0 then return sign * frac * 2 ^ -149 end - return sign * (1 + frac / 0x800000) * 2 ^ (exp - 127) -end - --- A temperature from two float32 registers (high word first), or nil. --- decode_f32_be above turns NaN into 0, and Fronius answers NaN --- (0x7FC00000) for a point it does not support, so a temperature read --- through it would pass for 0 °C. It also joins the words into one 32-bit --- number first, which flips the sign on a Lua build with 32-bit integers --- (docs/WRITING-A-DRIVER.md, "Numbers"). This one works on the 16-bit --- halves, refuses NaN and infinity, and drops anything outside -40..100 °C --- ("What a battery can do now"). -local function decode_temp_f32_be(hi, lo) if hi == nil or lo == nil then return nil end hi = hi % 0x10000 lo = lo % 0x10000 local sign = 1 if hi >= 0x8000 then sign = -1; hi = hi - 0x8000 end - local exponent = math.floor(hi / 128) - local mantissa = (hi % 128) * 65536 + lo + local exponent = math.floor(hi / 0x80) + local mantissa = (hi % 0x80) * 0x10000 + lo if exponent == 0xFF then return nil end - local v if exponent == 0 then - v = sign * mantissa * 2 ^ -149 - else - v = sign * (1 + mantissa / 0x800000) * 2 ^ (exponent - 127) + if mantissa == 0 then return 0 end + return sign * mantissa * 2 ^ -149 end - if v < -40 or v > 100 then return nil end + return sign * (1 + mantissa / 0x800000) * 2 ^ (exponent - 127) +end + +-- A temperature from two float32 registers (high word first), or nil when +-- the read failed, the device has no value, or it is outside -40..100 °C +-- ("What a battery can do now"). +local function decode_temp_f32_be(hi, lo) + local v = decode_f32_be(hi, lo) + if v == nil or v < -40 or v > 100 then return nil end return v end +-- SunSpec marks a point it does not implement with 0xFFFF in a uint16 and +-- 0x8000 in a scale factor (SunSpec information model). Both give nil. +local function sunspec_sf(raw) + if raw == nil or raw == 0x8000 then return nil end + local sf = host.decode_i16(raw) + if sf < -10 or sf > 10 then return nil end + return sf +end + +local function sunspec_u16(raw, sf) + if raw == nil or sf == nil or raw == 0xFFFF then return nil end + return apply_sf(raw, sf) +end + -- Turn a Lua array of u16s into an ASCII string, trimming NULs and spaces. -local function regs_to_string(regs, count) +-- `first` is the index of the first register (default 1). +local function regs_to_string(regs, count, first) if not regs then return "" end + first = first or 1 local s = "" - for i = 1, count do + for i = first, first + count - 1 do local r = regs[i] or 0 local hi = math.floor(r / 256) local lo = r % 256 @@ -152,6 +165,74 @@ local function probe_read(addr, count, kind) return nil end +---------------------------------------------------------------------------- +-- The SunSpec model chain: MPPT inputs and storage +-- +-- Source: Fronius's register map bundle 1.2.7-2 (QR-link/0024 in the +-- manifest), the float maps for GEN24 and Verto, with and without storage, +-- and the GEN24 Modbus manual 42,0410,2649. Fronius numbers registers from 1; +-- the wire address is one lower. +-- +-- Model 160 (Multiple MPPT) starts at register 40264, wire 40263 ("start +-- address for 'float' setting: 40263"). Its length L is 8 + 20 x N, one +-- 20-register block per DC input. With storage, N counts the MPPT trackers +-- plus two blocks for the battery: "StCha" (charge) and then "StDisCha" +-- (discharge), the last two. A GEN24 has N = 4 (L = 88); a Verto with three +-- trackers has N = 5 (L = 108); without storage N is the number of trackers. +-- +-- Model 124 (Basic Storage Control) "is only available for inverters with a +-- storage solution" and follows model 160 directly. Without storage the end +-- block (0xFFFF) is there instead, and it answers, so the driver learns there +-- is no battery without a failed read. Earlier versions read model 124 at +-- fixed addresses that assume a two-input model 160, which on a GEN24 with +-- storage are inside model 160's battery blocks. +-- +-- The int+SF maps start model 160 at 40254 and use a different inverter +-- model. This driver reads the float maps only; when model 160 is not at +-- 40264 it reads no DC input or battery values rather than guess. +---------------------------------------------------------------------------- + +local MPPT_ADDR = 40263 -- wire address of model 160's ID +local MAX_READ = 125 -- registers in one Modbus read + +local mppt_len = nil -- L of model 160, from its header +local mppt_missing = false -- model 160 is not where the float map puts it +local storage_addr = nil -- wire address of model 124's ID, with storage +local storage_checked = false + +local function find_models() + if mppt_len == nil and not mppt_missing then + local hdr = probe_read(MPPT_ADDR, 2, "holding") + if hdr == nil or hdr[2] == nil then return end + local len = hdr[2] + if hdr[1] == 160 and len >= 28 and (len - 8) % 20 == 0 + and len + 2 <= MAX_READ then + mppt_len = len + else + mppt_missing = true + host.log("info", string.format( + "Fronius: register 40264 holds model %d, not 160; reading no " .. + "DC input or battery values (is Modbus set to 'float'?)", hdr[1])) + return + end + end + if mppt_len ~= nil and not storage_checked then + local addr = MPPT_ADDR + 2 + mppt_len + local nxt = probe_read(addr, 2, "holding") + if nxt == nil or nxt[2] == nil then return end + storage_checked = true + if nxt[1] == 124 and nxt[2] == 24 then storage_addr = addr end + end +end + +-- Offsets within one read of model 160 (index 1 = its ID). Module k's block +-- starts at index 11 + 20 x (k - 1): ID, IDStr (8 registers), DCA, DCV, DCW. +local function module_base(k) return 11 + 20 * (k - 1) end + +local function module_name(regs, k) + return regs_to_string(regs, 8, module_base(k) + 1) +end + function driver_init(config) host.set_make("Fronius") end @@ -174,53 +255,28 @@ function driver_poll() end end - -- ---------------------------------------------------------------- SFs - -- Scale factors live in separate i16 registers. - - local rated_w_sf = 0 - local rwsf_regs = probe_read(40135, 1, "holding") - if rwsf_regs then rated_w_sf = host.decode_i16(rwsf_regs[1]) end - - local mppt_a_sf = 0 - local masf_regs = probe_read(40265, 1, "holding") - if masf_regs then mppt_a_sf = host.decode_i16(masf_regs[1]) end - - local mppt_v_sf = 0 - local mvsf_regs = probe_read(40266, 1, "holding") - if mvsf_regs then mppt_v_sf = host.decode_i16(mvsf_regs[1]) end - - local max_charge_sf = 0 - local mcsf_regs = probe_read(40331, 1, "holding") - if mcsf_regs then max_charge_sf = host.decode_i16(mcsf_regs[1]) end - - local soc_sf = 0 - local socsf_regs = probe_read(40335, 1, "holding") - if socsf_regs then soc_sf = host.decode_i16(socsf_regs[1]) end - - local bat_v_sf = 0 - local bvsf_regs = probe_read(40337, 1, "holding") - if bvsf_regs then bat_v_sf = host.decode_i16(bvsf_regs[1]) end - - local charge_rate_sf = 0 - local crsf_regs = probe_read(40338, 1, "holding") - if crsf_regs then charge_rate_sf = host.decode_i16(crsf_regs[1]) end + find_models() -- ---------------------------------------------------------------- PV - -- Inverter/AC values are SunSpec F32 BE pairs. + -- Inverter/AC values are SunSpec F32 BE pairs (model 113). - local ac_w = 0 + local ac_w = nil local acw_regs = probe_read(40091, 2, "holding") if acw_regs then ac_w = decode_f32_be(acw_regs[1], acw_regs[2]) end - local hz = 0 + local hz = nil local hz_regs = probe_read(40093, 2, "holding") if hz_regs then hz = decode_f32_be(hz_regs[1], hz_regs[2]) end - local lifetime_wh = 0 + local lifetime_wh = nil local le_regs = probe_read(40101, 2, "holding") if le_regs then lifetime_wh = decode_f32_be(le_regs[1], le_regs[2]) end - local dc_w = 0 + -- DCW, model 113 "DC Power". Not changed here: evcc's fronius-gen24 + -- template sums the MPPT inputs for PV instead, and Fronius's map does + -- not say whether this point includes the battery input. A field report + -- from a GEN24 with storage would settle it. + local dc_w = nil local dcw_regs = probe_read(40107, 2, "holding") if dcw_regs then dc_w = decode_f32_be(dcw_regs[1], dcw_regs[2]) end @@ -234,29 +290,42 @@ function driver_poll() local temp_regs = probe_read(40109, 2, "holding") if temp_regs then cabinet_c = decode_temp_f32_be(temp_regs[1], temp_regs[2]) end - -- Rated W: 40134, U16 raw × 10^rated_w_sf - local rated_w = 0 - local rw_regs = probe_read(40134, 1, "holding") - if rw_regs then rated_w = apply_sf(rw_regs[1], rated_w_sf) end - - -- MPPT1 A/V: 40282-40283, U16 each - local mppt1_a, mppt1_v = 0, 0 - local m1_regs = probe_read(40282, 2, "holding") - if m1_regs then - mppt1_a = apply_sf(m1_regs[1], mppt_a_sf) - mppt1_v = apply_sf(m1_regs[2], mppt_v_sf) + -- Rated W: WRtg and WRtg_SF, model 120 registers 40135-40136, one read. + local rated_w = nil + local rw_regs = probe_read(40134, 2, "holding") + if rw_regs then rated_w = sunspec_u16(rw_regs[1], sunspec_sf(rw_regs[2])) end + + -- Model 160 in one read, so the auto-scaled factors (DCA_SF, DCV_SF, + -- DCW_SF) come with the values they scale. MPPT 1 and 2 are the first + -- two blocks in every float map. + local mppt = nil + if mppt_len ~= nil then + mppt = probe_read(MPPT_ADDR, 2 + mppt_len, "holding") + if mppt and (mppt[1] ~= 160 or mppt[2 + mppt_len] == nil) then + mppt = nil + end end - -- MPPT2 A/V: 40302-40303, U16 each - local mppt2_a, mppt2_v = 0, 0 - local m2_regs = probe_read(40302, 2, "holding") - if m2_regs then - mppt2_a = apply_sf(m2_regs[1], mppt_a_sf) - mppt2_v = apply_sf(m2_regs[2], mppt_v_sf) + local mppt1_v, mppt1_a, mppt2_v, mppt2_a + local dca_sf, dcv_sf, dcw_sf, modules + if mppt then + dca_sf = sunspec_sf(mppt[3]) + dcv_sf = sunspec_sf(mppt[4]) + dcw_sf = sunspec_sf(mppt[5]) + modules = mppt[9] + if modules ~= nil and 8 + 20 * modules ~= mppt_len then modules = nil end + if modules ~= nil and modules >= 1 then + mppt1_a = sunspec_u16(mppt[module_base(1) + 9], dca_sf) + mppt1_v = sunspec_u16(mppt[module_base(1) + 10], dcv_sf) + end + if modules ~= nil and modules >= 2 then + mppt2_a = sunspec_u16(mppt[module_base(2) + 9], dca_sf) + mppt2_v = sunspec_u16(mppt[module_base(2) + 10], dcv_sf) + end end -- Per-phase AC current: 40073, 40075, 40077 (F32 BE pairs) - local l1_a, l2_a, l3_a = 0, 0, 0 + local l1_a, l2_a, l3_a = nil, nil, nil local l1a_regs = probe_read(40073, 2, "holding") if l1a_regs then l1_a = decode_f32_be(l1a_regs[1], l1a_regs[2]) end local l2a_regs = probe_read(40075, 2, "holding") @@ -265,7 +334,7 @@ function driver_poll() if l3a_regs then l3_a = decode_f32_be(l3a_regs[1], l3a_regs[2]) end -- Per-phase AC voltage: 40085, 40087, 40089 (F32 BE pairs) - local l1_v, l2_v, l3_v = 0, 0, 0 + local l1_v, l2_v, l3_v = nil, nil, nil local l1v_regs = probe_read(40085, 2, "holding") if l1v_regs then l1_v = decode_f32_be(l1v_regs[1], l1v_regs[2]) end local l2v_regs = probe_read(40087, 2, "holding") @@ -273,96 +342,89 @@ function driver_poll() local l3v_regs = probe_read(40089, 2, "holding") if l3v_regs then l3_v = decode_f32_be(l3v_regs[1], l3v_regs[2]) end - -- Emit PV (dc_w magnitude → negative for generation, per site convention) - host.emit("pv", { - w = -dc_w, - mppt1_v = mppt1_v, - mppt1_a = mppt1_a, - mppt2_v = mppt2_v, - mppt2_a = mppt2_a, - lifetime_wh = lifetime_wh, - temp_c = cabinet_c, - rated_w = rated_w, - }) + -- Emit PV (dc_w magnitude → negative for generation, per site + -- convention). DC power is PV's defining value: without it there is no + -- PV reading. Each other field is left out when it did not answer. + if dc_w ~= nil then + host.emit("pv", { + w = -dc_w, + mppt1_v = mppt1_v, + mppt1_a = mppt1_a, + mppt2_v = mppt2_v, + mppt2_a = mppt2_a, + lifetime_wh = lifetime_wh, + temp_c = cabinet_c, + rated_w = rated_w, + }) + end -- Diagnostics: long-format TS DB - host.emit_metric("pv_mppt1_v", mppt1_v) - host.emit_metric("pv_mppt1_a", mppt1_a) - host.emit_metric("pv_mppt2_v", mppt2_v) - host.emit_metric("pv_mppt2_a", mppt2_a) + if mppt1_v ~= nil then host.emit_metric("pv_mppt1_v", mppt1_v) end + if mppt1_a ~= nil then host.emit_metric("pv_mppt1_a", mppt1_a) end + if mppt2_v ~= nil then host.emit_metric("pv_mppt2_v", mppt2_v) end + if mppt2_a ~= nil then host.emit_metric("pv_mppt2_a", mppt2_a) end if cabinet_c ~= nil then host.emit_metric("inverter_temp_c", cabinet_c) end - host.emit_metric("grid_hz", hz) + if hz ~= nil then host.emit_metric("grid_hz", hz) end -- ----------------------------------------------------------- Battery -- - -- Fronius's GEN24 Modbus maps carry no battery temperature and no live - -- charge or discharge limit. Model 124 has no temperature point, and the - -- per-module Tmp in model 160 is "not supported". WChaMax is "Setpoint - -- for maximum charge", which the GEN24 manual defines as - -- max(MaxChaRte, MaxDisChaRte), the nameplate rates of model 120; it does - -- not move with the BMS, so it is not sent as available_charge_W. Nor is - -- there a grid import/export headroom point (model 122 WAval is "not - -- supported"). + -- Only with storage, which model 124 following model 160 proves. -- - -- NOTE, not changed here: the fixed model-124 addresses below assume a - -- two-module model 160. Fronius's own GEN24 storage maps (register map - -- bundle 1.2.7-2) add two storage modules to model 160 and put WChaMax - -- at register 40356 (float) or 40346 (int+SF), and the manual says to - -- find each model by walking the chain rather than by fixed address. - -- InBatV is "not supported" there, and OutWRte/InWRte are setpoints, not - -- measured rates. - - -- Max charge power: 40315, U16 raw × 10^max_charge_sf - local max_charge_w = 0 - local maxchg_regs = probe_read(40315, 1, "holding") - if maxchg_regs then - max_charge_w = apply_sf(maxchg_regs[1], max_charge_sf) - end - - -- Battery SoC: 40321, U16 raw (percent), convert to 0..1 fraction - local bat_soc = 0 - local bsoc_regs = probe_read(40321, 1, "holding") - if bsoc_regs then - bat_soc = apply_sf(bsoc_regs[1], soc_sf) / 100 - end - - -- Battery voltage: 40323, U16 raw × 10^bat_v_sf - local bat_v = 0 - local batv_regs = probe_read(40323, 1, "holding") - if batv_regs then - bat_v = apply_sf(batv_regs[1], bat_v_sf) - end - - -- Discharge rate % (I16): 40325 - local discharge_rate = 0 - local dis_regs = probe_read(40325, 1, "holding") - if dis_regs then - discharge_rate = apply_sf(host.decode_i16(dis_regs[1]), charge_rate_sf) - end + -- Power and voltage come from the two battery blocks of model 160, the + -- last two: "StCha" and "StDisCha". Fronius sets the charge block to 0 + -- while the battery discharges and the discharge block to 0 while it + -- charges, so battery W = charge DCW - discharge DCW, positive charging + -- (site convention; evcc's fronius-gen24 template reads it the same + -- way). Both blocks carry the battery port's voltage since firmware + -- 1.31; up to 1.30 only the active one did, so the driver takes the + -- larger, and leaves the voltage out when both are 0. The names are + -- checked, so a map the driver does not know sends no battery power. + -- + -- SoC is model 124's ChaState (offset 8) x 10^ChaState_SF (offset 22), + -- in percent: "Estimated_Capacity_Remaining [Wh] / + -- Estimated_Capacity_Maximum [Wh]" (GEN24 manual). + -- + -- Earlier versions took battery power from OutWRte / InWRte times + -- WChaMax. Those are the owner's charge and discharge rate setpoints + -- (WChaMax is max(MaxChaRte, MaxDisChaRte), a rating), not a measurement. + -- + -- Fronius's maps carry no battery temperature and no live charge or + -- discharge limit: model 124 has no temperature point, the battery + -- blocks' Tmp is "not supported", InBatV is "not supported", and model + -- 122's WAval (grid headroom) is "not supported". So none is sent. + + local bat_w, bat_v, bat_soc = nil, nil, nil + if storage_addr ~= nil then + if mppt and modules ~= nil and modules >= 3 then + local cha, dis = modules - 1, modules + if module_name(mppt, cha):sub(1, 5) == "StCha" + and module_name(mppt, dis):sub(1, 8) == "StDisCha" then + local cha_w = sunspec_u16(mppt[module_base(cha) + 11], dcw_sf) + local dis_w = sunspec_u16(mppt[module_base(dis) + 11], dcw_sf) + if cha_w ~= nil and dis_w ~= nil then bat_w = cha_w - dis_w end + local cha_v = sunspec_u16(mppt[module_base(cha) + 10], dcv_sf) + local dis_v = sunspec_u16(mppt[module_base(dis) + 10], dcv_sf) + local v = math.max(cha_v or 0, dis_v or 0) + if v > 0 then bat_v = v end + end + end - -- Charge rate % (I16): 40326 - local charge_rate = 0 - local chg_regs = probe_read(40326, 1, "holding") - if chg_regs then - charge_rate = apply_sf(host.decode_i16(chg_regs[1]), charge_rate_sf) + local st = probe_read(storage_addr, 23, "holding") + if st and st[1] == 124 and st[23] ~= nil then + local pct = sunspec_u16(st[9], sunspec_sf(st[23])) + if pct ~= nil and pct >= 0 and pct <= 100 then bat_soc = pct / 100 end + end end - -- Site convention: positive W = charging, negative W = discharging. - -- Fronius reports direction as two separate percent rates + max power. - local bat_w = 0 - if discharge_rate > 0 then - bat_w = -(discharge_rate / 100) * max_charge_w - elseif charge_rate > 0 then - bat_w = (charge_rate / 100) * max_charge_w + if bat_w ~= nil or bat_v ~= nil or bat_soc ~= nil then + host.emit("battery", { + w = bat_w, + v = bat_v, + soc = bat_soc, + }) end - - host.emit("battery", { - w = bat_w, - v = bat_v, - soc = bat_soc, - }) - host.emit_metric("battery_dc_v", bat_v) + if bat_v ~= nil then host.emit_metric("battery_dc_v", bat_v) end -- NOTE: This driver does NOT emit meter telemetry. A Fronius inverter is -- NOT a grid meter — its AC output represents inverter production, not the @@ -392,4 +454,8 @@ end function driver_cleanup() sn_read = false + mppt_len = nil + mppt_missing = false + storage_addr = nil + storage_checked = false end diff --git a/drivers/tests/invented-number-baseline.json b/drivers/tests/invented-number-baseline.json index 1aa5f20..935e481 100644 --- a/drivers/tests/invented-number-baseline.json +++ b/drivers/tests/invented-number-baseline.json @@ -23,7 +23,6 @@ "ctek_hybrid": 9, "ctek_v2": 9, "deye": 26, - "fronius": 10, "hello": 3, "janitza": 13, "kostal": 21, diff --git a/drivers/tests/test_fronius_storage_map.py b/drivers/tests/test_fronius_storage_map.py new file mode 100644 index 0000000..d3e2119 --- /dev/null +++ b/drivers/tests/test_fronius_storage_map.py @@ -0,0 +1,293 @@ +"""Fronius reads the battery where Fronius's GEN24 and Verto storage maps put it. + +Source: Fronius's register map bundle 1.2.7-2 (www.fronius.com/QR-link/0024, +linked from the GEN24 Modbus manual 42,0410,2649), the float maps with +storage. Fronius numbers registers from 1, so the wire address is one lower. + +* Model 160 (MPPT) starts at register 40264, wire 40263. Its length is + 8 + 20 x N. With storage, N counts the trackers plus two inputs for the + battery, "StCha" (charge) and "StDisCha" (discharge), the last two blocks. + A GEN24 has N = 4 (L = 88), a Verto with three trackers N = 5 (L = 108). +* Model 124 (storage) follows model 160 directly, and only with storage. + ChaState is at offset 8 and ChaState_SF at offset 22. +* Battery power is the charge input's DCW minus the discharge input's DCW + (Fronius sets the idle one to 0; evcc's fronius-gen24 template reads it + the same way). Battery voltage is the inputs' DCV: since firmware 1.31 + both carry it, before that only the active one did. + +Earlier releases read model 124 at fixed addresses that assume a two-input +model 160, so on a GEN24 with storage they landed in model 160's battery +blocks, and they took battery power from the OutWRte / InWRte setpoints. +They also sent a battery at 0 W, 0 V and 0 % on an inverter with none, and +their float decoder flipped the sign of every float on 32-bit Lua, which the +harness uses. +""" + +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" / "fronius.lua" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + +MPPT = 40263 # wire address of model 160's ID (register 40264) +NAN = (0x7FC0, 0x0000) + + +def u16(value: int) -> int: + return value & 0xFFFF + + +def text(s: str) -> list[int]: + raw = s.encode().ljust(16, b"\0") + return [raw[i] * 256 + raw[i + 1] for i in range(0, 16, 2)] + + +def site(trackers: int = 2, storage: bool = True, *, dca_sf=-2, dcv_sf=-1, + dcw_sf=0, cha=(0, 0, 0), dis=(0, 0, 0), soc_raw=5000, soc_sf=-2, + mppt1=(850, 3512), mppt2=(420, 3300), names=None) -> dict[int, int]: + """Registers of a Fronius float map, keyed by wire address. + + cha / dis are (DCA, DCV, DCW) raw values for the storage inputs. + """ + n = trackers + (2 if storage else 0) + length = 8 + 20 * n + regs: dict[int, int] = { + MPPT: 160, MPPT + 1: length, + MPPT + 2: u16(dca_sf), MPPT + 3: u16(dcv_sf), MPPT + 4: u16(dcw_sf), + MPPT + 5: 0, MPPT + 8: n, + } + if names is None: + names = [f"MPPT {k}" for k in range(1, trackers + 1)] + if storage: + names += [f"StCha {trackers + 1}", f"StDisCha {trackers + 2}"] + values = [mppt1, mppt2] + [(0, 0)] * (trackers - 2) + for k in range(1, n + 1): + base = MPPT + 10 + 20 * (k - 1) + regs[base] = k + for i, word in enumerate(text(names[k - 1])): + regs[base + 1 + i] = word + if k <= trackers: + dca, dcv = values[k - 1] + regs[base + 9], regs[base + 10], regs[base + 11] = dca, dcv, 0 + else: + regs[base + 9], regs[base + 10], regs[base + 11] = ( + cha if k == trackers + 1 else dis) + nxt = MPPT + 2 + length + if storage: + regs[nxt], regs[nxt + 1] = 124, 24 + regs[nxt + 8] = soc_raw + regs[nxt + 22] = u16(soc_sf) + regs[nxt + 26] = 0xFFFF # end block + else: + regs[nxt], regs[nxt + 1] = 0xFFFF, 0 + return regs + + +def _poll(registers: dict, fail: tuple = (), polls: int = 1) -> dict[str, str]: + setup = "\n".join( + f"host._modbus_registers.holding[{addr}] = {val}" + for addr, val in registers.items()) + failing = "\n".join( + f'host._modbus_read_fail_addresses[{addr}] = "Illegal Data Address"' + for addr in fail) + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() +{setup} +{failing} +dofile("{DRIVER}") +driver_init({{}}) +for _ = 1, {polls} do + host._emitted = {{}} + host._metrics = {{}} + local ok, err = pcall(driver_poll) + if not ok then print("POLL_ERROR " .. tostring(err)) os.exit(1) end +end +for _, der in ipairs({{"battery", "pv", "meter"}}) do + local list = host._emitted[der] + if list and #list > 0 then + print(der .. " emitted") + for k, v in pairs(list[#list]) do print(der .. "." .. k .. " " .. tostring(v)) end + end +end +for name, m in pairs(host._metrics) do print("metric." .. name .. " " .. tostring(m.value)) end +local reads = {{}} +for _, c in ipairs(host._calls) do + if c.func == "modbus_read" then reads[#reads + 1] = c.args[1] .. ":" .. c.args[2] end +end +print("reads " .. table.concat(reads, ",")) +''' + 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 test_gen24_charging(): + # DCW_SF 0: 1234 W into the battery. DCV_SF -1: 52.3 V. ChaState 65.43 %. + out = _poll(site(cha=(2360, 523, 1234), dis=(0, 523, 0), soc_raw=6543)) + assert float(out["battery.w"]) == pytest.approx(1234) + assert float(out["battery.v"]) == pytest.approx(52.3) + assert float(out["battery.soc"]) == pytest.approx(0.6543) + assert float(out["metric.battery_dc_v"]) == pytest.approx(52.3) + + +def test_gen24_discharging_is_negative(): + out = _poll(site(dcw_sf=-1, cha=(0, 518, 0), dis=(4800, 518, 25000))) + assert float(out["battery.w"]) == pytest.approx(-2500) + assert float(out["battery.v"]) == pytest.approx(51.8) + + +def test_gen24_old_firmware_voltage_on_the_active_input_only(): + # Up to firmware 1.30 the idle input's DCV is 0 as well. + out = _poll(site(cha=(0, 0, 0), dis=(1000, 510, 500))) + assert float(out["battery.v"]) == pytest.approx(51.0) + assert float(out["battery.w"]) == pytest.approx(-500) + + +def test_gen24_idle_old_firmware_leaves_voltage_out(): + # Both inputs at 0 V means neither is active, not a 0 V battery. + out = _poll(site(cha=(0, 0, 0), dis=(0, 0, 0))) + assert "battery.v" not in out + assert "metric.battery_dc_v" not in out + assert float(out["battery.w"]) == 0 + assert float(out["battery.soc"]) == pytest.approx(0.5) + + +def test_verto_three_trackers_and_storage(): + # Verto: N = 5, model 124 at register 40374 (wire 40373). + regs = site(trackers=3, cha=(0, 0, 0), dis=(0, 0, 0), soc_raw=8000) + regs.update({MPPT + 10 + 20 * 3 + 9: 1500, MPPT + 10 + 20 * 3 + 10: 530, + MPPT + 10 + 20 * 3 + 11: 800}) + assert regs[40373] == 124 + out = _poll(regs) + assert float(out["battery.w"]) == pytest.approx(800) + assert float(out["battery.v"]) == pytest.approx(53.0) + assert float(out["battery.soc"]) == pytest.approx(0.8) + + +def test_mppt_values_from_the_model_160_block(): + out = _poll(site(mppt1=(850, 3512), mppt2=(420, 3300))) + assert float(out["pv.mppt1_a"]) == pytest.approx(8.5) + assert float(out["pv.mppt1_v"]) == pytest.approx(351.2) + assert float(out["pv.mppt2_a"]) == pytest.approx(4.2) + assert float(out["pv.mppt2_v"]) == pytest.approx(330.0) + + +def test_no_storage_sends_no_battery(): + out = _poll(site(storage=False), polls=3) + assert "battery" not in out + assert "metric.battery_dc_v" not in out + assert float(out["pv.mppt1_v"]) == pytest.approx(351.2) + + +def test_no_storage_reads_nothing_past_the_end_block(): + # The register after model 160 is the end block there (wire 40313), + # which answers, so the driver learns there is no battery without + # reading past the end of the map, where a real inverter answers with + # an exception. + out = _poll(site(storage=False), polls=3) + assert "battery" not in out + for read in out["reads"].split(","): + addr, count = (int(x) for x in read.split(":")) + assert addr + count <= 40315, f"read {count} registers at {addr}" + + +def test_model_124_does_not_answer(): + out = _poll(site(cha=(0, 520, 900)), fail=(40353,), polls=4) + assert "battery" not in out + + +def test_soc_not_implemented_leaves_soc_out(): + for regs in (site(cha=(0, 520, 900), soc_raw=0xFFFF), + site(cha=(0, 520, 900), soc_sf=-32768)): + out = _poll(regs) + assert "battery.soc" not in out + assert float(out["battery.w"]) == pytest.approx(900) + + +def test_soc_out_of_range_is_dropped(): + out = _poll(site(cha=(0, 520, 900), soc_raw=10001)) + assert "battery.soc" not in out + + +def test_storage_inputs_not_named_as_documented(): + names = ["MPPT 1", "MPPT 2", "MPPT 3", "MPPT 4"] + out = _poll(site(cha=(0, 520, 900), names=names)) + assert "battery.w" not in out + assert "battery.v" not in out + assert float(out["battery.soc"]) == pytest.approx(0.5) + + +def test_model_160_not_where_the_float_map_puts_it(): + # The int+SF maps start model 160 at register 40254; at 40264 there is + # something else. The driver reads no DC input or battery values then. + regs = site() + regs[MPPT] = 0 + out = _poll(regs) + assert "battery" not in out + assert not any(k.startswith("pv.mppt") for k in out) + + +def test_model_160_does_not_answer(): + out = _poll(site(), fail=(MPPT,), polls=4) + assert "battery" not in out + assert not any(k.startswith("pv.mppt") for k in out) + + +def test_old_addresses_are_not_read(): + # Main read WChaMax at wire 40315, ChaState at 40321, InBatV at 40323 and + # OutWRte / InWRte at 40325 / 40326 with scale factors at 40331-40338. + regs = site(cha=(0, 520, 900)) + out = _poll(regs, fail=(40315, 40321, 40323, 40325, 40326, + 40331, 40335, 40337, 40338)) + assert float(out["battery.w"]) == pytest.approx(900) + assert float(out["battery.soc"]) == pytest.approx(0.5) + + +def test_float_values_keep_their_sign(): + # 6000.0 W DC, 50.0 Hz, 12345678 Wh. Main's decoder joined the words into + # one 32-bit number and compared it with 0x80000000, which is negative on + # 32-bit Lua, so every float came out negative here. + regs = site() + regs.update({40107: 0x45BB, 40108: 0x8000, # DCW 6000.0 + 40093: 0x4248, 40094: 0x0000, # Hz 50.0 + 40101: 0x4B3C, 40102: 0x614E}) # WH 12345678.0 + out = _poll(regs) + assert float(out["pv.w"]) == pytest.approx(-6000) + assert float(out["metric.grid_hz"]) == pytest.approx(50.0) + assert float(out["pv.lifetime_wh"]) == pytest.approx(12345678) + + +def test_float_nan_is_left_out_not_sent_as_zero(): + regs = site() + regs.update({40107: NAN[0], 40108: NAN[1], + 40093: NAN[0], 40094: NAN[1], + 40101: NAN[0], 40102: NAN[1]}) + out = _poll(regs) + assert "pv" not in out # DC power is PV's defining value + assert "metric.grid_hz" not in out + + +def test_failed_pv_reads_are_left_out(): + out = _poll(site(), fail=(40101, 40093, 40134)) + assert "pv.lifetime_wh" not in out + assert "pv.rated_w" not in out + assert "metric.grid_hz" not in out + assert "pv.w" in out + + +def test_rated_power_with_its_scale_factor(): + regs = site() + regs.update({40134: 1000, 40135: 1}) # WRtg 1000 x 10^1 + out = _poll(regs) + assert float(out["pv.rated_w"]) == pytest.approx(10000) diff --git a/index.yaml b/index.yaml index 6672d7e..4a41934 100644 --- a/index.yaml +++ b/index.yaml @@ -252,14 +252,14 @@ drivers: size_bytes: 43733 sha256: "c7b3ce58731031340a76c21f15fb87cddb4b6a2cb6ac4320b39f748cf7eae9e9" - name: "fronius" - version: "2.2.0" + version: "2.3.0" tier: core protocol: modbus connectivity: local ders: [battery, meter, pv] control: false - size_bytes: 15342 - sha256: "c277eee7c0e829b6f385648109ae0fe1dd4dd0d7d0cd1015e4df07b12e84f58f" + size_bytes: 19443 + sha256: "fb0beed13d3b51675ed90437979f5d0e78775c6c1696341e70a9790711972d70" - name: "fronius_api" version: "1.0.2" tier: community diff --git a/manifests/fronius.yaml b/manifests/fronius.yaml index e2b4cf9..153effb 100644 --- a/manifests/fronius.yaml +++ b/manifests/fronius.yaml @@ -1,5 +1,5 @@ name: "fronius" -version: "2.2.0" +version: "2.3.0" tier: core author: "Sourceful Labs AB" protocol: modbus @@ -59,12 +59,12 @@ upstream_docs: kind: register_map url_stability: stable min_host_version: "2.0.0" -size_bytes: 15342 +size_bytes: 19443 dkb_id: "fronius_symo_gen24" -sha256: "c277eee7c0e829b6f385648109ae0fe1dd4dd0d7d0cd1015e4df07b12e84f58f" +sha256: "fb0beed13d3b51675ed90437979f5d0e78775c6c1696341e70a9790711972d70" signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "" +changelog: "Read battery power, voltage and SoC where the GEN24 and Verto storage maps put them, send no battery without storage, and decode floats correctly on 32-bit Lua." diff --git a/support-status.json b/support-status.json index b6a7eb8..4499dfb 100644 --- a/support-status.json +++ b/support-status.json @@ -569,7 +569,7 @@ }, { "catalog_source": true, - "catalog_version": "2.2.0", + "catalog_version": "2.3.0", "driver_id": "fronius", "targets": { "blixt-l1": { From be0ec91d997a34955424e0bab697ce206252ef8b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 22 Nov 2026 13:42:41 +0100 Subject: [PATCH 2/2] fix(fronius): PV from the MPPT inputs with storage; look for a battery again Review of #272: - With storage, PV power is now the sum of the MPPT blocks before the battery blocks, as evcc's fronius-gen24 template reads it. Fronius's map does not say whether model 113's DC power includes the battery input, so a 3 kW discharge could have shown as 3 kW of sun. Model 113's DC power is used only where there is no battery input, and PV is left out for a poll where the storage model is known but the battery blocks are not readable. - The storage check is no longer sticky. While no storage model is known the driver reads the chain again every five minutes, and at once when model 160's length changes, so a battery fitted after start is found. Refs srcfl/device-drivers#260 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- CHANGELOG.md | 16 ++- drivers/lua/fronius.lua | 124 ++++++++++++++----- drivers/tests/test_fronius_storage_map.py | 139 +++++++++++++++++++--- index.yaml | 4 +- manifests/fronius.yaml | 6 +- 5 files changed, 232 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd68d6c..750082e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,11 +30,17 @@ Not yet checked on hardware (srcfl/device-drivers#260). each other PV field and metric only when its own read did. The MPPT values come from one read of model 160, with the scale factors that go with them. `fronius` leaves `invented-number-baseline.json` (10 to 0). -- **Not changed.** PV power still comes from model 113's DC power. evcc's - GEN24 template sums the MPPT inputs instead, and Fronius's map does not - say whether model 113 includes the battery input. In the int+SF setting - model 160 starts at 40254; the driver reads only the float maps, so it - now sends no DC input or battery values there rather than wrong ones. +- **PV power with storage** is the sum of the MPPT blocks before the + battery blocks, as evcc's GEN24 template reads it. Fronius's map does not + say whether model 113's DC power includes the battery input, so a 3 kW + discharge could have shown as 3 kW of sun. Model 113's DC power is used + only where there is no battery input. +- **A battery fitted later is found.** While no storage model is known the + driver looks for it again every five minutes, and at once when model + 160's length changes. +- **Not changed.** In the int+SF setting model 160 starts at 40254; the + driver reads only the float maps, so it now sends no DC input or battery + values there rather than wrong ones. ### ferroamp_modbus 2.2.2 diff --git a/drivers/lua/fronius.lua b/drivers/lua/fronius.lua index 71efc6d..4bc30c6 100644 --- a/drivers/lua/fronius.lua +++ b/drivers/lua/fronius.lua @@ -199,20 +199,52 @@ local mppt_len = nil -- L of model 160, from its header local mppt_missing = false -- model 160 is not where the float map puts it local storage_addr = nil -- wire address of model 124's ID, with storage local storage_checked = false +local mppt_logged = false + +-- A battery fitted after the driver started changes the chain: model 160 +-- grows by the two battery blocks and model 124 appears after it. So while +-- no storage model is known the driver looks again every five minutes, and +-- at once when model 160's own length no longer matches. That costs two +-- short reads every five minutes on an inverter without a battery. +local RECHECK_MS = 5 * 60 * 1000 +local checked_at = nil + +local function forget_models() + mppt_len = nil + mppt_missing = false + storage_addr = nil + storage_checked = false + checked_at = nil +end local function find_models() + if storage_addr == nil and checked_at ~= nil + and host.millis() - checked_at >= RECHECK_MS then + forget_models() + end if mppt_len == nil and not mppt_missing then local hdr = probe_read(MPPT_ADDR, 2, "holding") - if hdr == nil or hdr[2] == nil then return end + if hdr == nil or hdr[2] == nil then + -- A model 160 that never answers is treated as absent. + if (read_failures[MPPT_ADDR] or 0) >= GIVE_UP_AFTER then + mppt_missing = true + checked_at = host.millis() + end + return + end local len = hdr[2] if hdr[1] == 160 and len >= 28 and (len - 8) % 20 == 0 and len + 2 <= MAX_READ then mppt_len = len else mppt_missing = true - host.log("info", string.format( - "Fronius: register 40264 holds model %d, not 160; reading no " .. - "DC input or battery values (is Modbus set to 'float'?)", hdr[1])) + checked_at = host.millis() + if not mppt_logged then + mppt_logged = true + host.log("info", string.format( + "Fronius: register 40264 holds model %d, not 160; reading no " .. + "DC input or battery values (is Modbus set to 'float'?)", hdr[1])) + end return end end @@ -221,6 +253,7 @@ local function find_models() local nxt = probe_read(addr, 2, "holding") if nxt == nil or nxt[2] == nil then return end storage_checked = true + checked_at = host.millis() if nxt[1] == 124 and nxt[2] == 24 then storage_addr = addr end end end @@ -272,10 +305,8 @@ function driver_poll() local le_regs = probe_read(40101, 2, "holding") if le_regs then lifetime_wh = decode_f32_be(le_regs[1], le_regs[2]) end - -- DCW, model 113 "DC Power". Not changed here: evcc's fronius-gen24 - -- template sums the MPPT inputs for PV instead, and Fronius's map does - -- not say whether this point includes the battery input. A field report - -- from a GEN24 with storage would settle it. + -- DCW, model 113 "DC Power". Used for PV only without a battery input + -- (see "PV power" below). local dc_w = nil local dcw_regs = probe_read(40107, 2, "holding") if dcw_regs then dc_w = decode_f32_be(dcw_regs[1], dcw_regs[2]) end @@ -301,7 +332,12 @@ function driver_poll() local mppt = nil if mppt_len ~= nil then mppt = probe_read(MPPT_ADDR, 2 + mppt_len, "holding") - if mppt and (mppt[1] ~= 160 or mppt[2 + mppt_len] == nil) then + if mppt and mppt[1] == 160 and mppt[2] ~= mppt_len then + -- Model 160 changed length, for example a battery was fitted: + -- find the chain again on the next poll. + forget_models() + mppt = nil + elseif mppt and (mppt[1] ~= 160 or mppt[2 + mppt_len] == nil) then mppt = nil end end @@ -324,6 +360,38 @@ function driver_poll() end end + -- The battery blocks: the last two of model 160, named "StCha" and + -- "StDisCha" in both storage maps. The names are checked, so a layout + -- the driver does not know gives no battery blocks. + local cha, dis = nil, nil + if mppt and modules ~= nil and modules >= 3 + and module_name(mppt, modules - 1):sub(1, 5) == "StCha" + and module_name(mppt, modules):sub(1, 8) == "StDisCha" then + cha, dis = modules - 1, modules + end + + -- PV power. Fronius's map does not say whether model 113's DC power + -- includes the battery input, and evcc's fronius-gen24 template sums + -- the MPPT blocks instead. So with storage PV is the sum of the MPPT + -- blocks before the battery blocks; a 3 kW discharge then cannot show + -- as 3 kW of sun. Model 113's DC power is used only where there is no + -- battery input: no storage model after model 160, or a model 160 with + -- no battery blocks. With storage and no readable battery blocks, PV is + -- left out for that poll. + local pv_dc_w = nil + if cha ~= nil then + local sum = 0 + for k = 1, cha - 1 do + local w = sunspec_u16(mppt[module_base(k) + 11], dcw_sf) + if w == nil then sum = nil; break end + sum = sum + w + end + pv_dc_w = sum + elseif storage_addr == nil and (mppt_missing or storage_checked + or (mppt and modules ~= nil)) then + pv_dc_w = dc_w + end + -- Per-phase AC current: 40073, 40075, 40077 (F32 BE pairs) local l1_a, l2_a, l3_a = nil, nil, nil local l1a_regs = probe_read(40073, 2, "holding") @@ -342,12 +410,12 @@ function driver_poll() local l3v_regs = probe_read(40089, 2, "holding") if l3v_regs then l3_v = decode_f32_be(l3v_regs[1], l3v_regs[2]) end - -- Emit PV (dc_w magnitude → negative for generation, per site + -- Emit PV (DC power magnitude → negative for generation, per site -- convention). DC power is PV's defining value: without it there is no -- PV reading. Each other field is left out when it did not answer. - if dc_w ~= nil then + if pv_dc_w ~= nil then host.emit("pv", { - w = -dc_w, + w = -pv_dc_w, mppt1_v = mppt1_v, mppt1_a = mppt1_a, mppt2_v = mppt2_v, @@ -371,15 +439,14 @@ function driver_poll() -- -- Only with storage, which model 124 following model 160 proves. -- - -- Power and voltage come from the two battery blocks of model 160, the - -- last two: "StCha" and "StDisCha". Fronius sets the charge block to 0 + -- Power and voltage come from the two battery blocks of model 160 (see + -- above). Fronius sets the charge block to 0 -- while the battery discharges and the discharge block to 0 while it -- charges, so battery W = charge DCW - discharge DCW, positive charging -- (site convention; evcc's fronius-gen24 template reads it the same -- way). Both blocks carry the battery port's voltage since firmware -- 1.31; up to 1.30 only the active one did, so the driver takes the - -- larger, and leaves the voltage out when both are 0. The names are - -- checked, so a map the driver does not know sends no battery power. + -- larger, and leaves the voltage out when both are 0. -- -- SoC is model 124's ChaState (offset 8) x 10^ChaState_SF (offset 22), -- in percent: "Estimated_Capacity_Remaining [Wh] / @@ -396,18 +463,14 @@ function driver_poll() local bat_w, bat_v, bat_soc = nil, nil, nil if storage_addr ~= nil then - if mppt and modules ~= nil and modules >= 3 then - local cha, dis = modules - 1, modules - if module_name(mppt, cha):sub(1, 5) == "StCha" - and module_name(mppt, dis):sub(1, 8) == "StDisCha" then - local cha_w = sunspec_u16(mppt[module_base(cha) + 11], dcw_sf) - local dis_w = sunspec_u16(mppt[module_base(dis) + 11], dcw_sf) - if cha_w ~= nil and dis_w ~= nil then bat_w = cha_w - dis_w end - local cha_v = sunspec_u16(mppt[module_base(cha) + 10], dcv_sf) - local dis_v = sunspec_u16(mppt[module_base(dis) + 10], dcv_sf) - local v = math.max(cha_v or 0, dis_v or 0) - if v > 0 then bat_v = v end - end + if cha ~= nil then + local cha_w = sunspec_u16(mppt[module_base(cha) + 11], dcw_sf) + local dis_w = sunspec_u16(mppt[module_base(dis) + 11], dcw_sf) + if cha_w ~= nil and dis_w ~= nil then bat_w = cha_w - dis_w end + local cha_v = sunspec_u16(mppt[module_base(cha) + 10], dcv_sf) + local dis_v = sunspec_u16(mppt[module_base(dis) + 10], dcv_sf) + local v = math.max(cha_v or 0, dis_v or 0) + if v > 0 then bat_v = v end end local st = probe_read(storage_addr, 23, "holding") @@ -454,8 +517,5 @@ end function driver_cleanup() sn_read = false - mppt_len = nil - mppt_missing = false - storage_addr = nil - storage_checked = false + forget_models() end diff --git a/drivers/tests/test_fronius_storage_map.py b/drivers/tests/test_fronius_storage_map.py index d3e2119..983dbad 100644 --- a/drivers/tests/test_fronius_storage_map.py +++ b/drivers/tests/test_fronius_storage_map.py @@ -14,6 +14,12 @@ (Fronius sets the idle one to 0; evcc's fronius-gen24 template reads it the same way). Battery voltage is the inputs' DCV: since firmware 1.31 both carry it, before that only the active one did. +* With storage, PV power is the sum of the MPPT blocks before the battery + blocks, as evcc reads it: Fronius does not say whether model 113's DC + power includes the battery input. Without storage it is model 113's DC + power, as before. +* While no storage model is known, the driver looks again every five + minutes, and at once when model 160's length changes. Earlier releases read model 124 at fixed addresses that assume a two-input model 160, so on a GEN24 with storage they landed in model 160's battery @@ -23,6 +29,7 @@ harness uses. """ +import struct import subprocess from pathlib import Path @@ -51,10 +58,12 @@ def text(s: str) -> list[int]: def site(trackers: int = 2, storage: bool = True, *, dca_sf=-2, dcv_sf=-1, dcw_sf=0, cha=(0, 0, 0), dis=(0, 0, 0), soc_raw=5000, soc_sf=-2, - mppt1=(850, 3512), mppt2=(420, 3300), names=None) -> dict[int, int]: + mppt1=(850, 3512), mppt2=(420, 3300), tracker_w=None, + names=None) -> dict[int, int]: """Registers of a Fronius float map, keyed by wire address. - cha / dis are (DCA, DCV, DCW) raw values for the storage inputs. + cha / dis are (DCA, DCV, DCW) raw values for the storage inputs; + tracker_w the raw DCW of each MPPT tracker (0 when not given). """ n = trackers + (2 if storage else 0) length = 8 + 20 * n @@ -68,6 +77,7 @@ def site(trackers: int = 2, storage: bool = True, *, dca_sf=-2, dcv_sf=-1, if storage: names += [f"StCha {trackers + 1}", f"StDisCha {trackers + 2}"] values = [mppt1, mppt2] + [(0, 0)] * (trackers - 2) + tracker_w = list(tracker_w or [0] * trackers) for k in range(1, n + 1): base = MPPT + 10 + 20 * (k - 1) regs[base] = k @@ -75,7 +85,8 @@ def site(trackers: int = 2, storage: bool = True, *, dca_sf=-2, dcv_sf=-1, regs[base + 1 + i] = word if k <= trackers: dca, dcv = values[k - 1] - regs[base + 9], regs[base + 10], regs[base + 11] = dca, dcv, 0 + regs[base + 9], regs[base + 10] = dca, dcv + regs[base + 11] = tracker_w[k - 1] else: regs[base + 9], regs[base + 10], regs[base + 11] = ( cha if k == trackers + 1 else dis) @@ -91,26 +102,39 @@ def site(trackers: int = 2, storage: bool = True, *, dca_sf=-2, dcv_sf=-1, def _poll(registers: dict, fail: tuple = (), polls: int = 1) -> dict[str, str]: - setup = "\n".join( - f"host._modbus_registers.holding[{addr}] = {val}" - for addr, val in registers.items()) + return _run([(registers, 0, polls)], fail) + + +def _run(phases: list, fail: tuple = ()) -> dict[str, str]: + """Each phase: (registers, ms to advance the clock first, polls).""" failing = "\n".join( f'host._modbus_read_fail_addresses[{addr}] = "Illegal Data Address"' for addr in fail) - script = f''' -package.path = "{HARNESS}/?.lua;" .. package.path -require("host_mock") -host.reset() + steps = [] + for registers, advance_ms, polls in phases: + setup = "\n".join( + f"host._modbus_registers.holding[{addr}] = {val}" + for addr, val in registers.items()) + steps.append(f''' +host._modbus_registers.holding = {{}} {setup} -{failing} -dofile("{DRIVER}") -driver_init({{}}) +host._millis_counter = host._millis_counter + {advance_ms} for _ = 1, {polls} do host._emitted = {{}} host._metrics = {{}} local ok, err = pcall(driver_poll) if not ok then print("POLL_ERROR " .. tostring(err)) os.exit(1) end end +''') + body = "\n".join(steps) + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() +{failing} +dofile("{DRIVER}") +driver_init({{}}) +{body} for _, der in ipairs({{"battery", "pv", "meter"}}) do local list = host._emitted[der] if list and #list > 0 then @@ -258,7 +282,7 @@ def test_float_values_keep_their_sign(): # 6000.0 W DC, 50.0 Hz, 12345678 Wh. Main's decoder joined the words into # one 32-bit number and compared it with 0x80000000, which is negative on # 32-bit Lua, so every float came out negative here. - regs = site() + regs = site(storage=False) regs.update({40107: 0x45BB, 40108: 0x8000, # DCW 6000.0 40093: 0x4248, 40094: 0x0000, # Hz 50.0 40101: 0x4B3C, 40102: 0x614E}) # WH 12345678.0 @@ -269,7 +293,7 @@ def test_float_values_keep_their_sign(): def test_float_nan_is_left_out_not_sent_as_zero(): - regs = site() + regs = site(storage=False) regs.update({40107: NAN[0], 40108: NAN[1], 40093: NAN[0], 40094: NAN[1], 40101: NAN[0], 40102: NAN[1]}) @@ -291,3 +315,88 @@ def test_rated_power_with_its_scale_factor(): regs.update({40134: 1000, 40135: 1}) # WRtg 1000 x 10^1 out = _poll(regs) assert float(out["pv.rated_w"]) == pytest.approx(10000) + + +DCW_113 = 40107 # model 113 DC power, float32 + + +def f32(value: float) -> tuple[int, int]: + word = struct.unpack(">I", struct.pack(">f", value))[0] + return word >> 16, word & 0xFFFF + + +def with_dcw(regs: dict, watts: float) -> dict: + regs[DCW_113], regs[DCW_113 + 1] = f32(watts) + return regs + + +def test_pv_with_storage_is_the_mppt_sum(): + # 2500 W of sun and a 3000 W discharge. Model 113's DC power may hold + # both; PV comes from the MPPT blocks before the battery blocks. + regs = with_dcw(site(tracker_w=(1500, 1000), dis=(5800, 518, 3000)), 5500.0) + out = _poll(regs) + assert float(out["pv.w"]) == pytest.approx(-2500) + assert float(out["battery.w"]) == pytest.approx(-3000) + + +def test_pv_with_storage_uses_the_scale_factor(): + regs = with_dcw(site(dcw_sf=-1, tracker_w=(15000, 10000)), 9999.0) + out = _poll(regs) + assert float(out["pv.w"]) == pytest.approx(-2500) + + +def test_verto_pv_sums_three_trackers(): + regs = with_dcw(site(trackers=3, tracker_w=(1000, 800, 600)), 9999.0) + out = _poll(regs) + assert float(out["pv.w"]) == pytest.approx(-2400) + + +def test_pv_without_storage_uses_model_113(): + regs = with_dcw(site(storage=False, tracker_w=(1500, 1000)), 4000.0) + out = _poll(regs) + assert float(out["pv.w"]) == pytest.approx(-4000) + + +def test_pv_tracker_not_implemented_leaves_pv_out(): + regs = with_dcw(site(tracker_w=(1500, 0xFFFF)), 4000.0) + out = _poll(regs) + assert "pv" not in out + + +def test_pv_left_out_with_storage_but_no_battery_blocks(): + names = ["MPPT 1", "MPPT 2", "MPPT 3", "MPPT 4"] + regs = with_dcw(site(tracker_w=(1500, 1000), names=names), 5500.0) + out = _poll(regs) + assert "pv" not in out + assert float(out["battery.soc"]) == pytest.approx(0.5) + + +def test_battery_fitted_later_is_found(): + # Without a battery model 160 has two blocks. Once one is fitted it has + # four and model 124 follows; the driver sees the new length and looks + # again. + before = with_dcw(site(storage=False), 4000.0) + after = with_dcw(site(tracker_w=(1500, 1000), cha=(1000, 520, 700)), 3200.0) + out = _run([(before, 0, 2), (after, 0, 2)]) + assert float(out["battery.w"]) == pytest.approx(700) + assert float(out["pv.w"]) == pytest.approx(-2500) + + +def _storage_model_appears(advance_ms: int) -> dict[str, str]: + # Model 160 already has its battery blocks, but model 124 is not there + # yet (the end block is), as before a battery is commissioned. + before = site(cha=(0, 520, 700)) + before[40353], before[40354] = 0xFFFF, 0 + after = site(cha=(0, 520, 700)) + return _run([(before, 0, 1), (after, advance_ms, 1)]) + + +def test_storage_model_is_looked_for_again_after_five_minutes(): + out = _storage_model_appears(5 * 60 * 1000) + assert float(out["battery.soc"]) == pytest.approx(0.5) + assert float(out["battery.w"]) == pytest.approx(700) + + +def test_storage_model_is_not_looked_for_on_every_poll(): + out = _storage_model_appears(60 * 1000) + assert "battery" not in out diff --git a/index.yaml b/index.yaml index 4a41934..762fd25 100644 --- a/index.yaml +++ b/index.yaml @@ -258,8 +258,8 @@ drivers: connectivity: local ders: [battery, meter, pv] control: false - size_bytes: 19443 - sha256: "fb0beed13d3b51675ed90437979f5d0e78775c6c1696341e70a9790711972d70" + size_bytes: 21704 + sha256: "63472dda17a0ed32c167dadb4ecf02f032bf4fb2e648df046a56de818124d16c" - name: "fronius_api" version: "1.0.2" tier: community diff --git a/manifests/fronius.yaml b/manifests/fronius.yaml index 153effb..7d2b3b4 100644 --- a/manifests/fronius.yaml +++ b/manifests/fronius.yaml @@ -59,12 +59,12 @@ upstream_docs: kind: register_map url_stability: stable min_host_version: "2.0.0" -size_bytes: 19443 +size_bytes: 21704 dkb_id: "fronius_symo_gen24" -sha256: "fb0beed13d3b51675ed90437979f5d0e78775c6c1696341e70a9790711972d70" +sha256: "63472dda17a0ed32c167dadb4ecf02f032bf4fb2e648df046a56de818124d16c" signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "Read battery power, voltage and SoC where the GEN24 and Verto storage maps put them, send no battery without storage, and decode floats correctly on 32-bit Lua." +changelog: "Read battery power, voltage and SoC where the GEN24 and Verto storage maps put them, take PV from the MPPT inputs when a battery is fitted, send no battery without storage, and decode floats correctly on 32-bit Lua."