I have a template switch that works sort of. It shows as on, in the front end just as it should but it doesn’t seem to know it’s real state.
If it’s on and I have an automation try to turn it on it goes off.
This is the code:
The value_template is what determines the Template Switch’s current state.
If you turn on a Template Switch and it immediately sets its state back to off, it means the value_template failed to report the correct state.
There has to be a direct correlation between the state of switch.back_porch_lights and the state of sensor.mqtt_sensor. When back_porch_lights is on then mqtt_sensor must report on as well. If the two have no such correlation then mqtt_sensor is not a good choice to represent the Template Switch’s state.
The problem is that the lights these switches control are also controlled by a push button wall switch. So I use voltage as a way of telling the switch if its on or off.
I will see if I can use optimistic.
Thank you
The only way to make the Template Switch report the correct state (‘self aware’ as you called it) is via its value_template. If it reports the incorrect state, or reports it too slowly, the Template Switch won’t be ‘self aware’.
The other source of potential confusion is that the turn_on and turn_off services both rely on the same service call: light.toggle. Effectively, nothing actually sets a state but makes an assumption about the light’s current state and simply toggles it. For example, the light bulb might actually be off but by executing turn_off it gets toggled to on. Combine that with a slow acting value_template and everything is now out of sync (and optimistic mode can’t fix that).
I tried a few things and found that it does know its state. I changed the last entity to different switch just to see what happened and it did go the correct one. if it was possible to put a conditional statement before each turn_ on and Turn_off it could be made to work.
turn_off:
if sensor.mqtt_sensor is "on"
service: switch.toggle
data:
entity_id: switch.back_porch_lights
What did you change to make it work? Previously you said it took several seconds for sensor.mqtt_sensor to report a state-change. That was too slow for the Template Switch to correctly report its state. However, now you say it works so what did you do to correct it?
You can’t do that in the Template Switch but you could make turn_on and turn_off call a script. The script can contain conditions.
After working on this and not getting anywhere, I got to thinking that the scripts did what I needed in automations and the regular switch template works great on the front end so I’m going to just do it that way until my head need to be beat against the wall again.
This is the final code that configuration will accept but doesn’t do anything.