lot_manager/MQTT.py

94 lines
2.5 KiB
Python

import json
import time
import paho.mqtt.client as mqtt
from tool import push_stream, close_stream, update, exec_sh, get_record, get_list_record, get_status
import os
device_name = os.getenv('device_name')
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.subscribe('lot_mqtt')
def valid(msg, client):
origin_data = json.loads(msg.payload.decode('utf-8'))
dev_num = origin_data['device_name']
if dev_num is None:
client.publish('error', payload='dev_num must be supplied', qos=0)
return False
if dev_num != device_name:
return False
return True
# Message receiving callback
def on_message(client, userdata, msg):
if valid(msg, client) is False:
return
try:
origin_data = json.loads(msg.payload.decode('utf-8'))
data = origin_data["msg"]
if data is None:
client.publish('error', payload='msg must be supplied', qos=0)
return
if data == "push_stream":
# 启动推流视频
push_stream(client)
elif data == "close_stream":
# 关闭推流视频
close_stream(client)
elif data == "exec":
# 执行命令
exec_sh(msg, client)
elif data == "update":
# git更新项目和配置文件
update(client)
elif data == "record_list":
# 查看录像列表
get_list_record()
elif data == "record":
# 获取录像
get_record(msg, client)
elif data == "status":
# 查看运行状态
get_status(client)
else:
# 错误类型
client.publish('error', payload='No Such Type', qos=0)
except Exception as e:
pass
times = 120
def exec_shutdown():
pass
if __name__ == '__main__':
while True:
try:
client = mqtt.Client(client_id='device1')
client.username_pw_set("demo", "123456")
# Specify callback function
client.on_connect = on_connect
client.on_message = on_message
# Establish a connection
# ceshi-mqtt.lihaink.cn
client.connect('192.168.1.27', 1883)
# Publish a message
client.loop_forever()
except:
print("等待30秒连接")
time.sleep(30)
if times == 0:
# 重启机器
exec_shutdown()
times -= 1