Use the average platform.
This is my template:
- platform: average
name: "Medeltemperatur natt"
entities:
- sensor.vaderstation_temp_ute_temperature
end: "{{ now().replace(hour=6).replace(minute=0).replace(second=0) }}"
duration:
hours: 8
- platform: average
name: "Medeltemperatur dag"
entities:
- sensor.vaderstation_temp_ute_temperature
start: "{{ now().replace(hour=6).replace(minute=0).replace(second=0) }}"
end: "{{ now().replace(hour=22).replace(minute=0).replace(second=0) }}"
āMedeltemperatur nattā is night temperature
āMedeltemperatur dagā is daytime avg temperature.
Based on these sensors I send a notification around 07:01 for night tempā¦
service: notify.all_devices_notification
data:
message: >-
NATT rapport fƶr Temperaturer<br> Medel
{{states('sensor.medeltemperatur_natt')}}<br>MAX
{{state_attr('sensor.medeltemperatur_natt','max_value')}}<br>MIN
title: TEMPERATUR INFO (22:00 till 07:00)
The average is installed via HACS.
AVERAGE
1 Like
That is an option, but would be limited to the current day, right?
So a ābinary_sensor.person_awake if binary_sensor.night=onā or āsensor.person=awake if binary_sensor.night=onā for the last 7 days would not work
I was kind of trying to disguise the nerdyness of the question, haha
Yes, I do have a sensor for myself with states like sleeping/home/work/away
But I should expand it and have attributes for awake/sleeping etc
There is an issue on github but raising here as wellā¦ this integration is broken in 2022.5
2 Likes
theRat
(Simon)
May 3, 2022, 5:00am
125
@bdraco this integration gets broken by
home-assistant:dev
ā bdraco:get_states_dead_code
opened 09:01PM - 26 Apr 22 UTC
<!--
You are amazing! Thanks for contributing to our project!
Please, DO Nā¦ OT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
If your PR contains a breaking change for existing users, it is important
to tell them what breaks, how to make it work again and why we did this.
This piece of text is published with the release notes, so it helps if you
write it towards our users, not us.
Note: Remove this section if this PR is NOT a breaking change.
-->
Remove `get_state` and `get_states` history api calls
- These calls were no longer used in the codebase
and are dead code
There are a few more tests that can be removed once we
no longer have anyone doing v25 database migrations that
I left for now.
## Type of change
<!--
What type of change does your PR introduce to Home Assistant?
NOTE: Please, check only 1! box!
If your PR requires multiple boxes to be checked, you'll most likely need to
split it into multiple PRs. This makes things easier and faster to code review.
-->
- [ ] Dependency upgrade
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [x] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests
## Additional information
<!--
Details are important, and help maintainers processing your PR.
Please be sure to fill out additional details, if applicable.
-->
- This PR fixes or closes issue: fixes #
- This PR is related to issue:
- Link to documentation pull request:
## Checklist
<!--
Put an `x` in the boxes that apply. You can also fill these out after
creating the PR. If you're unsure about any of them, don't hesitate to ask.
We're here to help! This is simply a reminder of what we are going to look
for before merging your code.
-->
- [x] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] The code has been formatted using Black (`black --fast homeassistant tests`)
- [x] Tests have been added to verify that the new code works.
If user exposed functionality or configuration variables are added/changed:
- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]
If the code communicates with devices, web services, or third-party tools:
- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.
Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.
The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
The Integration Quality Scale scores an integration on the code quality
and user experience. Each level of the quality scale consists of a list
of requirements. We highly recommend getting your integration scored!
-->
- [ ] No score or internal
- [ ] š„ Silver
- [ ] š„ Gold
- [ ] š Platinum
<!--
This project is very active and we have a high turnover of pull requests.
Unfortunately, the number of incoming pull requests is higher than what our
reviewers can review and merge so there is a long backlog of pull requests
waiting for review. You can help here!
By reviewing another pull request, you will help raise the code quality of
that pull request and the final review will be faster. This way the general
pace of pull request reviews will go up and your wait time will go down.
When picking a pull request to review, try to choose one that hasn't yet
been reviewed.
Thanks for helping out!
-->
To help with the load of incoming pull requests:
- [ ] I have reviewed two other [open pull requests][prs] in this repository.
[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure
<!--
Thank you for contributing <3
Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io
Any idea on how to fix it?
1 Like
bdraco
(J. Nick Koston)
May 3, 2022, 1:44pm
126
That integration is a copy of history_stats with some modifications. It needs to be updated to use the newer apis and, the design which wonāt overload the database with queries like the version that this integration is based on
It would be better to add the new functionality to the core integration so it wonāt break in the future. If you donāt want to do that copy history_stats from 2022.5 and make the same changes again. The caveat is that this path means it will break again sometime in the future when something else in core changes.
Also its calling history.state_changes_during_period
value = 0
elapsed = 0
if self._period is None:
# Get current state
value = self._get_entity_state(entity)
_LOGGER.debug("Current state: %s", value)
else:
# Get history between start and now
history_list = history.state_changes_during_period(
self.hass, start, end, str(entity_id)
)
if entity_id not in history_list.keys():
value = self._get_entity_state(entity)
_LOGGER.warning(
'Historical data not found for entity "%s". '
"Current state used: %s",
entity_id,
value,
which defaults to include_start_time_state=True
def state_changes_during_period(
hass: HomeAssistant,
start_time: datetime,
end_time: datetime | None = None,
entity_id: str | None = None,
no_attributes: bool = False,
descending: bool = False,
limit: int | None = None,
include_start_time_state: bool = True,
) -> MutableMapping[str, list[State]]:
"""Return states changes during UTC period start_time - end_time."""
with session_scope(hass=hass) as session:
baked_query, join_attributes = bake_query_and_join_attributes(
hass, no_attributes, include_last_updated=False
)
baked_query += lambda q: q.filter(
(States.last_changed == States.last_updated)
& (States.last_updated > bindparam("start_time"))
So you probably want to remove
# Get the first state
item = history.get_state(self.hass, start, entity_id)
_LOGGER.debug("Initial historical state: %s", item)
last_state = None
last_time = start_ts
if item is not None and self._has_state(item.state):
last_state = self._get_entity_state(item)
As the start time state is already in the list.
those are lines 490-496 on mine for some reasonā¦
I tried removing those lines. Still errors.
Any chance @bdraco you could post what you think would be a working sensor.py?
bdraco
(J. Nick Koston)
May 4, 2022, 4:34am
128
Sorry, it looks like that integration hasnāt been maintained for years. Itās a project to update it, and thatās not something Iām particularly intrested in taking on.
Not that its a particularly good idea, but it will get it back to working again: You can copy the old code that was removed in Remove get_state and get_states history api calls by bdraco Ā· Pull Request #70830 Ā· home-assistant/core Ā· GitHub and inline it in the integration until it can be fixed properly
Shaad
(David)
May 5, 2022, 6:47am
129
Does anyone know about a core alternative that will allow to calculate time-base average ?
badmin
May 5, 2022, 7:54pm
130
I was relying on this custom component to automate lighting and covers around the house - based on 15 minute averages from my Ambient Weather lx sensor. I switched over to the core statistics sensor using Mean - working again, no noticable difference for my use-case.
Updated Statistics sensor followed by previous Average sensor:
sensor:
- platform: statistics
name: 'Avg Light 15'
entity_id: sensor.ambient_weather_solar_rad_lx
state_characteristic: mean
max_age:
minutes: 15
unique_id: sensor.statistics.avg_light_15
# - platform: average
# name: 'Avg Light 15'
# duration:
# minutes: 15
# entities:
# - sensor.ambient_weather_solar_rad_lx
I was just starting to look at this
For me, I would want to get the average of a sensor for the past 1,3 and 7 days
Max_Age is fine assuming that I can put
days: 1|3|7
But on the Average sensor I could put
end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
Guessing thereās no equivalent for this statistics based on the documentation?
The kicker for me is they removed min and max attributes from statistics as well. They now need to be seperate sensors. This screws up my flex table card
GitHub - jeroenterheerdt/HADailySensor: Sensor for Home Assistant that gets reset at midnight might work for you. I think it will for me as I always used midnight anyway
Maybe notā¦ it doesnāt have attributes. Going to request this on the repo.
Shaad
(David)
May 6, 2022, 6:53am
134
Take care that the calculation is different : with the core statistics sensor, if your paramater has the value 10 for 14 minutes, and then 20 for the last minute, the mean value will be 15.
With this custom component it would be something like 10.67 (temporal average).
1 Like
I used sensors like this:
- platform: average
name: average_sensor_0
entities:
- sensor.temp_sensor
precision: 1
start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}'
end: '{{ now() }}'
scan_interval: 1800
- platform: average
name: average_sensor_1
entities:
- sensor.temp_sensor
precision: 1
start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=1) }}'
end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=1) }}'
scan_interval: 1800
- platform: average
name: average_sensor_2
entities:
- sensor.temp_sensor
precision: 1
start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=2) }}'
end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=2) }}'
scan_interval: 1800
...
I havenāt found another way of doing this kind of moving average with sliding window moving in the past other sensors. Does anybody know if thereās an alternative?
Shaad
(David)
May 6, 2022, 1:13pm
136
Sure. Thatās also what Iām using.
What you are missing here is that this custom component does not work anymore with the last Home Assistant core version.
Maybe Andrey will be able to update his component. But still, it would be nice that this feature would be available in the core.
EDIT : oh no, you have figured out! I have read too fast
Maybe also useful for your use case.
Iāve changed the average sensor values of last days with an input number and an automation, like this:
input_number:
# Fresno
average_sensor_1:
name: "Average sensor day -1"
initial: 0
min: 0
max: 200
step: 0.1
average_sensor_2:
name: "Average sensor day -2"
initial: 0
min: 0
max: 200
step: 0.1
automation:
- id: update_average_previous_days
trigger:
# run at almost midnight
- platform: time
at: '23:59:50'
condition: []
action:
- service: input_number.set_value
target:
entity_id: input_number.average_sensor_2
data:
value: >-
{{ states('input_number.average_sensor_1') }}
- service: input_number.set_value
target:
entity_id: input_number.average_sensor_1
data:
value: >-
{{ states('sensor.ha_daily_sensor') }}
mode: single
where sensor.ha_daily_sensor
could be the sensor @DavidFW1960 talked about
I was using it too, and since my heating is depending on that, I decided to switch to HA integrated features. So I am using statistics in combination with min/Max now. Quadruples the number of YAML lines, but at least should be more future reliable.
With statistics, you need to choose state characteristic āaverage_linearā, which reflects time constants, too.
## Aufbereitung Temperaturdaten fĆ¼r Heizungssteuerung ##
# zuerst Statistics per Weathersensor #
- platform: statistics
name: "Durchschnitt AT Temp"
entity_id: sensor.openweathermap_temperature
state_characteristic: average_linear
sampling_size: 60
max_age:
hours: 1
precision: 1
- platform: statistics
name: "Durchschnitt AT TempFeel"
entity_id: sensor.openweathermap_feels_like_temperature
state_characteristic: average_linear
sampling_size: 60
max_age:
hours: 1
precision: 1
- platform: statistics
name: "Durchschnitt AT TempFC"
entity_id: sensor.openweathermap_forecast_temperature
state_characteristic: average_linear
sampling_size: 60
max_age:
hours: 1
precision: 1
# ZusammenfĆ¼hrung der drei Statistikwerte #
- platform: min_max
entity_ids:
- sensor.Durchschnitt_AT_Temp
- sensor.Durchschnitt_AT_TempFeel
- sensor.Durchschnitt_AT_TempFC
type: mean
name: "Durchschnitt AT"
round_digits: 1
# Stundenwert per Statistik auf Witterung Ć¼berfĆ¼hren #
- platform: statistics
name: "Witterung AT"
entity_id: sensor.Durchschnitt_AT
state_characteristic: average_linear
sampling_size: 100
max_age:
hours: 22
precision: 1
1 Like
There is a patch for the average integration by a third party link in the github issue. Iām going to switch to that tomorrow but may also try the daiky sensor above with some template sensors for min/max