EMHASS: An Energy Management for Home Assistant

You should be able to set a start and stop timestep. See → An EMS based on Linear Programming — emhass 0.10.3 documentation look for Time windows for deferrable loads

I’m only just looking into it myself for the same reason (Demand Tariff).

  • def_start_timestep: The timestep as from which each deferrable load is allowed to operate (if you don’t want the deferrable load to use the whole optimization timewindow). If you specify a value of 0 (or negative), the deferrable load will be optimized as from the beginning of the complete prediction horizon window. For example:
    • 0
    • 1
  • def_end_timestep: The timestep before which each deferrable load should operate. The deferrable load is not allowed to operate after the specified timestep. If a value of 0 (or negative) is provided, the deferrable load is allowed to operate in the complete optimization window). For example:
    • 0
    • 3

I don’t think the battery is a deferable load though, when you enable the battery in EMHASS the optimisation calculates the best time to charge and discharge the battery based on the cost (whether that’s from the grid or from solar).

1 Like

Ok you’re trying to stop the battery from charging between 3:00 and 8:30. I don’t seem to have that problem. (so far) But perhaps I need to think about it.

I don’t have a battery (yet).
But can you pass "SOCtarget": {{ states("sensor.current_soc")}} "soc_final": {{ states("sensor.current_soc")}} at runtime?

I am passing soc_final, but as I run it every minute it’s calculating that for in 24 hours time.

I think I’ve been able to work this out (no doubt I’ve done this the longest way possible with superfluous code ), but it seems to correctly assign a cost of $1 per kWh for the demand tariff period which means my optimisation doesn’t try and charge the battery during this time.

Here’s what I’m using in my REST command

      "load_cost_forecast":
      {% set current_time = now() %}
      {% set demand_tariff = ["15:00:00","21:00:00"] %}
      {% set start_time = current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(hours=(demand_tariff[0].split(":")[0]|int), minutes=(demand_tariff[0].split(":")[1]|int)) %}
      {% if start_time <= current_time %}
        {% set start_time = start_time + timedelta(days=1) %}
      {% endif %}
      {% set start_time_difference = start_time - current_time %}
      {% set end_time = current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(hours=(demand_tariff[1].split(":")[0]|int), minutes=(demand_tariff[1].split(":")[1]|int)) %}
      {% if end_time <= current_time %}
        {% set end_time = end_time + timedelta(days=1) %}
      {% endif %}
      {% set end_time_difference = end_time - current_time %}
      {% set start_window = max(0,start_time_difference.total_seconds() / 3600 * 2)|int(0) %}
      {% set end_window = max(0,end_time_difference.total_seconds() / 3600 * 2)|int(0) %}
      {% set values = ([states("sensor.amber_general_price")|float(0)] + state_attr("sensor.amber_general_forecast", "forecasts")|map(attribute="per_kwh")|list)[:48] %}
      {% set ns = namespace( x=[]) %}
      {% if end_window < 12 %}
        {% for y in values[0:end_window+1] %}
          {% set ns.x = ns.x + [1|float(2)] %}
        {% endfor %}
        {% for y in values[end_window+1:start_window+1] %}
          {% set ns.x = ns.x + [y|round(2)] %}
        {% endfor %}
        {% for y in values[start_window+1:48] %}
          {% set ns.x = ns.x + [1|float(2)] %}  
        {% endfor %}   
        {{ ns.x }}
      {% else %}
        {% for y in values[0:start_window+1] %}
          {% set ns.x = ns.x + [y|round(2)] %}{% endfor %}
        {% for y in values[start_window+1:end_window+1] %}
          {% set ns.x = ns.x + [1|float(2)] %}{% endfor %}
        {% for y in values[end_window+1:48] %}
          {% set ns.x = ns.x +  [y|round(2)] %}{% endfor %}
        {{ ns.x }}
      {% endif %},

Hi all,

sorry to come up with maybe dumb newbie questions (newbie to EMHASS, …). I have some experience with HA automations and templates, but none with NodeRed (but that should be manageable if needed), and some 20 years Linux administration

I’m planning to use EMHASS in a perhaps a bit complex environment:

  • PV modules on 4 roofs (2x west, 2x east)
  • 2x Deye Hybrid High Voltage inverters
  • each of which has a HV battery (Enerlution)
  • HA running supervised in a Debian virtual machine
  • hourly energy prices (Tibber Germany)
  • fixed amount for energy sold to the grid (0.0744 EUR/kWh)
  • three deferrable loads (washing machine, dishwasher, tumble dryer)

I do have a high 24/7 consumption due to some servers running 24/7, so the batteries do not last the whole night, sometime between 4am and 6am they are empty, normally.

The Deye inverters are connected to HA via Modbus and the Sunsyk/Deye Add-On.
Grid sell/buy is currently read from the energy meter, has to be switched to Tibber integration, I guess (Tibber Pulse needed, at that blocks the IR interface I’m currently using).
All loads are genuinely dump, but are controlled by ZigBee smart plugs with energy metering.
I have modeled the 4 PV strings in Forecast.Solar. Tibber should give the day-ahead-prices via the HA integration, I hope.

The goal is to minimize overall energy cost:

  • don’t run deferrable loads in peak cost hours (which vary from day to day)
  • possible load batteries from grid if suitable (this one is tricky, as a) the price difference between buy at night for charging and consumption during peak/next day has to be sufficiently high, taking into account 20% charge/discharge loss)
  • but only charge battery during night enough to cover the morning price peak and not block charging from PV during the rest of the day
  • no discharge to grid from battery (that’s not allowed under German EEG rules)

4 strings= with 18, 16, 12 and 12 modules, bifacial 430Wp each
both inverters have a 10 kWh Enerlution GroundHV-2500 battery pack each

I’m pretty sure I got some good grasp of the EMHASS concepts, but I do have problems/challenges in translating this into HA configs/automations.

Challenges:

  • I can’t find any Deye inverter in https://emhass-pvlib-database.streamlit.app/ - I have
    two Deye SUN-10K-SG01HP3-EU-AM2 (master/slave mode)
  • I can’t find the PV modules there either: bifacial (there is not a single bifacial JA Solar module in the database) JA Solar JAM5-4D41-430/LB - 430Wp, Voc=38,5V, Vmp=32.12V, Isc=14.14A, Imp=13.39A
  • I do not know how to get the day-ahead prices from Tibber integration into EMHASS
  • I am not totally sure how to get the Forecast.Solar values for the 4 configured roofs into EMHASS
  • I did find some examples how to switch the deferrable loads on and off using values from EMHASS with HA automations, but I do not completely understand them
  • the biggest challenge for me is the control of battery charging: Deye uses “Time of use” timetables with 6 timeslots, each having a switch for “Grid Charge” (fine), “start time”, “end time” (represented in HA as “select.*” entities via the Sunsyk/Deye-Addon, a “POWER” input variable and a “SOC” input entity. The select entities’ step size can be configured in the Sunsyk-Addon, default is 15 minutes. I honestly have no idea which values from EMHASS have to go into that - and even less of an idea of how to write an automation that feeds these values into the inverters (using the Sunsyk Addon) (a set of NodeRed flows would to as well, I guess)

Any example or hint where to find more specific information of howtos … all very welcome.

Thanks in advance

I’ll try to answer some of the questions:

Then just don’t set anything, use either the Solcast or the Solar.Forecast methods.

In EMHASS you pass this type of data at runtime, this is in a template on the shell command that you will be using in the automation to launch the energy optimization.
Here is the example for Nordpool: https://emhass.readthedocs.io/en/latest/forecasts.html#example-using-the-nordpool-integration

Some info here: https://community.home-assistant.io/t/forecast-solar-forecast-with-panels-on-both-sides-of-the-roof/475071
Otherwise we can go back to challenge number 1 and try to find an inverter and PV module in the DB with similar nominal powers as yours.

Here are the examples: https://emhass.readthedocs.io/en/latest/intro.html#common-for-any-installation-method
What part you don’t understand?

Yes this is the hardest part. You will need to figure out how to set values on your battery yourself or find someone with the same model as yours and look for help.
From EMHASS you basically will have the optimal SOC (state of charge) trajectory and also the charge/discharge powers that are related to that SOC. Now you need to build a custom automation to tell your battery to follow that SOC as close as possible. This is hardly generalizable and depends/differs on the various battery manufacturers out there.

Don’t know if it would help but my config using mostly node red is here EMHASS: An Energy Management for Home Assistant - #1027 by rcruikshank

I have setup an EMHASS instance with a dual deye inverter setup, so the battery automation should work directly for you.

We setup four scripts to control the battery:

alias: Grid Power Forecast Automation - Battery VDC based
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.p_grid_forecast
    to: null
    enabled: false
  - platform: time_pattern
    minutes: /3
condition:
  - condition: state
    entity_id: sensor.optim_status
    state: Optimal
action:
  - choose:
      - conditions:
          - condition: numeric_state
            entity_id: sensor.p_grid_forecast
            above: 5000
          - condition: numeric_state
            entity_id: sensor.p_batt_forecast
            below: -5000
        sequence:
          - service: script.turn_on
            metadata: {}
            data: {}
            target:
              entity_id: script.charge
        alias: Charge from Grid at MAX rate
      - conditions:
          - condition: numeric_state
            entity_id: sensor.p_grid_forecast
            below: -900
          - condition: numeric_state
            entity_id: sensor.p_batt_forecast
            above: 1000
          - alias: When Battery Voltage is above 49.5VDC
            condition: numeric_state
            entity_id: sensor.sunsynk_battery_voltage
            above: 49.2
        sequence:
          - service: script.turn_on
            metadata: {}
            data: {}
            target:
              entity_id: script.discharge
        alias: Discharge to Grid at MAX rate
      - conditions:
          - condition: numeric_state
            entity_id: sensor.p_grid_forecast
            below: -900
          - condition: numeric_state
            entity_id: sensor.p_batt_forecast
            above: 1000
          - alias: When Battery Voltage is below 49.5VDC
            condition: numeric_state
            entity_id: sensor.sunsynk_battery_voltage
            below: 49.2
        sequence:
          - service: script.turn_on
            metadata: {}
            data: {}
            target:
              entity_id:
                - script.discharge_battery_to_load_only_grid_off
        alias: Discharge to Load only at low SoC
      - conditions:
          - alias: When Battery_power_forecast = 0
            condition: numeric_state
            entity_id: sensor.p_batt_forecast
            below: 0.1
            above: -0.1
          - condition: numeric_state
            entity_id: sensor.p_grid_forecast
            above: 0.1
        sequence:
          - service: script.turn_on
            metadata: {}
            data: {}
            target:
              entity_id:
                - script.maintain_soc_consume_grid_pv
        alias: Consume Grid, no Charge
    default:
      - service: script.turn_on
        metadata: {}
        data: {}
        target:
          entity_id: script.discharge_battery_to_load_only_grid_off
mode: single




Wish the powerwall had this level of control, we are looking at moving to the country soon so will be looking at batteries that have local control.

Speaking off is there any way to tell EMHASS that a powerwall can only charge at particular rates e.g. 1kw or 5kw if TOU is used?

Agreed on the Powerwall front.

Moves afoot to get greater control but I’m not sure Tesla are that interested, although they did open FleetAPI up to open source yesterday.

https://developer.tesla.com/docs/fleet-api#faq

My experience is TBC sets it’s own charging rates, but they do vary with price (I’m injecting Amber price).

I can control difference charging rates 1.7 kW (raise SOC), 3.3 kW (backup mode), 5 kW (TBC+ OFFPEAK), but can only get one discharge rate 5 kW (TBC + PEAK).

1 Like

So I have a situation like this now where their’s a plan to charge the battery after 3pm which is inside the demand tariff window:


I think what I’ll do is intercept any command to charge the battery between 3 and 8:30 and change it to a command to put the battery into self management mode where it will charge if there is available PV production only.

Current node red flow:

Demand tariff change:

It’s not perfect but not sure how I can change the charge calculation to take into account the costs of the demand tariff?

Does this sound logical?

What you’re proposing here is what I initially did and logically correct. However what happened is EMHASS thought it was going to charge from the grid at 15:00 when the price was really low (don’t get me started about super low prices during the demand window…) in preparation for discharging from the grid in the evening but my intervention stopped it from doing so and was not as ready for the peak period as it thought it would be.

I think I worked out a solution above (EMHASS: An Energy Management for Home Assistant - #2484 by altonius) that basically changes the prices in the demand window to $1 per kWh. So EMHASS modeling doesn’t even consider charging from the grid during that time.
Short version of what it does is:

  1. Compare the current time and work out which window (From 0-48) the start and end times will be for the demand window
  2. Capture the list of the next 48 load prices from Amber
  3. If demand window has already started swap out the from 0 to the end period with “1.00”, then copy the amber prices from end to the start period, then do from the start period to 48 with “1.00”.
  4. Elseif for 0 to the start period copy the amber prices, then from start to end period swap with “1.00”, then from end period to 48 with the amber prices.

Then I pass the new list to my MPC optimisation I run each minute (instead of the usual amber list)

2 Likes

yes I see what you mean. I’ll have a look at you code or implement somehting to charge to 100% between 2 and 3. Your solution might be cleaner though.

this is how I do it with deye inverters. just chnage soc time of use and if delay solar charge set amps 0:

getting an odd error when upgrading the add-in to 0.10.6

1 Like

Same here.

You can try now, it should be solved.
For some unknown reason the github automatic build failed. I’ve manually launched the rebuild and now worked fine.
However it is still failing for arm architectures (Raspberry Pis)

2 Likes

evcc has a realy nice user interface specficly for EV charging and integrates nicely with home assistant (runs as an add-on and since recently also has an integration to control evething trough Home Assistant. Have a look at UI here evcc It controls charging power (solar, net) and has a templating system in place that allow you to easily connect to chargers (OCPP or modbus or API), EV’s, invertors, home batteries, power meters directly or trough home assistant. It also comes with a “planner” that allows you to set a desired SoC at a moment in the future and it wil create the plan taking solar and dynamic pricing into account. I am currently also looking for the best way to get this integrated in a way that evcc can be used to set the plan but EMHASS does it’s thing taking into account all other deferrable loads around the house. So basicly a translation of the plan (the number of kwh’s it needs) to a deferable load definition in EMHASS and an automation of to set charging according to the plublished EMHASS deferable load planning and let evcc (trough HA) do it’s thing with charging power limits.

Charging plan UI

The evcc HA integration

Another nice feature in evcc that is missing in emhass (or I haven’t found it in the docs yet) at the moment is to optimise charging depending on CO2 emissions instead of only looking at energy prices.

So basicly why evcc? : the UI and the nice integrations with specific charging stations etc that are not always availalbe as an integration in Home Assistant directly…