使用MQTT Python双向发布和订阅

2024-09-28 03:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个Python程序写在Raspberry pi3上,读取湿度和温度传感器的数据,并将这些数据发布到一个主题中。然后我可以用我的笔记本电脑接收这些数据。这是我的读取传感器数据并将其发布到Raspberry Pi中的主题的代码

import RPi.GPIO as GPIO
import time
import json
import Adafruit_DHT as dht
import math
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
# Creating the JSON Objects

dht22 = {}
arduino = {}
dht22Temp = []
dht22Hum = []
arduinoLED = []


dht22['temperature'] = dht22Temp
dht22['humidity'] = dht22Hum
dht22['sensor'] = 'DHT22'

arduino['blink'] = arduinoLED
arduino['actuator'] = 'arduinoLED'  

# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005

def main():
  # Main program block
  while True:

    h, t = dht.read_retry(dht.DHT22, 17) //Reading humidity and temp data from GPIO17
    t = round(t,2)
    h = round(h,2)

    if t > 25: 
      if len(arduinoLED) == 3:
        arduinoLED.pop(0)
        arduinoLED.append("true")
      else: 
        arduinoLED.append("true")
    else:
      if len(arduinoLED) == 3:
        arduinoLED.pop(0)
        arduinoLED.append("false")
      else: 
        arduinoLED.append("false")
    if len(dht22Temp) == 3:
      dht22Temp.pop(0)
      dht22Temp.append(t)
    else: 
      dht22Temp.append(t)
    if len(dht22Hum) == 3:
      dht22Hum.pop(0)
      dht22Hum.append(h)
    else: 
      dht22Hum.append(h)
    # lm35dzTemp.append(tempc) 


    # Publishing sensor information by JSON converting object to a string
    publish.single("topic/sensorTemperature", json.dumps(dht22), hostname = "test.mosquitto.org")
    publish.single("topic/sensorTemperature", json.dumps(arduino), hostname = "test.mosquitto.org")

    # Printing JSON objects
    print(dht22)
    print(arduino)
    time.sleep(2)

if __name__ == '__main__':

  try:
    main()
  except keyboardInterrupt:
    pass
  finally:

    GPIO.cleanup()

以下是我从笔记本电脑订阅和接收数据的代码:

^{pr2}$

我现在想做的是从我的笔记本电脑上发布一些东西(也许是在与订阅服务器相同的代码中,或者是在一个单独的文件中,该文件只会将一条消息发布到同一个主题-"topic/sensorTemperature")。但我的问题是:如何在我的Raspberry Pi(在我发布的第一个代码中)上发布和订阅消息?因为我是以无限循环的方式将消息发布到我的笔记本电脑上,所以我还需要一个无限循环来订阅相同(或不同的主题)来接收消息。如何同时运行其中两个循环?我需要两条不同的线吗?在

谢谢。在


Tags: 数据代码import主题ifaspublishelse
3条回答

按照Sergey的建议,您可以使用loop_start创建一个单独的线程来接收消息。在

您的主要功能如下:

def main():
    # Create a new client for receiving messages
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.subscribe(topic)
    client.connect(mqttserver)
    client.loop_start()
    while True:
        #code for publishing
        pass

只需将来自subscribing script的代码放入while True:之前的publishing script,并将loop_forever()替换为{}。当脚本在GPIO.cleanup()之前退出时,请使用loop_stop()。在

最简单的方法是在Raspberry上并行启动另一个Python进程(类似于笔记本电脑的脚本),处理从膝上型电脑接收到的消息。在

但如果您想在一个脚本中实现所有内容,您可以通过实现第一个片段(发布传感器数据)来扩展第二个代码片段(处理消息)。在

当然,在这种情况下,不能使用loop_forever()。当您调用loop_forever()时,它在客户端调用disconnect()之前永远不会返回,因此您无法处理收到的消息(主线程被阻塞)。Paho客户端也有例程loop()loop_start()/loop_stop()来控制网络循环。 看看他们:

1)函数loop()可以将timeout作为参数。它将阻塞,直到新消息到达或超时。在第一种情况下-预处理接收到的消息并计算到下一次发布之前的时间。再次将此时间作为参数传递给loop()。在第二种情况下,只需发布数据并调用loop(),直到下一次发布(在您的示例中为2秒)。在

2)loop_start()/loop_stop()启动和停止后台线程,为您发送和接收(和处理)数据。创建客户端,在回调函数上注册。主线程现在是免费的-使用它与第一个片段的逻辑(循环2秒睡眠)。在

相关问题 更多 >

    热门问题