Modified copy of sensor containing array in attributes

I’ve been searching for how to copy the following sensor and add to its values. The source sensor contains electricity prices for the day and tomorrow in an array each. As the values here do not include energy tax and transfer costs I’d like to make a copy of this sensor that includes these. The energy tax and transfer cost are available in other sensors. This is how the source sensor data looks like. Tomorrow is empty but populates the same way once prices are available.

today:
  - total: 0.2292
    startsAt: '2023-10-18T00:00:00.000+02:00'
  - total: 0.2277
    startsAt: '2023-10-18T01:00:00.000+02:00'
  - total: 0.2248
    startsAt: '2023-10-18T02:00:00.000+02:00'
  - total: 0.2275
    startsAt: '2023-10-18T03:00:00.000+02:00'
  - total: 0.2382
    startsAt: '2023-10-18T04:00:00.000+02:00'
  - total: 0.2523
    startsAt: '2023-10-18T05:00:00.000+02:00'
  - total: 0.8023
    startsAt: '2023-10-18T06:00:00.000+02:00'
  - total: 1.1543
    startsAt: '2023-10-18T07:00:00.000+02:00'
  - total: 2.3642
    startsAt: '2023-10-18T08:00:00.000+02:00'
  - total: 1.7918
    startsAt: '2023-10-18T09:00:00.000+02:00'
  - total: 1.3433
    startsAt: '2023-10-18T10:00:00.000+02:00'
  - total: 1.0724
    startsAt: '2023-10-18T11:00:00.000+02:00'
  - total: 1.0205
    startsAt: '2023-10-18T12:00:00.000+02:00'
  - total: 1.0123
    startsAt: '2023-10-18T13:00:00.000+02:00'
  - total: 0.9807
    startsAt: '2023-10-18T14:00:00.000+02:00'
  - total: 0.847
    startsAt: '2023-10-18T15:00:00.000+02:00'
  - total: 0.9003
    startsAt: '2023-10-18T16:00:00.000+02:00'
  - total: 0.9619
    startsAt: '2023-10-18T17:00:00.000+02:00'
  - total: 0.9899
    startsAt: '2023-10-18T18:00:00.000+02:00'
  - total: 0.8661
    startsAt: '2023-10-18T19:00:00.000+02:00'
  - total: 0.8059
    startsAt: '2023-10-18T20:00:00.000+02:00'
  - total: 0.5982
    startsAt: '2023-10-18T21:00:00.000+02:00'
  - total: 0.2461
    startsAt: '2023-10-18T22:00:00.000+02:00'
  - total: 0.221
    startsAt: '2023-10-18T23:00:00.000+02:00'
tomorrow: []
friendly_name: Tibber Prices

What I’ve tried to do is to create a Trigger Template Sensor that in the value block copies the attributes and then tries to loop through them to increment. What doesn’t work is that I can’t seem to modify the values. I have played around in the template dev tool and am getting a namespace error along the lines of the variable I’m trying to assign not being a member of the namespace. I think that should not be nescesarry as the variable I want to edit is available there to read already.

Here is a start as a sensor

 - trigger:
     - platform: state
       entity_id: sensor.tibber_prices
   sensor:
     - name: tibber_prices_with_fees
       state: >
         {{ trigger.to_state }}
       attributes:
         Today: >
           {% set todays_prices = state_attr('sensor.tibber_prices', 'today') %}
           {% for hour in todays_prices %}
             {% set hour['total'] += states('sensor.energy_and_tax') %}
           {% endfor %}
           {{ todays_prices }}

Maybe this will help, I am updating a reference sensor for forecast so I can check how much it deviates throughout the day. It uses the HACS script that you can find on HACS/automations

service: python_script.hass_entities
data:
  action: set_state_attributes
  entity_id: input_text.forecast_solar_0600
  state: "{{ 'Switched on at '~ now().strftime('%H.%M') }}"
  attributes:
    - icon: mdi:home
    - result: "{{ state_attr('sensor.solar_forecast_watt_hours_period_2','result') }}"

You are falling foul of the scope of variables, and need to use a namespace. Like this:

{% set todays_prices = [1, 2, 3] %}
{% set tax = 2 %}
{% set ns = namespace(tp_with_tax=[]) %}
{% for price in todays_prices %}
  {% set ns.tp_with_tax = ns.tp_with_tax + [price + tax] %}
{% endfor %}
{{ ns.tp_with_tax }}

If the tax were multiplied and not added, you could simply do:

{{ LIST_HERE|map('multiply', TAX_RATE_HERE)|list }}

but there is no add filter.

EDIT: I’m a genius, here’s a hacked-up add filter:

{{ LIST_HERE
   |batch(1)
   |map('sum', start=TAX_SENSOR|float(0))
   |list }}

If you want to totally recreate the structure of the original, here’s an example:

{% set todays_prices = [{'total':0.2292,
                         'startsAt': '2023-10-18T00:00:00.000+02:00'},
                        {'total':0.2277,
                         'startsAt': '2023-10-18T01:00:00.000+02:00'}] %}
{% set tax = "42" %}
{% set ns = namespace(tp_with_tax=[]) %}
{% for price in todays_prices %}
  {% set ns.tp_with_tax = ns.tp_with_tax + [{'total': price['total'] + tax|float(0),
                                             'startsAt': price['startsAt'] }] %}
{% endfor %}
{{ ns.tp_with_tax }}

@vingerha thanks for your reply. I have looked in HACS automations for hass_entities or something matching attributes but came up empty handed. I also do not understand how your sensor has multiple values (array). It seems from the code you posted there is only one entry under the result attribute?

Updated:

- trigger:
    - platform: state
      entity_id: sensor.tibber_prices
  sensor:
    - name: tibber_prices_with_fees
      state: >
        {{ trigger.to_state.state }}
      attributes:
        Today: >
          {% set todays_prices = state_attr('sensor.tibber_prices', 'today') %}
          {% set modified_prices = [] %}
          {% set energy_tax = states('sensor.energy_and_tax') | float %}
          {% set ns = namespace(tp_with_fees=[]) %}
          {% for hour in todays_prices %}
            {% set updated_hour = hour.copy() %}
            {% set updated_hour.total = hour.total + energy_tax %}
            {% set ns.tp_with_fees = ns.tp_with_fees + [updated_hour] %}
          {% endfor %}
          {{ ns.tp_with_fees }}

That won’t work:

You must use a namespace as in my post above. The inside of the for loop is a different scope to the outside, so your attempt to extend the array fails.

try my update, otherwise i did try to help you but failed…

regards

Thanks! I managed something based on your example. Did not seem to update so I added another trigger and now seems to work.

- trigger:
    - platform: state
      entity_id: sensor.tibber_prices
    - platform: time_pattern
      minutes: 15
  sensor:
    # Tibber + Eon
    - name: Electricity Prices Combined
      state: >
        {{ states('sensor.tibber_prices') }}
      attributes:
        today: >
          {% set tax = states('input_number.electricity_transfer_cost_per_kwh') | float + states('input_number.electricity_energy_tax_per_kwh') | float %}
          {% set ns = namespace(tp_with_tax=[]) %}
          {% set todays_prices = state_attr('sensor.tibber_prices', 'today') %}
          {% for price in todays_prices %}
            {% set ns.tp_with_tax = ns.tp_with_tax + [{'total': price['total'] + tax|float(0),
                                                      'startsAt': price['startsAt'] }] %}
          {% endfor %}
          {{ ns.tp_with_tax }}
        tomorrow: >
          {% set tax = states('input_number.electricity_transfer_cost_per_kwh') | float + states('input_number.electricity_energy_tax_per_kwh') | float %}
          {% set ns = namespace(tp_with_tax=[]) %}
          {% set tomorrow_prices = state_attr('sensor.tibber_prices', 'tomorrow') %}
          {% for price in tomorrow_prices %}
            {% set ns.tp_with_tax = ns.tp_with_tax + [{'total': price['total'] + tax|float(0),
                                                      'startsAt': price['startsAt'] }] %}
          {% endfor %}
          {{ ns.tp_with_tax }}

I really like how clean this looks! Very readable. I just got it working by @Troon 's example but I may just refactor and try your solution for how nice it looks. Thanks! :+1:

Hi How does your “input_number:el_transfer-cost” looks like , i have as you Tibber and EON, but currently just have various simple Templates, in a simple view. For current and used energy.
18.10.2023_22.03.36_REC

template:
  - sensor:
      - name: "Total Price"
        unit_of_measurement: "Sek/kWh"
        state: >
          {{ (states('sensor.electricity_price_***') | float + 1.1135) | round(2) }}
  - sensor:
      - name: "Total Cost"
        unit_of_measurement: "Sek"
        state: >
          {{ (states('sensor.monthly_net_consumption_***') | float * 1.1135) | round(2) + 
            (states('sensor.monthly_cost_***') | float + 181.25) | round(2) }}

I don’t know how often EON changes their “transfer-costs” and subscription-price(which i just added in “Total Cost - Month” ), but been thinking of an “input-entity”

Hi
Not sure what you mean with how the input_number looks. It’s just a helper declared either in the GUI or yaml. I am not getting the fees with any automation if that’s what you mean but enter them manually. I tend to look at the last bill and correct if needed. Of course, then I’m a month off if anything changes, but don’t know any better way currently to figure it out. Maybe the information is available somewhere online and a scraper could be used to fetch it. That’s a future project however. :slightly_smiling_face: haven’t actually googled to see if there is an easy way already available.

great to hear :slight_smile:

1 Like

OK, i thought you maybe had an “input_number” with some template(fetching it), and had your subscription cost included also (“divided” in some way, i.e down to per/Kwh level), and yes the info is available on EON’s website
either login:
https://www.eon.se/el/elnat/kostnad#/customer
Or download a “general” pdf
https://www.eon.se/el/elnat/avgift#elnatsavgifter
In both you’ll informed about the covering period, but who knows how companies like EON act, sometimes they “figure” out that they have to squeeze a little extra out of peoples wallet :slight_smile:
( And as i have auto-giro, i never look at my bills :thinking: )

So actually, half of your equations is a bit over-worked , as the 2 manually input_number.*** , entities, is just 1 sum ( currently 1.1135/for 16A, in area 4) … the rest of the year, cording to EON’s current “ideas/need” :slight_smile:

PS: if you are using very little Kwh ( i.e 300 Kwh a month And your monthly subscr-price is 181.25 you could/should add 0.6 per/Kwh(181.25 / 300kwh ), seems to me as an essential “sum” in such a forecast
I.e
electricity price. including fee + tax / per Kwh = 0.25
Transfercost + energy price+ tax / per Kwh = 1.1135
Subscr price for using 300Kwh/M / per Kwh = 0.6

One way to consider could be to use a changedetect.io container to fetch the data. I’m just starting to play with this tool myself but haven’t had enough time to get anything working with HA just yet.

And i hardly mentioned this, before the NEWS presented the “soon coming” increased transfer/energy cost, or was it Subscription cost :frowning: , they are incredible