diff --git a/CHANGELOG.md b/CHANGELOG.md index 94cbf23..d6ef35e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,41 @@ ## [Unreleased] +### sma 2.2.2: the inverter after a silent start, no made-up zeros + +Every read went through a guard that left a register alone until restart +after three misses. An inverter asleep at start-up, or held by another +Modbus client, used up every try while answering nothing, and the driver +then sent nothing until FTW restarted it. A register that did not answer +was sent as zero. + +A miss now counts only in a poll where another read answered, and a +register that misses three times on an inverter that does answer is asked +again every five minutes instead of never. A field whose register did not +answer is left out. PV and meter go out only when their power answered, +and the battery only when both its voltage and current did. SMA's NaN +still reads as 0, as before. The serial is read last, once the inverter +has answered in that poll. + +### sma_pv 1.1.3: the inverter after a silent start, no made-up zeros + +Every read went through a guard that left a register alone until restart +after three misses. An inverter asleep at start-up, or held by another +Modbus client, used up every try while answering nothing, and the driver +then sent nothing until FTW restarted it. It also settled on the first poll +whether a meter is paired and which lifetime register to read, so the same +start left it without a meter, and on the fallback lifetime register, for +the whole run. A register that did not answer was sent as zero. + +A miss now counts only in a poll where another read answered, and a +register that misses three times on an inverter that does answer is asked +again every five minutes instead of never. The meter is decided on every +poll from register 30885, and the lifetime counter falls back to 30529 only +while 30513 answers NaN or has been given up. The release ceiling is +sampled in the first poll where PV power answered. A field whose register +did not answer is left out, and so is a heatsink temperature that answers +NaN. The serial is read last, once the inverter has answered in that poll. + ### ferroamp 2.2.0: the EnergyHub limit, measured delivery, power per ESO The EnergyHub refuses a setpoint above its limit ("Max allowed power level is diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 5676964..50b72f2 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -134,10 +134,10 @@ Catalog source is not proof that a target can install or run a driver. | siemens_pac | 1.0.5 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | sigenergy | 1.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | sigenergy | 1.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| sma | 2.2.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| sma | 2.2.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| sma_pv | 1.1.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| sma_pv | 1.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| sma | 2.2.2 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| sma | 2.2.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| sma_pv | 1.1.3 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| sma_pv | 1.1.3 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | socomec | 1.0.4 | ftw-core | not_assessed | — | not_recorded | not_assessed | | socomec | 1.0.4 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | sofar | 2.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 775d19e..befab8f 100644 --- a/devices.yaml +++ b/devices.yaml @@ -1117,7 +1117,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1128,7 +1128,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma_pv" - version: "1.1.2" + version: "1.1.3" ders: [pv, meter] control: true firmware_versions: "" @@ -1139,7 +1139,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1150,7 +1150,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1161,7 +1161,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1172,7 +1172,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1183,7 +1183,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" @@ -1194,7 +1194,7 @@ manufacturers: protocols: - protocol: modbus driver: "sma" - version: "2.2.1" + version: "2.2.2" ders: [battery, meter, pv] control: false firmware_versions: "" diff --git a/drivers/lua/sma.lua b/drivers/lua/sma.lua index cfebfe7..955f56b 100644 --- a/drivers/lua/sma.lua +++ b/drivers/lua/sma.lua @@ -13,7 +13,7 @@ DRIVER = { id = "sma", name = "SMA hybrid inverter", manufacturer = "SMA", - version = "2.2.1", + version = "2.2.2", protocols = { "modbus" }, capabilities = { "meter", "pv", "battery" }, read_only = true, @@ -48,8 +48,7 @@ local function decode_u64_be(h1, h2, h3, h4) end -- SunSpec "not implemented" sentinel values. SMA registers that are not --- populated return these magic numbers; clamping them to 0 keeps --- telemetry sane. +-- populated return these magic numbers, which read as 0. local function u32_valid(v) -- 0xFFFFFFFF = U32 NaN return v ~= 4294967295 @@ -67,32 +66,78 @@ end -- -- The host counts every failed host.modbus_read against the poll whether or -- not this driver caught the error — "driver_poll: N of M modbus reads --- failed". So a register retried on every poll costs a failed poll on every --- poll, and the stale-telemetry watchdog takes the driver offline. The site --- then reports nothing at all, which is worse than reporting one field less. +-- failed". So a register retried on every poll costs a failed read on every +-- poll. Three tries absorb a transient blip; after that a register is asked +-- again every five minutes rather than never. Core keeps a poll fresh when +-- the inverter refuses one read and others answer, so one refused read in +-- sixty polls is cheap, and a register that answers again is back within +-- minutes instead of after a restart. -- --- Three attempts absorb a transient blip; after that we stop asking. A --- restart re-probes, so firmware that gains the register is picked up. +-- A miss counts only in a poll where another read answered. A poll in which +-- nothing answered is an inverter asleep, restarting or held by another +-- Modbus client, and says nothing about any one register: the driver keeps +-- asking and picks the inverter up on the first poll it answers. Core +-- reloads a driver with nothing left to read only if an earlier read had +-- succeeded, so giving up during such a start silenced the driver until +-- restart. local GIVE_UP_AFTER = 3 +local RETRY_EVERY_MS = 5 * 60 * 1000 local read_failures = {} +local last_try_ms = {} +-- Whether a read answered in this poll, and which reads missed. A miss is +-- counted only once the poll is over and only if something answered. +local poll_answered = false +local poll_missed = {} + +-- Every register asked for, not just the first. A short reply leaves the rest +-- nil, and arithmetic on nil ends the whole poll. +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 failures = read_failures[addr] or 0 + local now_ms = host.millis() + if failures >= GIVE_UP_AFTER + and now_ms - last_try_ms[addr] < RETRY_EVERY_MS then + return nil + end + last_try_ms[addr] = now_ms local ok, regs = pcall(host.modbus_read, addr, count, kind) - if ok and regs and regs[1] ~= nil then + if ok and complete(regs, count) then + poll_answered = true + if failures >= GIVE_UP_AFTER then + host.log("info", string.format( + "SMA: register %d answers again", addr)) + end 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( - "SMA: register %d did not answer %d times; leaving it alone " .. - "until restart", addr, GIVE_UP_AFTER)) - end + poll_missed[#poll_missed + 1] = addr return nil end +-- Count this poll's misses, if anything answered, and start the next poll. +local function settle_poll() + if poll_answered then + for _, addr in ipairs(poll_missed) do + local failures = (read_failures[addr] or 0) + 1 + read_failures[addr] = failures + if failures == GIVE_UP_AFTER then + host.log("info", string.format( + "SMA: register %d did not answer %d times; asking " .. + "again every %d minutes", addr, GIVE_UP_AFTER, + math.floor(RETRY_EVERY_MS / 60000))) + end + end + end + poll_answered, poll_missed = false, {} +end + -- What the battery can do now (docs/WRITING-A-DRIVER.md). A value outside -- these bounds is a sentinel or a decoding slip, not a reading, so it is -- left out rather than sent. @@ -120,16 +165,114 @@ end local sn_read = false ----------------------------------------------------------------------------- --- Lifecycle ----------------------------------------------------------------------------- +-- The I32 / U32 at regs[i], regs[i + 1]. SMA's NaN still reads as 0, as +-- before; a read that failed never gets here and leaves the field nil. +local function i32_at(regs, i) + local v = host.decode_i32_be(regs[i], regs[i + 1]) + if i32_valid(v) then return v end + return 0 +end +local function u32_at(regs, i) + local v = host.decode_u32_be(regs[i], regs[i + 1]) + if u32_valid(v) then return v end + return 0 +end -function driver_init(config) - host.set_make("SMA") +local function read_i32(addr) + local regs = probe_read(addr, 2, "input") + return regs and i32_at(regs, 1) or nil +end +local function read_u32(addr) + local regs = probe_read(addr, 2, "input") + return regs and u32_at(regs, 1) or nil +end +local function read_u64(addr) + local regs = probe_read(addr, 4, "input") + if regs == nil then return nil end + if not u64_valid(regs[1], regs[2], regs[3], regs[4]) then return 0 end + return decode_u64_be(regs[1], regs[2], regs[3], regs[4]) +end + +local function times(v, factor) + if v == nil then return nil end + return v * factor +end + +local function metric(name, value) + if value ~= nil then host.emit_metric(name, value) end +end + +-- Meter (SMA Energy Meter / Sunny Home Manager), given the read of total +-- power at 30885-30886 (I32 BE, watts; + = import, - = export). Sent only +-- when that read answered; any other field that did not answer is left out. +local function poll_meter(mw_regs) + local meter_w = mw_regs and i32_at(mw_regs, 1) or nil - -- SunSpec common model serial number: 30057-30058 (U32 BE). - -- Best-effort; older SMA firmware can report 0 here — we fall back - -- to make:endpoint identity in that case. + -- Per-phase meter power: 30887-30892, I32 BE pairs, watts (signed) + local l1_w, l2_w, l3_w = nil, nil, nil + local mpw_regs = probe_read(30887, 6, "input") + if mpw_regs then + l1_w, l2_w, l3_w = i32_at(mpw_regs, 1), i32_at(mpw_regs, 3), i32_at(mpw_regs, 5) + end + + -- Grid frequency: 30901-30902, U32 BE × 0.01 Hz + local hz = times(read_u32(30901), 0.01) + + -- Per-phase voltage: 30903-30908, U32 BE × 0.01 V pairs + local l1_v, l2_v, l3_v = nil, nil, nil + local lv_regs = probe_read(30903, 6, "input") + if lv_regs then + l1_v = u32_at(lv_regs, 1) * 0.01 + l2_v = u32_at(lv_regs, 3) * 0.01 + l3_v = u32_at(lv_regs, 5) * 0.01 + end + + -- Per-phase current: 30909-30914, U32 BE × 0.001 A pairs + local l1_a, l2_a, l3_a = nil, nil, nil + local la_regs = probe_read(30909, 6, "input") + if la_regs then + l1_a = u32_at(la_regs, 1) * 0.001 + l2_a = u32_at(la_regs, 3) * 0.001 + l3_a = u32_at(la_regs, 5) * 0.001 + end + + -- Import / export energy: 30581-30582 / 30583-30584, U32 BE, Wh + local import_wh = read_u32(30581) + local export_wh = read_u32(30583) + + if meter_w ~= nil then + host.emit("meter", { + w = meter_w, + l1_w = l1_w, + l2_w = l2_w, + l3_w = l3_w, + l1_v = l1_v, + l2_v = l2_v, + l3_v = l3_v, + l1_a = l1_a, + l2_a = l2_a, + l3_a = l3_a, + hz = hz, + import_wh = import_wh, + export_wh = export_wh, + }) + end + metric("meter_l1_w", l1_w) + metric("meter_l2_w", l2_w) + metric("meter_l3_w", l3_w) + metric("meter_l1_v", l1_v) + metric("meter_l2_v", l2_v) + metric("meter_l3_v", l3_v) + metric("meter_l1_a", l1_a) + metric("meter_l2_a", l2_a) + metric("meter_l3_a", l3_a) + metric("grid_hz", hz) +end + +-- SunSpec common model serial number: 30057-30058 (U32 BE). Best-effort; +-- older SMA firmware can report 0 here — we fall back to make:endpoint +-- identity in that case. +local function read_serial() local sn_regs = probe_read(30057, 2, "input") if sn_regs then local sn = host.decode_u32_be(sn_regs[1], sn_regs[2]) @@ -140,271 +283,129 @@ function driver_init(config) end end -function driver_poll() - -- Opportunistically retry SN if init couldn't read it (e.g. the - -- inverter was still booting). - if not sn_read then - local sn_regs = probe_read(30057, 2, "input") - if sn_regs then - local sn = host.decode_u32_be(sn_regs[1], sn_regs[2]) - if u32_valid(sn) and sn > 0 then - host.set_sn(tostring(sn)) - sn_read = true - end - end - end +---------------------------------------------------------------------------- +-- Lifecycle +---------------------------------------------------------------------------- +function driver_init(config) + host.set_make("SMA") + read_serial() +end + +-- A field whose register did not answer is left out, never sent as zero. +-- PV, battery and meter go out only when their power answered. +local function poll_once() ------------------------------------------------------------------ PV -- -- PV power: 30775-30776, I32 BE, watts - local pvw_regs = probe_read(30775, 2, "input") - local pv_w = 0 - if pvw_regs then - local v = host.decode_i32_be(pvw_regs[1], pvw_regs[2]) - if i32_valid(v) then pv_w = v end - end + local pv_w = read_i32(30775) - -- MPPT1 current: 30769-30770, I32 BE × 0.001 A - local m1a_regs = probe_read(30769, 2, "input") - local mppt1_a = 0 - if m1a_regs then - local v = host.decode_i32_be(m1a_regs[1], m1a_regs[2]) - if i32_valid(v) then mppt1_a = v * 0.001 end - end - - -- MPPT1 voltage: 30771-30772, I32 BE × 0.01 V - local m1v_regs = probe_read(30771, 2, "input") - local mppt1_v = 0 - if m1v_regs then - local v = host.decode_i32_be(m1v_regs[1], m1v_regs[2]) - if i32_valid(v) then mppt1_v = v * 0.01 end - end + -- MPPT1 current / voltage: 30769-30770 × 0.001 A, 30771-30772 × 0.01 V + local mppt1_a = times(read_i32(30769), 0.001) + local mppt1_v = times(read_i32(30771), 0.01) - -- MPPT2 current: 30957-30958, I32 BE × 0.001 A - local m2a_regs = probe_read(30957, 2, "input") - local mppt2_a = 0 - if m2a_regs then - local v = host.decode_i32_be(m2a_regs[1], m2a_regs[2]) - if i32_valid(v) then mppt2_a = v * 0.001 end - end - - -- MPPT2 voltage: 30959-30960, I32 BE × 0.01 V - local m2v_regs = probe_read(30959, 2, "input") - local mppt2_v = 0 - if m2v_regs then - local v = host.decode_i32_be(m2v_regs[1], m2v_regs[2]) - if i32_valid(v) then mppt2_v = v * 0.01 end - end + -- MPPT2 current / voltage: 30957-30958 × 0.001 A, 30959-30960 × 0.01 V + local mppt2_a = times(read_i32(30957), 0.001) + local mppt2_v = times(read_i32(30959), 0.01) -- PV lifetime generation: 30513-30516, U64 BE, Wh - local pvgen_regs = probe_read(30513, 4, "input") - local pv_gen_wh = 0 - if pvgen_regs and u64_valid(pvgen_regs[1], pvgen_regs[2], pvgen_regs[3], pvgen_regs[4]) then - pv_gen_wh = decode_u64_be(pvgen_regs[1], pvgen_regs[2], pvgen_regs[3], pvgen_regs[4]) - end + local pv_gen_wh = read_u64(30513) -- Inverter internal temperature: 30953-30954, S32, TEMP (× 0.1). -- Left out when the read fails or answers NaN. local itemp_regs = probe_read(30953, 2, "input") local inv_temp = nil - if itemp_regs and itemp_regs[2] ~= nil then + if itemp_regs then local v = host.decode_i32_be(itemp_regs[1], itemp_regs[2]) if i32_valid(v) then inv_temp = temp_c_from_tenths(v) end end -- Rated power: 31085-31086, U32 BE, watts - local rated_regs = probe_read(31085, 2, "input") - local rated_w = 0 - if rated_regs then - local v = host.decode_u32_be(rated_regs[1], rated_regs[2]) - if u32_valid(v) then rated_w = v end - end - - host.emit("pv", { - w = -pv_w, -- site convention: generation is negative - mppt1_v = mppt1_v, - mppt1_a = mppt1_a, - mppt2_v = mppt2_v, - mppt2_a = mppt2_a, - lifetime_wh = pv_gen_wh, - temp_c = inv_temp, - rated_w = rated_w, - }) - 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 inv_temp ~= nil then - host.emit_metric("inverter_temp_c", inv_temp) + local rated_w = read_u32(31085) + + if pv_w ~= nil then + host.emit("pv", { + w = -pv_w, -- site convention: generation is negative + mppt1_v = mppt1_v, + mppt1_a = mppt1_a, + mppt2_v = mppt2_v, + mppt2_a = mppt2_a, + lifetime_wh = pv_gen_wh, + temp_c = inv_temp, + rated_w = rated_w, + }) end + metric("pv_mppt1_v", mppt1_v) + metric("pv_mppt1_a", mppt1_a) + metric("pv_mppt2_v", mppt2_v) + metric("pv_mppt2_a", mppt2_a) + metric("inverter_temp_c", inv_temp) ------------------------------------------------------------- Battery -- -- Battery current: 30843-30844, I32 BE × 0.001 A (+ = charging) - local ba_regs = probe_read(30843, 2, "input") - local bat_a = 0 - if ba_regs then - local v = host.decode_i32_be(ba_regs[1], ba_regs[2]) - if i32_valid(v) then bat_a = v * 0.001 end - end + local bat_a = times(read_i32(30843), 0.001) -- Battery SoC: 30845-30846, U32 BE, percent → fraction - local bsoc_regs = probe_read(30845, 2, "input") - local bat_soc = 0 - if bsoc_regs then - local v = host.decode_u32_be(bsoc_regs[1], bsoc_regs[2]) - if u32_valid(v) then bat_soc = v / 100 end - end + local soc_pct = read_u32(30845) + local bat_soc = soc_pct and soc_pct / 100 or nil -- Battery temperature: 30849-30850, S32, TEMP (× 0.1). Left out when the -- read fails or answers NaN: 0 °C looks like a cold battery. local btemp_regs = probe_read(30849, 2, "input") local bat_temp = nil - if btemp_regs and btemp_regs[2] ~= nil then + if btemp_regs then local v = host.decode_i32_be(btemp_regs[1], btemp_regs[2]) if i32_valid(v) then bat_temp = temp_c_from_tenths(v) end end -- Battery voltage: 30851-30852, U32 BE × 0.01 V - local bv_regs = probe_read(30851, 2, "input") - local bat_v = 0 - if bv_regs then - local v = host.decode_u32_be(bv_regs[1], bv_regs[2]) - if u32_valid(v) then bat_v = v * 0.01 end - end + local bat_v = times(read_u32(30851), 0.01) -- Battery power: V*A. Site convention matches native here because - -- SMA reports signed current (+ = charging = into battery). - local bat_w = bat_v * bat_a - - -- Battery charge energy: 31397-31400, U64 BE, Wh - local bchg_regs = probe_read(31397, 4, "input") - local bat_charge_wh = 0 - if bchg_regs and u64_valid(bchg_regs[1], bchg_regs[2], bchg_regs[3], bchg_regs[4]) then - bat_charge_wh = decode_u64_be(bchg_regs[1], bchg_regs[2], bchg_regs[3], bchg_regs[4]) - end - - -- Battery discharge energy: 31401-31404, U64 BE, Wh - local bdis_regs = probe_read(31401, 4, "input") - local bat_discharge_wh = 0 - if bdis_regs and u64_valid(bdis_regs[1], bdis_regs[2], bdis_regs[3], bdis_regs[4]) then - bat_discharge_wh = decode_u64_be(bdis_regs[1], bdis_regs[2], bdis_regs[3], bdis_regs[4]) - end - - host.emit("battery", { - w = bat_w, - v = bat_v, - a = bat_a, - soc = bat_soc, - temp_c = bat_temp, - charge_wh = bat_charge_wh, - discharge_wh = bat_discharge_wh, - }) - host.emit_metric("battery_dc_v", bat_v) - host.emit_metric("battery_dc_a", bat_a) - if bat_temp ~= nil then - host.emit_metric("battery_temp_c", bat_temp) + -- SMA reports signed current (+ = charging = into battery). Without + -- both there is no battery power, and no battery reading. + local bat_w = nil + if bat_v ~= nil and bat_a ~= nil then bat_w = bat_v * bat_a end + + -- Battery charge / discharge energy: 31397-31400 / 31401-31404, U64 BE, Wh + local bat_charge_wh = read_u64(31397) + local bat_discharge_wh = read_u64(31401) + + if bat_w ~= nil then + host.emit("battery", { + w = bat_w, + v = bat_v, + a = bat_a, + soc = bat_soc, + temp_c = bat_temp, + charge_wh = bat_charge_wh, + discharge_wh = bat_discharge_wh, + }) end + metric("battery_dc_v", bat_v) + metric("battery_dc_a", bat_a) + metric("battery_temp_c", bat_temp) --------------------------------------------------------------- Meter -- - -- Meter total power: 30885-30886, I32 BE, watts (signed: + = import, - = export) - local mw_regs = probe_read(30885, 2, "input") - local meter_w = 0 - if mw_regs then - local v = host.decode_i32_be(mw_regs[1], mw_regs[2]) - if i32_valid(v) then meter_w = v end - end + poll_meter(probe_read(30885, 2, "input")) - -- Per-phase meter power: 30887-30892, I32 BE pairs, watts (signed) - local mpw_regs = probe_read(30887, 6, "input") - local l1_w, l2_w, l3_w = 0, 0, 0 - if mpw_regs then - local v1 = host.decode_i32_be(mpw_regs[1], mpw_regs[2]) - local v2 = host.decode_i32_be(mpw_regs[3], mpw_regs[4]) - local v3 = host.decode_i32_be(mpw_regs[5], mpw_regs[6]) - if i32_valid(v1) then l1_w = v1 end - if i32_valid(v2) then l2_w = v2 end - if i32_valid(v3) then l3_w = v3 end - end - - -- Grid frequency: 30901-30902, U32 BE × 0.01 Hz - local hz_regs = probe_read(30901, 2, "input") - local hz = 0 - if hz_regs then - local v = host.decode_u32_be(hz_regs[1], hz_regs[2]) - if u32_valid(v) then hz = v * 0.01 end - end - - -- Per-phase voltage: 30903-30908, U32 BE × 0.01 V pairs - local lv_regs = probe_read(30903, 6, "input") - local l1_v, l2_v, l3_v = 0, 0, 0 - if lv_regs then - local v1 = host.decode_u32_be(lv_regs[1], lv_regs[2]) - local v2 = host.decode_u32_be(lv_regs[3], lv_regs[4]) - local v3 = host.decode_u32_be(lv_regs[5], lv_regs[6]) - if u32_valid(v1) then l1_v = v1 * 0.01 end - if u32_valid(v2) then l2_v = v2 * 0.01 end - if u32_valid(v3) then l3_v = v3 * 0.01 end - end - - -- Per-phase current: 30909-30914, U32 BE × 0.001 A pairs - local la_regs = probe_read(30909, 6, "input") - local l1_a, l2_a, l3_a = 0, 0, 0 - if la_regs then - local v1 = host.decode_u32_be(la_regs[1], la_regs[2]) - local v2 = host.decode_u32_be(la_regs[3], la_regs[4]) - local v3 = host.decode_u32_be(la_regs[5], la_regs[6]) - if u32_valid(v1) then l1_a = v1 * 0.001 end - if u32_valid(v2) then l2_a = v2 * 0.001 end - if u32_valid(v3) then l3_a = v3 * 0.001 end - end - - -- Import energy: 30581-30582, U32 BE, Wh - local imp_regs = probe_read(30581, 2, "input") - local import_wh = 0 - if imp_regs then - local v = host.decode_u32_be(imp_regs[1], imp_regs[2]) - if u32_valid(v) then import_wh = v end - end - - -- Export energy: 30583-30584, U32 BE, Wh - local exp_regs = probe_read(30583, 2, "input") - local export_wh = 0 - if exp_regs then - local v = host.decode_u32_be(exp_regs[1], exp_regs[2]) - if u32_valid(v) then export_wh = v end - end - - host.emit("meter", { - w = meter_w, - l1_w = l1_w, - l2_w = l2_w, - l3_w = l3_w, - l1_v = l1_v, - l2_v = l2_v, - l3_v = l3_v, - l1_a = l1_a, - l2_a = l2_a, - l3_a = l3_a, - hz = hz, - import_wh = import_wh, - export_wh = export_wh, - }) - host.emit_metric("meter_l1_w", l1_w) - host.emit_metric("meter_l2_w", l2_w) - host.emit_metric("meter_l3_w", l3_w) - host.emit_metric("meter_l1_v", l1_v) - host.emit_metric("meter_l2_v", l2_v) - host.emit_metric("meter_l3_v", l3_v) - host.emit_metric("meter_l1_a", l1_a) - host.emit_metric("meter_l2_a", l2_a) - host.emit_metric("meter_l3_a", l3_a) - host.emit_metric("grid_hz", hz) + -- The serial last, and only once the inverter has answered this poll: + -- a read that times out makes the host skip the rest of the poll. + if not sn_read and poll_answered then read_serial() end return 5000 end +function driver_poll() + -- Reads made by a command since the last poll do not count. + poll_answered, poll_missed = false, {} + local interval = poll_once() + settle_poll() + return interval +end + ---------------------------------------------------------------------------- -- Control (read-only — SMA control is not implemented) ---------------------------------------------------------------------------- @@ -422,5 +423,8 @@ function driver_default_mode() end function driver_cleanup() - -- Read-only driver: nothing to clean up. + -- Read-only driver: nothing to revert on the device. + sn_read = false + read_failures, last_try_ms = {}, {} + poll_answered, poll_missed = false, {} end diff --git a/drivers/lua/sma_pv.lua b/drivers/lua/sma_pv.lua index 274e0f8..1d75f16 100644 --- a/drivers/lua/sma_pv.lua +++ b/drivers/lua/sma_pv.lua @@ -14,7 +14,7 @@ DRIVER = { id = "sma_pv", name = "SMA PV inverter (non-hybrid)", manufacturer = "SMA", - version = "1.1.2", + version = "1.1.3", protocols = { "modbus" }, capabilities = { "pv", "meter", "pv_curtail" }, description = "SMA Sunny Tripower commercial string inverters (STP 50-40 / 50-41 / X-class) via Modbus TCP, with active-power curtailment over Modbus holding register 40915.", @@ -48,8 +48,7 @@ local function decode_u64_be(h1, h2, h3, h4) end -- SunSpec "not implemented" sentinel values. SMA registers that are not --- populated return these magic numbers; clamping them to 0 keeps telemetry --- sane. +-- populated return these magic numbers, which read as 0. local function u32_valid(v) return v ~= 4294967295 -- 0xFFFFFFFF = U32 NaN end @@ -71,34 +70,82 @@ local function regs_all_ffff(regs, n) return true end --- A register this inverter does not answer must not be read forever. The host --- counts every failed modbus_read against the poll whether or not Lua caught --- it, so one absent optional register -- a second MPPT on a single-string --- model, say -- holds the driver at "1 of N reads failed" every five seconds --- and the stale-telemetry watchdog takes the site offline while the driver is --- still emitting good PV data. Ask three times, since a single miss can just --- be a slow link, then leave the register alone. A restart re-probes, so a --- firmware update that adds the register is picked up. +-- Registers this device has stopped answering. +-- +-- The host counts every failed host.modbus_read against the poll whether or +-- not this driver caught the error — "driver_poll: N of M modbus reads +-- failed". So a register retried on every poll costs a failed read on every +-- poll. Three tries absorb a transient blip; after that a register is asked +-- again every five minutes rather than never. Core keeps a poll fresh when +-- the inverter refuses one read and others answer, so one refused read in +-- sixty polls is cheap, and a register that answers again is back within +-- minutes instead of after a restart. +-- +-- A miss counts only in a poll where another read answered. A poll in which +-- nothing answered is an inverter asleep, restarting or held by another +-- Modbus client, and says nothing about any one register: the driver keeps +-- asking and picks the inverter up on the first poll it answers. Core +-- reloads a driver with nothing left to read only if an earlier read had +-- succeeded, so giving up during such a start silenced the driver until +-- restart. local GIVE_UP_AFTER = 3 +local RETRY_EVERY_MS = 5 * 60 * 1000 local read_failures = {} +local last_try_ms = {} +-- Whether a read answered in this poll, and which reads missed. A miss is +-- counted only once the poll is over and only if something answered. +local poll_answered = false +local poll_missed = {} + +-- Every register asked for, not just the first. A short reply leaves the rest +-- nil, and arithmetic on nil ends the whole poll. +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 failures = read_failures[addr] or 0 + local now_ms = host.millis() + if failures >= GIVE_UP_AFTER + and now_ms - last_try_ms[addr] < RETRY_EVERY_MS then + return nil + end + last_try_ms[addr] = now_ms local ok, regs = pcall(host.modbus_read, addr, count, kind) - if ok and regs and regs[1] ~= nil then + if ok and complete(regs, count) then + poll_answered = true + if failures >= GIVE_UP_AFTER then + host.log("info", string.format( + "SMA_PV: register %d answers again", addr)) + end 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( - "SMA_PV: register %d did not answer %d times; leaving it alone " .. - "until restart", addr, GIVE_UP_AFTER)) - end + poll_missed[#poll_missed + 1] = addr return nil end +-- Count this poll's misses, if anything answered, and start the next poll. +local function settle_poll() + if poll_answered then + for _, addr in ipairs(poll_missed) do + local failures = (read_failures[addr] or 0) + 1 + read_failures[addr] = failures + if failures == GIVE_UP_AFTER then + host.log("info", string.format( + "SMA_PV: register %d did not answer %d times; asking " .. + "again every %d minutes", addr, GIVE_UP_AFTER, + math.floor(RETRY_EVERY_MS / 60000))) + end + end + end + poll_answered, poll_missed = false, {} +end + ---------------------------------------------------------------------------- -- Control surface ---------------------------------------------------------------------------- @@ -115,72 +162,132 @@ local REG_W_SETPOINT = 40915 ---------------------------------------------------------------------------- -- Per-driver state ---------------------------------------------------------------------------- --- Resolved on the first poll cycle by probing optional sections. We pay this --- discovery cost exactly once per app restart rather than failing-and-falling- --- back on every poll. --- -- sn_read — true once the SunSpec serial has been latched --- has_meter — does this inverter expose a paired SMA Energy Meter? --- lifetime_reg — 30513 (U64) on CORE1+; 30529 (U32) on the rare older --- firmware that returns exception 0x02 at 30513 +-- release_probed — true once release_w has been sampled -- release_w — value to write to REG_W_SETPOINT when releasing a -- curtailment. Sampled from the inverter's current --- setpoint at probe time (i.e. its natural ceiling). +-- setpoint in the first poll where PV power answered +-- (i.e. its natural ceiling). -- curtail_active — true while a curtailment is in effect. Used by the -- watchdog path to know whether to issue a release. +-- +-- Whether a meter is paired and which lifetime register the firmware has +-- are decided on every poll from what the inverter answers. Up to 1.1.2 both +-- were settled once, on the first poll: an inverter that did not answer +-- then had no meter and the fallback lifetime register for the whole run. local sn_read = false -local has_meter = nil -local lifetime_reg = nil +local release_probed = false local release_w = 50000 local curtail_active = false --- Probe the inverter once to figure out which optional sections it populates. --- Called from driver_poll on the first cycle. --- --- The three reads below stay on a plain pcall rather than probe_read: each --- runs once per restart and its answer is cached, so none of them can cost a --- repeated failed read. Counting them would spend attempts on registers the --- poll has not asked for yet. The serial read is the other way round -- the --- poll retries it until it answers -- so that one is bounded. -local function probe_capabilities() - -- Meter: total power @ 30885 (I32). NaN here means no SMA Energy Meter / - -- Sunny Home Manager is paired with the inverter — most commercial string - -- inverters don't have one. - local ok, regs = pcall(host.modbus_read, 30885, 2, "input") - has_meter = ok and regs ~= nil and not regs_all_ffff(regs, 2) - - -- PV lifetime generation. Prefer U64 at 30513; fall back to U32 at 30529 - -- for older firmware that raises exception 0x02 there. - local ok2, regs2 = pcall(host.modbus_read, 30513, 4, "input") - if ok2 and regs2 and u64_valid(regs2[1], regs2[2], regs2[3], regs2[4]) then - lifetime_reg = 30513 - else - lifetime_reg = 30529 - end +-- The I32 / U32 at regs[i], regs[i + 1]. SMA's NaN still reads as 0, as +-- before; a read that failed never gets here and leaves the field nil. +local function i32_at(regs, i) + local v = host.decode_i32_be(regs[i], regs[i + 1]) + if i32_valid(v) then return v end + return 0 +end +local function u32_at(regs, i) + local v = host.decode_u32_be(regs[i], regs[i + 1]) + if u32_valid(v) then return v end + return 0 +end - -- Curtailment release ceiling. Whatever 40915 reads right now is the - -- inverter's natural cap — and that's what we restore on curtail_disable. - local ok3, sp_regs = pcall(host.modbus_read, REG_W_SETPOINT, 2, "holding") - if ok3 and sp_regs then - local v = host.decode_u32_be(sp_regs[1], sp_regs[2]) - if u32_valid(v) and v >= 1000 then release_w = v end - end +local function read_i32(addr) + local regs = probe_read(addr, 2, "input") + return regs and i32_at(regs, 1) or nil +end +local function read_u32(addr) + local regs = probe_read(addr, 2, "input") + return regs and u32_at(regs, 1) or nil +end +local function read_u64(addr) + local regs = probe_read(addr, 4, "input") + if regs == nil then return nil end + if not u64_valid(regs[1], regs[2], regs[3], regs[4]) then return 0 end + return decode_u64_be(regs[1], regs[2], regs[3], regs[4]) +end - host.log("info", string.format( - "SMA_PV capabilities resolved: meter=%s lifetime_reg=%d release_w=%d", - tostring(has_meter), lifetime_reg, release_w)) +local function times(v, factor) + if v == nil then return nil end + return v * factor end ----------------------------------------------------------------------------- --- Lifecycle ----------------------------------------------------------------------------- +local function metric(name, value) + if value ~= nil then host.emit_metric(name, value) end +end -function driver_init(config) - host.set_make("SMA") +-- Meter (SMA Energy Meter / Sunny Home Manager), given the read of total +-- power at 30885-30886 (I32 BE, watts; + = import, - = export). Sent only +-- when that read answered; any other field that did not answer is left out. +local function poll_meter(mw_regs) + local meter_w = mw_regs and i32_at(mw_regs, 1) or nil + + -- Per-phase meter power: 30887-30892, I32 BE pairs, watts (signed) + local l1_w, l2_w, l3_w = nil, nil, nil + local mpw_regs = probe_read(30887, 6, "input") + if mpw_regs then + l1_w, l2_w, l3_w = i32_at(mpw_regs, 1), i32_at(mpw_regs, 3), i32_at(mpw_regs, 5) + end + + -- Grid frequency: 30901-30902, U32 BE × 0.01 Hz + local hz = times(read_u32(30901), 0.01) + + -- Per-phase voltage: 30903-30908, U32 BE × 0.01 V pairs + local l1_v, l2_v, l3_v = nil, nil, nil + local lv_regs = probe_read(30903, 6, "input") + if lv_regs then + l1_v = u32_at(lv_regs, 1) * 0.01 + l2_v = u32_at(lv_regs, 3) * 0.01 + l3_v = u32_at(lv_regs, 5) * 0.01 + end - -- SunSpec common model serial number: 30057-30058 (U32 BE). - -- Best-effort; older SMA firmware can report 0 here — we fall back - -- to make:endpoint identity in that case. + -- Per-phase current: 30909-30914, U32 BE × 0.001 A pairs + local l1_a, l2_a, l3_a = nil, nil, nil + local la_regs = probe_read(30909, 6, "input") + if la_regs then + l1_a = u32_at(la_regs, 1) * 0.001 + l2_a = u32_at(la_regs, 3) * 0.001 + l3_a = u32_at(la_regs, 5) * 0.001 + end + + -- Import / export energy: 30581-30582 / 30583-30584, U32 BE, Wh + local import_wh = read_u32(30581) + local export_wh = read_u32(30583) + + if meter_w ~= nil then + host.emit("meter", { + w = meter_w, + l1_w = l1_w, + l2_w = l2_w, + l3_w = l3_w, + l1_v = l1_v, + l2_v = l2_v, + l3_v = l3_v, + l1_a = l1_a, + l2_a = l2_a, + l3_a = l3_a, + hz = hz, + import_wh = import_wh, + export_wh = export_wh, + }) + end + metric("meter_l1_w", l1_w) + metric("meter_l2_w", l2_w) + metric("meter_l3_w", l3_w) + metric("meter_l1_v", l1_v) + metric("meter_l2_v", l2_v) + metric("meter_l3_v", l3_v) + metric("meter_l1_a", l1_a) + metric("meter_l2_a", l2_a) + metric("meter_l3_a", l3_a) + metric("grid_hz", hz) +end + +-- SunSpec common model serial number: 30057-30058 (U32 BE). Best-effort; +-- older SMA firmware can report 0 here — we fall back to make:endpoint +-- identity in that case. +local function read_serial() local sn_regs = probe_read(30057, 2, "input") if sn_regs then local sn = host.decode_u32_be(sn_regs[1], sn_regs[2]) @@ -191,234 +298,120 @@ function driver_init(config) end end -function driver_poll() - -- Opportunistically retry SN if init couldn't read it (e.g. the - -- inverter was still booting), but only a bounded number of times -- - -- an inverter that never reports a serial must not cost a failed read - -- on every poll for the rest of its life. - if not sn_read then - local sn_regs = probe_read(30057, 2, "input") - if sn_regs then - local sn = host.decode_u32_be(sn_regs[1], sn_regs[2]) - if u32_valid(sn) and sn > 0 then - host.set_sn(tostring(sn)) - sn_read = true - end - end +-- Sample the curtailment release ceiling once. Whatever 40915 reads right +-- now is the inverter's natural cap — and that's what we restore on +-- curtail_disable. A plain pcall: it runs once per restart, from the first +-- poll where PV power answered. +local function probe_release() + release_probed = true + local ok, sp_regs = pcall(host.modbus_read, REG_W_SETPOINT, 2, "holding") + if ok and sp_regs and sp_regs[2] ~= nil then + local v = host.decode_u32_be(sp_regs[1], sp_regs[2]) + if u32_valid(v) and v >= 1000 then release_w = v end end + host.log("info", string.format("SMA_PV release ceiling: %d W", release_w)) +end - -- Resolve which optional sections this inverter populates. One-shot, - -- cached for the lifetime of this driver instance. - if has_meter == nil then probe_capabilities() end +---------------------------------------------------------------------------- +-- Lifecycle +---------------------------------------------------------------------------- +function driver_init(config) + host.set_make("SMA") + read_serial() +end + +-- A field whose register did not answer is left out, never sent as zero. +-- PV and meter go out only when their power answered. +local function poll_once() ------------------------------------------------------------------ PV -- -- PV power: 30775-30776, I32 BE, watts - local pvw_regs = probe_read(30775, 2, "input") - local pv_w = 0 - if pvw_regs then - local v = host.decode_i32_be(pvw_regs[1], pvw_regs[2]) - if i32_valid(v) then pv_w = v end - end - - -- MPPT1 current: 30769-30770, I32 BE × 0.001 A - local m1a_regs = probe_read(30769, 2, "input") - local mppt1_a = 0 - if m1a_regs then - local v = host.decode_i32_be(m1a_regs[1], m1a_regs[2]) - if i32_valid(v) then mppt1_a = v * 0.001 end + local pv_w = read_i32(30775) + + if not release_probed and pv_w ~= nil then probe_release() end + + -- MPPT1 current / voltage: 30769-30770 × 0.001 A, 30771-30772 × 0.01 V + local mppt1_a = times(read_i32(30769), 0.001) + local mppt1_v = times(read_i32(30771), 0.01) + + -- MPPT2 current / voltage: 30957-30958 × 0.001 A, 30959-30960 × 0.01 V + local mppt2_a = times(read_i32(30957), 0.001) + local mppt2_v = times(read_i32(30959), 0.01) + + -- PV lifetime generation: U64 at 30513, or U32 at 30529 on the rare + -- older firmware that answers NaN at 30513 or refuses it (exception + -- 0x02). A refused 30513 is given up after three misses and asked again + -- every five minutes, like any register. + local pv_gen_wh = nil + local gen_regs = probe_read(30513, 4, "input") + if gen_regs and u64_valid(gen_regs[1], gen_regs[2], gen_regs[3], gen_regs[4]) then + pv_gen_wh = decode_u64_be(gen_regs[1], gen_regs[2], gen_regs[3], gen_regs[4]) + elseif gen_regs or (read_failures[30513] or 0) >= GIVE_UP_AFTER then + pv_gen_wh = read_u32(30529) end - -- MPPT1 voltage: 30771-30772, I32 BE × 0.01 V - local m1v_regs = probe_read(30771, 2, "input") - local mppt1_v = 0 - if m1v_regs then - local v = host.decode_i32_be(m1v_regs[1], m1v_regs[2]) - if i32_valid(v) then mppt1_v = v * 0.01 end - end - - -- MPPT2 current: 30957-30958, I32 BE × 0.001 A - local m2a_regs = probe_read(30957, 2, "input") - local mppt2_a = 0 - if m2a_regs then - local v = host.decode_i32_be(m2a_regs[1], m2a_regs[2]) - if i32_valid(v) then mppt2_a = v * 0.001 end - end - - -- MPPT2 voltage: 30959-30960, I32 BE × 0.01 V - local m2v_regs = probe_read(30959, 2, "input") - local mppt2_v = 0 - if m2v_regs then - local v = host.decode_i32_be(m2v_regs[1], m2v_regs[2]) - if i32_valid(v) then mppt2_v = v * 0.01 end - end - - -- PV lifetime generation. Register location resolved once by - -- probe_capabilities and cached — no per-poll exception handling needed. - local pv_gen_wh = 0 - if lifetime_reg == 30513 then - local pvgen_regs = probe_read(30513, 4, "input") - if pvgen_regs and u64_valid(pvgen_regs[1], pvgen_regs[2], pvgen_regs[3], pvgen_regs[4]) then - pv_gen_wh = decode_u64_be(pvgen_regs[1], pvgen_regs[2], pvgen_regs[3], pvgen_regs[4]) - end - else - local pvgen_regs = probe_read(30529, 2, "input") - if pvgen_regs then - local v = host.decode_u32_be(pvgen_regs[1], pvgen_regs[2]) - if u32_valid(v) then pv_gen_wh = v end - end - end - - -- Inverter heatsink temp: 30953-30954, I32 BE × 0.1 C + -- Inverter heatsink temp: 30953-30954, I32 BE × 0.1 C. Left out when the + -- read fails or answers NaN. local itemp_regs = probe_read(30953, 2, "input") - local inv_temp = 0 + local inv_temp = nil if itemp_regs then local v = host.decode_i32_be(itemp_regs[1], itemp_regs[2]) if i32_valid(v) then inv_temp = v * 0.1 end end -- Rated power: 31085-31086, U32 BE, watts. Note: CORE2 firmware can - -- report 0 here — release_w from probe_capabilities is more reliable. - local rated_regs = probe_read(31085, 2, "input") - local rated_w = 0 - if rated_regs then - local v = host.decode_u32_be(rated_regs[1], rated_regs[2]) - if u32_valid(v) then rated_w = v end - end + -- report 0 here — release_w from probe_release is more reliable. + local rated_w = read_u32(31085) -- Current event number (manufacturer). Useful diagnostic — non-zero -- values indicate the inverter has an active event/warning. The actual -- event description isn't exposed over Modbus on STP X / CORE2. - local evt_regs = probe_read(30247, 2, "input") - local event_no = 0 - if evt_regs then - local v = host.decode_u32_be(evt_regs[1], evt_regs[2]) - if u32_valid(v) then event_no = v end + local event_no = read_u32(30247) + + if pv_w ~= nil then + host.emit("pv", { + w = -pv_w, -- site convention: generation is negative + mppt1_v = mppt1_v, + mppt1_a = mppt1_a, + mppt2_v = mppt2_v, + mppt2_a = mppt2_a, + lifetime_wh = pv_gen_wh, + temp_c = inv_temp, + rated_w = rated_w, + }) end - - host.emit("pv", { - w = -pv_w, -- site convention: generation is negative - mppt1_v = mppt1_v, - mppt1_a = mppt1_a, - mppt2_v = mppt2_v, - mppt2_a = mppt2_a, - lifetime_wh = pv_gen_wh, - temp_c = inv_temp, - rated_w = rated_w, - }) - 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) - host.emit_metric("inverter_temp_c", inv_temp) - host.emit_metric("sma_event_no", event_no) - host.emit_metric("curtail_cap_w", release_w) + metric("pv_mppt1_v", mppt1_v) + metric("pv_mppt1_a", mppt1_a) + metric("pv_mppt2_v", mppt2_v) + metric("pv_mppt2_a", mppt2_a) + metric("inverter_temp_c", inv_temp) + metric("sma_event_no", event_no) + host.emit_metric("curtail_cap_w", release_w) --------------------------------------------------------------- Meter -- -- Skipped on inverters without a paired SMA Energy Meter / Sunny Home -- Manager — the registers return all-0xFFFF which would otherwise emit -- as meter_w = -1 (decoded as signed I32) and confuse the site meter. - if has_meter then - - -- Meter total power: 30885-30886, I32 BE, watts (signed: + = import, - = export) + -- Most commercial string inverters have none. local mw_regs = probe_read(30885, 2, "input") - local meter_w = 0 - if mw_regs then - local v = host.decode_i32_be(mw_regs[1], mw_regs[2]) - if i32_valid(v) then meter_w = v end - end - - -- Per-phase meter power: 30887-30892, I32 BE pairs, watts (signed) - local mpw_regs = probe_read(30887, 6, "input") - local l1_w, l2_w, l3_w = 0, 0, 0 - if mpw_regs then - local v1 = host.decode_i32_be(mpw_regs[1], mpw_regs[2]) - local v2 = host.decode_i32_be(mpw_regs[3], mpw_regs[4]) - local v3 = host.decode_i32_be(mpw_regs[5], mpw_regs[6]) - if i32_valid(v1) then l1_w = v1 end - if i32_valid(v2) then l2_w = v2 end - if i32_valid(v3) then l3_w = v3 end - end - - -- Grid frequency: 30901-30902, U32 BE × 0.01 Hz - local hz_regs = probe_read(30901, 2, "input") - local hz = 0 - if hz_regs then - local v = host.decode_u32_be(hz_regs[1], hz_regs[2]) - if u32_valid(v) then hz = v * 0.01 end - end - - -- Per-phase voltage: 30903-30908, U32 BE × 0.01 V pairs - local lv_regs = probe_read(30903, 6, "input") - local l1_v, l2_v, l3_v = 0, 0, 0 - if lv_regs then - local v1 = host.decode_u32_be(lv_regs[1], lv_regs[2]) - local v2 = host.decode_u32_be(lv_regs[3], lv_regs[4]) - local v3 = host.decode_u32_be(lv_regs[5], lv_regs[6]) - if u32_valid(v1) then l1_v = v1 * 0.01 end - if u32_valid(v2) then l2_v = v2 * 0.01 end - if u32_valid(v3) then l3_v = v3 * 0.01 end - end + if mw_regs and not regs_all_ffff(mw_regs, 2) then poll_meter(mw_regs) end - -- Per-phase current: 30909-30914, U32 BE × 0.001 A pairs - local la_regs = probe_read(30909, 6, "input") - local l1_a, l2_a, l3_a = 0, 0, 0 - if la_regs then - local v1 = host.decode_u32_be(la_regs[1], la_regs[2]) - local v2 = host.decode_u32_be(la_regs[3], la_regs[4]) - local v3 = host.decode_u32_be(la_regs[5], la_regs[6]) - if u32_valid(v1) then l1_a = v1 * 0.001 end - if u32_valid(v2) then l2_a = v2 * 0.001 end - if u32_valid(v3) then l3_a = v3 * 0.001 end - end - - -- Import energy: 30581-30582, U32 BE, Wh - local imp_regs = probe_read(30581, 2, "input") - local import_wh = 0 - if imp_regs then - local v = host.decode_u32_be(imp_regs[1], imp_regs[2]) - if u32_valid(v) then import_wh = v end - end - - -- Export energy: 30583-30584, U32 BE, Wh - local exp_regs = probe_read(30583, 2, "input") - local export_wh = 0 - if exp_regs then - local v = host.decode_u32_be(exp_regs[1], exp_regs[2]) - if u32_valid(v) then export_wh = v end - end - - host.emit("meter", { - w = meter_w, - l1_w = l1_w, - l2_w = l2_w, - l3_w = l3_w, - l1_v = l1_v, - l2_v = l2_v, - l3_v = l3_v, - l1_a = l1_a, - l2_a = l2_a, - l3_a = l3_a, - hz = hz, - import_wh = import_wh, - export_wh = export_wh, - }) - host.emit_metric("meter_l1_w", l1_w) - host.emit_metric("meter_l2_w", l2_w) - host.emit_metric("meter_l3_w", l3_w) - host.emit_metric("meter_l1_v", l1_v) - host.emit_metric("meter_l2_v", l2_v) - host.emit_metric("meter_l3_v", l3_v) - host.emit_metric("meter_l1_a", l1_a) - host.emit_metric("meter_l2_a", l2_a) - host.emit_metric("meter_l3_a", l3_a) - host.emit_metric("grid_hz", hz) - - end -- if has_meter + -- The serial last, and only once the inverter has answered this poll: + -- a read that times out makes the host skip the rest of the poll. + if not sn_read and poll_answered then read_serial() end return 5000 end +function driver_poll() + -- Reads made by a command since the last poll do not count. + poll_answered, poll_missed = false, {} + local interval = poll_once() + settle_poll() + return interval +end + ---------------------------------------------------------------------------- -- Control — PV curtailment -- @@ -483,4 +476,6 @@ end function driver_cleanup() -- Don't leave a curtailment sticking after a driver hot-reload or shutdown. if curtail_active then write_w_setpoint(release_w) end + read_failures, last_try_ms = {}, {} + poll_answered, poll_missed = false, {} end diff --git a/drivers/tests/invented-number-baseline.json b/drivers/tests/invented-number-baseline.json index 6ecec62..07f5ef1 100644 --- a/drivers/tests/invented-number-baseline.json +++ b/drivers/tests/invented-number-baseline.json @@ -28,8 +28,6 @@ "schneider_meter": 13, "siemens_pac": 13, "sigenergy": 5, - "sma": 26, - "sma_pv": 21, "socomec": 13, "sofar": 20, "solaredge": 20, diff --git a/drivers/tests/lua_harness/test_wakes_after_silence.lua b/drivers/tests/lua_harness/test_wakes_after_silence.lua new file mode 100644 index 0000000..314a179 --- /dev/null +++ b/drivers/tests/lua_harness/test_wakes_after_silence.lua @@ -0,0 +1,214 @@ +-- A Modbus driver must pick its device up again by itself once the device +-- answers, without a restart, and must keep asking a register it gave up on. +-- +-- Several drivers wrapped every read in "give up after three misses until +-- restart". A device asleep at start-up (an inverter at night) or held by +-- another Modbus client answers nothing, so every register used up its three +-- tries on a dead link and the driver never asked again. It then sent nothing +-- until FTW restarted it, and the serial number Core keys the device on was +-- never read. +-- +-- The script compares each case with a healthy run of the same driver: +-- +-- 1. asleep from driver_init for eight polls, then awake; +-- 2. awake, then silent for eight polls, then awake again; +-- 3. each register the healthy run reads is refused for six polls while the +-- rest answer, then answers: it must be asked again within five minutes. +-- +-- After 1 and 2 the driver must emit what the healthy run emits, report the +-- same serial, and read every register the healthy run reads. +-- +-- Usage: lua55 test_wakes_after_silence.lua [fixture.lua] +-- A fixture is a Lua file that fills host._modbus_registers for a driver that +-- needs particular values before it reports anything; without one, every +-- register reads 100 and 40000-40001 hold the SunSpec marker. +local driver_path = arg[1] +local fixture = arg[2] +assert(driver_path, "usage: test_wakes_after_silence.lua [fixture.lua]") + +dofile("drivers/tests/lua_harness/host_mock.lua") + +local CONFIG = { + host = "127.0.0.1", port = 502, unit_id = 1, slave_id = 1, + nominal_w = 10000, rated_w = 10000, +} +local TRANSPORT = "modbus transport failure: i/o timeout" +local REFUSAL = "modbus exception function=0x03 code=0x02" +local RETRY_MS = 5 * 60 * 1000 +local KINDS = { "pv", "battery", "meter", "ev", "heatpump", "vehicle", "v2x_charger" } + +local function fill_registers() + if fixture then + dofile(fixture) + return + end + local regs = {} + for addr = 0, 65535 do regs[addr] = 100 end + regs[40000] = 0x5375 + regs[40001] = 0x6e53 + host._modbus_registers.holding = regs + host._modbus_registers.input = regs +end + +-- A fresh driver. `asleep` fails every read and write from driver_init on. +local function start(asleep) + host.reset() + host._millis_step = 0 + host._millis_counter = 1000000 + fill_registers() + host._modbus_read_error = asleep + host._modbus_write_error = asleep + driver_init, driver_poll, driver_command = nil, nil, nil + driver_default_mode, driver_cleanup = nil, nil + driver_command_v2, driver_default_mode_v2 = nil, nil + DRIVER, PROTOCOL = nil, nil + dofile(driver_path) + if type(driver_init) == "function" then driver_init(CONFIG) end +end + +local function wake() + host._modbus_read_error = nil + host._modbus_write_error = nil +end + +local function silence() + host._modbus_read_error = TRANSPORT + host._modbus_write_error = TRANSPORT +end + +-- One poll, after the interval the last one asked for. Returns which register +-- addresses it read (with whether each answered) and which kinds it emitted. +local next_gap = 5000 +local function poll(label) + host._millis_counter = host._millis_counter + next_gap + local before = #host._calls + local emitted_before = {} + for _, kind in ipairs(KINDS) do + emitted_before[kind] = #(host._emitted[kind] or {}) + end + local ok, ret = pcall(driver_poll) + assert(ok, label .. ": driver_poll raised: " .. tostring(ret)) + next_gap = tonumber(ret) or 5000 + if next_gap <= 0 then next_gap = 5000 end + local r = { reads = {}, kinds = {} } + for i = before + 1, #host._calls do + local c = host._calls[i] + if c.func == "modbus_read" then + local addr = c.args[1] + local failed = host._modbus_read_error ~= nil + or host._modbus_read_fail_addresses[addr] ~= nil + r.reads[addr] = r.reads[addr] or not failed + end + end + for _, kind in ipairs(KINDS) do + if #(host._emitted[kind] or {}) > emitted_before[kind] then + r.kinds[kind] = true + end + end + return r +end + +local function serial() + for i = #host._calls, 1, -1 do + if host._calls[i].func == "set_sn" then return host._calls[i].args[1] end + end + return nil +end + +-- Union of what the last `n` of `polls` read and emitted. Some drivers read a +-- slow block on every few polls only. +local function union(polls, n) + local reads, kinds = {}, {} + for i = #polls - n + 1, #polls do + for addr, answered in pairs(polls[i].reads) do + if answered then reads[addr] = true end + end + for kind in pairs(polls[i].kinds) do kinds[kind] = true end + end + return reads, kinds +end + +local function sorted_keys(t) + local keys = {} + for k in pairs(t) do keys[#keys + 1] = k end + table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + return keys +end + +local function run(label, polls_count) + local polls = {} + for i = 1, polls_count do polls[#polls + 1] = poll(label .. " " .. i) end + return polls +end + +local WINDOW = 6 + +---------------------------------------------------------------------------- +-- Healthy reference. +---------------------------------------------------------------------------- +start(nil) +next_gap = 5000 +local healthy = run("healthy", 12) +local want_reads, want_kinds = union(healthy, WINDOW) +local want_sn = serial() +assert(next(want_kinds) ~= nil, + "the healthy run emitted nothing; give this driver a fixture") + +local function check(label, polls) + local reads, kinds = union(polls, WINDOW) + for _, kind in ipairs(sorted_keys(want_kinds)) do + assert(kinds[kind], label .. ": no " .. kind .. " emitted after the device answered") + end + for _, addr in ipairs(sorted_keys(want_reads)) do + assert(reads[addr], label .. ": register " .. addr + .. " not read after the device answered") + end + if want_sn ~= nil then + assert(serial() == want_sn, label .. ": serial " .. tostring(serial()) + .. ", healthy run reported " .. tostring(want_sn)) + end +end + +---------------------------------------------------------------------------- +-- 1. Asleep from start-up, then awake. +---------------------------------------------------------------------------- +start(TRANSPORT) +next_gap = 5000 +run("asleep", 8) +wake() +check("asleep at start-up", run("awake", 12)) + +---------------------------------------------------------------------------- +-- 2. Silent mid-session, then awake again. +---------------------------------------------------------------------------- +start(nil) +next_gap = 5000 +run("before", 4) +silence() +run("silent", 8) +wake() +check("silent mid-session", run("back", 12)) + +---------------------------------------------------------------------------- +-- 3. A register refused while the rest answer is asked again within five +-- minutes of being given up. +---------------------------------------------------------------------------- +for _, addr in ipairs(sorted_keys(want_reads)) do + start(nil) + next_gap = 5000 + host._modbus_read_fail_addresses[addr] = REFUSAL + run("refused " .. addr, 6) + host._modbus_read_fail_addresses[addr] = nil + local elapsed, answered = 0, false + local n = 0 + while elapsed <= RETRY_MS + 2 * next_gap do + n = n + 1 + local r = poll("register " .. addr .. " after refusal " .. n) + elapsed = elapsed + next_gap + if r.reads[addr] then answered = true break end + end + assert(answered, "register " .. addr .. " was not asked again within five " + .. "minutes after it was refused six times") +end + +print("ok " .. driver_path) diff --git a/drivers/tests/test_sma_wakes.py b/drivers/tests/test_sma_wakes.py new file mode 100644 index 0000000..ca06d19 --- /dev/null +++ b/drivers/tests/test_sma_wakes.py @@ -0,0 +1,196 @@ +"""sma, sma_pv: the inverter is read again once it answers, without a restart. + +Up to sma 2.2.1 and sma_pv 1.1.2 every read went through a guard that left a +register alone until restart after three misses. An inverter asleep or held +by another Modbus client at start-up used up every try, and the driver then +sent nothing until FTW restarted it. sma_pv also settled on its first poll +whether a meter is paired and which lifetime register to read, so the same +start left it without a meter for the whole run. A register that did not +answer was sent as zero. + +Now a miss counts only in a poll where another read answered, and a register +given up is asked again every five minutes. sma_pv decides the meter and the +lifetime register on every poll from what the inverter answers. A field whose +register did not answer is left out; PV, battery and meter go out only when +their power answered. The serial is read last. +""" + +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" + +pytestmark = pytest.mark.skipif( + not LUA.exists(), reason="run make check to build ./lua55") + +REFUSAL = "modbus exception function=0x03 code=0x02" + + +def u32(value: int) -> list[int]: + value &= 0xFFFFFFFF + return [value >> 16, value & 0xFFFF] + + +SITE: dict[int, int] = {} +for addr, words in { + 30775: u32(3000), # PV 3000 W + 30769: u32(8500), # MPPT1 8.5 A + 30771: u32(60000), # MPPT1 600 V + 30513: [0, 0, 0, 12345], # lifetime 12345 Wh (U64) + 30529: u32(999), # lifetime on older firmware (U32) + 30843: u32(-10000), # battery -10 A + 30845: u32(60), # SoC 60 % + 30851: u32(40000), # 400 V + 30885: u32(-1500), # meter exporting 1500 W + 30887: u32(-500) * 3, # per phase + 30901: u32(5000), # 50.00 Hz +}.items(): + for i, word in enumerate(words): + SITE[addr + i] = word + + +def run(driver: str, body: str, registers: dict[int, int] | None = None) -> dict[str, str]: + regs = SITE | (registers or {}) + setup = "\n".join( + f"host._modbus_registers.input[{addr}] = {value}" + for addr, value in regs.items()) + script = f''' +package.path = "{HARNESS}/?.lua;" .. package.path +require("host_mock") +host.reset() +host._millis_step = 0 +host._millis_counter = 1000000 +{setup} +dofile("{ROOT / "drivers" / "lua" / driver}.lua") +local function poll(n) + for i = 1, n do + host._millis_counter = host._millis_counter + 5000 + local ok, err = pcall(driver_poll) + if not ok then print("POLL_ERROR " .. tostring(err)) os.exit(1) end + end +end +local function report(tag) + for _, der in ipairs({{"pv", "battery", "meter"}}) do + local list = host._emitted[der] or {{}} + print(tag .. "." .. der .. ".count " .. #list) + if #list > 0 then + for k, v in pairs(list[#list]) do + if type(v) ~= "table" then print(tag .. "." .. der .. "." .. k .. " " .. tostring(v)) end + end + end + end + for name, m in pairs(host._metrics) do print(tag .. ".metric." .. name .. " " .. tostring(m.value)) end +end +local function reads(addr) + local n = 0 + for _, c in ipairs(host._calls) do + if c.func == "modbus_read" and c.args[1] == addr then n = n + 1 end + end + return n +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) + + +@pytest.mark.parametrize("driver", ["sma", "sma_pv"]) +def test_sma_picks_the_inverter_up_again(driver: str) -> None: + result = subprocess.run( + [str(LUA), "drivers/tests/lua_harness/test_wakes_after_silence.lua", + f"drivers/lua/{driver}.lua"], + capture_output=True, text=True, cwd=ROOT) + assert result.returncode == 0, result.stdout + result.stderr + assert "ok" in result.stdout + + +def test_sma_pv_finds_the_meter_after_a_silent_start() -> None: + out = run("sma_pv", ''' +host._modbus_read_error = "modbus transport failure: i/o timeout" +driver_init({}) +poll(3) +host._modbus_read_error = nil +poll(1) +report("p") +''') + assert out["p.meter.count"] == "1" + assert float(out["p.meter.w"]) == -1500 + assert float(out["p.pv.lifetime_wh"]) == 12345 + + +def test_sma_pv_without_a_meter_sends_none() -> None: + out = run("sma_pv", 'driver_init({}) poll(2) report("p")', + {30885: 0xFFFF, 30886: 0xFFFF}) + assert out["p.meter.count"] == "0" + assert out["p.pv.count"] == "2" + + +def test_sma_pv_older_firmware_reads_lifetime_from_30529() -> None: + # 30513 refused: no lifetime until it has missed three times, then the + # U32 at 30529; 30513 is asked again five minutes later. + out = run("sma_pv", f''' +host._modbus_read_fail_addresses[30513] = "{REFUSAL}" +driver_init({{}}) +poll(3) +report("early") +poll(1) +report("late") +local before = reads(30513) +poll(60) +print("retried " .. (reads(30513) - before)) +''') + assert "early.pv.lifetime_wh" not in out + assert float(out["late.pv.lifetime_wh"]) == 999 + assert out["retried"] == "1" + + +def test_sma_pv_nan_lifetime_falls_back_to_30529() -> None: + out = run("sma_pv", 'driver_init({}) poll(1) report("p")', + {30513: 0xFFFF, 30514: 0xFFFF, 30515: 0xFFFF, 30516: 0xFFFF}) + assert float(out["p.pv.lifetime_wh"]) == 999 + + +@pytest.mark.parametrize("failed, kind", [(30775, "pv"), (30843, "battery"), + (30851, "battery"), (30885, "meter")]) +def test_sma_stream_left_out_when_its_power_does_not_answer(failed: int, + kind: str) -> None: + out = run("sma", f''' +host._modbus_read_fail_addresses[{failed}] = "{REFUSAL}" +driver_init({{}}) +poll(1) +report("p") +''') + assert out[f"p.{kind}.count"] == "0" + for other in {"pv", "battery", "meter"} - {kind}: + assert out[f"p.{other}.count"] == "1" + + +@pytest.mark.parametrize("driver", ["sma", "sma_pv"]) +def test_sma_fields_that_do_not_answer_are_left_out(driver: str) -> None: + fail = (30769, 30771, 30513, 30529, 31085, 30887, 30901, 30903, 30909, + 30581, 30583, 30845) + marks = "\n".join( + f'host._modbus_read_fail_addresses[{a}] = "{REFUSAL}"' for a in fail) + out = run(driver, f''' +driver_init({{}}) +{marks} +poll(1) +report("p") +''') + for key in ("pv.mppt1_a", "pv.mppt1_v", "pv.lifetime_wh", "pv.rated_w", + "meter.l1_w", "meter.hz", "meter.l1_v", "meter.l1_a", + "meter.import_wh", "meter.export_wh", "battery.soc", + "metric.pv_mppt1_a", "metric.grid_hz", "metric.meter_l1_w", + "metric.meter_l1_v"): + assert f"p.{key}" not in out, key + assert float(out["p.pv.w"]) == -3000 + assert float(out["p.meter.w"]) == -1500 diff --git a/index.yaml b/index.yaml index dbe7732..0803a6d 100644 --- a/index.yaml +++ b/index.yaml @@ -610,24 +610,24 @@ drivers: size_bytes: 8937 sha256: "486f6ba044758729e70832762a12373ec4e446bac087047f21418b599f595fef" - name: "sma" - version: "2.2.1" + version: "2.2.2" tier: core protocol: modbus connectivity: local ders: [battery, meter, pv] control: false - size_bytes: 15686 - sha256: "ade3e713b083bf8c51b81b6cf9edfa78c7dcafb5263cee342b4afdf5a0359651" + size_bytes: 15546 + sha256: "45ce05d5b4806fbfe31e44a090bb9a5fd1d8ba304ca477e73c7bf4414221da39" - name: "sma_pv" - version: "1.1.2" + version: "1.1.3" tier: core protocol: modbus connectivity: local setup: [installer] ders: [pv, meter] control: true - size_bytes: 19700 - sha256: "2a1d1d15f9ed073a7be86dd9394d4959a8169ddb74296047b1e406f1de8d4532" + size_bytes: 19111 + sha256: "9eb0eb3a7f8e8f8e1782219b39a11c1c82ee7db2b27c911e19c1980c12d8c9e2" - name: "socomec" version: "1.0.4" tier: community diff --git a/manifests/sma.yaml b/manifests/sma.yaml index 7e522f6..fd4d5a1 100644 --- a/manifests/sma.yaml +++ b/manifests/sma.yaml @@ -1,5 +1,5 @@ name: "sma" -version: "2.2.1" +version: "2.2.2" tier: core author: "Sourceful Labs AB" protocol: modbus @@ -62,12 +62,12 @@ upstream_docs: kind: manual url_stability: stable min_host_version: "2.0.0" -size_bytes: 15686 +size_bytes: 15546 dkb_id: "sma" -sha256: "ade3e713b083bf8c51b81b6cf9edfa78c7dcafb5263cee342b4afdf5a0359651" +sha256: "45ce05d5b4806fbfe31e44a090bb9a5fd1d8ba304ca477e73c7bf4414221da39" signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "" +changelog: "Reads the inverter again after a silent start, and leaves out fields whose register did not answer." diff --git a/manifests/sma_pv.yaml b/manifests/sma_pv.yaml index a44ad73..d20e092 100644 --- a/manifests/sma_pv.yaml +++ b/manifests/sma_pv.yaml @@ -1,5 +1,5 @@ name: "sma_pv" -version: "1.1.2" +version: "1.1.3" tier: core author: "Sourceful Labs AB" protocol: modbus @@ -16,9 +16,10 @@ tested_devices: notes: "SMA Sunny Tripower commercial string inverters (STP 50-40 / 50-41 / X-class) via Modbus TCP, with active-power curtailment over Modbus holding register 40915." min_driver_version: "1.0.0" min_host_version: "2.0.0" -size_bytes: 19700 +size_bytes: 19111 dkb_id: "sma_pv" -sha256: "2a1d1d15f9ed073a7be86dd9394d4959a8169ddb74296047b1e406f1de8d4532" +sha256: "9eb0eb3a7f8e8f8e1782219b39a11c1c82ee7db2b27c911e19c1980c12d8c9e2" signature: "" bytecode_sha256: "" +changelog: "Reads the inverter again after a silent start, decides the meter and lifetime register on every poll, and leaves out fields whose register did not answer." diff --git a/support-status.json b/support-status.json index 307b2e0..a6533e6 100644 --- a/support-status.json +++ b/support-status.json @@ -1367,7 +1367,7 @@ }, { "catalog_source": true, - "catalog_version": "2.2.1", + "catalog_version": "2.2.2", "driver_id": "sma", "targets": { "blixt-l1": { @@ -1388,7 +1388,7 @@ }, { "catalog_source": true, - "catalog_version": "1.1.2", + "catalog_version": "1.1.3", "driver_id": "sma_pv", "targets": { "blixt-l1": {