After implementing power monitoring in my apartment I wanted the ability to take the data I receive from my electric provider that includes the start and end of the billing cycle and use that as a means of calculating real-time consumption.
The issue is the history stats component doesn’t have any means of getting the total usage within a date range. So I thought I was out of luck. However, the restful API provided for home assistant does allow getting states within a range and so I used a command line component to use curl and gather the info I need.
- platform: command_line
name: Monthly Usage Difference
command: "curl -X GET -H 'x-ha-access:HA-PASSWORD' -H 'Content-Type:application/json' http://localhost:8123/api/history/period/{{ strptime(states.sensor.monthly_energy_usage.attributes['Data'][1]['stop_time'], '%Y/%m/%d %H:%M:%S').isoformat(timespec='seconds') }}.000Z?filter_entity_id=sensor.home_kwh_total"
unit_of_measurement : 'Kwh'
value_template: '{{ states.sensor.home_kwh_total.state | float - value_json[0][0]["state"] | float }}'
Basically the code above gets the states for sesnor.home_kwh_total extracts the first one within the date specified and then subtracts the current state from that state to get the difference.
In my case home_kwh_total is the total kWh recorded by my Aeotec Z-Wave energy monitor from the time it was first turned on. The state sensor.monthly_energy_usage.attributes[‘Data’][1][‘stop_time’] is also the last time that my electric company read my meter.
So ultimately the above code finds the difference from the last meter read by my electric provider (usually 2-days old) and gets the difference from the total kWh from the energy monitor. Basically so I can add the difference to the current read from the electric provider to get the real-time to the minute read of the total usage.