MQTT Switch Blocking

Hello

I have been reviewing all the documentation and forums but cannot find an answer for my query.

I have an mqtt switch that operates my garage door opener. An ESP32 receives the commands, operates the relevent relays, reads the position switches and sends the feedbacks fine, all via mqtt.

What I would like to be able to do is conditionally block the operation of the switch (ie say for example
‘’’
{% if is_state(‘binary_sensor.house_occupied’,‘off’)%}
‘’’

so that in these conditions neither an automation or an (inadvertant) manual toggle of the switch would operate the door unexpectedly if the house occupied conditions were not met.

I have tried various templating of the payload and command topics (essentially trying to send a null command if conditions are not met), but the whole template itself is published to either the topic or the payload.

I have read up and it seems you cannot template these settings. I have also read up on template switches, but that doesn’t seem to answer the question either.

Simply, can anyone suggest a clean way that enables / disables / blocks the manual operation of an MQTT switch

Much appreciated

You can achieve your goal using a ‘middleman’ automation.

Let’s say your MQTT Switch is currently configured like this:

switch:
  - platform: mqtt
    name: Garage Door
    state_topic: garage_door/state
    command_topic: garage_door/command

Change command_topic to something different, like this:

switch:
  - platform: mqtt
    name: Garage Door
    state_topic: garage_door/state
    command_topic: temp/garage_door

Now add a ‘middleman’ automation that subscribes to temp/garage_door and publishes the received payload to garage_door/command but only if the condition is true.

- alias: Garage Door Manager
  trigger:
    platform: mqtt
    topic: temp/garage_door
  condition:
    condition: state
    entity_id: binary_sensor.house_occupied
    state: 'on'
  action:
    service: mqtt.publish
    data_template:
      topic: garage_door/command
      payload: '{{ trigger.payload }}'

If binary_sensor.house_occupied is off the payload is not published to garage_door/command. in the Lovelace UI, the MQTT Switch’s toggle will automatically move from on to off.


Another way would be to use a Conditional card in the UI that hides the Garage Switch when binary_sensor.house_occupied is off. This prevents anyone from setting it to on when they shouldn’t.

Thanks for the swift reply

I see your flow and will apply it tonight.

Would be nice to contain it all in the switch for neatness, but a totally workable solution

Cheers