#Time sensor is on in a time period

1 messages · Page 1 of 1 (latest)

eager comet
#

I have a sensor, bedroom_2_heater and I need to find out how long it was in the "on" state between start_time and end_time please.

#

This is for use in a template sensor. AI is, unforuntately, tying itslef up in knots because I don't seem to be able to get the query right

#

This is the code as I've got it so far... I just can't get the history of the on-time between the start and end.

#
  - sensor:
    - name: "Bedroom 2 Cost Yesterday"
      unit_of_measurement: "£"
      state_class: measurement
      state: >
        {% set start_time = (now() - timedelta(days=1)).replace(hour=0, minute=0, second=0) %}
        {% set end_time = (now() - timedelta(days=1)).replace(hour=23, minute=59, second=59) %}
        {% set on_time = -bedroom on-time between start and end goes here- %}
        {% set unit_cost = states('input_number.electricity_unit_cost') | float(default=0) %}
        {% set heater_power = states('input_number.bedroom_2_consumption') | float(default=0) %}
        {% if unit_cost > 0 and heater_power > 0 %}
          {{ (((on_time / 3600) * heater_power * unit_cost) / 10000000) | round(2, 'ceil') }}
        {% else %}
          {{ 0 | round(2) }}
        {% endif %}
placid tiger
#

Then use the state of this sensor directly in your template.

eager comet
#

Thanks. I was trying to avoid setting up another sensor... or that was my hope 🙂

rose prairie
#

So let me get this straight
You have a binary sensor representing a heater's state and are just trying to get a cost to run it for each day?

eager comet
#

Yes.

#

But I'm dynamically changing the times... because if I get up in the morning, I want to know what's happened overnight, which goes across the midnight threshold.

#

At the moment I have a history stat for each of what I want to read, and if I could get rid of those, it would be a bonus because I've got a number of heaters in the house to monitor.

#

And then I'm having to use automations to calculate the costs and put them in the final variables, every 10 minutes.

rose prairie
#

So the way I do this is slightly different

  1. Template sensor: 0 / power * current electricity price to give a cost/hr
  2. Integral helper to give a total running cost of the device
  3. Statistics helper to give the change in the integral in the last 24hrs
#

If you just want to display it in a graph you can do without 3

eager comet
#

Can you share the code for your template sensor please?

rose prairie
#

{{ states('input_number.power_input') | float(0) * states('sensor.current_electricity_price') | float(0) if states('binary_sensor.active') | bool(false) else 0 }}