
硬菜
import os
import time
import datetime
import threading
from queue import Queue
import paho.mqtt.client as mqtt
class MqttSubscription:
def __init__(self,mqttIP,mqttPWD,TOPIC):
self.mqttip = mqttIP
self.mqttport = 1883
self.mqttuser = "hailuo"
self.mqttpwd = mqttPWD
self.topic = TOPIC
self.descqueue = Queue()
self.logqueue = Queue()
self.ADM_command = "0"
self.ADM_subtask_state = "0"
self.ass = "0"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.username_pw_set(self.mqttuser, self.mqttpwd)
self.client.connect(self.mqttip, self.mqttport, 6000)
self.client_id = f'yp-get-mqtt-TEST2'
self.payload = ""
def on_connect(self, client, userdata, flags, rc):
print(f'connected to mqtt with resurt code:{rc}::{self.client_id}')
client.subscribe(self.topic)
def on_message(self, client, userdata, msg):
msg_topic = str(msg.topic)
payload = str(msg.payload)[2:-1]
if len(payload) > 0 :
if "Truck/DESC" in msg_topic:
data = msg_topic.split("/")
truckcode = data[2]
sc = f"{truckcode}/{payload}"
self.descqueue.put(sc)
def analysis_desc(self):
while not self.descqueue.empty():
descmsg = self.descqueue.get()
desc = descmsg.split("/")
truckcode = desc[0]
payload = desc[1]
payload_s = payload.split(",")
t = time.strftime("%H:%M:%S")
if payload_s[0] == "2" :
elif payload_s[1] == "3":
commond = "停车任务"
logdata = f"{t} 矿卡{truckcode}--收到云控下发【{commond}】指令,路线:{payload_s[2]},目的地:{payload_s[3]},{payload_s[4]},{payload_s[5]}"+" --"+payload
self.logqueue.put(logdata)
def recordlogtofile(self):
while not self.logqueue.empty():
logmsg = self.logqueue.get()
timedate = datetime.datetime.now()
path = f"{os.path.dirname(os.path.abspath(__file__))}\\logs\\" + f"{timedate.month}.{timedate.day}.txt"
with open(path,"a") as f:
f.write(logmsg+"\n")
def get_message(self):
self.client.subscribe(self.topic)
self.client.on_message = self.on_message
print(f"---正在监听---")
self.client.loop_forever()
def run(self):
t = threading.Thread(target=self.get_message)
t.setDaemon(True)
t.start()
time.sleep(1)
while True:
self.analysis_desc()
self.recordlogtofile()
time.sleep(0.2)
if __name__ == '__main__':
mqttIP = ''
mqttPWD = ""
TOPIC = "#"
m = MqttSubscription(mqttIP,mqttPWD,TOPIC)
m.run()