lot_manager/data_upload.py

56 lines
1.7 KiB
Python
Raw Normal View History

2023-12-09 18:49:22 +08:00
import json
2023-12-05 16:21:08 +08:00
import time
2023-12-09 18:49:22 +08:00
2023-12-05 16:21:08 +08:00
import paho.mqtt.client as mqtt
2023-12-02 11:45:52 +08:00
2023-12-09 15:23:18 +08:00
from device import device_name
2023-12-09 18:49:22 +08:00
from tool import *
def valid(msg, client):
origin_data = json.loads(msg.payload.decode('utf-8'))
if 'msg' not in origin_data:
client.publish('error', payload='msg must be supplied', qos=0)
return False
if 'device_name' not in origin_data:
client.publish('error', payload='device_name must be supplied', qos=0)
return False
client.publish('error', payload=device_name, qos=0)
if device_name != origin_data['device_name']:
return False
return True
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):
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()
if MQTT.client.is_connected():
print("连接成功")
MQTT.client.loop_forever()
except:
print("重新连接")
time.sleep(1)