This commit is contained in:
xyj 2023-12-09 17:25:13 +08:00
parent 8b07f14419
commit c7eeb48577
2 changed files with 29 additions and 29 deletions

23
MQTT.py
View File

@ -9,6 +9,7 @@ from tool import push_stream, close_stream, update, exec_sh, get_record, get_lis
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("成功订阅")
client.subscribe('lot_mqtt')
@ -71,22 +72,18 @@ def exec_shutdown():
if __name__ == '__main__':
while True:
try:
client = mqtt.Client(client_id=device_name)
client.username_pw_set("demo", "123456")
# Specify callback function
client.on_connect = on_connect
client.on_message = on_message
# Establish a connection
# 尝试连接 MQTT 服务器
while True:
try:
# ceshi-mqtt.lihaink.cn
client.connect('ceshi-mqtt.lihaink.cn', 1883)
# Publish a message
client.connect('192.168.1.27', 1883)
client.loop_forever()
except:
print("等待30秒连接")
time.sleep(30)
if times == 0:
# 重启机器
exec_shutdown()
times -= 1
except Exception as e:
print("Connection failed:", e)
time.sleep(10)
print("正在尝试重连")

View File

@ -15,27 +15,30 @@ def on_connect(client, userdata, flags, rc):
times = 3
def on_connect_fail(client, userdata):
def on_disconnect(client, userdata, rc):
print("失败,执行本地存储")
# subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True)
times = 3
if __name__ == '__main__':
while True:
try:
client = mqtt.Client(client_id=device_name)
client.username_pw_set("demo", "123456")
# Specify callback function
client.on_connect = on_connect
client.on_connect_fail = on_connect_fail
# Establish a connection
client.connect('ceshi-mqtt.lihaink.cn', 1883)
# Publish a message
client.on_disconnect = on_disconnect
# 尝试连接 MQTT 服务器
while True:
try:
# ceshi-mqtt.lihaink.cn
client.connect('192.168.1.27', 1883)
client.loop_forever()
except Exception as e:
print("等待5秒重新连接客户端")
time.sleep(5)
print("Connection failed:", e)
if times == 0:
on_connect_fail(None, None)
# 执行本地存储
on_disconnect(None, None, None)
print("正在尝试重连")
time.sleep(5)
times -= 1