我嘗試在MQTT代理(Ubuntu的服務器)執行此代碼,類型錯誤:on_connect()到底需要3個參數(4給出)
當從出版商獲取的數據將發送到UDP_IP。
我的代碼:
import json
import socket
import paho.mqtt.client as mqtt
# MQTT Settings
MQTT_Broker = "192.168.0.106"
MQTT_Topic = "#"
MQTT_Port = 1883
Keep_Alive_Interval = 45
UDP_IP = "192.168.0.108"
UDP_RAW_PORT = 5567
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
def on_connect(mosq, obj, rc):
mqttc.subscribe(MQTT_Topic, 0)
def on_message(mosq, obj, msg):
gps_handler(msg.topic, msg.payload)
def gps_handler(Topic, jsonData):
jsonData = jsonData[1:-1]
sock.sendto(jsonData, (UDP_IP, UDP_RAW_PORT))
print jsonData
def on_subscribe(mosq, obj, mid, granted_qos):
pass
mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
# Connect
mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval))
# Continue the network loop
mqttc.loop_forever()
當我執行
Traceback (most recent call last):
File "port_5567.py", line 38, in <module>
mqttc.loop_forever()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1470, in loop_forever
rc = self.loop(timeout, max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 995, in loop
rc = self.loop_read(max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1273, in loop_read
rc = self._packet_read()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1838, in _packet_read
rc = self._packet_handle()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2291, in _packet_handle
return self._handle_connack()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2349, in _handle_connack
self.on_connect(self, self._userdata, flags_dict, result)
TypeError: on_connect() takes exactly 3 arguments (4 given)
我不知道是什麼原因讓Ubuntu的服務器上的這個錯誤,
在樹莓派(Debian的),它可以工作。
'mqttc.on_connect'是一個實例方法。它隱式地將實例作爲第一個參數傳遞給方法(通常稱爲「self」) – Li357
謝謝!這很有用,但爲什麼在Raspberry Pi上不需要自己? – Link
你在兩臺機器上使用哪種版本的Python(也是什麼版本的Python MQTT庫)? – hardillb