Count hours while a binary sensor is on

I want to monitor how many hours my 3d printer is printing, set a lifetime for my nozzle using an input number and get a reminder to replace my nozzle when it’s lifetime reaches 0.

I have created input_number.printer_nozzle_lifetime.
When my printer is working binary_sensor.octoprint_printing is on. It’s off when it’s not printing and it’s unavailalble when octoprint is not running.

I created these sensors:

sensor:
  - platform: template
    sensors:
      printer_total_printing_time:
        friendly_name: "Printer Total Printing Time"
        entity_id:
          - binary_sensor.octoprint_printing
          - sensor.time
        unit_of_measurement: "hours"
        value_template: >-
          {% if states.binary_sensor.octoprint_printing.state == 'on' %}
            {% set duration = (as_timestamp(now()) - as_timestamp(states.binary_sensor.octoprint_printing.last_changed)) / 3600 %}
            {{ duration | round(2) }}
          {% endif %}

sensor:
  - platform: template
    sensors:
      printer_nozzle_life_remaining:
        friendly_name: "Printer Nozzle Life Remaining"
        unit_of_measurement: "hours"
        value_template: >-
          {{ states('input_number.printer_nozzle_lifetime') | float - states('sensor.printer_total_printing_time') | float | round(2) }}

I get the values I want but after restarting home assistant the printer_total_printing_time is unavailable. I want to be able to reset it manually but not losing it’s value after restarting.
How could I achieve the behavior I want?

Have you tried history_stats?

1 Like