MQTT sensor instead of input_boolean for global variables

I have a few automation variables that I store as input_booleans. I don’t have them hidden as they help with occasional debugging. I just put them in an “Administration” view. This works fine but they look like switches in the front end and to prevent accidental manual toggling of these switches I would prefer they appeared as binary_sensors.

Is there any reason why I can’t use MQTT binary sensors for this purpose instead?

I’m pretty sure I can publish to the topic from HA automations when I want to set or reset the sensor and I can trigger automations or have conditions based on the sensor state, so this seems valid to me but I’m pretty new to MQTT.

I do have the Mosquito MQTT server enabled already on my hassio pi.

I guess I should use ‘retain’ when publishing so that the sensors have a value on restart of HA?

Thoughts?

no reason why you couldn’t. Just make sure that you return an on or off for these. You may need to create a value_template to define when a state is on and when it’s off

I’m planning on making them binary MQTT sensors and if I just publish ‘on’ or ‘off’ values to the topics I don’t think templates will be required.

EDIT: actualy I might take your advice and define the on and off states as ‘true’ and ‘false’ respectively. It makes for a much easier toggling of the state, e.g

  action:
    service: mqtt.publish
    data_template:
      payload_template: '{{ not states.binary_sensor.recycling_week.state }}'
      topic: 'home-assistant/variable/recycling_week'
1 Like

Works perfectly.

This is a much better way of storing global variables that should only be changed pragmatically. I can still tweak them if required using mqttfx or HA’s mqtt publish tool.

Also, the publish retain flag was required for the sensor to have a value on HA restart.

HI,

Only just beginning with publishing mqtt sensors ea myself, please let me ask, why would you state this as a variable?
If have a couple events published, also read as sensors, that simply use this:

  - service: mqtt.publish
    data_template:
      topic: "activity_selection"
      retain: true
      payload: "{{ states('input_select.activity') }}"

with the sensor reading it:

sensor:
  - platform: mqtt
    name: Activity selection
    state_topic: "activity_selection"

works just fine, and on more than 1 Pi.
Is this different in any way?
thx,
Marius

It’s only a “variable” in the sense that I can store some arbitrary value in an mqtt sensor and retrieve it for use or alter it later. Actual variables in templating are only local to that template. These mqtt sensors are global. They can be stored in one automation and used anywhere else in HA. It’s semantics really. Strictly speaking they should still be called sensors.

You are doing the same thing, not just on one pi but multiple, which is another advantage. I’m really liking mqtt.