【mqtt笔记】通过Queue处理mqtt日志

博客涉及Python和大数据相关内容。Python作为开发语言,在大数据领域有重要应用,同时还可能关联测试工具等方面,虽内容简略,但聚焦信息技术领域的这些关键元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Alt

硬菜

#!/usr/bin/python
# -*- coding: utf-8 -*-
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)
    
    # log写入.txt文件           
    def recordlogtofile(self):
        while not self.logqueue.empty():
            logmsg = self.logqueue.get()
            # print(logmsg)
            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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值