How do you set value in a sensor and retain it.. each reboot looses it

hi im trying to make some Last month Entity Power usage… and i set automation to run at the end of the month at 23:59:00 now it basicly works i can get it to set the state… but when i reboot home assistant it sets it to unavliable

here is the templates

        - name: "Last Months Power Usage Total"
          state: "{{ states('sensor.last_months_power_usage_total') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_total') }}"

        - name: "Last Months Power Usage On-Peak"
          state: "{{ states('sensor.last_months_power_usage_on_peak') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_on_peak') }}"
        - name: "Last Months Power Usage Mid-Peak"
          state: "{{ states('sensor.last_months_power_usage_mid_peak') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_mid_peak') }}"
        - name: "Last Months Power Usage Off-Peak"
          state: "{{ states('sensor.last_months_power_usage_off_peak') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_off_peak') }}"

        #############################################
        #### Last Months Electricity Usage Costs ####
        #############################################
        - name: "Last Months Power Usage Total Cost"
          state: "{{ states('sensor.last_months_power_usage_total_cost') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_total_cost') }}"

        - name: "Last Months Power Usage On-Peak Cost"
          state: "{{ states('sensor.last_months_power_usage_on_peak_cost') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_on_peak_cost') }}"
        - name: "Last Months Power Usage Mid-Peak Cost"
          state: "{{ states('sensor.last_months_power_usage_mid_peak_cost') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_mid_peak_cost') }}"
        - name: "Last Months Power Usage Off-Peak Cost"
          state: "{{ states('sensor.last_months_power_usage_off_peak_cost') }}"
          availability: "{{ has_value('sensor.last_months_power_usage_off_peak_cost') }}"

and my automation is

alias: Energy - Set Last Month's Power Usage
description: ""
triggers:
  - trigger: time
    at: "23:59:00"
conditions:
  - condition: template
    value_template: "\"{{ (now() + timedelta(days=1)).day == 1 }}\""
actions:
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_total
      state: "{{ states('sensor.current_monthly_consumption')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_on_peak
      state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_mid_peak
      state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_off_peak
      state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_total_cost
      state: "{{ states('sensor.current_monthly_consumption')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_on_peak_cost
      state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak_cost')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_mid_peak_cost
      state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak_cost')}}"
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: sensor.last_months_power_usage_off_peak_cost
      state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak_cost')}}"
mode: single

what am i doing wrong that its buggering up my sensor on reboot
its acting like a switch going connected and unavliable when it looses wifi connection
here is screen shot of one of them

It’s because of this action: python_script.set_state

You probably noticed that there’s no native action for setting a sensor entity’s state. That’s by design; its state value is meant to updated exclusively by its underlying integration.

You used a custom python_script to, effectively, “poke” a value into the state machine. However, that technique produces an ephemeral value; it doesn’t survive a restart.

Instead of an automation that attempts to set the values of Template Sensors, I suggest you consider creating Trigger-based Template Sensors (their state value survives a restart).

template:
  - trigger:
      - trigger: template
        value_template: >
          {{ (now().hour, now().minute) == (23, 59) and (now() + timedelta(days=1)).day == 1 }}
    sensor:
      - name: Last Months Power Usage Total
        unique_id: last_months_power_usage_total
        state: "{{ states('sensor.current_monthly_consumption') }}"
      - name: Last Months Power Usage On Peak
        unique_id: last_months_power_usage_on_peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak') }}"
      - name: Last Months Power Usage Mid Peak
        unique_id: last_months_power_usage_mid_peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak') }}"
      - name: Last Months Power Usage Off Peak
        unique_id: last_months_power_usage_off_peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak') }}"
      - name: Last Months Power Usage Total Cost
        unique_id: last_months_power_usage_total_cost
        state: "{{ states('sensor.current_monthly_consumption') }}"
      - name: Last Months Power Usage On Peak Cost
        unique_id: last_months_power_usage_on_peak_cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak_cost') }}"
      - name: Last Months Power Usage Mid Peak Cost
        unique_id: last_months_power_usage_mid_peak_cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak_cost') }}"
      - name: Last Months Power Usage Off Peak Cost
        unique_id: last_months_power_usage_off_peak_cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak_cost') }}"

@123 it didnt work i added the boot on HA restart

    - trigger:
        - trigger: template
          value_template: >
            {{ (now().hour, now().minute) == (23, 59) and (now() + timedelta(days=1)).day == 1 }}
        - trigger: homeassistant
          event: start

and when it boots up it sets the sensors to unknown and when HA says its started it turns the all the values to unavliable

are my templates wrong?
i also had to look up what the word ephemeral ment lol

and i was hoping to figure a way you could just have a sensor that read the last months data and put it in the sensor… like from all the line charts… but i couldnt find anything so me doing it this way was best way i could figure out how to do a a reading of previous months cost and usage
once this works i plan to do yesterdays and Last weeks power usage… i wish there was easier way unless there is a way but this seemed best i could do


her is screen shot of one sensor with ur coding

Copy-paste this into the Template Editor and let me know what it reports.

      - name: Last Months Power Usage Total
        state: "{{ states('sensor.current_monthly_consumption') }}"
      - name: Last Months Power Usage On Peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak') }}"
      - name: Last Months Power Usage Mid Peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak') }}"
      - name: Last Months Power Usage Off Peak
        state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak') }}"
      - name: Last Months Power Usage Total Cost
        state: "{{ states('sensor.current_monthly_consumption') }}"
      - name: Last Months Power Usage On Peak Cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak_cost') }}"
      - name: Last Months Power Usage Mid Peak Cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak_cost') }}"
      - name: Last Months Power Usage Off Peak Cost
        state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak_cost') }}"
- name: Last Months Power Usage Total
        state: "311.1"
      - name: Last Months Power Usage On Peak
        state: "14.46"
      - name: Last Months Power Usage Mid Peak
        state: "50.80"
      - name: Last Months Power Usage Off Peak
        state: "24.90"
      - name: Last Months Power Usage Total Cost
        state: "311.1"
      - name: Last Months Power Usage On Peak Cost
        state: "0.079"
      - name: Last Months Power Usage Mid Peak Cost
        state: "0.0"
      - name: Last Months Power Usage Off Peak Cost
        state: "0.0"

so least the template editor showing the values at least

For testing purposes, replace the existing triggers with a Time Trigger. Set it a few minutes in the future and (after Reloading Template Entities) wait for it to trigger at the scheduled time. It’s a better simulation than a startup trigger.

it didnt work didnt run or least i cant tell how you know if it ran but i set it to

        - trigger: time_pattern
          # This will update every night
          hours: 18
          minutes: 0

for 6pm and it never ran

i think i gotta rem out orginal templates i made i found like _2 when i searched for the states… so like cost_2

so ill rem out the old and restart and see what happens

so i think its working for whatever reason its also a pain where the cost sensor resets to unknown and u gotta wait for it to count and yet the energy page shows the cost… but for whatever reason its now 1 decimal place i added a round 2… but its not working so i cant 100% test if its working least there are 0 now and not the unavliable after i had to delete the orginal and then rename the ones woth _2 to without it…

but here you see single decimal

i added the round(2) i googled but its not adding it… i guess it needs to be in the unique_id: line

      sensor:
        - name: Last Months Power Usage Total
          unique_id: last_months_power_usage_total
          state: "{{ states('sensor.current_monthly_consumption')|float|round(2) }}"
        - name: Last Months Power Usage On Peak
          unique_id: last_months_power_usage_on_peak
          state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak')|float|round(2) }}"
        - name: Last Months Power Usage Mid Peak
          unique_id: last_months_power_usage_mid_peak
          state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak')|float|round(2) }}"
        - name: Last Months Power Usage Off Peak
          unique_id: last_months_power_usage_off_peak
          state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak')|float|round(2) }}"
        - name: Last Months Power Usage Total Cost
          unique_id: last_months_power_usage_total_cost
          state: "{{ states('sensor.current_monthly_consumption')|float|round(2) }}"
        - name: Last Months Power Usage On Peak Cost
          unique_id: last_months_power_usage_on_peak_cost
          state: "{{ states('sensor.energy_import_hydro_one_monthly_on_peak_cost')|float|round(2) }}"
        - name: Last Months Power Usage Mid Peak Cost
          unique_id: last_months_power_usage_mid_peak_cost
          state: "{{ states('sensor.energy_import_hydro_one_monthly_mid_peak_cost')|float|round(2) }}"
        - name: Last Months Power Usage Off Peak Cost
          unique_id: last_months_power_usage_off_peak_cost
          state: "{{ states('sensor.energy_import_hydro_one_monthly_off_peak_cost')|float|round(2) }}"

probably just easier let it run for a while to get 2 decimals and ill see how well it works… so far it seems to work for the consumption the cost not yet so ill let you know later if its working ill just let it sit and idle to get new cost i dunno why it easily starts at 0 but it does go figure lol

and i appreciatre the help so far as it was stuck

If the original value is 311.1 then round(2) will produce 311.1 and not 311.10 because it doesn’t do “zero-padding” (i.e. trailing zeros).

If you want “zero-padding” then follow the instructions in the following post:

so couple things… everytime i reboot HA it resets the Costs. is there no way for the Energy it retains it? it retains it on the Energy Page… but not the actual sensor…

2nd there is no Preceision when you choose Gear… not an option and then i i did the timer to run at 8pm and then did this



no precision option

since the costs sensors dont retain after a reboot

how do you do math sensor i tried this before
but
a = a +b
so sensor = sensor + cost
this way it will retain after a reboot

i had tried this but this just gave me issues

        # - name: "weekly cost test"
        #   state: "{{ states('sensor.weekly_cost_test') | float(0) + states('sensor.current_daily_cost') }}"
        #   availability: "{{ has_value('sensor.weekly_cost_test') }}"
        #   state_class: total_increasing

and also reset the actual energy cost… like a reboot it erases it yet it saves it in the Energy page

I had problems with restoring a value of one of my sensors on reboot. My application is a flow meter. I’m using an Arduino runing MySensors through a MySensors Gateway to HA. The Arduino EEPROM has a life of about 100,000 writes, which would be exceeded quickly. I found that value in HA’s input number suvives a reboot/power cycle.

Here’s how it works:

  • On an Arduino boot, the pulse count variable is presented to HA and the pulse count, being 0, is sent to HA.
  • If HA sees the state (value) as zero, HA will send the value in the input number
  • If HA sees the state as neither zero nor one, HA will update the input number with the value sent.

Here’s the automation YAML

alias: WaterMeterSavePulseCount
description: Saves the pulse count to non-volatile memory 1.0
triggers:
  - trigger: state
    entity_id:
      - sensor.pulsecount
    not_from:
      - unknown
      - unavailable
    not_to:
      - unknown
      - unavailable
conditions: []
actions:
  - if:
      - condition: state
        entity_id: sensor.pulsecount
        state: "0"
    then:
      - data:
          value: "{{ states('input_number.pulsecountnonvolatile') }}"
        target:
          entity_id: text.pulsecountstored
        action: text.set_value
    else:
      - if:
          - condition: state
            entity_id: sensor.pulsecount
            state: "1"
        then: []
        else:
          - data:
              value: "{{ states('sensor.pulsecount') }}"
            target:
              entity_id: input_number.pulsecountnonvolatile
            action: input_number.set_value
mode: single

@OldSurferDude ok ill take a look at the way you do it. always looking for new ways of doing stuff

@123
so there is precision display on the orginal sensor… from the ulity meter … but the ones created from the trigger… it removes the display precison
so if its 0.06 it displays it at 0.0 but on the orginal sensor it shows 0.06
and is there anyway to retain the utlity meter costs on reboot other then in the energy page… but the trigger part did work to spit that 8 decimal into it… and it should have spit out 2 decimals i guess… very frustrating but i keep plugging away to do a weekly and yesterdays display… in the mean time

Given that this application involves multiple sensor entities, just saying “Costs” doesn’t identify which cost-related sensor entity you’re referring to. There are 8 cost-related entities, 4 sources and 4 Trigger-based. Which ones are being reset?

Add a unit_of_measurement field (with an appropriate value) to each Trigger-based Template Sensor that you want to control its display precision.

I don’t understand the issue. I have sensor entities created by the Utility Meter integration and they don’t lose their values after a restart.

so all the Utility Meter Costs reset to 0 on reboot

  - entity: sensor.energy_import_hydro_one_weekly_on_peak_cost
    name: On Peak
  - entity: sensor.energy_import_hydro_one_weekly_mid_peak_cost
    name: Mid Peak
  - entity: sensor.energy_import_hydro_one_weekly_off_peak_cost
    name: Off Peak
  - entity: sensor.current_weekly_cost

type: entities
entities:
  - entity: sensor.energy_import_hydro_one_monthly_on_peak_cost
    name: On Peak
  - entity: sensor.energy_import_hydro_one_monthly_mid_peak_cost
    name: Mid Peak
  - entity: sensor.energy_import_hydro_one_monthly_off_peak_cost
    name: Off Peak
  - entity: sensor.current_monthly_cost
title: monthly cost

type: entities
entities:
  - entity: sensor.energy_import_hydro_one_daily_on_peak_cost
    name: On Peak
  - entity: sensor.energy_import_hydro_one_daily_mid_peak_cost
    name: Mid Peak
  - entity: sensor.energy_import_hydro_one_daily_off_peak_cost
    name: Off Peak
  - entity: sensor.current_daily_cost
title: Daily cost

they only retain on the Energy Dashboard… but on the sensors itself or you goto to States page and search for them they are always unknown after a reboot and start off with unknown then go 0.0

so here you see Before the reboot we at 11 cents

before reboot


after reboot


energy page you see it retains the values but it doesnt retain it in the sensor after a reboot

so its not retaining it in the sensor so my dashboard page is always resetting to unknown and starting at 0 after a reboot

so if it doesnt retain id like to make a retaining sensor that saves it every time it updates

You’ll need to fix that before proceeding with what I suggested (or with what OldSurferDude suggested or anything else for that matter). This is now a completely different problem to solve. Good luck!

It normally does; resetting on startup is abnormal.