I offer you the “deluxe” solution.
Let’s say we have three RF sensors:
- A contact sensor that reports both its
on
and off
states (assume ‘A1A’ = ‘ON’ and ‘A2A’ = ‘OFF’).
- A motion sensor that reports only its
on
state (assume ‘B1B’ = ‘ON’).
- A button that only reports its
on
state (assume ‘C1C’ = ‘ON’).
-
Because the contact sensor reports both of its states, the demultiplexer automation can use retain: true
when publishing to the contact sensor’s topic. When Home Assistant restarts, it will re-subscribe to the contact sensor topic’s and receive its current (retained) state from the broker.
-
The other two sensors (motion sensor and button) don’t report their off
state. We will use the off_delay
option to automatically reset them to off
. However, this technique does not publish off
to their respective MQTT topic (i.e. once set to on
the topic will always show on
). Therefore the demultiplexer automation should publish to their topics using retain: false
. Otherwise, using retain: true
, when you restart Home Assistant, it would erroneously set these sensors to on
.
To make the automation neater, and avoid elaborate if-elif-else trees, we will use dictionaries.
This one defines which commands belongs to a sensor’s topic.
{ 'A1A':'sensor1', 'A2A':'sensor1', 'B1B':'sensor2', 'C1C':'sensor3' }
This one defines which commands represents ON
or OFF
.
{ 'A1A':'ON', 'A2A':'OFF', 'B1B':'ON', 'C1C':'ON' }
Finally, this one defines which commands are retained or not.
{ 'A1A':'true', 'A2A':'true', 'B1B':'false', 'C1C':'false' }
Putting it all together, we get this demultiplexer automation. If it receives a command that is not defined in the dictionaries, it will publish it to home/unknown
(with retain: false
).
- alias: 'RF_Bridge demultiplexer'
hide_entity: true
trigger:
platform: mqtt
topic: tele/RF_Bridge/RESULT
action:
service: mqtt.publish
data_template:
topic: >-
{% set cmd = trigger.payload_json.RfReceived.Data %}
{% set commands = { 'A1A':'sensor1', 'A2A':'sensor1', 'B1B':'sensor2', 'C1C':'sensor3' } %}
{% set topic = commands[cmd] if cmd in commands.keys() else 'unknown' %}
home/{{topic}}
payload: >-
{% set cmd = trigger.payload_json.RfReceived.Data %}
{% set commands = { 'A1A':'ON', 'A2A':'OFF', 'B1B':'ON', 'C1C':'ON' } %}
{% set payload = commands[cmd] if cmd in commands.keys() else cmd %}
{{payload}}
retain: >-
{% set cmd = trigger.payload_json.RfReceived.Data %}
{% set commands = { 'A1A':'true', 'A2A':'true', 'B1B':'false', 'C1C':'false' } %}
{% set retain = commands[cmd] if cmd in commands.keys() else 'false' %}
{{retain}}
Configuring the binary sensors becomes an easy task:
- platform: mqtt
name: 'Bathroom Door'
state_topic: 'home/sensor1'
device_class: Door
- platform: mqtt
name: 'Hallway Motion'
state_topic: 'home/sensor2'
off_delay: 5
device_class: motion
- platform: mqtt
name: 'Button1'
state_topic: 'home/sensor3'
off_delay: 1
FWIW, I tested all of this and can confirm it works.