diff --git a/documents/README/changelog/Changelog_YamBMS_1.8.0_Auto_CVL.md b/documents/README/changelog/Changelog_YamBMS_1.8.0_Auto_CVL.md index 9bcb3e6..b5c42ee 100644 --- a/documents/README/changelog/Changelog_YamBMS_1.8.0_Auto_CVL.md +++ b/documents/README/changelog/Changelog_YamBMS_1.8.0_Auto_CVL.md @@ -9,35 +9,39 @@ ## Problem `Auto CVL` is a PI controller that reduces the `Requested Charge Voltage (CVL)` sent to the -inverter when a cell voltage rises above target, to avoid tripping the BMS `OVP` alarm. Its -computation was hardcoded around `Bulk Voltage`: +inverter when cell voltage rises above target, to avoid tripping the BMS `OVP` alarm. -- the PI's starting point / reference (`CVL`, `CVL_orig`) was always `bulk_voltage`; -- the deadband reference (`cell_bulk_v`) was always `bulk_voltage / cell_count`; -- the lower clamp (`min_CVL`) was always `float_voltage`; -- the upper clamp (`max_CVL`) was always `bulk_voltage + boost`. +In 1.7.0 it was strictly a Bulk-phase function. `yambms_core.yaml` built the requested voltage +one branch per phase, and only the Bulk branch added the correction: -However, `yambms_core.yaml` already adds the resulting offset (`var_auto_cvl`) to -`requested_charge_voltage` **unconditionally**, regardless of the charging phase (`Bulk`, -`Float`, or `Stop`). So the function was never actually gated to Bulk — it just computed a -Bulk-anchored correction that got silently applied during Float/Stop too, where the reference -values no longer made sense. Concretely: in `Stop` (target = nominal voltage, the lowest value -on the whole voltage scale), the old `min_CVL = float_voltage` floor sat *above* the actual -target, so any correction would have pulled the requested voltage *up* toward float voltage -instead of down — silently defeating the purpose of `Stop`. +``` +Bulk : bulk_voltage + charger_offset + var_auto_cvl +Float : float_voltage + charger_offset + var_auto_float +Stop : rebulk_voltage + charger_offset +``` -Real-world motivation for fixing this: some inverters hold their output voltage a bit above -(~0.1–0.3 V) the requested `CVL`, in every phase, not just Bulk. `Auto CVL` needed to become a -general "help the pack respect whatever `requested_charge_voltage` currently is" function, -regardless of which phase produced that target. +The controller itself matched that scope: its reference (`CVL`, `CVL_orig`) and deadband +reference (`cell_bulk_v`) were anchored to `bulk_voltage`, its ceiling to `bulk_voltage + boost`, +its floor to `float_voltage`. + +The gap: **`Float` and `Stop` had no correction at all.** Some inverters hold their output +voltage a bit above (~0.1–0.3 V) the requested `CVL`, and they do so in every phase, not just +Bulk. Once charging is meant to taper or stop, an uncompensated overshoot keeps pushing current +into a pack that is already full — exactly when it is least wanted. `Auto CVL` therefore needed +to become a general "help the pack respect whatever `requested_charge_voltage` currently is" +function, regardless of which phase produced that target. + +Extending it was not a matter of removing a phase check. Every reference the controller used was +a Bulk constant, and the metric that makes sense in Bulk (`max_cell_v`, protecting against a +single runner cell) is not the one that makes sense once the pack is full. ## Design decisions -Reached iteratively, each validated against one hard invariant: **Bulk's observable behavior -must not change** unless explicitly agreed otherwise. +Each was validated against one hard invariant: **Bulk's observable behavior must not change** +unless explicitly stated otherwise. 1. **Phase source of truth**: read the existing `yambms${id}_charging_instruction` text sensor - (already published by `yambms_core.yaml`, values `"Bulk"`/`"Float"`/`"Stop"`) instead of + (already published by `yambms_core.yaml`, values `"Bulk"` / `"Float"` / `"Stop"`) instead of duplicating the `charge_status` → phase classification logic in this file. 2. **Bulk** (kept close to identical): still tracks `max_cell_v` against `bulk_voltage`, still @@ -49,15 +53,15 @@ must not change** unless explicitly agreed otherwise. observable difference is confined to edge cases where the correction saturates. 3. **Float / Stop use a different metric**: `average_cell_v = total_voltage / cell_count` - instead of `max_cell_v`. Rationale: the goal here is compensating a roughly-constant inverter - overshoot (not protecting against a single runner cell), and the average is naturally - smoother than a single-cell reading — so no deadband is needed; the correction reacts as soon - as `average_cell_v` exceeds the target. + instead of `max_cell_v`. Rationale: the goal here is compensating a roughly constant inverter + overshoot, not protecting against a single runner cell, and the average is naturally smoother + than a single-cell reading — so no deadband is needed; the correction reacts as soon as + `average_cell_v` exceeds the target. 4. **Float / Stop are unidirectional**: the correction only ever pulls `CVL` down, never above - target. Implemented by setting `max_CVL = target_v` — combined with the existing - clamp-and-freeze anti-windup pattern (only commit the integral when not clamped), this - naturally prevents any upward correction without needing a separate code path. + target. Implemented by setting `max_CVL = target_v`, and by clamping the integral term at `0` + so it can never wind up positive — an upward correction is blocked by the ceiling anyway, and + a lingering positive integral would only delay the reaction to the next real overshoot. 5. **Float's target tracks the live `Auto Float` glide, not the final `Float Voltage`**: `target_v = float_voltage + var_auto_float`. `yambms_auto_float.yaml` already ramps the @@ -67,36 +71,99 @@ must not change** unless explicitly agreed otherwise. paced) Auto Float ramp. Tracking the live glide value means `Auto CVL` only reacts to a real overshoot *beyond* whatever Auto Float currently requests. -6. **Per-phase floors, chained down the voltage ladder**: - - Float floor = `cell_count × var_cell_nominal_v` (Stop's own target — never pull Float below - what Stop would ask for anyway). - - Stop floor = `cell_count × var_cell_max_discharge_v` — a chemistry constant that existed in - `yambms_core.yaml` but was previously unused (commented `// Not used`). This gives `Stop` a - real correction range below nominal voltage, comfortably above actual discharge cut-off, so - a poorly-behaved inverter can't keep trickling current in even after charging has stopped. +6. **Float's floor is derived from `Rebulk V.`, not from a fixed voltage**: + `min_CVL = Rebulk V. + ${auto_cvl_rebulk_margin_v}` (default margin 0.5 V). + This is the single most important safety property of the Float branch. Any fixed floor — + including `cell_count × var_cell_nominal_v`, which is exactly the lower bound of the + `Rebulk V.` range — can sit *at or below* the rebulk threshold, depending on the user's + settings. `Auto CVL` would then be able to pull the pack down far enough to satisfy + `max_cell_v ≤ Rebulk V. / cell_count`, triggering a rebulk it caused itself and looping + Float → Bulk → Float indefinitely. Deriving the floor from the actual `Rebulk V.` entity + keeps that margin correct whatever the configuration. If `Rebulk V.` is unavailable, the + floor falls back to `cell_count × var_cell_nominal_v`; if the Float target is already at or + below the floor, the floor is clamped to the target so `Auto CVL` stays neutral rather than + pushing the voltage back up. -7. **Two independent PI loops, not one shared state**: Bulk uses `integral_bulk` / - `prev_integral_bulk`; Float and Stop share `integral_avg` / `prev_integral_avg` (they track - the same metric — `average_cell_v` — so carrying state between them is meaningful). Carrying - state from Bulk into Float/Stop would not be: the measured quantity itself changes nature - (`max_cell_v` vs `average_cell_v`) at that transition, so an accumulated integral from one - would not represent a valid correction for the other. +7. **Stop's target moves from `Rebulk V.` to `cell_count × var_cell_nominal_v`**, and its floor + becomes `cell_count × var_cell_max_discharge_v` — a chemistry constant that existed in + `yambms_core.yaml` but was previously unused (commented `// Not used`). + In 1.7.0, `Stop` requested `Rebulk V.` itself, which left the pack sitting on the very + threshold that decides when to rebulk. Anchoring `Stop` to nominal voltage instead gives it a + target that is independent of the rebulk decision, and a real correction range below it, + comfortably above actual discharge cut-off — so a poorly-behaved inverter can't keep + trickling current in after charging has stopped. -8. **NaN/availability guards are branch-specific**: only `cell_count`, `bulk_voltage`, and the - `charging_instruction` state are required upfront (common to all phases). `balance_delta` / - `max_cell_v` are only required to enter the Bulk branch; `float_voltage` / `total_voltage` - are only required to enter the Float/Stop branch. This avoids a sensor hiccup on one branch's - inputs (e.g. `total_voltage`, an aggregated BMS value more likely to be transiently - unavailable than a restored config entity) silently disabling the other phase's correction — - which would have broken the Bulk invariant in that edge case. +8. **Bounded anti-windup on the Float/Stop integral**: the integral is capped at + `-(target_v - min_CVL) / ki`, i.e. at the correction the floor can actually deliver. Without + this bound, a pack that stays above target while the CVL has no effect — an inverter + substituting its own voltage target, for instance a Deye in ToU mode — winds the integral + down without limit, and the CVL stays pinned to the floor long after the cause is gone. + +9. **PI state is reset when crossing the Bulk ↔ Float/Stop boundary**. Bulk uses + `integral_bulk`; Float and Stop share `integral_avg` (they track the same metric — + `average_cell_v` — so carrying state between them is meaningful). Carrying state across the + Bulk boundary is not: the measured quantity itself changes nature (`max_cell_v` vs + `average_cell_v`) at that transition, so an accumulated integral from one phase does not + represent a valid correction for the other. Without the reset, a stale integral from before a + Float cycle would be re-injected on the next rebulk. Turning the `Automatic Charge Voltage` + switch off also clears both PI states entirely. + +10. **NaN / availability guards are branch-specific**: only `cell_count`, `bulk_voltage` and the + `charging_instruction` state are required upfront (common to all phases). `balance_delta` and + `max_cell_v` are only required to enter the Bulk branch; `float_voltage` and `total_voltage` + only to enter the Float/Stop branch. This avoids a sensor hiccup on one branch's inputs (e.g. + `total_voltage`, an aggregated BMS value more likely to be transiently unavailable than a + restored config entity) silently disabling the other phase's correction — which would have + broken the Bulk invariant in that edge case. ## Result | Phase | Metric | Target (`target_v`) | Floor | Ceiling | Deadband | |---|---|---|---|---|---| | Bulk | `max_cell_v` | `bulk_voltage` | `cell_count × var_cell_min_charge_v` | `bulk_voltage + boost` | `balance_trigger_voltage` | -| Float | `average_cell_v` | `float_voltage + var_auto_float` | `cell_count × var_cell_nominal_v` | `target_v` | none | +| Float | `average_cell_v` | `float_voltage + var_auto_float` | `Rebulk V. + rebulk margin` | `target_v` | none | | Stop | `average_cell_v` | `cell_count × var_cell_nominal_v` | `cell_count × var_cell_max_discharge_v` | `target_v` | none | +`yambms_core.yaml` now builds the requested voltage from a per-phase base plus a common set of +offsets, instead of a separate formula per branch: + +``` +base : Bulk -> bulk_voltage | Float -> float_voltage | Stop -> cell_count × nominal_v +result : base + charger_offset + var_auto_cvl + var_auto_float + var_auto_custom_cvl +``` + +Each offset is `0` when its function is idle or disabled, so the phases that used to receive no +correction now receive one only when it is actually enabled. + +### New entities + +Two diagnostic sensors expose the two halves of the charge voltage setpoint, so a misbehaving +correction can be read directly from the dashboard instead of being inferred: + +- **`Auto CVL Delta`** — the correction `Auto CVL` is currently applying. Negative when it is + reducing the charge voltage, `0` when idle. +- **`Auto Float Voltage Delta`** — the remaining offset of the `Auto Float` glide above the + target float voltage. Reaches `0` once the ramp is complete. + +Together they reconstruct the setpoint published by `yambms_core.yaml`: + +``` +Requested Charge Voltage = base target + Auto Float Delta + Auto CVL Delta +``` + +### New substitution + +`auto_cvl_rebulk_margin_v` (default `0.5`) — safety margin kept above `Rebulk V.` by the Float +floor. It must exceed the spread between pack average and highest cell, otherwise `max_cell_v` +can reach the rebulk threshold while the average is still above the floor. Increase it on a +poorly balanced pack. + +## Known limitations + +- On entering `Float`, `Auto CVL` runs every second while `Auto Float` runs every 60 s. During + that window `var_auto_float` is still `0`, so `Auto CVL` briefly targets `float_voltage` + instead of the start of the glide. The requested voltage can dip for up to a minute before the + glide takes over. To be addressed in `yambms_auto_float.yaml`. + Documentation updated in the same change: `documents/README/YamBMS_functions.md`, `Auto CVL` section. diff --git a/packages/yambms/yambms_auto_cvl.yaml b/packages/yambms/yambms_auto_cvl.yaml index f1962a3..84aabc0 100644 --- a/packages/yambms/yambms_auto_cvl.yaml +++ b/packages/yambms/yambms_auto_cvl.yaml @@ -1,5 +1,5 @@ # Updated : 2026.08.11 -# Version : 2.5.0 +# Version : 2.6.0 # GitHub : https://github.com/Sleeper85/esphome-yambms # YamBMS ( Yet another multi-BMS Merging Solution ) @@ -18,8 +18,19 @@ # along with this program. If not, see . # Originally developed by @MrPablo +# Adapted and reorganized to an interval lambda for the new CVL core by @Sleeper85 # Updated to support `Float` and `Stop` CVL by @Sleeper85 +substitutions: + # +--------------------------------------+ + # | Use the settings below with caution | + # +--------------------------------------+ + # Auto CVL - Float : safety margin kept above `Rebulk V.` when pulling the requested charge + # voltage down. Without it, Auto CVL can drag the pack below the rebulk threshold and trigger + # its own rebulk, looping Float -> Bulk -> Float. Derived from `Rebulk V.` at runtime so it + # stays correct whatever the user configures. + auto_cvl_rebulk_margin_v: '0.5' + switch: - platform: template name: "Automatic Charge Voltage" @@ -29,7 +40,33 @@ switch: optimistic: true entity_category: config +sensor: + # Auto CVL + - platform: template + id: yambms${yambms_id}_auto_cvl + device_id: yambms_yambms${yambms_id} + name: "Auto CVL" + update_interval: never + unit_of_measurement: V + device_class: voltage + state_class: measurement + accuracy_decimals: 1 + + # Auto CVL Delta + - platform: template + id: yambms${yambms_id}_auto_cvl_delta + device_id: yambms_yambms${yambms_id} + name: "Auto CVL Delta" + update_interval: never + unit_of_measurement: V + device_class: voltage + state_class: measurement + accuracy_decimals: 1 + number: + # Term to adjust the proportional gain of the auto voltage control PI logic. + # The higher the setting, the faster the correcting response. + # Too high a value will cause oscillation. - platform: template name: "Auto CVL Kp Term" id: yambms${yambms_id}_auto_cvl_kp @@ -42,9 +79,10 @@ number: initial_value: 0.05 optimistic: true entity_category: config - # Term to adjust the proportional gain of the auto voltage control PI logic. - # The higher the setting, the faster the correcting response. Too high a value will cause oscillation. + # Term to adjust the integral gain of the auto voltage control PI logic. + # The higher the setting, the more the correction response will be increased over time. + # Too high a value will cause oscillation. - platform: template name: "Auto CVL Ki Term" id: yambms${yambms_id}_auto_cvl_ki @@ -57,8 +95,6 @@ number: initial_value: 0.5 optimistic: true entity_category: config - # Term to adjust the integral gain of the auto voltage control PI logic. - # The higher the setting, the more the correction response will be increased over time. Too high a value will cause oscillation. - platform: template name: "Auto CVL Boost Charge V." @@ -75,144 +111,204 @@ number: optimistic: true entity_category: config -sensor: - # +--------------------------------------+ - # | Auto Charge Voltage Control | - # +--------------------------------------+ - - platform: template - id: auto_cvl - update_interval: 1s # must have the same value as the "dt" variable in the lamda below - unit_of_measurement: V - device_class: voltage - internal: true - filters: - - round: 1 - lambda: |- - // Variables +interval: + - interval: 1s # must have the same value as the `dt` variable in the lamda below + then: + # +--------------------------------------+ + # | Auto Charge Voltage Control | + # +--------------------------------------+ + - lambda: |- + // Variables - // Bulk : protects a runner max_cell_v against the Bulk target - static float integral_bulk = 0.0; // Integral term initialization - static float prev_integral_bulk = 0.0; // Prior Integral term initialization - - // Float / Stop : compensates the pack average_cell_v against the current Float/Stop target - // (a separate PI state : the tracked quantity changes nature at the Bulk <-> Float/Stop boundary) - static float integral_avg = 0.0; - static float prev_integral_avg = 0.0; + // Bulk : protects a runner max_cell_v against the Bulk target + static float integral_bulk = 0.0; // Integral term initialization + static float prev_integral_bulk = 0.0; // Prior Integral term initialization + + // Float / Stop : compensates the pack average_cell_v against the current Float/Stop target + // (a separate PI state : the tracked quantity changes nature at the Bulk <-> Float/Stop boundary) + static float integral_avg = 0.0; + static float prev_integral_avg = 0.0; - float cell_count = id(yambms${yambms_id}_cell_count).state; - float bulk_voltage = id(yambms${yambms_id}_bulk_voltage).state; - float float_voltage = id(yambms${yambms_id}_float_voltage).state; - float balance_delta = id(yambms${yambms_id}_balance_trigger_voltage).state; - float max_cell_v = id(yambms${yambms_id}_max_cell_voltage).state; - float total_voltage = id(yambms${yambms_id}_total_voltage).state; + float cell_count = id(yambms${yambms_id}_cell_count).state; + float bulk_voltage = id(yambms${yambms_id}_bulk_voltage).state; + float float_voltage = id(yambms${yambms_id}_float_voltage).state; + float balance_delta = id(yambms${yambms_id}_balance_trigger_voltage).state; + float max_cell_v = id(yambms${yambms_id}_max_cell_voltage).state; + float total_voltage = id(yambms${yambms_id}_total_voltage).state; - float kp = id(yambms${yambms_id}_auto_cvl_kp).state; // Proportional gain, adjust as needed - float ki = id(yambms${yambms_id}_auto_cvl_ki).state; // Integral gain, adjust as needed - float dt = 1.0; // Time step, adjust based on update_interval + float kp = id(yambms${yambms_id}_auto_cvl_kp).state; // Proportional gain, adjust as needed + float ki = id(yambms${yambms_id}_auto_cvl_ki).state; // Integral gain, adjust as needed + float dt = 1.0; // Time step, adjust based on update_interval - // Check if the common values are available, if not return bulk voltage as CVL - if (isnan(cell_count) || isnan(bulk_voltage) || - !id(yambms${yambms_id}_charging_instruction).has_state() || cell_count <= 0) { - id(yambms${yambms_id}_var_auto_cvl) = 0.0; - return bulk_voltage; - } + float CVL = bulk_voltage; + float CVL_orig = bulk_voltage; - // Check feature enabled - if (!id(yambms${yambms_id}_switch_auto_cvl).state){ - id(yambms${yambms_id}_var_auto_cvl) = 0.0; - prev_integral_bulk = 0.0; - prev_integral_avg = 0.0; - return bulk_voltage; - } + std::string charging_instruction = id(yambms${yambms_id}_charging_instruction).state; - std::string charging_instruction = id(yambms${yambms_id}_charging_instruction).state; - float CVL = bulk_voltage; - float CVL_orig = bulk_voltage; + // +----------------------------------------------------------+ + // | Gate #1 : Check if the common values are available + // +----------------------------------------------------------+ + if (isnan(cell_count) || isnan(bulk_voltage) || !id(yambms${yambms_id}_charging_instruction).has_state() || cell_count <= 0) + { + // Reset values + id(yambms${yambms_id}_var_auto_cvl) = 0.0; + id(yambms${yambms_id}_auto_cvl).publish_state(CVL); + id(yambms${yambms_id}_auto_cvl_delta).publish_state(0.0); + return; + } - // +-----------------------------------------------+ - // | Bulk | - // +-----------------------------------------------+ - if ((charging_instruction == "Bulk") && !isnan(balance_delta) && !isnan(max_cell_v)) { - float min_CVL = cell_count * id(yambms${yambms_id}_var_cell_min_charge_v); // Minimum CVL - float max_CVL = bulk_voltage + id(yambms${yambms_id}_auto_cvl_boost_charge_v).state; // Maximum CVL - float cell_bulk_v = (bulk_voltage / cell_count); - float max_allowed_voltage = cell_bulk_v + balance_delta; + // +----------------------------------------------------------+ + // | Gate #2 : Check feature enabled + // +----------------------------------------------------------+ + if (!id(yambms${yambms_id}_switch_auto_cvl).state) + { + // Reset values + integral_bulk = 0.0; + prev_integral_bulk = 0.0; + integral_avg = 0.0; + prev_integral_avg = 0.0; + id(yambms${yambms_id}_var_auto_cvl) = 0.0; + id(yambms${yambms_id}_auto_cvl).publish_state(CVL); + id(yambms${yambms_id}_auto_cvl_delta).publish_state(0.0); + return; + } - // PI Algorithm - float error = cell_bulk_v - max_cell_v; - // It's possible for PI control to start before BMS values are available, so don't store non-number values - if (isnan(prev_integral_bulk)) { - prev_integral_bulk = 0; - integral_bulk = 0; - } - // Check if max cell voltage is in deadband - if ((max_cell_v <= max_allowed_voltage) && (max_cell_v >= cell_bulk_v)) { - // No integral error within deadband zone - } else { - integral_bulk = prev_integral_bulk + error * dt; - } - // Calculate PI output - float output = kp * error + ki * integral_bulk; - // Update CVL - CVL += output; - // If CVL is less than lower limit, enforce limit - if (CVL < min_CVL) { - CVL = min_CVL; - } - // If CVL is greater than upper limit, enforce limit - else if (CVL > max_CVL) { - CVL = max_CVL; - } - else { - prev_integral_bulk = integral_bulk; - } - } - // +-----------------------------------------------+ - // | Float / Stop | - // +-----------------------------------------------+ - else if (((charging_instruction == "Float") || (charging_instruction == "Stop")) && - !isnan(float_voltage) && !isnan(total_voltage)) { - float target_v; - float min_CVL; - if (charging_instruction == "Float") { - // Live Auto Float glide target (bulk_voltage -> float_voltage), not the final float_voltage : - // Auto CVL must never react ahead of the Auto Float ramp still in progress - target_v = float_voltage + id(yambms${yambms_id}_var_auto_float); - min_CVL = cell_count * id(yambms${yambms_id}_var_cell_nominal_v); - } else { // Stop - target_v = cell_count * id(yambms${yambms_id}_var_cell_nominal_v); - min_CVL = cell_count * id(yambms${yambms_id}_var_cell_max_discharge_v); - } - float max_CVL = target_v; // Never correct above target - float average_cell_v = (total_voltage / cell_count); - float target_cell_v = (target_v / cell_count); + // +----------------------------------------------------------+ + // | Reset PI state when crossing the Bulk <-> Float/Stop boundary + // | (Float <-> Stop keeps its shared state on purpose : both track average_cell_v) + // +----------------------------------------------------------+ + bool is_bulk_phase = (charging_instruction == "Bulk"); + static bool prev_is_bulk_phase = is_bulk_phase; + if (is_bulk_phase != prev_is_bulk_phase) + { + integral_bulk = 0.0; + prev_integral_bulk = 0.0; + integral_avg = 0.0; + prev_integral_avg = 0.0; + prev_is_bulk_phase = is_bulk_phase; + } - CVL = target_v; - CVL_orig = target_v; + // +----------------------------------------------------------+ + // | Auto CVL - Bulk + // +----------------------------------------------------------+ + if ((charging_instruction == "Bulk") && !isnan(balance_delta) && !isnan(max_cell_v)) + { + float min_CVL = cell_count * id(yambms${yambms_id}_var_cell_min_charge_v); // Minimum CVL + float max_CVL = bulk_voltage + id(yambms${yambms_id}_auto_cvl_boost_charge_v).state; // Maximum CVL + float cell_bulk_v = (bulk_voltage / cell_count); + float max_allowed_voltage = cell_bulk_v + balance_delta; - // PI Algorithm : no deadband, react as soon as average_cell_v exceeds target_cell_v - float error = target_cell_v - average_cell_v; - if (isnan(prev_integral_avg)) { - prev_integral_avg = 0; - integral_avg = 0; - } - if (average_cell_v <= target_cell_v) { - // No integral error, nothing to compensate - } else { - integral_avg = prev_integral_avg + error * dt; - } - float output = kp * error + ki * integral_avg; - CVL += output; - if (CVL < min_CVL) { - CVL = min_CVL; - } - else if (CVL > max_CVL) { - CVL = max_CVL; - } - else { - prev_integral_avg = integral_avg; - } - } + // PI Algorithm + float error = cell_bulk_v - max_cell_v; + // It's possible for PI control to start before BMS values are available, so don't store non-number values + if (isnan(prev_integral_bulk)) + { + prev_integral_bulk = 0; + integral_bulk = 0; + } + // Check if max cell voltage is in deadband + if ((max_cell_v <= max_allowed_voltage) && (max_cell_v >= cell_bulk_v)) + { + // No integral error within deadband zone + } + else + { + integral_bulk = prev_integral_bulk + error * dt; + } + // Calculate PI output + float output = kp * error + ki * integral_bulk; + // Update CVL + CVL += output; + // If CVL is less than lower limit, enforce limit + if (CVL < min_CVL) + { + CVL = min_CVL; + } + // If CVL is greater than upper limit, enforce limit + else if (CVL > max_CVL) + { + CVL = max_CVL; + } + else + { + prev_integral_bulk = integral_bulk; + } + } - id(yambms${yambms_id}_var_auto_cvl) = CVL - CVL_orig; - return CVL - CVL_orig; + // +----------------------------------------------------------+ + // | Auto CVL - Float / Stop + // +----------------------------------------------------------+ + else if (((charging_instruction == "Float") || (charging_instruction == "Stop")) && !isnan(float_voltage) && !isnan(total_voltage)) + { + float target_v; + float min_CVL; + if (charging_instruction == "Float") + { + // Live Auto Float glide target (bulk_voltage -> float_voltage), not the final float_voltage : + // Auto CVL must never react ahead of the Auto Float ramp still in progress + target_v = float_voltage + id(yambms${yambms_id}_var_auto_float); + // Floor derived from `Rebulk V.` : Auto CVL must never be able to drag the pack down + // to the rebulk threshold, or it would trigger its own rebulk and loop + float rebulk_v = id(yambms${yambms_id}_rebulk_voltage).state; + min_CVL = isnan(rebulk_v) ? (cell_count * id(yambms${yambms_id}_var_cell_nominal_v)) + : (rebulk_v + ${auto_cvl_rebulk_margin_v}); + } + else // Stop + { + target_v = cell_count * id(yambms${yambms_id}_var_cell_nominal_v); + min_CVL = cell_count * id(yambms${yambms_id}_var_cell_max_discharge_v); + } + + // A target already at or below the floor leaves no room to correct : clamp to the + // target itself so Auto CVL stays neutral instead of pushing the voltage back up + if (min_CVL > target_v) min_CVL = target_v; + + float max_CVL = target_v; // Never correct above target + float average_cell_v = (total_voltage / cell_count); + float target_cell_v = (target_v / cell_count); + + CVL = target_v; + CVL_orig = target_v; + + // PI Algorithm : no deadband, react as soon as average_cell_v exceeds target_cell_v + float error = target_cell_v - average_cell_v; + if (isnan(prev_integral_avg)) + { + prev_integral_avg = 0; + } + + // Accumulate on any error sign, but never let the integral wind up positive : max_CVL + // already blocks any upward correction, so a lingering positive integral would only + // delay the reaction to the next real overshoot instead of protecting against it + integral_avg = prev_integral_avg + error * dt; + if (integral_avg > 0) integral_avg = 0; + + // Anti-windup : cap the integral at the correction min_CVL can actually deliver. + // Without it, a pack that stays above target while the CVL has no effect (inverter + // substituting its own target, e.g. Deye in ToU mode) winds the integral down without + // bound, and the CVL stays pinned to the floor long after the cause is gone. + if (ki > 0) + { + float integral_min = -(target_v - min_CVL) / ki; + if (integral_avg < integral_min) integral_avg = integral_min; + } + float output = kp * error + ki * integral_avg; + CVL += output; + if (CVL < min_CVL) + { + CVL = min_CVL; + } + else if (CVL > max_CVL) + { + CVL = max_CVL; + } + prev_integral_avg = integral_avg; + } + + float auto_cvl_delta = CVL - CVL_orig; + auto_cvl_delta = roundf(auto_cvl_delta * 10.0f) / 10.0f; + id(yambms${yambms_id}_var_auto_cvl) = auto_cvl_delta; + + // Publish the sensor + id(yambms${yambms_id}_auto_cvl).publish_state(CVL); + id(yambms${yambms_id}_auto_cvl_delta).publish_state(auto_cvl_delta);