Using MQTT to control devices?

In MQTT components, I can use MQTT Statesteam to receive state changes.

How do I control non-MQTT devices using MQTT? Or I have to use the REST / WebSocket API to control them?

Is this possible?

$ mosquitto_pub -t "homeassistant/switch/bedroom_light" -m ON
1 Like

This is an introduction to MQTT, which I think is really what you need.
https://www.hivemq.com/blog/how-to-get-started-with-mqtt

The answer is in a careful reading of your question.

Let me try to rephrase my question -

I have a TP-Link Switch named “fan_switch”, and I have configured MQTT statestream to publish state changes to MQTT broker, so if “fan_switch” is turned ON, it will publish on to "homeassistant/switch/fan_switch/state".

Is there a way for HASS to subscribe to "homeassistant/switch/fan_switch/command" so that I can publish “off” to that topic to have HASS turn OFF the “fan_switch”?

mqtt_statestream:
  base_topic: homeassistant
  include:
    domains:
      - switch

How does your TP-Link communicate with MQTT?

TP-link is not using MQTT, it is using - https://www.home-assistant.io/components/switch.tplink/

I’m using TP-Link as an example, it can be any of the switches under the “switches” component.

I can use REST API /api/services/switch/turn_off + entity_id to OFF the switch. Is there an equivalent for using MQTT topics to turn the switch on/off ?

Why would you need that? HA can control it without putting MQTT between them.

Yea, I know. I’m building a bridge to sync all devices between HA and another smart home hub.

To do this you would write an automation that triggers off the MQTT message and sets the switch state accordingly in the action.

But that would require me to set a MQTT trigger for each of the HA devices…

You may be able to use templates to reduce that number, but I don’t know too much about that.

Personally, I use appdaemon so I write all automations in Python.

Thanks for pointing me in the right direction!

- alias: Control switches via MQTT
  trigger:
    platform: mqtt
    topic: +/switch/+/cmd
  action:
    - service_template: >
        homeassistant.turn_{{trigger.payload}}
      data_template:
        entity_id: >-
          {{ trigger.topic.split('/')[-3] }}.{{ trigger.topic.split('/')[-2] }}
9 Likes

This worked great, thanks for posting.

I copied the code into automations.yml.

Posting an MQTT message containing either on or off to topic:
<anything>/switch/<entityName>/cmd allowed me to control my device over MQTT.

My use case is adapting an existing Node-RED scenes system I built to work with Home Assistant devices that don’t have MQTT.