Raspberry Pi 作为 MQTT 发布者和订阅者

Raspberry Pi as MQTT publisher and subscriber

我正在尝试同时将 RPi 设置为发布者和订阅者。我将以这种方式做到这一点,我将把 subscriber.py 和 publisher.py 作为线程,然后 运行 一个接一个地放置它们。 当涉及到我遵循的代码时 https://iotbytes.wordpress.com/mosquitto-mqtt-broker-on-raspberry-pi/ 并且我也从这里获取了代码。起初,我 运行 两个代码都没有任何线程。 Publisher.py 工作正常。 当我 运行 subscriber.py 我得到以下信息:

Traceback (most recent call last):
  File "/home/pi/subscriber.py", line 34, in <module>
    mqttc.loop_forever()
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 1756, in loop_forever
    rc = self._loop(timeout)
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 1164, in _loop
    rc = self.loop_read()
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 1556, in loop_read    rc = self._packet_read()
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 2439, in _packet_read
    rc = self._packet_handle()
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 3039, in _packet_handle
    return self._handle_connack()
  File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 3138, in _handle_connack
    on_connect(
TypeError: on_connect() takes 3 positional arguments but 4 were given

这很奇怪,因为它没有放置 4 个参数。

代码:

import paho.mqtt.client as mqtt

# Define Variables
MQTT_BROKER = "test.mosquitto.org" # "192.168.0.13" #"MQTT Broker IP or DNS Name"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "testTopic"

# Define on_connect event Handler
def on_connect(mosq, obj, rc):
        #Subscribe to a the Topic
        mqttc.subscribe(MQTT_TOPIC, 0)

# Define on_subscribe event Handler
def on_subscribe(mosq, obj, mid, granted_qos):
    print ("Subscribed to MQTT Topic")

# Define on_message event Handler
def on_message(mosq, obj, msg):
        print (msg.payload)

# Initiate MQTT Client
mqttc = mqtt.Client()

# Register Event Handlers
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe

# Connect with MQTT Broker
mqttc.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

# Continue the network loop
mqttc.loop_forever()

回调函数 on_connect 总是用四个参数调用。 https://github.com/eclipse/paho.mqtt.python/, e.g. here下有几个例子:

def on_connect(mqttc, obj, flags, rc):
    print("rc: " + str(rc))

这不容易辨别,因为函数调用发生在后台,您看不到调用函数的参数。

在您的代码中,您只定义了三个参数。这会导致令人困惑的错误消息。

即使不使用它们,您也需要定义具有四个参数的函数。