Raspberry Pi作为MQTT出版商和订户
我正在尝试同时建立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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回调函数
on_connect
始终使用四个参数调用。 ,例如,eg 在这里这是不容易辨别的,因为函数调用发生在后台,并且您看不到调用函数的参数。
在您的代码中,您仅定义三个参数。这导致了令人困惑的错误消息。
即使您不使用它们,也需要使用四个参数来定义该函数。
The callback function
on_connect
is always called with four arguments. There are several examples under https://github.com/eclipse/paho.mqtt.python/, e.g. here:This is not easily discernible since the function call happens in the background and you don't get to see the arguments with which the function is being called.
In your code you only define three arguments. This leads to the confusing error message.
You need to define the function with four arguments even when you are not using them.