import time import paho.mqtt.client as mqtt from tool import * times = 6 class DataUploadClient: def __init__(self, broker, port, topic): self.broker = broker self.port = port self.topic = topic self.client = mqtt.Client() 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('success', payload='连接成功,执行数据推送和本地存储' + str(time.time()), 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('192.168.1.27', 1883, 'lot_mqtt') while True: try: MQTT.start() MQTT.client.loop_forever() except: # print("重新连接") time.sleep(10) if times == 0: MQTT.on_disconnect(None, None, None) times -= 1