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

View File

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