lot_manager/data_upload.py

44 lines
1.2 KiB
Python
Raw Normal View History

2023-12-07 16:35:05 +08:00
import os
2023-12-05 16:21:08 +08:00
import subprocess
import time
import paho.mqtt.client as mqtt
2023-12-02 11:45:52 +08:00
2023-12-09 15:23:18 +08:00
from device import device_name
2023-12-02 11:45:52 +08:00
def on_connect(client, userdata, flags, rc):
global times
if rc == 0:
2023-12-09 16:38:12 +08:00
print("连接成功,执行数据推送和本地存储")
2023-12-09 16:40:40 +08:00
client.publish('success', payload='连接成功,执行数据推送和本地存储', qos=0)
2023-12-09 16:38:12 +08:00
# subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/start_data_upload.sh'], shell=True)
2023-12-05 16:21:08 +08:00
times = 3
2023-12-02 10:53:31 +08:00
2023-12-09 17:25:13 +08:00
def on_disconnect(client, userdata, rc):
2023-12-09 16:38:12 +08:00
print("失败,执行本地存储")
# subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True)
2023-12-02 11:37:32 +08:00
2023-12-05 16:21:08 +08:00
times = 3
2023-12-09 17:25:13 +08:00
2023-12-09 17:36:30 +08:00
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:
# ceshi-mqtt.lihaink.cn
client.connect('192.168.1.27', 1883)
2023-12-09 17:43:08 +08:00
client.loop_start()
2023-12-09 17:36:30 +08:00
except Exception as e:
print("Connection failed:", e)
if times == 0:
# 执行本地存储
on_disconnect(None, None, None)
print("正在尝试重连")
time.sleep(5)
times -= 1