python - 来自 csv 文件的 MQTT 消息
问题描述
我有一个 csv 文件,我需要将此文件作为 MQTT 消息发送,但我需要它通过一行发送几秒钟的中断,然后是下一行和几秒钟的中断。这有点像传感器模拟,但数据在 csv 文件中。我试图以几种不同的方式解决它,但没有任何效果。我正在用 Python 编码。谢谢你们的帮助。这里的代码是我的最新尝试,在运行函数 MQTT_publish() 后,我收到了 5 秒中断的消息,但每条消息都是整个文件,而不仅仅是一行。我真的不知道该怎么办。
def MQTT_publish(broker, file, topic):
client = mqtt.Client()
print("Connecting to broker", broker)
client.connect(broker)
client.loop_start()
print("Publishing...")
client.loop_start()
with open(file, 'r') as read_obj:
data = reader(read_obj)
for row in data:
client.publish(f"{topic}", str(row))
time.sleep(5)
client.loop_stop()
def on_message(client, userdata, message):
print(str(message.payload.decode("utf-8")))
def MQTT_subscribe(broker, topic):
client = mqtt.Client()
print("Connecting to broker", broker)
client.connect(broker)
print(f"Subscribing {topic}")
client.subscribe(f"{topic}")
client.on_message = on_message
client.loop_forever()
broker = "mqtt.eclipse.org"
解决方案
你不应该使用 readlines() 吗?
myfile = open(file, 'r')
Lines = myfile.readline()
for line in Lines:
client.publish(f"{topic}", str(line.strip()))
time.sleep(5)
这是假设文件中的数据是带有换行符的 ASCII。
推荐阅读
- php - PHP 联系表问题 - 找到 302
- android - 如何访问不是活动的 java 类中的 xml 文件的元素?
- kubernetes - 在 EKS 上安装 kubernetes helm 时在哪里可以找到 ca.key
- javascript - React - TypeError:无法读取未定义的属性“setState”(箭头函数)
- python - 查找所有连续子数组
- ios - CollectionView 添加到视图时不滚动
- java - 如何从自定义视图类中正确终止活动?
- java - 如何在java中打印非ASCII字符?
- r - 来自带有 2 个字节分隔符的文本文件的 R 数据框
- vue.js - nuxtjs(dotenv 除外)上推荐的动态运行时配置技术