【发布时间】: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