本帖最后由 lipzbob 于 2019-6-14 18:52 编辑
有时候mqtt服务端安装后不知道如何调试,今天在没有硬件的情形下用几行python代码就可以连通ha实现联动。为理解mqtt的原理提供个清晰的思路。mqtt代理是安装的mosquitto IP地址:10.84.193.69,端口:1883
今天模拟的是mqtt的开关,代码如下:(后期加了UI,效果见:用python 模拟 mqtt客户端之二)
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("home/8ch/2")
def on_message(client, userdata, msg):
#print(msg.topic+":"+str(msg.payload.decode()))
print(msg.topic+":"+msg.payload.decode("utf-8"))
client.publish("home/8ch/2/stat", "OFF"*bool(msg.payload.decode("utf-8")=='OFF')+"ON"*bool(msg.payload.decode("utf-8")=='ON'))
if __name__ == '__main__':
client = mqtt.Client()
client.username_pw_set("admin", "password1") # 必须设置,否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
HOST = "10.84.193.69"
client.connect(HOST, 1883, 60)
client.loop_start()
HA是的设置如下:
mqtt:
broker: 10.84.193.69
port: 1883
client_id: home-assistant-1
keepalive: 60
username: pi
password: raspberry
discovery: true
switch:
- platform: mqtt
name: "t1"
state_topic: "home/8ch/2/stat"
command_topic: "home/8ch/2"
qos: 1
payload_on: "ON"
payload_off: "OFF"
retain: true
配置好以后启动进入ha就能看到一个t1的开关,点击即可体验打开关闭开关t1的情境,同时在python客户端可以实时看到ha发送到客户端的命令。
|