AlanQ
(Alan)
April 7, 2021, 12:55pm
1
I hope someone can help. I have a wifi plug with current monitoring and use the info from that as a current sensor in HA. This is used on the tumble dryer to get a notification when it has finished. It works well except that every once in a while the wifi plug goes unavailable and when it becomes available again it triggers a false alert. Any suggestions on how better to code this?
- id: 646380wer4
alias: Tumble Dryer Finished
trigger:
- below: '50'
entity_id: sensor.pm1_watts
for: 00:01:00
platform: numeric_state
condition:
- condition: numeric_state
entity_id: sensor.pm1_voltage
above: '200'
- condition: time
after: 07:00
before: '23:00'
action:
- service: media_player.volume_set
entity_id:
- media_player.everywhere
data:
volume_level: '0.6'
- delay: 00:00:01
- service: notify.alexa_media
data:
target:
- media_player.everywhere
data:
type: announce
message: HURRAY! your pants have finished drying
mode: single
1 Like
123
(Taras)
April 7, 2021, 1:10pm
2
I thought this was fixed for the Numeric State Trigger in the version 2021.3.X. Which version are you using?
AlanQ
(Alan)
April 7, 2021, 1:17pm
3
I’m on 2021.3.3. I see 2021.3.4 is available so I will upgrade although I didn’t notice this issue in the release notes. Be great if that fixes it!
123
(Taras)
April 7, 2021, 1:30pm
4
I believe the correction is in the major release (2021.3 .X), so if you’re not experiencing its improvement then upgrading to the 2021.3.4 patch release won’t help.
It was my understanding that the Numeric State Trigger, on startup, would only trigger if the previous value is a valid numeric value. For example, if it was null
or unknown
and then changed to 45
that should not cause the Numeric State Trigger to trigger (if using below: 50
). I thought unavailable
is handled the same way but your experience implies it isn’t. Perhaps the for
option influences it.
AlanQ
(Alan)
April 7, 2021, 1:37pm
5
Thanks for the explanation but it seems I’ll still have the issue then. I set it to below 50 for 1 minute to make sure the cycle had properly ended. I’ll test without the “for” statement and see what happens.
123
(Taras)
April 7, 2021, 1:58pm
6
The behavior I described is found in this PR:
home-assistant:dev
← amelchio:raise-condition-error
opened 09:22PM - 03 Feb 21 UTC
## Proposed change
This introduces a `ConditionError` exception for cases whe… re the condition helpers are unable to decide a condition. An example is when an entity is unavailable. The helpers have previously returned `False` in this situation but that is really just an arbitrary guess and a potential silent failure.
As a MVP the exception is implemented for the `numeric_state` condition.
With this PR, more useful logging becomes available, for example:
```
[homeassistant.components.automation] Error in 'condition' evaluation: Unknown entity sensor.front_door
[homeassistant.components.automation] Error in 'condition' evaluation: Attribute 'battery_level' (of entity binary_sensor.front_door) does not exist
[homeassistant.components.automation] Error in 'condition' evaluation: Template error: ZeroDivisionError: division by zero
[homeassistant.components.automation] Error in 'condition' evaluation: The below entity input_number.temperature_threshold_low is not available
[homeassistant.helpers.script] Error in 'choose' evaluation: Entity sensor.front_door_battery_level state 'one-hundred' cannot be processed as a number
[homeassistant.helpers.script] Error in 'condition' evaluation: Unknown entity sensor.missing
[homeassistant.helpers.script] Error in 'while' evaluation: Unknown entity sensor.front_door_battery_level
[homeassistant.helpers.script] Error in 'until' evaluation: Template error: ZeroDivisionError: division by zero
[homeassistant.components.homeassistant.triggers.numeric_state] Entity media_player.office state 'paused' cannot be processed as a number
```
This PR is actually a bit of a detour while working on home-assistant/architecture#456. Specifically, we do not want to trigger `numeric_state` when moving from true to unavailable and back to true. However, before this PR we cannot identify unavailable because it just evaluates the condition to false.
## Type of change
<!--
What type of change does your PR introduce to Home Assistant?
NOTE: Please, check only 1! box!
If your PR requires multiple boxes to be checked, you'll most likely need to
split it into multiple PRs. This makes things easier and faster to code review.
-->
- [ ] Dependency upgrade
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [x] New feature (which adds functionality to an existing integration)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests
## Example entry for `configuration.yaml`:
<!--
Supplying a configuration snippet, makes it easier for a maintainer to test
your PR. Furthermore, for new integrations, it gives an impression of how
the configuration would look like.
Note: Remove this section if this PR does not have an example entry.
-->
```yaml
# Example configuration.yaml
```
## Additional information
<!--
Details are important, and help maintainers processing your PR.
Please be sure to fill out additional details, if applicable.
-->
- This PR fixes or closes issue:
- This PR is related to issue: #40331, home-assistant/architecture#456
- Link to documentation pull request:
## Checklist
<!--
Put an `x` in the boxes that apply. You can also fill these out after
creating the PR. If you're unsure about any of them, don't hesitate to ask.
We're here to help! This is simply a reminder of what we are going to look
for before merging your code.
-->
- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] The code has been formatted using Black (`black --fast homeassistant tests`)
- [x] Tests have been added to verify that the new code works.
If user exposed functionality or configuration variables are added/changed:
- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]
If the code communicates with devices, web services, or third-party tools:
- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.
Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
Updated by running `python3 -m script.gen_requirements_all`.
- [ ] Untested files have been added to `.coveragerc`.
The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
The Integration Quality Scale scores an integration on the code quality
and user experience. Each level of the quality scale consists of a list
of requirements. We highly recommend getting your integration scored!
-->
- [ ] No score or internal
- [ ] 🥈 Silver
- [ ] 🥇 Gold
- [ ] 🏆 Platinum
<!--
This project is very active and we have a high turnover of pull requests.
Unfortunately, the number of incoming pull requests is higher than what our
reviewers can review and merge so there is a long backlog of pull requests
waiting for review. You can help here!
By reviewing another pull request, you will help raise the code quality of
that pull request and the final review will be faster. This way the general
pace of pull request reviews will go up and your wait time will go down.
When picking a pull request to review, try to choose one that hasn't yet
been reviewed.
Thanks for helping out!
-->
To help with the load of incoming pull requests:
- [ ] I have reviewed two other [open pull requests][prs] in this repository.
[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone
<!--
Thank you for contributing <3
Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io
This line:
Specifically, we do not want to trigger numeric_state
when moving from true to unavailable and back to true
It was created as a result of this discussion in the Architecture repo:
opened 10:51PM - 07 Nov 20 UTC
closed 08:11AM - 20 Feb 21 UTC
## Context
Inspired by https://github.com/home-assistant/core/issues/40331 I … would like to discuss the startup behaviour of `numeric_state` and `template` triggers. These two triggers are a bit special because they do not directly represent events but rather a Boolean value. They trigger when the Boolean value turns true.
So what happens if the value is already true at startup? Nothing currently happens _at startup_ because automations are disabled at startup. However, once the first relevant state change happens, the trigger is evaluated. If it is still true, _then_ it fires.
This is the example from the issue.
```yaml
- alias: 'Switch on lights at night'
trigger:
- platform: numeric_state
entity_id: sun.sun
value_template: "{{ state.attributes.elevation }}"
below: 3.0
action:
- service: switch.turn_on
entity_id: group.plugs_auto
```
If Home Assistant is restarted at night, this will turn on the lights maybe half an hour later (because `sun.sun` rarely updates during the night). That is generally unexpected and undesired.
Here is another example that will fire the first time light brightness is changed after startup (if the light is on during the restart);
```yaml
- alias: 'Log office light turning on'
trigger:
- platform: template
value_template: '{{ states("light.office") == "on" }}'
action:
- service: system_log.write
data:
message: 'The office light is now on'
```
After that first firing, brightness changes will never again affect the template.
## Proposal
I propose that these two triggers should only fire when going from false to true.
They should not fire if already true at startup. They should not fire if going from true to unavailable and back to true.
Full disclosure: I actually implemented the current behavior for `numeric_state` (in https://github.com/home-assistant/core/pull/10125). I was in doubt about how to handle it back then and I now think I did it the wrong way around (even though everybody agreed with me).
## Consequences
The main potential benefit is that lights and other stuff would no longer toggle for every restart.
This is a breaking change but I struggle to think of examples where the current behavior is desirable (please help). One situation is testing though: when implementing the above automation it is nice that one does not have to wait for the next sunset to see that it works.
If one really wants the current behavior it can be implemented with a `homeassistant` start trigger combined with a condition.
CC: @aaronwolen @Tom7320 @stefanroelofs (from the mentioned issues)
However, I think it was superseded by another PR:
home-assistant:dev
← home-assistant:frenck-2021-0784
opened 03:41PM - 04 Mar 21 UTC
<!--
You are amazing! Thanks for contributing to our project!
Please, DO N… OT DELETE ANY TEXT from this template! (unless instructed).
-->
## Proposed change
<!--
Describe the big picture of your changes here to communicate to the
maintainers why we should accept this pull request. If it fixes a bug
or resolves a feature request, be sure to link to that issue in the
additional information section.
-->
The numeric state condition should not raise on unavailable or unknown states. These are known states defined in our model. It are valid states, the entity exists as well, just not a matching one (for whatever reason).
Introduced in #45923
## Case 1
**Senario before this PR:**
- Entity available, condition matches -> trigger
- Entity becomes unavailable
- Entity becomes available again -> condition matches -> NO trigger
**Senario after:**
- Entity available, condition matches -> trigger
- Entity becomes unavailable
- Entity becomes available again -> condition matches -> trigger
The difference is in the trigger after the state becomes known or available again. It would trigger if it matches at that point. The main reason: We don't know the state in between and should not assume that either.
## Case 2
**Senario before this PR:**
- Home Assistant starts up, does not have a known state yet (battery-powered?)
- Entity becomes available again -> condition matches -> NO trigger
**Senario after:**
- Home Assistant starts up, does not have a known state yet (battery-powered?)
- Entity becomes available again -> condition matches -> trigger
The difference is in the trigger after the state becomes known or available again. It would trigger if it matches at that point. The main reason: We don't know the state in between and should not assume that either.
## Case 3
A condition can be unavailable/unknown at any time. This is part of our core state engine model. If an entity becomes unavailable/unknown, the numeric state condition would never match.
**Situation before this change:**
An warning is logged.
![image](https://user-images.githubusercontent.com/195327/109988795-2cd06f80-7d08-11eb-8b4e-769a77a532e9.png)
**Situation after:**
The condition doesn't match and returns `False`, not log is made.
The reasoning for this; is that it is a valid and known state that never matches. It is not up to automation to log/warn about known states that never match. If we want warnings/alerts/logs about devices being in an unknown or unavailable state, that should be handled by something else (e.g., the state engine, not automations).
See: #47368
As a final word; even if the created situation is the wanted one (which I highly doubt), it should have been marked as breaking change. As this changes the behavior.
## Type of change
<!--
What type of change does your PR introduce to Home Assistant?
NOTE: Please, check only 1! box!
If your PR requires multiple boxes to be checked, you'll most likely need to
split it into multiple PRs. This makes things easier and faster to code review.
-->
- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests
## Additional information
<!--
Details are important, and help maintainers processing your PR.
Please be sure to fill out additional details, if applicable.
-->
- This PR fixes or closes issue: fixes #47368
- This PR is related to issue:
- Link to documentation pull request:
## Checklist
<!--
Put an `x` in the boxes that apply. You can also fill these out after
creating the PR. If you're unsure about any of them, don't hesitate to ask.
We're here to help! This is simply a reminder of what we are going to look
for before merging your code.
-->
- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] The code has been formatted using Black (`black --fast homeassistant tests`)
- [x] Tests have been added to verify that the new code works.
If user exposed functionality or configuration variables are added/changed:
- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]
If the code communicates with devices, web services, or third-party tools:
- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.
Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
Updated by running `python3 -m script.gen_requirements_all`.
- [ ] Untested files have been added to `.coveragerc`.
The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
The Integration Quality Scale scores an integration on the code quality
and user experience. Each level of the quality scale consists of a list
of requirements. We highly recommend getting your integration scored!
-->
- [x] No score or internal
- [ ] 🥈 Silver
- [ ] 🥇 Gold
- [ ] 🏆 Platinum
<!--
This project is very active and we have a high turnover of pull requests.
Unfortunately, the number of incoming pull requests is higher than what our
reviewers can review and merge so there is a long backlog of pull requests
waiting for review. You can help here!
By reviewing another pull request, you will help raise the code quality of
that pull request and the final review will be faster. This way the general
pace of pull request reviews will go up and your wait time will go down.
When picking a pull request to review, try to choose one that hasn't yet
been reviewed.
Thanks for helping out!
-->
To help with the load of incoming pull requests:
- [x] I have reviewed two other [open pull requests][prs] in this repository.
[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone
<!--
Thank you for contributing <3
Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io
It appears to introduce the behavior you observed:
Entity available, condition matches → trigger
Entity becomes unavailable
Entity becomes available again → condition matches → trigger
tom_l
April 7, 2021, 5:02pm
7
Yeah the change was reverted after comments in the release notes topic.
1 Like
AlanQ
(Alan)
April 8, 2021, 11:25am
8
Thanks for the info. I tried removing the “for” condition but it still occurs. I had hoped that using the “below” as the trigger meant that nothing would happen until the sensor had registered something above that value but it seems that the unavailable condition overrides. I think I somehow need to add a condition “and the sensor has not been unavailable within the last 10 minutes”
Yeah the change was reverted as it needed more discussion. Maybe we can start that discussion here?
The issue that this thread highlights is: how should the unavailable
state be treated in a trigger?
Take the trigger from above (simplified):
trigger:
- platform: numeric_state
entity_id: sensor.watts
below: 50
If the sensor goes from 0
to unavailable
and back to 0
, do we want the trigger to fire? We do not really know because the value might or might not have been above 50 during the outage so both choices could be said to be right.
One way to look at it is “we do not know what happened so we have to trigger or we might miss an event”.
The other way to look at it is “we have no knowledge that the threshold was crossed so we should not trigger”.
A related example to consider:
trigger:
- platform: state
entity_id: media_player.music
from: 'playing'
to: 'idle'
What should happen here if the state goes through playing
-> unavailable
-> idle
?
(Note, I am asking how things should preferably work if starting from scratch; not how they work today)
AlanQ
(Alan)
April 9, 2021, 4:13pm
10
Thanks amelchio for the insight into the thinking, I can see it is a potential can of worms. Perhaps we need a sort of failsafe = 1 or failsafe = 0 option, so we can choose which we think is the better option - trigger or do not trigger if the state is unknown.
For now I have created a history stats sensor to monitor if the sensor watts registers unavailable and added a condition to check this. I’ve only just done that so will need a few days to see if it works.
123
(Taras)
April 9, 2021, 4:35pm
11
I think the trigger should occur when value changes from one valid state to another, where “valid” is determined by the entity (i.e. on/off for input_booleans and switches, etc). That would make unavailable
universally an invalid value. Accordingly, there would be no triggering for playing
-> unavailable
-> idle
(unless I was explicitly looking for unavailable
in from
or to
).
If I’m not mistaken, I believe that’s what your PR had implemented.
My PR did not address state
, I have only thought about that situation later on. But it already works like you said because unavailable
is treated like any other value.
For numeric_state
, my PR ignored unavailable
which is not exactly the same. With my PR, a state going through 0
-> 100
-> unavailable
-> 0
would still trigger because we know that the threshold has been crossed at least once.
Your approach has the benefit that it will only trigger at the right time which could also be important.
I think you may be able to avoid the history stats sensor and use a template condition like {{ trigger.from_state != "unavailable" }}
but I didn’t test.
I have been thinking about this, I actually like your proposal better because it is more predictable.
However, one question. If we modify the trigger by removing from:
…
trigger:
- platform: state
entity_id: media_player.music
to: 'idle'
… would you then expect it to fire for unavailable
→ idle
?
123
(Taras)
April 12, 2021, 1:46pm
15
If I follow my proposal’s rules, no. If I wanted to detect unavailable
→ idle
I would need to explicitly indicate it with from: unavailable
(because unavailable
is not any entity’s “normal” state).
Unless I am mistaken, I believe the proposal would also prevent your example from triggering on startup when the entity’s initial state changes from unknown (or unavailable) to something known and valid.
To be honest, I have not subjected the proposal to an exhaustive list of test cases so it might have drawbacks that I haven’t envisioned.
AlanQ
(Alan)
April 13, 2021, 1:05pm
16
Thanks for the suggestion amelchio but for now the history stats sensor has solved the problem and I have no more false triggers. Until it is fixed with an official HA update here’s my code in case it helps anyone else:
within the sensor section of config yaml:
- platform: history_stats
name: PM1 Available
entity_id: switch.pm1_switch
state: "unavailable"
type: time
duration: 00:02:30
end: "{{ now() }}"
and added as a condition with the automation:
condition:
- condition: numeric_state
entity_id: sensor.pm1_available
below: '0.01'
The template condition is probably a neater way to solve it but I know this works so for now I will leave well alone.
simbesh
December 5, 2022, 7:21am
17
for anyone else who gets here and is still stuck like me, its actually
{{ trigger.from_state.state != "unavailable" }}
2 Likes
walter-ve
(Walter Ve)
September 6, 2023, 10:07pm
18
Not sure if replying here is appropriate after 3 years…
I also hit this issue;
platform: numeric_state
entity_id: sensor.0x001784510cdb4c3b_illuminance_lux
for:
hours: 0
minutes: 5
seconds: 0
below: 800
When the sensor became unavailable after a mqtt upgrade, it triggered this condition; I am not sure now how the HA should work. Nor can I find the expected behavior.
What is the appropriate solution for preventing an unavailable to some proper value firing the trigger (which I think is conceptually false).
Walter
Ps; really like the above discussion ;-).