From c7eeb48577d488a6bd9682800d7f5f0aca1c7fe2 Mon Sep 17 00:00:00 2001 From: xyj <10908227994@qq.com> Date: Sat, 9 Dec 2023 17:25:13 +0800 Subject: [PATCH] update --- MQTT.py | 27 ++++++++++++--------------- data_upload.py | 31 +++++++++++++++++-------------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/MQTT.py b/MQTT.py index 5c3660c..17fda4b 100755 --- a/MQTT.py +++ b/MQTT.py @@ -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__': + client = mqtt.Client(client_id=device_name) + client.username_pw_set("demo", "123456") + # Specify callback function + client.on_connect = on_connect + # 尝试连接 MQTT 服务器 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 # 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("正在尝试重连") + diff --git a/data_upload.py b/data_upload.py index e5a6e46..94c940e 100755 --- a/data_upload.py +++ b/data_upload.py @@ -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__': + client = mqtt.Client(client_id=device_name) + client.username_pw_set("demo", "123456") + # Specify callback function + client.on_connect = on_connect + client.on_disconnect = on_disconnect + # 尝试连接 MQTT 服务器 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 + # ceshi-mqtt.lihaink.cn + client.connect('192.168.1.27', 1883) client.loop_forever() except Exception as e: - print("等待5秒重新连接客户端") - time.sleep(5) - if times == 0: - on_connect_fail(None, None) - times -= 1 \ No newline at end of file + print("Connection failed:", e) + if times == 0: + # 执行本地存储 + on_disconnect(None, None, None) + print("正在尝试重连") + time.sleep(5) + times -= 1