GithubHelp home page GithubHelp logo

limych / ha-average Goto Github PK

View Code? Open in Web Editor NEW
324.0 10.0 28.0 1.21 MB

Average Sensor for Home Assistant

License: Other

Python 69.63% Shell 27.99% Dockerfile 0.45% Makefile 1.93%
home-assistant sensor average hacs home-assistant-component home-assistant-sensor

ha-average's Introduction

Please ⭐ this repo if you find it useful

Average Sensor for Home Assistant

GitHub Release GitHub Activity License

hacs Project Maintenance Support me on Patreon

Community Forum

This sensor allows you to calculate the average state for one or more sensors over a specified period. Or just the average current state for one or more sensors, if you do not need historical data.

Initially it was written special for calculating of average temperature, but now it can calculate average of any numerical data.

Example

What makes this sensor different from others built into HA:

Compare with the min-max sensor:
This sensor in the mean mode produces exactly the same average value from several sensors. But, unlike our sensor, it cannot receive the current temperature data from a weather, climate and water heater entities.

Compare with statistics sensor:
This sensor copes with the averaging of data over a certain period of time. However… 1) it cannot work with several sources at once (and can't receive temperature from weather, climate and water heater entities, like min-max sensor), 2) when calculating the average, it does not take into account how much time the temperature value was kept, 3) it has a limit on the number of values ​​it averages - if by chance there are more values, they will be dropped.

Note:
You can find a real example of using this component in my Home Assistant configuration.

I also suggest you visit the support topic on the community forum.

Breaking changes

  • Since version 2.0.0 the mechanism for specifying the unique ID of sensors has been changed. To prevent duplicate sensors from being created, add option unique_id: __legacy__ to the settings of already available sensors. For more information, see below.
    Another way is to manually delete all old sensors via Configuration > Entities. Then restart HA and all the _2’s were was the original sensors again complete with their history.
    My Entities
  • Since version 1.3.0 the default sensor name is “Average” instead of “Average Temperature”

Known Limitations and Issues

  • Due to the fact that HA does not store in history the temperature units of measurement for weather, climate and water heater entities, the average sensor always assumes that their values ​​are specified in the same units that are now configured in HA globally.

Installation

Install from HACS (recommended)

  1. Have HACS installed, this will allow you to easily manage and track updates.
  2. Search in HACS for "Average" integration or just press the button below:
    Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.
  3. Click Install below the found integration.

... then if you want to use configuration.yaml to configure sensor...

  1. Add average sensor to your configuration.yaml file. See configuration examples below.
  2. Restart Home Assistant

Manual installation

  1. Using the tool of choice open the directory (folder) for your HA configuration (where you find configuration.yaml).
  2. If you do not have a custom_components directory (folder) there, you need to create it.
  3. In the custom_components directory (folder) create a new folder called average.
  4. Download file average.zip from the latest release section in this repository.
  5. Extract all files from this archive you downloaded in the directory (folder) you created.

... then if you want to use configuration.yaml to configure sensor...

  1. Add average sensor to your configuration.yaml file. See configuration examples below.
  2. Restart Home Assistant

Configuration Examples

To measure the average of current values from multiple sources:

# Example configuration.yaml entry
sensor:
  - platform: average
    name: 'Average Temperature'
    entities:
      - weather.gismeteo
      - sensor.owm_temperature
      - sensor.dark_sky_temperature

To measure the average of all values of a single source over a period:

# Example configuration.yaml entry
sensor:
  - platform: average
    name: 'Average Temperature'
    duration:
      days: 1
    entities:
      - sensor.gismeteo_temperature

or you can combine this variants for some reason.

* * *

I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm:


Patreon
or support via Bitcoin or Etherium:
Bitcoin
16yfCfz9dZ8y8yuSwBFVfiAa3CNYdMh7Ts

Configuration Variables

entities:
(list) (Required)
A list of temperature sensor entity IDs.

Note:
You can use weather provider, climate and water heater entities as a data source. For that entities sensor use values of current temperature.

Note:
You can use groups of entities as a data source. These groups will be automatically expanded to individual entities.

unique_id
(string) (Optional)
An ID that uniquely identifies this sensor. Set this to a unique value to allow customization through the UI.

Note:
If you used the component version 1.4.0 or earlier, you can specify the special value __legacy__, so that no duplicates of already existing sensors are created.
The use of this special value in newly created sensors is not recommended.

Another way is to manually delete all old sensors via Configuration > Entities. Then restart HA and all the _2’s were was the original sensors again complete with their history.
My Entities

name:
(string) (Optional)
Name to use in the frontend.
Default value: "Average"

start:
(template) (Optional)
When to start the measure (timestamp or datetime).

end:
(template) (Optional)
When to stop the measure (timestamp or datetime).

duration:
(time) (Optional)
Duration of the measure.

precision:
(number) (Optional)
The number of decimals to use when rounding the sensor state.
Default value: 2

process_undef_as:
(number) (Optional)
Process undefined values (unavailable, sensor undefined, etc.) as specified value.

By default, undefined values are not included in the average calculation. Specifying this parameter allows you to calculate the average value taking into account the time intervals of the undefined sensor values.

Note:
This parameter does not affect the calculation of the count, min and max attributes.

Average Sensor Attributes

start:
Timestamp of the beginning of the calculation period (if period was set).

end:
Timestamp of the end of the calculation period (if period was set).

sources:
Total expanded list of source sensors.

count_sources:
Total count of source sensors.

available_sources:
Count of available source sensors (for current calculation period).

count:
Total count of processed values of source sensors.

min:
Minimum value of processed values of source sensors.

max:
Maximum value of processed values of source sensors.

Time periods

The average integration will execute a measure within a precise time period. You should provide none, only duration (when period ends at now) or exactly 2 of the following:

  • When the period starts (start variable)
  • When the period ends (end variable)
  • How long is the period (duration variable)

As start and end variables can be either datetimes or timestamps, you can configure almost any period you want.

Duration

The duration variable is used when the time period is fixed. Different syntaxes for the duration are supported, as shown below.

# 15 seconds
duration: 15
# 6 hours
duration: 06:00
# 1 minute, 30 seconds
duration: 00:01:30
# 2 hours and 30 minutes
duration:
  # supports seconds, minutes, hours, days
  hours: 2
  minutes: 30

* * *

I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm:


Patreon
or support via Bitcoin or Etherium:
Bitcoin
16yfCfz9dZ8y8yuSwBFVfiAa3CNYdMh7Ts

Examples

Here are some examples of periods you could work with, and what to write in your configuration.yaml:

Last 5 minutes: ends right now, last 5 minutes.

duration:
  minutes: 5

Today: starts at 00:00 of the current day and ends right now.

start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'

Yesterday: ends today at 00:00, lasts 24 hours.

end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
  hours: 24

This morning (06:00–11:00): starts today at 6, lasts 5 hours.

start: '{{ now().replace(hour=6).replace(minute=0).replace(second=0) }}'
duration:
  hours: 5

Current week: starts last Monday at 00:00, ends right now.

Here, last Monday is today as a timestamp, minus 86400 times the current weekday (86400 is the number of seconds in one day, the weekday is 0 on Monday, 6 on Sunday).

start: '{{ as_timestamp( now().replace(hour=0).replace(minute=0).replace(second=0) ) - now().weekday() * 86400 }}'
end: '{{ now() }}'

Last 30 days: ends today at 00:00, lasts 30 days. Easy one.

end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
  days: 30

All your history starts at timestamp = 0, and ends right now.

start: '{{ 0 }}'
end: '{{ now() }}'

Note:
The Template Dev Tools page of your home-assistant UI can help you check if the values for start, end or duration are correct. If you want to check if your period is right, just click on your component, the start and end attributes will show the start and end of the period, nicely formatted.
Developer Tools: Templates

Track updates

You can automatically track new versions of this component and update it by HACS.

Troubleshooting

To enable debug logs use this configuration:

# Example configuration.yaml entry
logger:
  default: info
  logs:
    custom_components.average: debug

... then restart HA.

Contributions are welcome!

This is an active open-source project. We are always open to people who want to use the code or contribute to it.

We have set up a separate document containing our contribution guidelines.

Thank you for being involved! 😍

Authors & contributors

The original setup of this component is by Andrey "Limych" Khrolenok.

For a full list of all authors and contributors, check the contributor's page.

This Home Assistant custom component was created and is updated using the HA-Blueprint template. You can use this template to maintain your own Home Assistant custom components.

License

creative commons Attribution-NonCommercial-ShareAlike 4.0 International License

See separate license file for full text.


ha-average's People

Contributors

antonverburg avatar ctso avatar dependabot[bot] avatar eifinger avatar eseglem avatar github-actions[bot] avatar iantrich avatar jcgoette avatar k1rd3rf avatar limych avatar linushoppe avatar lmagyar avatar ludeeus avatar matthewflamm avatar mattrayner avatar misa1515 avatar mjmeli avatar myztillx avatar oncleben31 avatar raman325 avatar rianoc avatar robvanoostenrijk avatar rodpayne avatar rroller avatar salem84 avatar scottg489 avatar swartjean avatar tefinger avatar tetienne avatar tompipe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ha-average's Issues

If sensor get 'unknown' after startup pulls error

I have some sensors after startup from Home Assistant they have 'unknown' as state. After some seconds the get the correct value. But the logs show a error:

TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

So I think your sensor must check if there is 'unknown' or something except a number and must skip these entities.

Would be very nice to consider this.

Regards, Steffen

Version of the custom_component

Configuration

Add your configs here.

Describe the bug

A clear and concise description of what the bug is.

Debug log


Add your logs here.

HA 2021.6 error on LazyState

Environment

  • Home Assistant Core release with the issue: 2021.6 b
  • This custom component release with the issue: 1.7.3
  • Last working this custom component release (if known): on 2021.5
  • Operating environment (Home Assistant/Supervisor/Docker/venv): HA OS

Describe the bug

Configuration.yaml

  - platform: average
    name: Mean indoor measured temp
    entities:
      - sensor.temperatuur_living
      - sensor.dining_table_sensor_temperature
      - sensor.auditorium_sensor_temperature
      - etcetc

Steps to Reproduce

Expected behavior

Debug log


2021-05-27 15:11:17 ERROR (MainThread) [homeassistant.config] Platform error: sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config.py", line 853, in async_process_component_config
    platform = p_integration.get_platform(domain)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 472, in get_platform
    cache[full_name] = self._import_platform(platform_name)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 477, in _import_platform
    return importlib.import_module(f"{self.pkg_path}.{platform_name}")
  File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/config/custom_components/average/sensor.py", line 23, in <module>
    from homeassistant.components.history import LazyState
ImportError: cannot import name 'LazyState' from 'homeassistant.components.history' (/usr/src/homeassistant/homeassistant/components/history/__init__.py)

Additional context

Edit: now see this home-assistant/core#51140 and PR to fix that home-assistant/core#51144

so guess not a CC issue, but core... feel free to close.

Ignore unavailable

Is your feature request related to a problem? Please describe.

Yes, if one of the entities goes unavailable, the sensor output is 'unknown'

Describe the solution you'd like

If I have 5 sensors and one goes offline, ignore the offline one and give me the average reading of the remaining 4.

Describe alternatives you've considered

Using a template sensor ignores the unavailable entity, but of course treats it as zero, which skews the average for the remaining sensors.

median

I would suggest to implement "median" from defined number of readings per time as an option. at this moment, this could be easily achieved by averaging large set of values, but this is not suitable for some applitations.

Example of state where average is not enough - battery powered water level sensor, which sends 10 measurement sequence every 2 hours. 10 measurements are because sensor readings are varying on water level movements. Sensor is ultrasonic, so some of readings are completely out of range because of bounces etc, e.g. my sewage reports it is 9m deep from time to time, so average varies a lot. Median from 10 measurements every 2 hours provides almost perfect result.

Current Day Period?

I'm currently using the statistics sensor for Temperature. My Weather provider, BOM, shows 0 for the current day once the minimum and maximum for the day have passed. So I do the statistics sensor for 24 hours and look for the minimum and maximum.... which means it looks at yesterday as well. I saw this component and was hoping it would be able to limit the average to values from TODAY but it's just like the stats sensor where you have to specify a time period.

Would be awesome if you could set the average period to today for instance.

Presumable it shows minimum and maximum as attributes?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Convert to int when precision: 0

Is your feature request related to a problem? Please describe.
It is truly a minor thing but when no decimals are needed it still kind of bugs me that the values display with .0
Example units are battery (%) and illumination (lx).

Describe the solution you'd like
Just convert to int when precision: 0

Describe alternatives you've considered
N/A

Additional context
N/A

State count very high

First of all, thank you and congratulations for this great contribution to HA.

I don't know if this is really a bug or I'm missing something.

I have this sensors configured:

- platform: rest
  name: pws_fresno_report
  json_attributes:
    - observations
  value_template: '{{ value_json["observations"][0]["obsTimeLocal"].title() }}'
  resource: !secret wunderground_fresno_url
  scan_interval: 1800

- platform: template
  sensors:
    pws_fresno_precip_total:
      value_template: '{{ states.sensor.pws_fresno_report.attributes.observations[0].metric.precipTotal }}'
      friendly_name: Lluvia Total Fresno el Viejo        
      unit_of_measurement: "L"

- platform: average
  name: irrigation_unlimited_rain_fresno_0
  entities:
    - sensor.pws_fresno_precip_total
  precision: 1
  start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}'
  end: '{{ now() }}'
  scan_interval: 1800

- platform: average
  name: irrigation_unlimited_rain_fresno_1
  entities:
    - sensor.pws_fresno_precip_total
  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

I record the states of my sensors for 14 days:

recorder:
  purge_keep_days: 14

When I check the total count of sensor states of each sensor during the last 14 days I get the next:

  • sensor.pws_fresno_report: 895
  • sensor.pws_fresno_precip_total: 145
  • sensor.irrigation_unlimited_rain_fresno_0: 10552
  • sensor.irrigation_unlimited_rain_fresno_1: 152

I don't understad why the sensor.irrigation_unlimited_rain_fresno_0 count is so high compared with sensor.irrigation_unlimited_rain_fresno_1 if both have the same scan_interval.

Thank you.

All 'average' sensors are 'unavailable' after update.

  • Home Assistant Core release with the issue: core-2021.5.1
  • This custom component release with the issue: 2.0.0
  • Last working this custom component release (if known):
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Home Assistant OS 5.13 (Docker)

After update to latest 'average' integration version all average sensors stopped working. They all are 'unavailable' now.

- platform: average
    name: 'Average Bedroom Temperature'
    entities:
      - sensor.humidifier_temperature
      - sensor.temperature_lumi_158d0001bf2eee
      - sensor.bedroom_thermostat_temperature

Proper value for "undefined values (unavailable, sensor undefined, etc.)"

Proper value for "undefined values (unavailable, sensor undefined, etc.)"

Great work on your sensor, thanks!

What is the expected 'value' for a sensor attribute that is not 'correct'. I am creating some MQTT sensors that publish JSON attributes. When the sensor returns an error, I publish JSON with attributes to indicate an error. However I do not publish the attribute that I am using as an input to your average sensor. This returns the error below in the HA log:

2020-10-12 19:44:57 ERROR (MainThread) [custom_components.average.sensor] Could not convert value "" to float

Versions

  • Version of the Home Assistant: 0.115.6
  • Version of the custom component: 'release/1.6.5'

Configuration

Add your configs here.

Describe the bug

A clear and concise description of what the bug is.

To Reproduce

If applicable, describe the steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Debug log


Add your logs here.

Additional context

Add any other context about the problem here.

Unexpected behaviour

Can you explain this behaviour? Currently I have this code:

- platform: average
  name: "Average temperature"
  end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) }}'
  duration:
    hours: 24
  entities:
    - weather.home

HA

On the left side (where the graph shows horizontal lines) you see my old settings with this in the code:
end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
On the right side are the settings applied shown above.
Why does the behaviour change? What I would like to achieve is the average temperature at 23:59 of the previous 24 hours, the same as happens on the left side but there it was at 0:00.

Unavailable sensor becomes 0

When the input sensor has gaps (unavailable) the average returns 0 values.

Version of the custom_component
1.4.3

Configuration

  - platform: average
    name: bathroom_humidity
    precision: 2
    duration:
      minutes: 1
    entities:
      - sensor.bathroom_humidity_average

image

image

Extend documentation comparing your sensor with the HA built-in filter sensor

Is your feature request related to a problem? Please describe.

Your sensors works as required, it shows the real, correct average of a sensor during a time period. The built in HA filter sensor changes it's output only, when it's input changes, ie. filter sensor is off by 1 precision nearly all the time. Your sensor is correct.

Describe the solution you'd like

Add a "Compare with filter sensor:" paragraph to the documentation mentioning this.

Describe alternatives you've considered

--

Additional context

Red line: original noisy sensor
Dark orange: filter sensor
Light orange: average sensor
(History card selected these fantastic colors...)

Filter_02

- platform: filter
  name: "Filter sensor"
  entity_id: sensor.xxx
  filters:
    - filter: time_simple_moving_average
      window_size: "00:01"
      precision: 1

- platform: average
  name: 'Average sensor'
  entities:
    - sensor.xxx
  duration:
    minutes: 1
  precision: 1

Weighted contribution

Is your feature request related to a problem? Please describe.

No

Describe the solution you'd like

Weighted contribution of sensors.
E.g. if you have three sensors but for whatever reason you prefer that one sensor contributes 50% and the two other sensos only contribute 25% each to the average. Or any other combination.

Not a huge priority but if it doesn't require too much it would be pretty neat.

Describe alternatives you've considered

I can of course just create multiple average sensors or template sensors. But I already have too many.

Additional context

Avoid that unavailable and unknown values are used to make average.

Environment

  • Home Assistant Core release with the issue:
  • This custom component release with the issue:
  • Last working this custom component release (if known):
  • Operating environment (Home Assistant/Supervisor/Docker/venv):

Describe the bug
I use the average sensor to calculate average temperature in the house. I am using 6 zigbee sensor. If the battery of one gets
low it disconnects and it reports unavailable or unknown as state. I can notice this as the average value drops because i think
that the value is used to make the average is 0.

Configuration.yaml

Add your configs here if any.

Steps to Reproduce
Just make one sensor states to report "unavailable" or "unknown"

Expected behavior

Ignore "unavailable" and "unknown" states of the sensors

Debug log


Add your logs here.

Additional context

Could not convert value to float

Versions

  • Version of the Home Assistant: core-2021.3.4, supervisor-2021.03.6, Home Assistant OS 5.12
  • Version of the custom component: 1.7.2

Configuration

My matching sensor looks like this:

    luftreiniger_oben_temperature:
      friendly_name: 'Temperatur'
      unit_of_measurement: '° C'
      device_class: 'temperature'
      value_template: '{{ states.fan.luftreiniger_oben.attributes.temperature }}'

The AVG entry as follows:

- platform: average

  name: 'Temperatur Oben AVG'
  entities:
    - sensor.treppenhaus_bewegungsmelder_oben_temperature
    - sensor.buro_bewegungsmelder_temperature
    - sensor.luftreiniger_oben_temperature

I get the following error:

Logger: custom_components.average.sensor
Source: custom_components/average/sensor.py:270
Integration: average (documentation, issues)
First occurred: 0:31:27 (2468 occurrences)
Last logged: 21:01:50

Could not convert value "<state sensor.luftreiniger_oben_temperature=22.3; unit_of_measurement=° C, friendly_name=Temperatur, device_class=temperature @ 2021-03-27T20:13:27.468485+01:00>" to float

What's going wrong?

Not quite ignoring null values.

Environment

  • Home Assistant Core release with the issue: 2021.7.1
  • This custom component release with the issue: 2.1.0
  • Last working this custom component release (if known): N/A
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Docker on Debian

Describe the bug

The sensor does not quite ignore null values it seems. Example below.

Configuration.yaml

  - platform: average
    name: motion_sensor_1_temperature_average
    precision: 4
    duration:
      minutes: 1
    entities:
      - sensor.motion_sensor_1_temperature

image
image
image

Steps to Reproduce

Expected behavior

If the goal is to ignore null values then the result above should have been either null or the average of last known non-null values. Or maybe some other option. I don't know what the best approach is.

Debug log


Add your logs here.

Additional context

Error of HACS incompatibility

Environment

  • Home Assistant Core release with the issue: 2021.4.4

  • This custom component release with the issue: 1.7.3

  • Last working this custom component release (if known):

  • Operating environment (Home Assistant/Supervisor/Docker/venv): Home Assistant NUC

Describe the bug

Source: loader.py:783 
First occurred: 11:51:26 PM (1 occurrences) 
Last logged: 11:51:26 PM

You are using a custom integration average which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant

Configuration.yaml

Add your configs here if any.

Steps to Reproduce

Tried to remove repository and reinstall numerous times

Expected behavior

HACS supported integration

Debug log


Add your logs here.

Additional context

Feature request: Ability to retrieve other items than temperature from weather/climate

Is your feature request related to a problem? Please describe.

Right now when a weather entity is included, it defaults to temperature.

Describe the solution you'd like

I would like it to default to the ATTR_UNIT_OF_MEASUREMENT from the other entities included. This would be useful for me; i want to have a baseline of the humidity in my location using my own sensors and the humidity reported from my weather service.

An alternative would be a new variable by which i can define the attribute which should be included.

Describe alternatives you've considered

For now I'll make an temporary template sensor for extracting the humidty from the weather sensor.

Additional context

ZeroDivisionError: division by zero when calculating the average.

I have multiple sensors going into an average and I have been getting the following in my logs on 0.99.2.

image

Update for sensor.average_inside_temperature fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 261, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 439, in async_device_update
    await self.async_update()
  File "/config/custom_components/average/sensor.py", line 283, in async_update
    value /= elapsed
ZeroDivisionError: division by zero

'unique_id' ignored

Environment

  • Home Assistant Core release with the issue: core-2021.6.6
  • This custom component release with the issue: 2.1.0
  • Last working this custom component release (if known): ?
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Home Assistant Supervised

Describe the bug

The value in 'unique_id' is ignored.
There is entity ID "sensor.atmosfericky_tlak_prumer_za_15_min" in HA, i would like "atmosfericky_tlak_average15", as it is in 'unique_id' specified.
I tested it with and without '' ""...

/config/configuration.yaml

sensor: !include sensors.yaml

/config/sensors.yaml

-   platform: average
    name: 'Atmosférický tlak (průměr za 1 min).'
    unique_id: atmosfericky_tlak_average1
    precision: 2
    duration:
      minutes: 1
    entities:
    - sensor.temp_001_aqara_pressure
    - sensor.temp_002_aqara_pressure
    - sensor.temp_003_aqara_pressure
    - sensor.temp_004_aqara_pressure
    - sensor.temp_005_aqara_pressure
    - sensor.temp_006_aqara_pressure
    - sensor.temp_008_aqara_pressure
    - sensor.temp_009_aqara_pressure
    - sensor.temp_010_aqara_pressure

-   platform: average
    name: 'Atmosférický tlak (průměr za 15 min).'
    unique_id: atmosfericky_tlak_average15
    precision: 2
    duration:
      minutes: 15
    entities:
    - sensor.temp_001_aqara_pressure
    - sensor.temp_002_aqara_pressure
    - sensor.temp_003_aqara_pressure
    - sensor.temp_004_aqara_pressure
    - sensor.temp_005_aqara_pressure
    - sensor.temp_006_aqara_pressure
    - sensor.temp_008_aqara_pressure
    - sensor.temp_009_aqara_pressure
    - sensor.temp_010_aqara_pressure

Steps to Reproduce

Expected behavior

Debug log


Add your logs here.

Additional context

Define what average this sensor calculates

It is unclear to me what kind of average this sensor calculates.

The "average" temperature for a timperiod (Ex: Average temperature of a day) is normaly just a single value and thus a horizontal line on a graph. (The average has no real timestamp itself, it is the average that is valid over the entire timerange.)

At first sight it seems what is being calculated is a moving average for a certain timeperiod, and the calculated average value is updated when the corresponding sensor value changes.
(This average is timestamped with the time of calculation, and hence the changes of average in the graph.)

However, I'm greatly confused by the screenshot in the README.md: Temperature 48h

Near the end of the graph, you see the actual outdoor temperature is below average and still decreasing.
However, the average temperature is rising during that same period, which is the oposite of what is expected from an average.

Is this a bug? Or what kind of average does this sensor calculate?

Entity is renamed after every restart of HA

Version of the Home Assistant: core-2021.3.1
Version of the custom component: v1.7.1

Configuration

    name: 'Temperature Last 3 Day Average'
    duration:
      days: 3
    entities:
      - sensor.temperaturelightcourtyard_am2301_temperature

Bug
After restart / reboot of Home assistant the entity of Average sensor becomes unavailable. New entity is created with _1 , _2 , _3 and so on - see attached screenshot
entity

LOG

2021-03-05 18:18:03 INFO (MainThread) [homeassistant.components.sensor] Setting up sensor.average
2021-03-05 18:18:03 INFO (MainThread) [custom_components.average.sensor]
-------------------------------------------------------------------
Average Sensor
Version: 1.7.1
This is a custom integration!
If you have ANY issues with this you need to open an issue here:
https://github.com/Limych/ha-average/issues
-------------------------------------------------------------------

2021-03-05 18:18:03 INFO (MainThread) [homeassistant.helpers.entity_registry] Registered new sensor.average entity: sensor.temperature_last_3_day_average_4

The sensor does not work in HA 2021.7.3

Environment

  • Home Assistant Core release with the issue:
  • 2021.7.3
  • This custom component release with the issue:
  • 2.1.0
  • Last working this custom component release (if known):
  • 2021.6.6
  • Operating environment (Home Assistant/Supervisor/Docker/venv):
  • HASS OS

Describe the bug
The component does not work. Instead of calculating the average of sensors, it is listed as unavailable. The system does not report any issues setting it up though, as it sometimes does.

Configuration.yaml

  - platform: average
    name: "AvLux"
    duration:
      minutes: 10
    entities:
      - sensor.sofa_lux_illuminance_lux
      - sensor.bedroom_lux_illuminance_lux
      - sensor.kitchen_lux_illuminance_lux

Steps to Reproduce
No steps necessary

Expected behavior
It would calculate the number and show in Lovelace

Debug log

2021-07-17 18:34:05 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.avkitchlux fails
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 401, in async_update_ha_state
await self.async_device_update()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 609, in async_device_update
raise exc
File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/homeassistant/homeassistant/util/init.py", line 280, in wrapper
result = method(*args, **kwargs)
File "/config/custom_components/average/sensor.py", line 327, in update
self._update_state()
File "/config/custom_components/average/sensor.py", line 499, in _update_state
history_list = history.state_changes_during_period(
File "/usr/src/homeassistant/homeassistant/components/recorder/history.py", line 142, in state_changes_during_period
with session_scope(hass=hass) as session:
File "/usr/local/lib/python3.9/contextlib.py", line 117, in enter
return next(self.gen)
File "/usr/src/homeassistant/homeassistant/components/recorder/util.py", line 57, in session_scope
session = hass.data[DATA_INSTANCE].get_session()
TypeError: 'NoneType' object is not callable

Add your logs here.


**Additional context**
<!--
  Add any other context about the problem here.
-->

Option for adding more attributes

I have just installed this and I quite like it.

I am currently using both template sensors and min_max sensors. But neither are really good solutions I think.
The min_max sensor creates spikes when one of the source sensors goes unknown:
image
And the template sensor requires to write a lot of code if you want to add the slightes bit of complexity/additional info.

So this looks better since it seems to create gaps if any source values are missing instead of spikes, which I prefer:
image

And when adding the time duration average (I assume the math is essentially the same as the time_simple_moving_average in the filter sensor) in the same sensor, a couple of intermidiate sensors are no longer needed.

But was wondering if the following additional features would be possible to add without too much work:

Option to add the source sensors as sensor attributes would be cool. Something like this:
image

It could also be interesting to add the time since last_update of the source sensor which was updated the longest time ago.

Separate charts, one with data and one with average

Environment

  • Home Assistant Core release with the issue: 2021.9.7
  • This custom component release with the issue: 2.2.0
  • Last working this custom component release (if known): I don't know
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Home Assistant OS 6.4

Describe the bug

I creating Avarage sensor how it is decribed in documentaion, but Avarage is on additional entity, not together with main sensor.
And also when it isn't set [Duration] I have identical values of main sensor. Look on link https://ibb.co/1bG7VyY

Configuration.yaml

Add your configs here if any.
#Avarage
  - platform: average
    name: 'Average Flights Tracked'
    duration:
      days: 1
    entities:
      - sensor.fr24_feeder_aircraft_tracked
  - platform: average
    name: 'Average Flights Uploaded'
    entities:
      - sensor.fr24_feeder_aircraft_uploaded
  - platform: average
    name: 'Average CPU Temperature'
    entities:
      - sensor.cpu_temperature

Steps to Reproduce

Expected behavior

All data on one chart

Debug log


Add your logs here.

Additional context

Component does not work in HA 2021.6.4

As in the topic, the component does not work and is immediately listed by HA during start-up as the one that could not be configured. Re-installing it does not help.

Not working negative number

Environment

  • Home Assistant Core release with the issue:
  • This custom component release with the issue:
  • Last working this custom component release (if known):
  • Operating environment (Home Assistant/Supervisor/Docker/venv):

Describe the bug

Configuration.yaml

  - platform: average
    name: 'Průměrný rozdíl teploty'
    precision: 2
    entities:
      - sensor.rozdil_teploty_obyvak
      - sensor.rozdil_teploty_kuchyn
      - sensor.rozdil_teploty_chodba
      - sensor.rozdil_teploty_koupelna
      - sensor.rozdil_teploty_patro
      - sensor.rozdil_teploty_loznice
      - sensor.rozdil_teploty_sklep
      - sensor.rozdil_teploty_patro_pokoj
      

Steps to Reproduce

Expected behavior

Debug log


Add your logs here.

Additional context

Enable START and END to not require 2 variables

Request

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

I would like to be able to call just 1 variable of either Start or Stop.
My usable of Average works out the average lux of 2 or more motion/lux sensors (Philips Hue sensors).
My current automation takes the average lux and, depending on the value, will turn lights on.
The problem is, when lights go on, the lux average goes up. Hue sensors capture lux every 5 minutes or when there is motion (however when there is motion after a high lux, a race condition occurs and the new average lux remains high due to both motion sensors needing to gather new lux data - generally, 1 of the sensors will show low lux (beta season movement triggered a lux update request), however as the 2nd Sensor hasn’t been activated to take a new reading, its value is still high and therefore average lux is too high and no lights come on)

Scenario 1 - Working well
Sensor 1 value is 3 lux.
Sensor 2 value is 3 lux.
Last motion was 10 minutes ago.
Average lux has the correct low value (eg 3).
When there is motion, automation checks average lux, which is below threshold, and turns on the light.
Average lux value goes to 90 (due to sensor 1 and 2 having average lux of 90).

Scenarios 2 - Not working as expected
Scenario 1 has been executed.
Lights turn off.
Average lux is 90.
Within 1 minute, motion sensors detect new motion.
Sensor 1 value is 3 (due to lights off and motion triggered a new lux reading).
Sensor 2 value is 90 (due to no new lux sensor update and the 5 minute trigger for a new reading hasn’t been reached).
Average lux value changes due to 1 motion sensor lux reading at 3 (due to new motion). But sensor 2 lux value hasn’t changed and so is still 90.
Average lux value is 46.5.
Automation evaluates average lux value but doesn’t turn on the lights.

A clear and concise description of what you want to happen.

To be able to call average sensor update with a Start or Stop.
Start would begin recording new sensor values.
Stop would stop recording sensor values.
Or some other way to be able to start and stop recording average values

Add any other context or screenshots about the feature request here.

Do not save near empty first recorder entry of an average sensor

Environment

  • Home Assistant Core release with the issue: 2021.10.4
  • This custom component release with the issue: 2.2.0
  • Last working this custom component release (if known): -
  • Operating environment (Home Assistant/Supervisor/Docker/venv): OS

Describe the bug

Please add unit_of_measurement and device_class attributes to the first recorder entry of an average sensor. Currently each recorder/database entry contains these attributes, only the first entry not. If the real sensor gets unavailable later, it's not a problem, the average sensor will store the the above attributes. This is a problem only for the first ever recorder database state entry of the average sensor.

UPDATE:

After adding the average sensor to the configuration and restarting HA core, the first ever recorder entry of an average sensor doesn't contain any data. Without unit_of_measurement and device_class attributes eg. the history graph card can't put sensors to the same chart, if they don't have the same unit_of_measurement.

This bug always appears after the average sensor is created, but sometimes happen after a plain HA core restart also (but I wasn't able to reproduce this second case deterministically, I think it is related to the availability of HA components during restart, and if the recorder is not available, maybe this causes the same problem as the average sensor first start, ie. no historic data is available).

My guess is that this bug is caused by the source sensor (or it's data) is temporarily unavailable. This is not a problem, if the system is already on and has source/average data available when the source sensor become temporarily unavailable. Though it is a problem, if the source sensor is not available during system startup and if it is the first time after creating the sensor, there won't be any previous data available and will result in a saved near empty state, with 100% certainty.

I have to delete manually the first entry of the new average sensor from the recorder database, because Home Assistant gets the "static" attributes, like unit_of_measurement from the first entry. Without proper unit_of_measurement, eg. the history graph card can't put sensors to the same chart, if they don't have the same unit_of_measurement.

Configuration.yaml

sensor:
  - platform: average
    name: 'Bedroom2 humidity average'
    entities:
      - sensor.bedroom2_humidity
    duration:
      minutes: 1
    precision: 1
    process_undef_as: 50.0

Steps to Reproduce

Adding the average sensor to the configuration and restarting HA core.

Expected behavior

Debug log


Add your logs here.

Additional context

First ever entry of an average sensor in states table, attributes column:

{
	"state_class": "measurement",
	"friendly_name": "Bedroom2 humidity average"
}

Typical non-first entry of a working sensor's average sensor:

{
	"state_class": "measurement",
	"start": "2021-10-13T15:36:22+02:00",
	"end": "2021-10-13T15:37:22+02:00",
	"sources": [
		"sensor.bedroom2_humidity"
	],
	"count_sources": 1,
	"available_sources": 1,
	"count": 1,
	"max_value": 67.8,
	"min_value": 67.8,
	"unit_of_measurement": "%",
	"friendly_name": "Bedroom2 humidity average",
	"device_class": "humidity"
	"icon": "hass:water-percent"
}

Typical non-first entry of an unavailable sensor's average sensor:

{
	"state_class": "measurement",
	"start": "2021-10-13T15:36:23+02:00",
	"end": "2021-10-13T15:37:23+02:00",
	"sources": [
		"sensor.spare_humidity"
	],
	"count_sources": 1,
	"available_sources": 1,
	"count": 0,
	"unit_of_measurement": "%",
	"friendly_name": "Spare humidity average",
	"device_class": "humidity",
	"icon": "hass:water-percent"
}

2021.6 Dev release error....

Environment

  • Home Assistant Core release with the issue: 2021.6.0.dev20210525
  • This custom component release with the issue: latest
  • Last working this custom component release (if known): none in this dev release
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Supervised

Describe the bug

Configuration.yaml

  - platform: average
    name: today_temp_bom
    entities:
      - sensor.brisbane_temp
    start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    end: '{{ now() }}'

Steps to Reproduce

Expected behavior

Debug log

Logger: homeassistant.config
Source: custom_components/average/sensor.py:23
Integration: average (documentation, issues)
First occurred: 12:48:37 PM (1 occurrences)
Last logged: 12:48:37 PM

Platform error: sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config.py", line 853, in async_process_component_config
    platform = p_integration.get_platform(domain)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 472, in get_platform
    cache[full_name] = self._import_platform(platform_name)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 477, in _import_platform
    return importlib.import_module(f"{self.pkg_path}.{platform_name}")
  File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/config/custom_components/average/sensor.py", line 23, in <module>
    from homeassistant.components.history import LazyState
ImportError: cannot import name 'LazyState' from 'homeassistant.components.history' (/usr/src/homeassistant/homeassistant/components/history/__init__.py)

Additional context

Average over time period fails

Versions

  • Version of the Home Assistant: 2021.1.2
  • Version of the custom component: 1.6.6

Configuration

- platform: average
  name: Bedroom Average Overnight Temperature
  start: '{{ as_timestamp( now().replace(hour=23).replace(minute=0).replace(second=0) ) - 86400 }}'
  duration:
    hours: 8
  entities:
    - sensor.bedroom_sensor_temperature

Describe the bug

I have several average sensors to assess environmental factors that might impact sleep quality so average from 11 pm to 7am. These all worked for many months but after a HASS release (aprox 17 Dec - but don't know exactly which version as I am usually take a few days to update) they all fail with this error. I have tried various different timestamp and date time configurations but without success.

To Reproduce

n/a

Expected behavior

Average temperature from 11pm last night to 7am this morning.

Screenshots

n/a

Debug log


Logger: homeassistant.helpers.entity
Source: util/dt.py:131 
First occurred: 22:01:22 (4 occurrences) 
Last logged: 22:02:47

Update for sensor.bedroom_average_overnight_temperature fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 278, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 474, in async_device_update
    raise exc
  File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 239, in wrapper
    result = method(*args, **kwargs)
  File "/config/custom_components/average/sensor.py", line 280, in update
    self._update_state()
  File "/config/custom_components/average/sensor.py", line 369, in _update_state
    self._update_period()
  File "/config/custom_components/average/sensor.py", line 305, in _update_period
    start = dt_util.parse_datetime(start_rendered)
  File "/usr/src/homeassistant/homeassistant/util/dt.py", line 131, in parse_datetime
    return ciso8601.parse_datetime(dt_str)
TypeError: argument 1 must be str, not float

Additional context

First ever GitHub Issue so please be gentle and let me know if you need more context.

Component throws error if you specify: 'process_undef_as: 0'

Upgraded to current version, if you specify an integer 0 not float 0.0 app throws error.

Recommend updating documentation to reflect requirement.

process_undef_as: 0

process_undef_as:
(number) (Optional)
Process undefined values (unavailable, sensor undefined, etc.) as specified value.

Issue with sensors not reporting continuously

Hi

I have an issue with sensors that only report data when there is a change. I'm using the built in filter sensor that produce wrong data when no more data is coming in, i.e. when the sun goes down and no more sun kw is reported it still shows the last calculated average. I was hoping your sensor would solve my issue as you took into account the time you have had a value. But I get a new issue with large jumps in readings instead, likely also caused by the sensor not reporting any value for some time.

The red curve is the filter sensor (moving average, window 30min) and the other colour is the average sensor (duration 30min). Is this something that can be solved?

bild

/Henrik

Conflicting info, UI supported or not?

Environment

  • Home Assistant Core release with the issue: 2021.05.0
  • This custom component release with the issue: 1.7.3
  • Last working this custom component release (if known): none
  • Operating environment (Home Assistant/Supervisor/Docker/venv): venv

Describe the bug

After installing via HACS i get an message saying that I should add via the UI (info.md).
But there isn't any integration called "average" or variations thereof that I can add with the UI.
The readme.md only documents installation via configuration.yaml. Which one is it?

Configuration.yaml

Add your configs here if any.

Steps to Reproduce

Expected behavior

Debug log


Add your logs here.

Additional context

ValueError: None is not a recognized temperature unit.

Versions

  • Version of the Home Assistant: 0.118.4
  • Version of the custom component: 1.6.5

Configuration

- platform: average
  name: 'Interior Temperature 1h'
  duration:
    hours: 1
  entities:
    - sensor.interior_temperature

sensor.interior_temperature has the following output:

sensors:
  - sensor.temperature1
  - sensor.temperature2
  - ...
unit_of_measurement: °C
friendly_name: Interior Temperature
device_class: temperature

Describe the bug

unit_of_measurement of source sensor is not recognized correctly. Avg sensor value is unavailable.

To Reproduce

If applicable, describe the steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

Avg output of last hour of source sensor.

Screenshots

If applicable, add screenshots to help explain your problem.

Debug log


Logger: homeassistant.helpers.entity
Source: custom_components/average/sensor.py:260
First occurred: 0:03:46 (15 occurrences)
Last logged: 0:10:34

Update for sensor.interior_temperature_1h fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 278, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 474, in async_device_update
    raise exc
  File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 239, in wrapper
    result = method(*args, **kwargs)
  File "/config/custom_components/average/sensor.py", line 299, in update
    self._update_state()
  File "/config/custom_components/average/sensor.py", line 477, in _update_state
    current_state = self._get_entity_state(item)
  File "/config/custom_components/average/sensor.py", line 275, in _get_entity_state
    self._get_temperature(entity) if self._temperature_mode else entity.state
  File "/config/custom_components/average/sensor.py", line 260, in _get_temperature
    raise ValueError(
ValueError: None is not a recognized temperature unit.

Additional context

Add any other context about the problem here.

Latest Update causes a couple of errors in log

Versions

  • Version of the Home Assistant: 2021.3.1
  • Version of the custom component:

Configuration

  - platform: average
    name: ha_dockermon_memory_average
    entities:
      - sensor.ha_dockermon_memory
    duration:
      days: 2

I have a bunch of those sensors....
Describe the bug
A clear and concise description of what the bug is.
Log error. Not 100% sure it's average causing this but it only happened after updating average.
Debug log


2021-03-05 14:21:14 ERROR (SyncWorker_42) [homeassistant.util.json] Failed to serialize to JSON: /config/.storage/core.entity_registry. Bad data at $.data.entities[432].unique_id=<_sha1.sha1 object at 0x7f5d95d46a40>(<class '_sha1.sha1'>, $.data.entities[433].unique_id=<_sha1.sha1 object at 0x7f5d95d46960>(<class '_sha1.sha1'>, $.data.entities[434].unique_id=<_sha1.sha1 object at 0x7f5d995fc3b0>(<class '_sha1.sha1'>, $.data.entities[435].unique_id=<_sha1.sha1 object at 0x7f5d9229ca40>(<class '_sha1.sha1'>, $.data.entities[436].unique_id=<_sha1.sha1 object at 0x7f5d9229cb90>(<class '_sha1.sha1'>, $.data.entities[437].unique_id=<_sha1.sha1 object at 0x7f5d9229cce0>(<class '_sha1.sha1'>, $.data.entities[438].unique_id=<_sha1.sha1 object at 0x7f5d9229ce30>(<class '_sha1.sha1'>, $.data.entities[439].unique_id=<_sha1.sha1 object at 0x7f5d9229cf80>(<class '_sha1.sha1'>, $.data.entities[440].unique_id=<_sha1.sha1 object at 0x7f5d92263110>(<class '_sha1.sha1'>, $.data.entities[441].unique_id=<_sha1.sha1 object at 0x7f5d922632d0>(<class '_sha1.sha1'>, $.data.entities[442].unique_id=<_sha1.sha1 object at 0x7f5d92263490>(<class '_sha1.sha1'>, $.data.entities[443].unique_id=<_sha1.sha1 object at 0x7f5d922635e0>(<class '_sha1.sha1'>, $.data.entities[444].unique_id=<_sha1.sha1 object at 0x7f5d92263730>(<class '_sha1.sha1'>, $.data.entities[445].unique_id=<_sha1.sha1 object at 0x7f5d92263880>(<class '_sha1.sha1'>, $.data.entities[446].unique_id=<_sha1.sha1 object at 0x7f5d9229c570>(<class '_sha1.sha1'>, $.data.entities[447].unique_id=<_sha1.sha1 object at 0x7f5d93d20260>(<class '_sha1.sha1'>, $.data.entities[448].unique_id=<_sha1.sha1 object at 0x7f5d995fc880>(<class '_sha1.sha1'>, $.data.entities[449].unique_id=<_sha1.sha1 object at 0x7f5d92263260>(<class '_sha1.sha1'>, $.data.entities[450].unique_id=<_sha1.sha1 object at 0x7f5d92263ab0>(<class '_sha1.sha1'>, $.data.entities[451].unique_id=<_sha1.sha1 object at 0x7f5d925ee180>(<class '_sha1.sha1'>
2021-03-05 14:21:14 ERROR (MainThread) [homeassistant.helpers.storage] Error writing config for core.entity_registry: Failed to serialize to JSON: /config/.storage/core.entity_registry. Bad data at $.data.entities[432].unique_id=<_sha1.sha1 object at 0x7f5d95d46a40>(<class '_sha1.sha1'>, $.data.entities[433].unique_id=<_sha1.sha1 object at 0x7f5d95d46960>(<class '_sha1.sha1'>, $.data.entities[434].unique_id=<_sha1.sha1 object at 0x7f5d995fc3b0>(<class '_sha1.sha1'>, $.data.entities[435].unique_id=<_sha1.sha1 object at 0x7f5d9229ca40>(<class '_sha1.sha1'>, $.data.entities[436].unique_id=<_sha1.sha1 object at 0x7f5d9229cb90>(<class '_sha1.sha1'>, $.data.entities[437].unique_id=<_sha1.sha1 object at 0x7f5d9229cce0>(<class '_sha1.sha1'>, $.data.entities[438].unique_id=<_sha1.sha1 object at 0x7f5d9229ce30>(<class '_sha1.sha1'>, $.data.entities[439].unique_id=<_sha1.sha1 object at 0x7f5d9229cf80>(<class '_sha1.sha1'>, $.data.entities[440].unique_id=<_sha1.sha1 object at 0x7f5d92263110>(<class '_sha1.sha1'>, $.data.entities[441].unique_id=<_sha1.sha1 object at 0x7f5d922632d0>(<class '_sha1.sha1'>, $.data.entities[442].unique_id=<_sha1.sha1 object at 0x7f5d92263490>(<class '_sha1.sha1'>, $.data.entities[443].unique_id=<_sha1.sha1 object at 0x7f5d922635e0>(<class '_sha1.sha1'>, $.data.entities[444].unique_id=<_sha1.sha1 object at 0x7f5d92263730>(<class '_sha1.sha1'>, $.data.entities[445].unique_id=<_sha1.sha1 object at 0x7f5d92263880>(<class '_sha1.sha1'>, $.data.entities[446].unique_id=<_sha1.sha1 object at 0x7f5d9229c570>(<class '_sha1.sha1'>, $.data.entities[447].unique_id=<_sha1.sha1 object at 0x7f5d93d20260>(<class '_sha1.sha1'>, $.data.entities[448].unique_id=<_sha1.sha1 object at 0x7f5d995fc880>(<class '_sha1.sha1'>, $.data.entities[449].unique_id=<_sha1.sha1 object at 0x7f5d92263260>(<class '_sha1.sha1'>, $.data.entities[450].unique_id=<_sha1.sha1 object at 0x7f5d92263ab0>(<class '_sha1.sha1'>, $.data.entities[451].unique_id=<_sha1.sha1 object at 0x7f5d925ee180>(<class '_sha1.sha1'>


Average does not change, when sensor does not update for a while

This sensor is great and I want to primarily use it to calculate the autarky I have due to solar power.
There is a live autarky sensor I have integrated.

My issue is, that this sensor changes to 0 once no sun is out and the battery is empty. Then it stays on this value until it is charged again. It does not send any updates. Now I have a time frame from 11:47 pm until 9:53 am, which is only represented by one value.
This is 0 and should drive down the average quite significantly.

Any chance to take the timeframe a value has not changed into account?

[BUG] process_undef_as isn't used when source sensor is unavailable, average value goes to 0.0

Versions

  • Version of the Home Assistant: 2021.1.4
  • Version of the custom component: 1.6.7

Configuration

- platform: average
  name: 'Working room Temperature Average'
  entities:
    - sensor.working_room_temperature
  duration:
    minutes: 1
  precision: 1
  process_undef_as: 25.0

Describe the bug

process_undef_as has no effect on the calculated average, it doesn't even hold the last known value, it goes to 0.0 if the source sensor is unavailable.

To Reproduce

Source sensor state goes to 'unavailable' due to power or communication failure, but average sensor doesn't use the process_undef_as value.

Expected behavior

Average value slowly goes to the configured process_undef_as value.

Screenshots

Red line: Source sensor
Blue line: Average sensor

Average_01

Debug log

2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Updating sensor "Working room Temperature Average"
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Process start template: None
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Process end template: None
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Process duration: 0:01:00
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Start: 2021-01-22 19:43:20.243343+01:00, End: 2021-01-22 19:44:20.243343+01:00
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Processing entity "sensor.working_room_temperature"
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Initial historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:42:00.480175+01:00>
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:43:20.243343+01:00>
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Historical average state: 23.0
2021-01-22 19:44:20 DEBUG (SyncWorker_1) [custom_components.average.sensor] Total average state: 23.0

2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Updating sensor "Working room Temperature Average"
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Process start template: None
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Process end template: None
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Process duration: 0:01:00
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Start: 2021-01-22 19:43:50.227068+01:00, End: 2021-01-22 19:44:50.227068+01:00
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Processing entity "sensor.working_room_temperature"
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Initial historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:42:00.480175+01:00>
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:43:50.227068+01:00>
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=unavailable; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:44:26.507631+01:00>
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Historical average state: 23.0
2021-01-22 19:44:50 DEBUG (SyncWorker_4) [custom_components.average.sensor] Total average state: 23.0

2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Updating sensor "Working room Temperature Average"
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Process start template: None
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Process end template: None
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Process duration: 0:01:00
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Start: 2021-01-22 19:44:20.255588+01:00, End: 2021-01-22 19:45:20.255588+01:00
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Processing entity "sensor.working_room_temperature"
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Initial historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:42:00.480175+01:00>
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=23.0; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:44:20.255588+01:00>
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=unavailable; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:44:26.507631+01:00>
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Historical average state: 23.0
2021-01-22 19:45:20 DEBUG (SyncWorker_3) [custom_components.average.sensor] Total average state: 23.0

2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Updating sensor "Working room Temperature Average"
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Process start template: None
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Process end template: None
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Process duration: 0:01:00
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Start: 2021-01-22 19:44:50.257547+01:00, End: 2021-01-22 19:45:50.257547+01:00
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Processing entity "sensor.working_room_temperature"
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Initial historical state: <state sensor.working_room_temperature=unavailable; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:44:26.507631+01:00>
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Historical state: <state sensor.working_room_temperature=unavailable; unit_of_measurement=°C, friendly_name=Working room SI7021 Temperature, device_class=temperature @ 2021-01-22T19:44:50.257547+01:00>
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Historical average state: 0
2021-01-22 19:45:50 DEBUG (SyncWorker_2) [custom_components.average.sensor] Total average state: 0.0

Additional context

This for loop in _update_state goes through the historical states, but doesn't detect if all the states are unavailable, value = 0 remains 0, and the counted average goes to 0. I think this _has_state check is unnecessary, because _get_state_value will return the _undef value.

ValueError: could not convert string to float: 'None'

Version of the custom_component
1.4.2 bb1cdba

Configuration

sensors:
# original sensor
  - platform: mqtt
    name: "Sonoff1 Temperature"
    state_topic: "tele/sonoff1/SENSOR"
    unit_of_measurement: '°C'
    value_template: "{{value_json['SI7021'].Temperature}}"

# average sensor
  - platform: average
    name: 'Sonoff1 Temperature Average'
    duration:
      days: 1
    entities:
      - sensor.sonoff1_temperature

# repeat the above with sonoff5 and sonoff6

Describe the bug

When the original sensor entity to compute the average of, is available but has an unknown state, this error occurs.
This might be related to #2?

To Reproduce

  1. Unplug the temperature sensor. (Here i did that for the sonoff1 sensor which is the living room.)
  2. The state of the original temperature sensor entity changes to unknown (see fig 1).
  3. Create the average sensor as shown above and restart HA
    (So during the first start of the average sensor, the original sensor has no value, but there are still values in the period (1 day) to compute the average of, see fig 2)
  4. The average sensor produces that error and does not compute the average value (see fig 3).
  5. Even after plugging the sensor back in so it transmits data to HA and the original sensor entity has a float value again (see living room temp in fig 2 at the right side), the average sensor still throws that error.

The other average sensors (sonoff5 and sonoff6) worked fine, as they had a not-unknown state for their original sensors for > 1 day.

Expected behavior

I expected the average sensor to produce an average value of the configured period of all the not-unknown values in that period. It looks like, the average sensor cannot cope with past (or still ongoing) sections in the state history that have unknown values.

Screenshots

fig 1
image

fig 2
image

fig 3
image

Debug log

Update for sensor.sonoff1_temperature_average fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 279, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 472, in async_device_update
    await self.hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 240, in wrapper
    result = method(*args, **kwargs)
  File "/config/custom_components/average/sensor.py", line 284, in update
    self._update_state()
  File "/config/custom_components/average/sensor.py", line 472, in _update_state
    current_state = self._get_entity_state(item)
  File "/config/custom_components/average/sensor.py", line 260, in _get_entity_state
    state = self._get_temperature(entity) if self._temperature_mode \
  File "/config/custom_components/average/sensor.py", line 248, in _get_temperature
    temperature = float(temperature)
ValueError: could not convert string to float: 'None'

Thanks for your work at this component! Feel free to let me know how to further assist you in tracing this down.

Precision not working correctly

Version of the custom_component

c78e313 (installed via HACS)

Configuration

sensor:
  - platform: average
    name: 'Overloop gemiddelde lichtsterkte'
    duration:
      minutes: 15
    precision: 0
    entities:
      - sensor.0x0017880102139e87_illuminance

Describe the bug

I would expect precision: 0 to display 0 decimals.

image

Top N-precentile

Can I suggest you implement an N-percentile average feature?
It will be used to get more accurate average reading from not so accurate sensors like PM sensors.
The way to implement is just simple to sort the data range by value and drop some percent of top/bottom values before calculating the average.

Configurable variables should be:

  • N percent
  • Drop from: top, bottom, both(N/2 each)

Average sensor updating often

Environment

  • Home Assistant Core release with the issue: core-2021.8.8
  • This custom component release with the issue: 2.2.0
  • Last working this custom component release (if known):
  • Operating environment (Home Assistant/Supervisor/Docker/venv): Home Assistant Core I think

Describe the bug
Im using irrigation_unlimited. The 5 day moving average sensor is updating every 30 sec but the input sensor sensor.wupws_temp_2 did not.

sensor.wupws_temp_2
sensor.irrigation_unlimited_temperature_5_day_moving_average

Configuration.yaml

# Filename: irrigation_unlimited_adjustment.yaml
#
# This file is a package and should be located in the config/packages
# folder. If you do not have a packages folder then create it and add
# the following to configuration.yaml
#
# homeassistant:
#  packages: !include_dir_named packages
#
# More information on packages can be found at https://www.home-assistant.io/docs/configuration/packages
#
# Set up some observation sensors.
# This uses the Weather Underground (WUnderground) https://www.home-assistant.io/integrations/wunderground/ integration.
# Rain information (wupws_preciptotal) is a daily accumulation total. So we want to grab the
# data just before midnight to get the daily total. We shouldn't be too eager to look after midnight
# because the reset from WU may take a few minutes to come through, currently 10 min. Increase this
# if data is unreliable.
# Note: Requires the ha-average integration to be installed https://github.com/Limych/ha-average
sensor:
  - platform: average
    name: irrigation_unlimited_rain_0
    entities:
      - sensor.wupws_preciptotal_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}'
    end: '{{ now() }}'

  - platform: average
    name: irrigation_unlimited_rain_1
    entities:
      - sensor.wupws_preciptotal_2
    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) }}'

  - platform: average
    name: irrigation_unlimited_rain_2
    entities:
      - sensor.wupws_preciptotal_2
    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) }}'

  - platform: average
    name: irrigation_unlimited_rain_3
    entities:
      - sensor.wupws_preciptotal_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=3) }}'
    end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=3) }}'

  - platform: average
    name: irrigation_unlimited_rain_4
    entities:
      - sensor.wupws_preciptotal_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}'
    end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=4) }}'

  - platform: average
    name: irrigation_unlimited_temperature_0
    entities:
      - sensor.wupws_temp_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) }}'
    end: '{{ now() }}'

  - platform: average
    name: irrigation_unlimited_temperature_1
    entities:
      - sensor.wupws_temp_2
    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) }}'

  - platform: average
    name: irrigation_unlimited_temperature_2
    entities:
      - sensor.wupws_temp_2
    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) }}'

  - platform: average
    name: irrigation_unlimited_temperature_3
    entities:
      - sensor.wupws_temp_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=3) }}'
    end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=3) }}'

  - platform: average
    name: irrigation_unlimited_temperature_4
    entities:
      - sensor.wupws_temp_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}'
    end: '{{ now().replace(hour=23).replace(minute=59).replace(second=0) - timedelta(days=4) }}'

  - platform: average
    name: irrigation_unlimited_temperature_5_day_moving_average
    entities:
      - sensor.wupws_temp_2
    precision: 1
    start: '{{ now().replace(hour=0).replace(minute=30).replace(second=0) - timedelta(days=4) }}'
    end: '{{ now() }}'

  # Five day weighted rain total sensor.
  # Adjust the weight values (0.7, 0.3, 0.15, 0.05) to suit your needs (0.0 = ignore that day).
  - platform: template
    sensors:
      irrigation_unlimited_rain_weighted_total:
        friendly_name: "Irrigation Unlimited Rain Weighted Total"
        unit_of_measurement: 'mm'
        icon_template: 'mdi:umbrella'
        value_template: >
          {% set rain_total = state_attr('sensor.irrigation_unlimited_rain_0','max_value') | float %}
          {% set rain_total = rain_total + state_attr('sensor.irrigation_unlimited_rain_1','max_value') | float * 0.7 %}
          {% set rain_total = rain_total + state_attr('sensor.irrigation_unlimited_rain_2','max_value') | float * 0.3 %}
          {% set rain_total = rain_total + state_attr('sensor.irrigation_unlimited_rain_3','max_value') | float * 0.15 %}
          {% set rain_total = rain_total + state_attr('sensor.irrigation_unlimited_rain_4','max_value') | float * 0.05 %}
          {{ rain_total | round(1) }}

# Automation to adjust the run times for Irrigation Unlimited.
# It uses the 5 day weighted rain total and the moving 5 day average temperature sensors
# created above to generate a variation.
# Adjust rain_total_threshold, rain_rate_threshold and temperature_threshold variables to suit you needs.
automation:
  - alias: Irrigation Unlimited Adjustment
    trigger:
      platform: state
      entity_id:
        - sensor.irrigation_unlimited_rain_weighted_total
        - sensor.irrigation_unlimited_temperature_5_day_moving_average
        - sensor.wupws_preciprate_2
    action:
      service: irrigation_unlimited.adjust_time
      data:
        entity_id: binary_sensor.irrigation_unlimited_c1_m
        percentage: >
          {# Threshold variables #}
          {% set rain_total_threshold = 3.5 %}
          {% set rain_rate_threshold = 1.0 %}
          {% set temperature_threshold = 20.0 %}

          {# Sensor data #}
          {% set rain_total = states('sensor.irrigation_unlimited_rain_weighted_total') | float %}
          {% set rain_rate = states('sensor.wupws_preciprate_2') | float %}
          {% set temperature_average = states('sensor.irrigation_unlimited_temperature_5_day_moving_average') | float %}

          {# Threshold variables #}
          {% set rain_multiplier = (1 - (rain_total / rain_total_threshold)) %}
          {% set temperature_multiplier = temperature_average / temperature_threshold %}

          {% set multiplier = 1.0 %}
          {% if rain_rate < rain_rate_threshold and rain_multiplier > 0 and rain_total < rain_total_threshold %}
            {% set multiplier = multiplier * temperature_multiplier %}
            {% set multiplier = multiplier * rain_multiplier %}
          {% else %}
            {% set multiplier = 0.0 %} {# It's raining or enough already #}
          {% endif %}

          {# Return multiplier as a percentage #}
          {{ (multiplier * 100) | round(0) }}

Steps to Reproduce

Expected behavior

Debug log


Logger: homeassistant.helpers.template
Source: helpers/template.py:1406
First occurred: 3:40:17 PM (14 occurrences)
Last logged: 3:43:06 PM

Template variable warning: 'None' has no attribute 'last_updated' when rendering 'wupws_temp: {{ states.sensor.wupws_temp.last_updated }} Moving average: {{ states.sensor.irrigation_unlimited_temperature_5_day_moving_average.last_updated }}'

Additional context
Screen Shot 2021-08-28 at 10 55 59 am
Screen Shot 2021-09-01 at 4 42 27 pm

Use of helpers

does the possibility exist to use a helper or entity to provide the timestamp reference for start and end?

Update group entity sources when group members change

Is your feature request related to a problem? Please describe.
The main issue I'm having is that whenever I add an entity to a group to be used with this integration, the new entity isn't factored by the integration. For example, I have the group "average temperature" and in the group I have 2 entities, one with 50F and the other with 100F. The initial average is 75F, but when I add another entity to the group via a service call, this integration doesn't take into account the third entity I just added and the average is still 75F.

Describe the solution you'd like
I'd like the integration to have a way of knowing that the group's members have changed, and then get the new entities it should use in the averaging function. OR, if the integration can't "listen" to changes, just add an option for the number of minutes the integration will refresh the group's membership.

Describe alternatives you've considered
No other alternatives that I know of.

Additional context
This integration is the cornerstone of my thermostat in home assistant. It would save me a lot of manual work if group members could be refreshed every now and then.

isse in the logs

-->

Version of the custom_component

Installed: c78e313
Available: c78e313

Configuration

## HACS: https://github.com/Limych/ha-average
  - platform: average
    name: 'Average Temp - Living Room'
    entities:
      - sensor.button_living_room_temperature_measurement
      - sensor.living_room_temperature_tracker
      - sensor.mps_living_room_window_temperature_measurement

  - platform: average
    name: 'Average Temp - Jamie Office'
    entities:
      - sensor.jamie_office_temperature_tracker
      - sensor.mps_jamie_office_door_temperature_measurement

Describe the bug

Getting this error in my logs

Debug log


Log Details (ERROR)
Sat Dec 07 2019 22:43:44 GMT+0000 (Greenwich Mean Time)
Error doing job: Exception in callback <function EventBus.async_listen_once.<locals>.onetime_listener at 0xad484e40>
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
  File "/usr/src/homeassistant/homeassistant/core.py", line 663, in onetime_listener
    self._hass.async_run_job(listener, event)
  File "/usr/src/homeassistant/homeassistant/core.py", line 371, in async_run_job
    target(*args)
  File "/config/custom_components/average/sensor.py", line 207, in sensor_startup
    sensor_state_listener(None, None, None)
  File "/config/custom_components/average/sensor.py", line 194, in sensor_state_listener
    self._update_state()
  File "/config/custom_components/average/sensor.py", line 496, in _update_state
    self._state = round(sum(values) / len(values), self._precision)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Unavailable (again)

Version of the custom_components c827054

Configuration

- platform: average
  name: Average light level
  entities:
    - sensor.bathroom_light_level
    - sensor.landing_light_level
    - sensor.kitchen_light_level

Describe the bug

Sensor value shows as Unknown

Debug log


Exception in callback async_track_state_change.<locals>.state_change_listener(<Event state_...053304+01:00>>) at /usr/src/homeassistant/homeassistant/helpers/event.py:76
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 95, in state_change_listener
    event.data.get("new_state"),
  File "/usr/src/homeassistant/homeassistant/core.py", line 368, in async_run_job
    target(*args)
  File "/config/custom_components/average/sensor.py", line 194, in sensor_state_listener
    self._update_state()
  File "/config/custom_components/average/sensor.py", line 375, in _update_state
    self._update_period()
  File "/config/custom_components/average/sensor.py", line 357, in _update_period
    if start > now:
TypeError: '>' not supported between instances of 'NoneType' and 'datetime.datetime'

Screenshot_20191011-044037

Get average for a specific time period over a number of days.

Hello!

I am currently using this sensor to get the average temperature at night and another for the average temperature during the day.

I use variations of the following

  - platform: average
    name: 'Average Temperature During Sun'
    start: '{{ now().replace(hour=19).replace(minute=0).replace(second=0) }}'
    duration:
       hours: 20
    entities:
      - sensor.temperature_measurement

The problem is that this gets the average of the current day. If I read the sensor at 12:00, the values for the current day's night have not been captured, and I get a flawed average.

Popup output

Start: 2021-01-05T19:00:00-05:00
End: 2021-01-05T22:46:58-05:00

image

End date is currently showing the latest available time.

Describe the solution you'd like
I would like the ability to get the average of a sensors value between two specific times, over a range of time. For example, The average temperature between 6am and 6pm over the past week or the average temperature between 6pm and 3 am for the past 24 hours.

Describe alternatives you've considered

I tried to specify both hours and days in duration, hoping this would accomplish it.

  - platform: average
    name: 'Average Temperature During Sun'
    start: '{{ now().replace(hour=19).replace(minute=0).replace(second=0) }}'
    duration:
       hours: 20
       days: 5
    entities:
      - sensor.temperature_measurement

Maybe I should just skip using Duration hours in duration and manually specify ranges and use days?

  - platform: average
    name: 'Average Temperature During Sun'
    start: '{{ now().replace(hour=19).replace(minute=0).replace(second=0) }}'
    end: '{{ now().replace(hour=15).replace(minute=0).replace(second=0) }}'
    duration:
       days: 1
    entities:
      - sensor.temperature_measurement

**
Additional context

Really love this tool, this is a much easier way to handle averaging values than some of the alternatives!

Component throws "[custom_components.average.sensor] Could not convert value "" to float"

sensors.yaml

  - platform: mqtt
    name: "KEYT Symbol Error Quality"
    state_topic: "hdhomerun/status/keyt"
    value_template: "{{ value_json.seq }}"
    json_attributes_topic: "hdhomerun/status/keyt"
    unit_of_measurement: 'error'

  - platform: average
    name: 'KEYT Symbol Error Quality Average'
    precision: 0
    process_undef_as: 0.0
    duration:
      minutes: 30
    entities:
      - sensor.keyt_symbol_error_quality

values in recorder database state field other than integers
unknown
"" <- this is state with no value EMPTY

log with debug turned on for component:

2021-02-06 17:41:16 DEBUG (SyncWorker_14) [custom_components.average.sensor] Historical average state: 44.951466059434786
2021-02-06 17:41:16 DEBUG (SyncWorker_14) [custom_components.average.sensor] Total average state: 43.2
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Updating sensor "SoCalPBS Symbol Error Quality Average"
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Process start template: None
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Process end template: None
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Process duration: 0:30:00
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Start: 2021-02-06 17:11:16.688510-08:00, End: 2021-02-06 17:41:16.688510-08:00
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Processing entity "sensor.socalpbs_symbol_error_quality"
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Initial historical state: None
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=0; timestamp=20210207011107, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=49, seq=0, bps=19299328, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:11:16.688510-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=unknown; unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:20:42.286933-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=0; timestamp=20210207012049, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=16, seq=0, bps=19293312, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:20:49.822422-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=unknown; unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:24:09.562432-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=0; timestamp=20210207012411, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=16, seq=0, bps=19392576, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:24:11.136209-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=; timestamp=20210207013639, device=10124488, tuner=0, status=error, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:36:40.861852-08:00>
2021-02-06 17:41:16 ERROR (SyncWorker_11) [custom_components.average.sensor] Could not convert value "" to float
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=0; timestamp=20210207013645, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=31, seq=0, bps=19303840, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:36:45.875919-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=unknown; timestamp=20210207013745, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=19, seq=0, bps=19391072, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:37:46.006870-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical state: <state sensor.socalpbs_symbol_error_quality=0; timestamp=20210207013745, device=10124488, tuner=0, ch=auto:575000000, lock=8vsb, ss=100, snq=19, seq=0, bps=19391072, pps=0, status=signal, unit_of_measurement=error, friendly_name=SoCalPBS Symbol Error Quality @ 2021-02-06T17:37:46.007145-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Historical average state: 0.0
2021-02-06 17:41:16 DEBUG (SyncWorker_11) [custom_components.average.sensor] Total average state: 0.0
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Updating sensor "KEYT Symbol Error Quality Average"
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Process start template: None
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Process end template: None
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Process duration: 0:30:00
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Start: 2021-02-06 17:11:16.698229-08:00, End: 2021-02-06 17:41:16.698229-08:00
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Processing entity "sensor.keyt_symbol_error_quality"
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Initial historical state: None
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207011107, device=10124488, tuner=1, ch=auto:551000000, lock=8vsb, ss=100, snq=69, seq=0, bps=19392576, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:11:16.698229-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=unknown; unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:20:42.666023-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207012049, device=10124488, tuner=1, ch=auto:551000000, lock=8vsb, ss=100, snq=48, seq=0, bps=19394080, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:20:49.800675-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=unknown; unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:24:09.564048-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207012411, device=10124488, tuner=1, ch=auto:551000000, lock=8vsb, ss=100, snq=21, seq=0, bps=19373024, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:24:11.112695-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=; timestamp=20210207012626, device=10124488, tuner=1, status=error, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:26:27.153926-08:00>
2021-02-06 17:41:16 ERROR (SyncWorker_8) [custom_components.average.sensor] Could not convert value "" to float
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207012636, device=10124488, tuner=1, ch=auto:551000000, lock=8vsb, ss=100, snq=32, seq=0, bps=19213600, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:26:36.357451-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=; timestamp=20210207013639, device=10124488, tuner=1, status=error, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:36:39.580941-08:00>
2021-02-06 17:41:16 ERROR (SyncWorker_8) [custom_components.average.sensor] Could not convert value "" to float
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207013645, device=10124488, tuner=1, ch=auto:551000000, lock=8vsb, ss=100, snq=65, seq=0, bps=19318880, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:36:45.871232-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=unknown; unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:37:46.238276-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical state: <state sensor.keyt_symbol_error_quality=0; timestamp=20210207013755, device=10124488, tuner=1, ch=auto:551000000, lock=none, ss=100, snq=0, seq=0, bps=19394080, pps=0, status=signal, unit_of_measurement=error, friendly_name=KEYT Symbol Error Quality @ 2021-02-06T17:37:55.625229-08:00>
2021-02-06 17:41:16 DEBUG (SyncWorker_8) [custom_components.average.sensor] Historical average state: 0.0

hdhomerun_states

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.