參考中文教程: https://www.hachina.io/docs/7230.html
1HomeAssistant中MQTT設備的自動發現邏輯是:
- MQTT設備將自身的配置信息發布在事前定義的主題位置上
- HomeAssistant從這個主題位置讀取信息,生成對應的系統內實體設備
2支持自動發現的設備包括:
- 開關型傳感器(binary_sensor)
- 攝像頭(camera)
- 窗簾(cover)
- 電扇(fan)
- 燈(light)
- 傳感器(sensor)
- 開關(switch)
3HomeAssistant支持自動發現,需要在配置文件中增加:
mqtt:
# 此處為mqtt原有的一些配置
# ……
# 配置自動發現
discovery: true
# 自動發現使用的主題位置前綴,缺省為homeassistant
discovery_prefix: homeassistant
4設備將自己的配置信息發布在主題位置:
<discovery_prefix>/<component>/[<node_id>/]<object_id>/config
<discovery_prefix>
:配置文件中的discovery_prefix,缺省為homeassistant<component>
:設備所在的域,例如light、switch、binary_sensor等<node_id>
:可選,節點ID<object_id>
:設備ID
配置信息采用JSON格式。
例如,MQTT設備在主題:
homeassistant/switch/irrigation/config
發布信息:
{"name": "garden", "command_topic": "hachina/switch/irrigation/set", "state_topic": "hachina/switch/irrigation/state"}
當HomeAssistant讀取此信息,相當於配置文件中存在以下內容:
switch:
- platform: mqtt
name: "garden"
command_topic: "hachina/switch/irrigation/set"
state_topic: "hachina/switch/irrigation/state"
3 實戰操作
打開手機mqtt調試助手
在hass配置信息話題上發布自己的消息
遠程登錄hass,我們發現自動多出一一個設備
設備類型 開關
名字 garden
說明:
- 重發送配置,不會出現重復的設備。
- hass重啟后,必須重新發送配置信息,否則hass不會自動找到它。
- 必須指定設備類型
- 燈 homeassistant/light/led1/config
- 開關 homeassistant/switch/kaiguan1/config
手動和自動添加對比:
燈光這個設備,是之前我們自己手動在配置文件中添加的

警告:
自動發現設備的時候,一定要改配置話題第三個參數ID,
- 跟換設備名沒關系。設備名重復,ID不重復,可以添加。
- ID重復,不管設備名重復不重復,只能有一個
第一個設備 名字 RGBlight ID garden 存在
homeassistant/light/garden/config
{"name": "RGBlight", "command_topic": "hachina/rgb1/light/switch",
第二個設備 名字light ID garden1 存在
homeassistant/light/garden1/config
{"name": "light", "command_topic": "hachina/rgb1/light/switch",
第三個設備 名字light ID garden2 存在
homeassistant/light/garden2/config
{"name": "light", "command_topic": "hachina/rgb1/light/switch",
第四個設備 名字light ID garden 不存在
homeassistant/light/garden/config
{"name": "light", "command_topic": "hachina/rgb1/light/switch",
ID和第一個配置ID沖突,只能存在一個