import configparser import time import paho.mqtt.client as mqtt from device import device_name from tool import * config = configparser.ConfigParser() config.read('/home/pi/lot_manager/conf/main/config.conf') 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 self.client = mqtt.Client(client_id=device_name) 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.username_pw_set(self.username, self.password) self.client.connect(self.broker, self.port) if __name__ == '__main__': 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(broker, port, topic, username, password) 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