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

27
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__':
client = mqtt.Client(client_id=device_name)
client.username_pw_set("demo", "123456")
# Specify callback function
client.on_connect = on_connect
# 尝试连接 MQTT 服务器
while True: while True:
try: 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 # 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__':
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: while True:
try: try:
client = mqtt.Client(client_id=device_name) # ceshi-mqtt.lihaink.cn
client.username_pw_set("demo", "123456") client.connect('192.168.1.27', 1883)
# 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.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)
times -= 1 print("正在尝试重连")
time.sleep(5)
times -= 1