Last Updated or created 2024-01-14
Posted because I could not find a good example on the interwebs.
Below creates a virtual HA button which toggles a blinking led.
(button and variables are called eprint for another function, change to something meaningful. )
Home Assistant virtual mqtt switch (configuration.yml)
See switch part
mqtt:
light:
- name: "KitchenOutside"
payload_on: "99"
payload_off: "0"
unique_id: "KitchenOutside"
brightness_scale: "99"
brightness_state_topic: ha433/kitchenoutside/brightcontrol
brightness_command_topic: ha433/kitchenoutside/brightcontrol
state_topic: ha433/kitchenoutside/brightcontrol
command_topic: ha433/kitchenoutside/control
optimistic: false
on_command_type: brightness
#-----8<-------------snip ########### EXAMPLES light and sensor
sensor:
- name: "LivingTemperature"
state_topic: "home/8461/payload"
unit_of_measurement: "°C"
value_template: "{{ value_json.svalue1 }}"
- name: "LivingHumidity"
state_topic: "home/8461/payload"
unit_of_measurement: "%"
value_template: "{{ value_json.svalue2 }}"
#--------8<--- snip ################################ ONLY PART BELOW NEEDED
switch:
unique_id: esphome_switch
name: "Esp Home Switch"
state_topic: "esphome/eprint/tmpstate"
command_topic: "esphome/eprint/state"
payload_on: "ON"
payload_off: "OFF"
state_on: "ON"
state_off: "OFF"
optimistic: false
qos: 0
retain: true
ESP Home config for a ESP32
esphome:
name: lolin32litemqttled
friendly_name: lolin32litemqttled
esp32:
board: esp32dev
framework:
type: arduino
# Enable logging
logger:
# Enable Home Assistant API
api:
encryption:
key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
ota:
password: "xxxxxxxxxxxxxxxxxxxxxxxx"
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Lolin32Litemqttled"
password: "xxxxxxxxxxxxxxxxxxx"
captive_portal:
switch:
- platform: gpio
pin:
number: 22
mode: output
id: blueLED
- platform: template
name: "eprint"
id: eprint_enable
optimistic: on
interval:
- interval: 1000ms
then:
if:
condition:
switch.is_on: eprint_enable
then:
- switch.toggle: blueLED
mqtt:
broker: 192.168.1.2
on_message:
- topic: esphome/eprint/state
qos: 0
payload: "OFF"
then:
- switch.turn_off: eprint_enable
- topic: esphome/eprint/state
qos: 0
payload: "ON"
then:
- switch.turn_off: eprint_enable
