目录结构
1、py代码
offRelay12-yixing.py
# _*_ coding: utf-8 _*_
# 须用到第三方库:paho-mqtt
# 安装命令 python3 -m pip install paho-mqtt
import time
import json
import paho.mqtt.client as mqtt
# 函数:关闭所有房间的12路继电器模块上指定的一个灯光
# 参数:rlyindex 1-12
def CloseOneRelayAllRoom(rlyindex:int):
# 遍历字典[],list_netcode
for netway in list_netway:
net_code_temp = netway['net_code']
if(len(net_code_temp) <= 0):
print ("name:", netway['name'],",","net_code为空, 跳过")
else:
# print ("name:", netway['name'],",","net_code:",netway['net_code'])
# 关继电器命令
offReleyJson = {
"put": {
"relay_id": 1,
"relay_value": "OFF",
"relay_devID": 48,
"relay_order": rlyindex
}
}
# json格式化输出成字符串
offReleyStr = json.dumps(offReleyJson)
sendTopic = "HTPW100"+net_code_temp
# print("mqtt发布:",offReleyStr,",topic=",sendTopic)
mqttc.publish(sendTopic, offReleyStr, qos=0)
# 函数: 连接Mqtt服务器成功后的回调函数
def on_connect(client, userdata, flags, reason_code, properties):
print("mqtt connect server",BROKER_ADDRESS,"seccesed !")
global isMqttConnected
isMqttConnected = True
print ("功能:时时关闭所有房间12路继电器的灯光。")
filejson = open('net-code.json','r') # 打开json文件
filejson_text = filejson.read() # 读取json文件内容
list_netway = json.loads(filejson_text) # 转成python字典[],list_netway
BROKER_ADDRESS = "hotekey.cn" # MQTT服务器地址
BROKER_PORT = 1883 # MQTT服务器端口
# 创建MQTT客户端实例,用api版本2
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
# 指定connect成功之后的回调函数
mqttc.on_connect = on_connect
# 连接到MQTT代理
mqttc.connect(BROKER_ADDRESS, BROKER_PORT, 60)
# 开始MQTT客户端的网络循环--异步运行mqtt
mqttc.loop_start()
print ("MQTT 初始化完成,开始进入主循环 while true:")
# 标志mqtt是否连接成功
isMqttConnected = False
# 主循环
while True:
if isMqttConnected == True: # mqtt正确连接
for relayNum in range (1,12+1):
print ("所有房间,关闭12路继器的回路",relayNum)
CloseOneRelayAllRoom(relayNum)
time.sleep(1/4) # 回路之间延时
print() # 空行
time.sleep(10) # 一个完整循环延时
else: # mqtt未连接
time.sleep(1)
print("run ... waiting mqtt connected")
2、使用到的文件
net-code.json
[
{
"net_code": "3373413436373417413432",
"name": "Net-qin"
},
{
"net_code": "964547463439330C353137",
"name": "Net-ye"
},
{
"net_code": "1222222222222222222221",
"name": "988"
}
]
3、启动命令
python3 offRelay12-yixing.py