硬件:网络继电器(支持socket协议),HA主机一台
网络继电器
卖家写的:原本的控制命令([size=13.6364px] [size=13.6364px]发送on1即打开第一路继电器,发送off1关闭第一路继电器,第2-8路控制方法一样。发送read读继电器的状态,如返回relay00000001,表示第一路继电器吸合,2-8路继电器断开。可延时控制,例如发送on1:02,表示继电器吸合2秒后松开,发送on:12表示继电器吸合12秒后松开,延时最长99秒。)
怎么玩的不说了 直接贴脚本
#-*-coding:utf-8-*-
import paho.mqtt.client as mqtt
import sys
import socket
import signal
from time import ctime,sleep
HOST = '10.0.0.8'
PORT = 5000
# 当连接上服务器后回调此函数
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# 放在on_connect函数里意味着
# 重新连接时订阅主题将会被更新
client.subscribe("cmnd/Relay/#")
# 从服务器接受到消息后回调此函数
def on_message(client, userdata, msg):
print("主题:"+msg.topic+" 消息:"+str(msg.payload))
print (str(msg.payload))
if str(msg.payload) == 'b\'ON\'':
msg ='on'+msg.topic[-1]
s.send(msg.encode('utf-8'))
print(msg)
#msgt = msg.topic
#msgt.replace('cmnd','stat')
client.publish('stat/Relay/'+msg[-1], payload='ON', qos=0, retain=False) #发布消息
elif str(msg.payload) == 'b\'OFF\'':
msg ='off'+msg.topic[-1]
s.send(msg.encode('utf-8'))
print(msg)
#msgt = msg.topic
#msgt.replace('cmnd','stat')
client.publish('stat/Relay/'+msg[-1], payload='OFF', qos=0, retain=False) #发布消息
else:
print ('1')
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
client = mqtt.Client()
#参数有 Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
client.on_connect = on_connect #设置连接上服务器回调函数
client.on_message = on_message #设置接收到服务器消息回调函数
client.username_pw_set("mqtt", "mqtt")
client.connect("10.0.0.9", 1883, 60) #连接服务器,端口为1883,维持心跳为60秒
client.loop_forever()
这个脚本只是测试的(功能可以实现),有很多地方需要优化,比如(意外终端之类的)
下面是ha的脚本 这个就是mqtt 很简单 我也贴下(我就贴2个看下)
#mqtt to tcp
- platform: mqtt
name: "Relay1"
state_topic: "stat/Relay/1"
command_topic: "cmnd/Relay/1"
qos: 1
payload_on: "ON"
payload_off: "OFF"
retain: true
- platform: mqtt
name: "Relay2"
state_topic: "stat/Relay/2"
command_topic: "cmnd/Relay/2"
qos: 1
payload_on: "ON"
payload_off: "OFF"
retain: true
好了 这样就可以玩了!欢迎大神帮我优化脚本,哦 这个脚本做开机启动!!!~
|