首页 > 解决方案 > 来自 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"

标签: pythoncsvmqttiot

解决方案


你不应该使用 readlines() 吗?

myfile = open(file, 'r')
Lines = myfile.readline()
for line in Lines:
  client.publish(f"{topic}", str(line.strip()))
  time.sleep(5)

这是假设文件中的数据是带有换行符的 ASCII。


推荐阅读