2023-12-11 14:11:12 +08:00
|
|
|
import configparser
|
2023-12-05 16:21:08 +08:00
|
|
|
import time
|
2023-12-09 18:49:22 +08:00
|
|
|
|
2023-12-05 16:21:08 +08:00
|
|
|
import paho.mqtt.client as mqtt
|
2023-12-02 11:45:52 +08:00
|
|
|
|
2023-12-11 14:11:12 +08:00
|
|
|
from device import device_name
|
2023-12-09 18:49:22 +08:00
|
|
|
from tool import *
|
2023-12-11 14:45:46 +08:00
|
|
|
|
2023-12-11 15:16:16 +08:00
|
|
|
config = configparser.ConfigParser()
|
|
|
|
config.read('/home/pi/lot_manager/conf/main/config.conf')
|
2023-12-11 09:15:23 +08:00
|
|
|
times = 6
|
2023-12-09 18:49:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
class DataUploadClient:
|
2023-12-11 14:11:12 +08:00
|
|
|
def __init__(self, broker, port, topic, username, password):
|
2023-12-09 18:49:22 +08:00
|
|
|
self.broker = broker
|
|
|
|
self.port = port
|
|
|
|
self.topic = topic
|
2023-12-11 14:11:12 +08:00
|
|
|
self.username = username
|
|
|
|
self.password = password
|
2023-12-11 15:16:16 +08:00
|
|
|
# 千万不要指定client_id 不然死翘翘
|
2023-12-11 15:11:22 +08:00
|
|
|
self.client = mqtt.Client()
|
2023-12-11 14:45:46 +08:00
|
|
|
self.client.username_pw_set(self.username, self.password)
|
2023-12-09 18:49:22 +08:00
|
|
|
self.client.on_connect = self.on_connect
|
|
|
|
self.client.on_disconnect = self.on_disconnect
|
|
|
|
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
2023-12-11 15:00:51 +08:00
|
|
|
self.client.publish('success', payload='连接成功,执行数据推送和本地存储' + str(time.time()), qos=0)
|
2023-12-11 15:16:16 +08:00
|
|
|
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/start_data_upload.sh'], shell=True)
|
2023-12-09 18:49:22 +08:00
|
|
|
|
|
|
|
def on_disconnect(self, client, userdata, rc):
|
2023-12-11 15:16:16 +08:00
|
|
|
# print("失败,执行本地存储")
|
|
|
|
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True)
|
2023-12-09 18:49:22 +08:00
|
|
|
|
|
|
|
def start(self):
|
|
|
|
self.client.connect(self.broker, self.port)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2023-12-11 15:16:16 +08:00
|
|
|
broker = config.get("broker", "host")
|
|
|
|
# 这里必须是int类型
|
|
|
|
port = config.getint("broker", "port")
|
|
|
|
topic = config.get("topic", "name")
|
|
|
|
username = config.get("security", "username")
|
|
|
|
password = config.get("security", "password")
|
|
|
|
# MQTT = DataUploadClient("192.168.1.27", 1883, "lot_mqtt", "demo", "123456")
|
|
|
|
MQTT = DataUploadClient(broker, 1883, port, username, password)
|
2023-12-09 18:49:22 +08:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
MQTT.start()
|
|
|
|
MQTT.client.loop_forever()
|
|
|
|
except:
|
2023-12-09 18:57:28 +08:00
|
|
|
time.sleep(10)
|
2023-12-11 09:15:23 +08:00
|
|
|
if times == 0:
|
|
|
|
MQTT.on_disconnect(None, None, None)
|
2023-12-11 14:45:46 +08:00
|
|
|
times -= 1
|