确认homeassistant已经配置自动发现后,编写python代码运行即可:
Switches开关如下:
homeasstant官网说明:https://www.home-assistant.io/docs/mqtt/discovery/
视频过程:HA自动发现mqtt设备(灯光篇)lighting
python代码:
#homeassistant-MQTT-Discovery
import paho.mqtt.client as mqtt
import time
#HOST = "test.mosquitto.org"
HOST = "127.0.0.1"
PORT = 1883
def on_message_callback(client, userdata, message):
print(message.topic " " ":" str(message.payload))
client.publish('homeassistant/light/kitchen/state', message.payload)
def on_connect(client, userdata, flags, rc):
print("Connected with result code " str(rc))
if(str(rc) == '0'):
print("start")
client.publish("homeassistant/light/kitchen/config",
'{\
"~": "homeassistant/light/kitchen",\
"name": "Kitchen",\
"unique_id": "kitchen_light",\
"cmd_t": "~/set",\
"stat_t": "~/state",\
"schema": "json",\
"brightness": true\
}')
client.subscribe("homeassistant/light/kitchen/set")
# client.subscribe("#")#订阅所有主题
client = mqtt.Client()
client.connect(HOST, PORT, 60)
client.username_pw_set('coolcall', '123123')
client.on_connect = on_connect
client.on_message = on_message_callback
client.loop_start()#起了一个新的线程用于 message 的接收,当内部的线程接收到 message 后再调用回调函数。
运行后,可在homeassistant的mqtt实体注册或者开发者工具选项里面发现设备。
单独发送测试命令:
#client.publish('homeassistant/light/kitchen/state', '{"state": "OFF"}')
client.publish('homeassistant/light/kitchen/state', '{"state": "ON", "brightness": 255}')
添加是提到首页概览中:
测试成功
,