This commit is contained in:
xyj 2023-12-09 18:57:28 +08:00
parent 984527fd62
commit d1d2161c72
2 changed files with 4 additions and 16 deletions

12
MQTT.py
View File

@ -15,7 +15,6 @@ def valid(msg, client):
if 'device_name' not in origin_data: if 'device_name' not in origin_data:
client.publish('error', payload='device_name must be supplied', qos=0) client.publish('error', payload='device_name must be supplied', qos=0)
return False return False
client.publish('error', payload=device_name, qos=0)
if device_name != origin_data['device_name']: if device_name != origin_data['device_name']:
return False return False
return True return True
@ -28,17 +27,12 @@ class MQTTClient:
self.topic = topic self.topic = topic
self.client = mqtt.Client() self.client = mqtt.Client()
self.client.on_connect = self.on_connect self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.on_message = self.on_message self.client.on_message = self.on_message
def on_connect(self, client, userdata, flags, rc): def on_connect(self, client, userdata, flags, rc):
print("Connected with result code " + str(rc))
self.client.subscribe(self.topic) self.client.subscribe(self.topic)
client.publish('success', payload='成功订阅lot_mqtt' + str(time.time()), qos=0) client.publish('success', payload='成功订阅lot_mqtt' + str(time.time()), qos=0)
def on_disconnect(self, client, userdata, rc):
print("Disconnected with code " + str(rc))
def on_message(self, client, userdata, msg): def on_message(self, client, userdata, msg):
if not valid(msg, client): if not valid(msg, client):
client.publish('error', payload='验证失败', qos=0) client.publish('error', payload='验证失败', qos=0)
@ -83,10 +77,6 @@ if __name__ == '__main__':
while True: while True:
try: try:
MQTT.start() MQTT.start()
if MQTT.client.is_connected():
print("连接成功")
MQTT.client.loop_forever() MQTT.client.loop_forever()
except: except:
print("重新连接") time.sleep(15)
time.sleep(1)

View File

@ -35,7 +35,7 @@ class DataUploadClient:
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/start_data_upload.sh'], shell=True) subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/start_data_upload.sh'], shell=True)
def on_disconnect(self, client, userdata, rc): def on_disconnect(self, client, userdata, rc):
print("失败,执行本地存储") # print("失败,执行本地存储")
subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True) subprocess.Popen(['/usr/bin/bash /home/pi/lot_manager/bash/stop_data_upload.sh'], shell=True)
def start(self): def start(self):
@ -47,9 +47,7 @@ if __name__ == '__main__':
while True: while True:
try: try:
MQTT.start() MQTT.start()
if MQTT.client.is_connected():
print("连接成功")
MQTT.client.loop_forever() MQTT.client.loop_forever()
except: except:
print("重新连接") # print("重新连接")
time.sleep(1) time.sleep(10)