it sets the state in the state machine. The state in HA will then not reflect the state on the device, but anything that accesses the state in HA will see what is in the state machine.
There are times when it is needed (rarely but…) to update the state. I used that script a while back but I can’t remember what I used it for.
it works perfectly fine for entities that don’t update regularly or HA doesn’t do any polling of the device.
So, essentially it could be used as a ‘fake’ trigger for some other automation to kick in ?
No. It helps with sensors and states that are “unavailable” until first state change, such as doors that are rarely open or fire alarms. An “assumed state” option would be better, but this is what we have now. I just don’t want to have a bunch of “Unavailable” entities after restarts, however conceptually pure it may be.
Actually, there is at least one more use case. I’m using Aqara motion sensor with HW hack that sends updates every 5 seconds. But still, when it sends the data, there is hardcoded delay of 60 or 90 seconds (not sure at the moment). So even the sensor itself updates every 5 seconds, HA will not react, because it respects the hardcoded delay. I’ve created an AppDaemon app that reset that machine state inside the HA. Actually it set the motion state from ON to OFF in 5 seconds after motion was detected. If there is another motion detected, it again set it to ON in HA, which triggers the AppDaemon app, which set it to OFF. This repeats in loop until there is no more movement. This way I can much more precisely react on the real movement.
If anyone interested, this is the AppDaemon app:
import hassapi as hass
import json
import time
# MODULE = 'aqara_motion_reset'
# CLASS = 'AqaraMotionReset'
# CONF_TIMEOUT = 'timeout'
CONF_MOTION_SENSORS = 'motion_sensors'
DEFAULT_TIMEOUT = 5
class AqaraMotionReset(hass.Hass):
def initialize(self):
"""Initialize the Aqara app."""
if self.args["writedebug"] == 1:
self.set_log_level("DEBUG")
self.timeout = self.args["timeout"]
motion_sensors = self.args.get(CONF_MOTION_SENSORS, [])
for entity_id in motion_sensors:
# self.listen_state(self.motion_sensor_state_on, entity_id)
self.log("{} detected motion".format(entity_id), log = "debug_log", level = "DEBUG")
self.listen_state(self.motion_sensor_state_on, entity_id, new = "on")
def motion_sensor_state_on(self, entity_id, attribute, old, new, kwargs):
"""Set motion sensor state to on"""
if not entity_id:
return
if new != "on":
return
state = self.get_state(entity_id, attribute="all")
#self.set_state(entity_id, state="on", attributes=state.get("attributes", {}))
timeout = self.timeout
self.run_in(self.motion_sensor_state_off, timeout, entity_id=entity_id)
def motion_sensor_state_off(self, kwargs):
"""Set motion sensor state to off"""
entity_id = kwargs.get("entity_id")
if not entity_id:
return
state = self.get_state(entity_id, attribute="all")
self.set_state(entity_id, state="off", attributes=state.get("attributes", {}))
And this is how I call it from apps.yaml:
aqara_motion_reset:
module: aqara_motion_reset
class: AqaraMotionReset
timeout: 5
motion_sensors:
- binary_sensor.lumi_lumi_sensor_motion_aq2_ias_zone_kitchen
log: debug_log
writedebug: 0
I have been trying all night to get this thing to work as well, but cannot change the state of a binary sensor. I’ve installed the Python script, and created a binary_sensor in configuration.yaml:
template:
- binary_sensor:
- name: "SeatHomeSensor"
device_class: motion
state: "false"
Then I’ve created an automation that looks like this:
alias: SeatComesHome
description: ""
trigger:
- platform: state
entity_id:
- device_tracker.vss_position
to: home
condition: []
action:
- service: python_script.set_state
data:
entity_id: binary_sensor.seathomesensor
state: "true"
mode: single
I’ve tried running the action, but nothing happens. The state does not change. What am I doing wrong?
you don’t need to do this. Just make a normal template sensor.
template:
- trigger:
- id: 'on'
platform: state
entity_id: device_tracker.vss_position
to: home
- id: 'off'
platform: state
entity_id: device_tracker.vss_position
to: not_home
binary_sensor:
- name: "SeatHomeSensor"
device_class: motion
state: "{{ trigger.id }}"
I urge you to ignore this thread and actually try to use Home Assistant the intended way, you should never have to ‘set the state’. This whole thread essentially skirts around a non-existing problem due to people not taking the time to learn HA’s nuances.
you can even simply what was written above into just a template sensor without triggers
template:
- binary_sensor:
- name: "SeatHomeSensor"
device_class: motion
state: "{{ is_state('device_tracker.vss_position', 'home') }}"
Hi Petro,
Thanks for you input and suggestion. I’ve tried the methods (copying your code into configuration.yaml, only changing the actual VSS entity name), but it doesn’t work. I’ve tried both methods and none of them work.
What could I possible be doing wrong?
post your attempts
Here is a snippet from configuration.yaml
template:
- trigger:
- id: 'on'
platform: state
entity_id: device_tracker.vsszzzknzmw006178_position
to: Home
- id: 'off'
platform: state
entity_id: device_tracker.vsszzzknzmwxxxxxx_position
to: Away
binary_sensor:
- name: "SeatHomeSensor3"
device_class: motion
state: "{{ trigger.id }}"
- binary_sensor:
- name: "SeatHomeSensor4"
device_class: motion
state: "{{ is_state('device_tracker.vsszzzknzmwxxxxxx_position', 'Home') }}"
Device trackers only have a state of home
or not_home
. You’re using Home
and Away
.
Ah - you’re absolutely right. I was sure I had tried that first (copying your code), and that it didn’t work, and therefore changed it. Whatever transpired, it is now sorted. It works like a charm. Thank you for the help (and simpler solution).
I have several template sensors that are made of the sum of other sensors (related to energy metering).
When electricity is out, I have other sensors that report reserve battery power load. I need to temporarily swap the initial template sensors figures to another ones (from reserve battery sensor).
Is there any possible way to automate this setting? Developer Tools allow using “Set State” that could override sensor value, in this case, I can only null them, for instance, or manually assign any value, but I need to. Any way to automate state setting without python_script?
Thanks!
But python script is very easy to do.
service: python_script.set_state
data:
entity_id: sensor.foxess_local_moc
state: "0"
Hi all,
I wanted to set all my entities to a defined state after rebooting HA. I found this script here and I do not really understand, if I have to define a state for every single entity. Is it possible to set a state for e.g. all mqtt devices?
You state that one should use HA the intended way and ignore this thread.
So here’s my situation, I have a number of automations that trigger on motion detection to turn on a light. The light remains one for a set period of time after the trigger and that is usually at least 30 seconds after the cool-down period for the sensor (which I have at 30 seconds for all my motion detectors). The automations are such that the lights will stay on if motion continues to be detected during the time between after the cool down period of the sensor and the timeout time.
All of my motion detectors are Z-Wave and all but one are either usb or ac powered (not battery).
Occasionally, the sensor state change is not rec’d by HA (as near as I can tell anyway because ZWaveJS is rather lacking on debug/diagnostic tools). This results in the light staying off when it should have got turned on which is annoying, but the more troubling consequence is when HA doesn’t get the state change after the cool down period so the light stays on and that’s an equivalent hundreds of watts worth of lighting in the garage (600 watts) or kitchen (400 watts).
When this happens, the next time motion is detected usually then “resets” the cycle and the light will turn off and all will be well until the next time this happens.
I also note that there are certain times of the day when this is more likely to happen - I suspect that this is when Z-Wave is re-polling, etc. as part of its self healing processes which, as far as I have seen so far, is not something I have any control over as to the timing.
So I’m looking at using this script to reset the state of the motion detectors to “Clear” a few seconds after the cool down period (so likely 35 seconds after the trigger) so the lights will turn off anyway if HA doesn’t get the state change the way it is supposed to via Z-Wave.
What is your take on this use for this script?
Ping the zwave sensor. Don’t change the state in the state machine.
Zwave does not self heal unless told to by the system. Healing is a last resort in most cases. This is most likely some other unrelated issue. I’d start by looking at the problems with your zwave network instead of searching for bandaides to mask the problem. This whole thread is bandaide, not a solution to a problem.
You should pay attention to your TX and RX, you want to have a low dropped values or a low ratio. e.g.
Pinging a sensor that is asleep does not seem like much of an option.
As for troubleshooting - I used to use Vera as a controller and it had far more debug/diagnostic capabilities then ZWave JS has which is seriously disappointing. I’ve factory reset the sensors, deleted them, rejoined them, and have done everything I can think of at this point to resolve the issue. The Garage Motion Sensor is literally the closest to the HA appliance, less than 10 feet away with one drywall constructed wall between them.
Here’s what I get from the Garage Motion Detector:
Device Statistics
Commands TX # of commands successfully sent to the node: 30
Commands RX # of commands received from the node, including responses to sent commands: 41 Commands Dropped TX # of outgoing commands that were dropped because they could not be sent: 1
Commands Dropped RX # of commands from the node that were dropped by the host: 20
Timeout Response # of Get-type commands where the node’s response did not come in time: 0
RTT Average round-trip-time in ms of commands to this node: 167.5
RSSI Average RSSI in dBm of frames received by this node: -52
Last Working Route
Protocol Z-Wave
Data Rate 40 kbps
RSSI -54 dBm
Route Failed Between N/A
Repeaters + RSSI None, direct connection
Next to Last Working Route
Protocol Z-Wave
Data Rate 100 kbps
RSSI -52 dBm
Route Failed Between N/A
Repeaters + RSSI
**Repeater Device:**RSSI:
Hall Down Light:-63 dBm
I guess the question then becomes what to do about this as it appears that the host is dropping a lot of commands. I’m also confused as to why a direct connection is at 40 kbps whereas a relayed connection runs at 100 kbps.
So what is the solution here? New sensors? These are ZooZ ZSE18 sensors in most cases. AEON Labs ZW100 in the kitchen, and the two sensors that I have never found to have this problem with are AC Hardwired HomeSeer Technologies HS-FLS100-G2 devices.
That’s going to be device dependent, and that’s the speed of the transmission. What you care about with dropped packets is the signal strength, which is the RSSI.
-25 to -45db is typically good signal strength
-45 to -73db is typically okay signal strength
-73db & beyond is bad signal strength
Also keep in mind that background signals can interfere.
Do you have your zwave stick mounted directly to your system? Does your system properly shield the internal signals from your USB ports? Raspberry Pis do not have any shielding and you’d want to get a usb extension cable for the ZStick.