【问题标题】:Paho-MQTT message data from subscribe topic and write to a file来自订阅主题的 Paho-MQTT 消息数据并写入文件
【发布时间】:2020-03-07 23:23:02
【问题描述】:

您好,我正在尝试使用 paho-mqtt 订阅消息/主题,但未连接到客户端。这是代码的sn-p。

import time
import sys
import os
from functools import partial

import paho.mqtt.client as mqttClient
# To convert *.txt to *.csv for later use.
# import pandas as pd

sys.path.append(os.path.join(os.path.dirname(__file__),'../'))
from src.node_utils import create_node_logger, connect_to_broker
from src import topics


class LoggingNode():
"""# use to log the details of this two topics
# state_encoders = root + '/' + 'state_encoders'
# format
# Instance of State class
# estimates the robots position based on encoder ticks

# state_model = root + '/' + 'state_model'
# format
# Instance of State class for where the motion model estimates the
# robot will be based on wheel_velocity
#------------------------------------------------------------------#
#------------------------------------------------------------------# """
    def __init__(self, client, logger):
        self.state = None
        self.logger = logger
        self.client = client

    # initialize subscription to encoders and wheel_velocity
    def on_connect(self, userdata, flags, rc):
        suc1 = self.client.subscribe(topics.state_encoders)
        suc2 = self.client.subscribe(topics.state_model)
        self.logger.info('Connected and Subscribed: {} {}'.format(suc1, suc2))

    def on_message(self, client, userdata, message):
        print('heelo')
        print("Message received: "  + message.payload)
        with open('/home/test.txt','a+') as f:
             f.write("Message received: "  + message.payload + "\n")

    Connected = False   #global variable for the state of the connection

if __name__ == '__main__':
    node_name = 'logging_node'
    logger = create_node_logger(node_name)
    client = connect_to_broker()

    node = LoggingNode(client, logger)

    client.on_connect = node.on_connect
    client.message_callback_add(topics.state_model, node.on_message)
    logger.info('Started logging Node loop')


    try:
        client.loop_forever()
    except KeyboardInterrupt:
        logger.info("KeyboardInterrupt seen")

这是连接的状态模型。这也是发布消息。无论如何我可以订阅数据并将其放入 *.txt 和/或 *.csv 吗?

这是正确发布消息的实际节点。

jay@jay-MS-7885:~/autonomous-class/src$ python3 state_estimation_node.py $HOSTNAME
2020-03-07 19:04:22,412 node:state_estimate INFO 
  Started state_estimate loop

2020-03-07 19:04:22,413 node:state_estimate INFO 
  Connected and Subscribed: (0, 3) (0, 4)

【问题讨论】:

  • 我不明白是什么问题。
  • 它没有订阅topics.state_encoders & topics.state_model。我在单独的节点中运行所有内容,它在那里发布消息,但我不能在这里订阅。
  • 可能问题出在不同的地方——它将消息发送到不同的队列。不运行就很难解决。
  • 顺便说一句:您是否使用其他工具测试过队列? IE。在 shell/bash 中使用 mosquitto
  • 我已按照您的建议进行了检查。像魅力一样工作。

标签: python python-3.x mqtt paho


【解决方案1】:

对于任何回到这篇文章的人。我找到了一个解决这个问题的方法,最简单的方法是通过mosquitto_sub 实现这一目标,正如上面建议的furus

这里有一些有用的命令。

%-------Look up all the topics which are running--------%
mosquitto_sub -v -h jay-MS-7885.local -p 1883 -t '#'  

%-------------------write up encoder topics output-----------------------%
%------------------------------------------------------------------------%
# state.model logs - Format use - mosquitto_sub -t topic.name | time-stamp | tee -a filename.fileextension --%
%------------------------------------------------------------------------%
mosquitto_sub -t robot/state/encoders | tee -a mqtt_encoder_log.txt

mosquitto_sub -t robot/state/model | tee -a mqtt_model_log.txt

%------------------------------------------------------------------------%
%--------------------------add time stamp--------------------------------%
%------------------------------------------------------------------------%
mosquitto_sub -t robot/state/model | tee -a mqtt_encoder_log.txt | ts

mosquitto_sub -t robot/state/model | xargs -d$'\n' -L1 bash -c 'date "+%Y-%m-%d %T.%3N $0"' >> tee -a mqtt_encoder_log.txt

mosquitto_sub -t robot/state/model | xargs -d$'\n' -L1 bash -c 'date "+%Y-%m-%d %T.%3N $0"' | tee -a mqtt_encoder_log.txt

mosquitto_sub -t robot/state/model | ts | tee -a mqtt_encoder_log.txt

%------------------------------------------------------------------------%
%----------------------Write CSV file for the topic----------------------%
%------use seed option if you need to see the same in command prompt-----%
%------------------------------------------------------------------------%

mosquitto_sub -t robot/state/model | tee -a mqtt_log.csv | sed '$!d'

这也可能是useful

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多