Solved: config example of how to retrofit MQTT onto devices that previously used api

Hi @indeeed,

Thank you so much for pointing me in the right direction. As usual, it was actually simple, but understanding that it was simple took some time.

I am trying to switch my devices to MQTT-only (because of reasons), and I was struggling to understand specifically how, because I’ve found many conflicting examples.

But at the end of the day, it is painless, and you just need to configure a broker, and then add state (and command) topics to any switch/sensor etc etc.

If any other esp-home users are also visual learners, here is a working example of the yaml you would use for a basic device, in this case a Sonoff Basic R3:

esphome:
  name: your_device_name
  platform: ESP8266 #or whatever
  board: esp01_1m
  on_boot:
    priority: 225
    then:
      - light.turn_off: statlight

wifi:
  networks:
    - ssid: !secret iotnetwork
      password: !secret iotpassword
    - ssid: !secret fallback
      password: !secret fallback_password
  manual_ip:
    static_ip: your_ip
    gateway: your_gateway
    subnet: your_subnet
    dns1: your_dns
#  fast_connect: true

# Enable logging
logger:

# Enable Home Assistant API
# api: 
# you can remove the api section because you don't need it

mqtt:
  broker: your_broker
  username: your_mqtt_username
  password: your_mqtt_password
  #you can put further options as needed
  #also this is where you'll put special mqtt automations 

ota:

binary_sensor:
  - platform: gpio
    id: button
    pin:
      number: GPIO0
      mode: INPUT_PULLUP
      inverted: True
    on_press:
      - switch.toggle: relay
      - light.toggle: statlight

output:
  - platform: gpio
    pin: 
      number: GPIO13
      inverted: True
    id: led

light:
  - platform: binary
    id: statlight
    output: led
	
switch:
  - platform: gpio
    name: "your_switch"
    pin: GPIO12
    id: relay
    state_topic: some_topic/status
    command_topic: some_topic/command
	
#   so basically leave everything as it was when you were using the api,
#   but now add state and command topics as options.

Thank you, this community is extremely helpful.

3 Likes