50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
import json
|
|
import time
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
from tool import *
|
|
from config import broker, port, subscribe_topic, username, password, info_topic
|
|
|
|
times = 6
|
|
|
|
|
|
class DataUploadClient:
|
|
def __init__(self, broker, port, topic, username, password):
|
|
self.broker = broker
|
|
self.port = port
|
|
self.topic = topic
|
|
self.username = username
|
|
self.password = password
|
|
# 千万不要指定client_id 不然死翘翘
|
|
self.client = mqtt.Client()
|
|
self.client.username_pw_set(self.username, self.password)
|
|
self.client.on_connect = self.on_connect
|
|
self.client.on_disconnect = self.on_disconnect
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
|
global times
|
|
times = 6
|
|
self.client.publish(info_topic, payload=json.dumps(subscribe_topic + ':连接成功,执行数据推送和本地存储'), qos=0)
|
|
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/start_data_upload.sh'], shell=True)
|
|
|
|
def on_disconnect(self, client, userdata, rc):
|
|
# print("失败,执行本地存储")
|
|
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True)
|
|
|
|
def start(self):
|
|
self.client.connect(self.broker, self.port)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
MQTT = DataUploadClient(broker, port, subscribe_topic, username, password)
|
|
while True:
|
|
try:
|
|
MQTT.start()
|
|
MQTT.client.loop_forever()
|
|
except:
|
|
time.sleep(10)
|
|
if times == 0:
|
|
MQTT.on_disconnect(None, None, None)
|
|
times -= 1
|