EOS_connect icon indicating copy to clipboard operation
EOS_connect copied to clipboard

calculating price for stored energy in battery and using dynamically for optimization

Open ohAnd opened this issue 11 months ago • 11 comments

based on discussion in PR #172

Sorry for the late response. I was a little busy the last few weeks.

This is all still work in progress, but working pretty well so far. I have a rather complex template sensor to calculate the battery energy price. For this to work, I have created two sensors calculating the PV and the grid power that flows into the battery. In addition, I have a sensor with the current energy price (in my case, Tibber) and the total energy stored in the battery, which is provided by my BMS.

My battery is never discharged below ~15%. I am subtracting this energy amount (ENERGY_FLOOR_KWH) before doing the whole calculation.

template:
  - trigger:
      # Trigger calculation whenever power, price, or battery energy changes
      - platform: state
        entity_id: 
          - sensor.batterie_leistung_netz
          - sensor.batterie_leistung_pv
          - sensor.strompreis
          - sensor.batterie_energie
    sensor:
      - name: "Batterie Speicher Preis"
        unique_id: batterie_speicher_preis
        unit_of_measurement: "€/kWh"
        icon: mdi:currency-eur
        state: >-
          {# --- CONFIGURATION --- #}
          {% set ENERGY_FLOOR_KWH = 6.8 %}
          {% set EFFICIENCY_RATE = 0.88 %}   {# 12% loss expressed as 0.88 efficiency #}
          {% set price_pv = 0.0 %}
          
          {# Calculate loss factor: 1 / 0.88 ≈ 1,136 (accounts for energy lost during charging) #}
          {% set EFFICIENCY_LOSS_FACTOR = 1.0 / EFFICIENCY_RATE %}
          
          {# --- INPUT SENSORS (Safely convert to float or None) --- #}
          {% set current_energy_kwh = states('sensor.batterie_energie') | float(none) %}
          {% set power_grid_w = states('sensor.batterie_leistung_netz') | float(none) %}
          {% set power_pv_w = states('sensor.batterie_leistung_pv') | float(none) %}
          {% set price_grid = states('sensor.strompreis') | float(none) %}
          {% set old_avg_price = this.state | float(0) %}
          
          {# --- FAILSAFE: Check for unavailable sensors --- #}
          {% if current_energy_kwh is none or power_grid_w is none or power_pv_w is none or price_grid is none %}
            {% set final_price = old_avg_price if old_avg_price > 0 else 0.00 %}
          {% else %}
            
            {# Usable energy above the 6.8 kWh floor #}
            {% set circulating_energy_kwh = [current_energy_kwh - ENERGY_FLOOR_KWH, 0] | max %}
            {% set total_power_w = power_grid_w + power_pv_w %}
            {% set final_price = old_avg_price %}
            
            {# Precise time tracking between updates #}
            {% set time_delta_seconds = (now() - this.last_updated).total_seconds() | float(1) %}
            {% set time_delta_hours = time_delta_seconds / 3600 %}
            
            {# --- CHARGING LOGIC --- #}
            {% if total_power_w > 10 and time_delta_seconds > 0.01 %}
              
              {# Calculate added energy in kWh #}
              {% set added_grid_kwh = (power_grid_w / 1000) * time_delta_hours %}
              {% set added_pv_kwh = (power_pv_w / 1000) * time_delta_hours %}
              {% set added_total_kwh = added_grid_kwh + added_pv_kwh %}
              
              {# Apply Efficiency Loss Factor only to the NEWLY added costs #}
              {% set cost_grid_effective = added_grid_kwh * price_grid * EFFICIENCY_LOSS_FACTOR %}
              {% set cost_pv_effective = added_pv_kwh * price_pv * EFFICIENCY_LOSS_FACTOR %}
              {% set cost_added_effective = cost_grid_effective + cost_pv_effective %}
              
              {# Estimate state BEFORE this update for mathematical consistency #}
              {% set prev_circulating_energy = [circulating_energy_kwh - added_total_kwh, 0] | max %}
              
              {# Value of existing inventory #}
              {% set value_old = prev_circulating_energy * old_avg_price %}
              
              {# Weighted average calculation #}
              {% set new_total_value = value_old + cost_added_effective %}
              {% set new_circulating_energy = prev_circulating_energy + added_total_kwh %}
              
              {% if new_circulating_energy > 0.01 %}
                {% set final_price = new_total_value / new_circulating_energy %}
              {% else %}
                {% set final_price = 0.00 %}
              {% endif %}
            
            {% else %}              
              {# --- DISCHARGING / STANDBY --- #}
              {% if circulating_energy_kwh < 0.01 %}
                 {% set final_price = 0.00 %}
              {% else %}
                 {# Hold price during discharge or until new energy is added #}
                 {% set final_price = old_avg_price if old_avg_price > 0 else price_grid %}
              {% endif %}
            {% endif %}
          {% endif %}
          
          {{ final_price | float(0) | round(4) }}

Originally posted by @rockinglama in https://github.com/ohAnd/EOS_connect/issues/172#issuecomment-3677994551

ohAnd avatar Dec 20 '25 18:12 ohAnd

@rockinglama thanks for the insights - based on the idea I tried it with historic data ... and it seems ;-) right ...

please check the current dev ... it needs some additional config at

battery:
    ...
    price_calculation_enabled: false # Enable dynamic battery price calculation based on history - default: false
    price_update_interval: 900 # Interval for price update in seconds - default: 900 (15 min)
    price_history_lookback_hours: 96 # Hours of history to analyze for price calculation - default: 96
    battery_power_sensor: "" # HA entity ID or OpenHAB item for battery power in W (positive = charging)
    pv_power_sensor: "" # HA entity ID or OpenHAB item for PV power in W
    grid_power_sensor: "" # HA entity ID or OpenHAB item for grid power in W (positive = import)
    load_power_sensor: "" # HA entity ID or OpenHAB item for load power in W
    price_sensor: "" # HA entity ID or OpenHAB item for electricity price in €/kWh or ct/kWh
    charging_threshold_w: 50.0 # Minimum battery power to consider as charging (W) - default: 50.0
    grid_charge_threshold_w: 100.0 # Minimum grid surplus to consider as grid charging (W) - default: 100.0

approach in short: find all charging sessions in the last (default) 96 hours and check how much usable energy is currently stored - with that amount check the recent charging sessions and it's price sources (0=pv or dyn/fix grid price at useful slices) and calculate the price per Wh for the usable stored energy...

in the webui there is a new visulization via menu or direct click at the battery state icons: (unfortunately - battery was ruinning empty shortly before the screenshot ;-)) Image


some feedback would be valuable ;-)

ohAnd avatar Dec 22 '25 20:12 ohAnd

I just set up the new feature as well and already a small feedback: EVCC reports negative numbers for battery power when it's being charged. Since I guess most EOS users will use it together with EVCC might make sense to change it or add a toggle control for it in the config?

nanoBit93 avatar Dec 23 '25 09:12 nanoBit93

@nanoBit93 is this given as always 0 or < 0 ? or it's a +/- sensor means '-' for charging and '+' for discharging the battery? I want to avoid to much config ... simplest way - the incoming value will be used as absolute - other ones with sensors + and - can use a small helper ... or maybe an automatic detection ...

ohAnd avatar Dec 23 '25 09:12 ohAnd

@ohAnd here is what it looks like on my end:

Image

My 'Stored Energy Price' is always displaying '0'. I have assigned my Tibber sensor to the price_sensor, which outputs in EUR/kWh."

FidoWue avatar Dec 27 '25 16:12 FidoWue

@ohAnd here is what it looks like on my end:

...

My 'Stored Energy Price' is always displaying '0'. I have assigned my Tibber sensor to the price_sensor, which outputs in EUR/kWh."

Looks right "if" there were no grid charging - then it is assumed for now as 0 €/kWh (details to bring in storage life time costs etc. can be discused later)

short explanation what you see:

  • all chargings in the recent 96h were be extracted
  • e.g. yesterday 9:43 (started) for 3.4 hours and it was given by the sensor data:
  • a PV charge with 5.996 kWh (minor part of 0.017 grid charge is something for more detailing later of tresholds inner the calculation)
  • and then today same for 3.3 hours with a sum of 5.566 kWh ~ 100% PV charge
  • the current soc of your battery shows a usable capacity (depending on min soc / bat capacity in config) of 3.6 kWh
  • only for this amount of energy it will be looked backwards for the price aggregation -> stored 3.643 (in green in the table)
  • and this was full in PV-Charge - so a price of 0 €/kWh for the stored usable energy will be given to the optimizer

Thanks for testing!

ohAnd avatar Dec 27 '25 17:12 ohAnd

Looks right "if" there were no grid charging

yes, that is right.

FidoWue avatar Dec 27 '25 19:12 FidoWue

@ohAnd i got 12 warnings today:

[BATTERY-PRICE] No energy charged in identified events

FidoWue avatar Dec 27 '25 21:12 FidoWue

@ohAnd With grid charging:

Image

FidoWue avatar Jan 01 '26 21:01 FidoWue

OMG, what an awesome feature! HYPED!

Popoboxxo avatar Jan 05 '26 00:01 Popoboxxo

fyi #195

Popoboxxo avatar Jan 08 '26 13:01 Popoboxxo

I am using EOS‑Connect together with Home Assistant, and I noticed that the battery_price_handler frequently produces warnings like this during nighttime: PV≈0 but PV attribution occurred | sensor_age: pv=50000s My PV sensor correctly reports 0 W during the night. However, because the value does not change for several hours, Home Assistant does not create new entries in the history database. EOS‑Connect reads the historical data via the HA History API and interprets these old entries as “stale”, even though the sensor is functioning normally.

Root Cause • Home Assistant only stores state changes in its history database. • Template sensors with a constant value (e.g., PV = 0 W at night) do not generate new history entries. Even if I try to set an dummy attribute every second • EOS‑Connect relies on the history timestamps to determine sensor freshness. • As a result, PV values are incorrectly treated as outdated. • This leads to wrong attribution: battery charging is incorrectly classified as PV‑powered instead of grid‑powered.

Impact • PV contribution is massively overestimated. • Grid charging is misinterpreted as PV charging. • Cost calculations become inaccurate.

Suggested Improvements

  1. If PV=0 , ignore sensor age. Zero PV at night is expected and should not trigger stale‑sensor logic.
  2. Only apply sensor age checks when the value is > 0.
  3. Optional: Add a configuration option to define acceptable sensor age thresholds per sensor type.

treffer-priv avatar Feb 09 '26 09:02 treffer-priv