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 # 千万不要指定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): 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__': 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) while True: try: MQTT.start() MQTT.client.loop_forever() except: time.sleep(10) if times == 0: MQTT.on_disconnect(None, None, None) times -= 1