1. Create an MQTT Light using a script
Assuming you have an existing scripts.yaml
file, paste this into it and save the file:
Click to reveal scripts
## MQTT Discovery Test
example_create:
alias: 'Example MQTT Light - Create'
sequence:
service: mqtt.publish
data:
topic: 'homeassistant/light/example/config'
retain: true
payload: >
{
"name": "Example",
"unique_id": "ABC123",
"stat_t": "home/example",
"cmd_t": "home/example/set",
"bri_stat_t": "home/example/brightness",
"bri_cmd_t": "home/example/brightness/set"
}
example_delete:
alias: 'Example MQTT Light - Delete'
sequence:
service: mqtt.publish
data:
topic: 'homeassistant/light/example/config'
retain: true
payload: ''
Then carry out the following simple steps
- Execute Configuration > Server Controls > Check Configuration and confirm it reports no errors.
- Execute Configuration > Server Controls > Reload Scripts
- Execute Configuration > Scripts > Example MQTT Light - Create
Congratulations! You have used a script to create an MQTT Light via MQTT Discovery.
2. Control/remove the light
If you check Developer tools > States, you will find a new entity named light.example
and its state will be off
.
- To turn on
light.example
, publish ON
to home/example
.
- To change its brightness, publish
125
to home/example/brightness
- To remove
light.example
from your system, execute:
Configuration > Scripts > Example MQTT Light - Delete
3. Advantages of this method
One of the advantages (compared to manually defining MQTT entities in YAML) is that you don’t need to restart Home Assistant to add/remove MQTT entities. Another advantage is that you can define Devices using MQTT Discovery but cannot do that via YAML.
Here’s an example of what I mean. The following script defines a switch
. However, I want the switch to be represented as an entity of a device called “X10 CM11A”. Notice the additional “device” information included in its discovery payload (you can’t do that if you were to define the switch in YAML).
- service: mqtt.publish
data:
topic: homeassistant/switch/pool_pump/config
retain: true
payload: >
{
"name": "Pool Pump",
"state_topic": "home/pump/powerstate",
"command_topic": "command/pump/powerstate",
"payload_on": "1",
"payload_off": "0",
"state_on": "1",
"state_off": "0",
"unique_id": "x10_pool_pump_switch",
"device": {
"identifiers": ["x10"],
"name": "X10 CM11A",
"model": "CM11A",
"manufacturer": "X10",
"sw_version": "1.X"
}
}
The result will be the creation of a Device called “X10 CM11A” and “Pool Pump” is one of the several entities belonging to it.