您好,我正在尝试从树莓派2设备传输数据,并通过mqtt在另一台计算机的终端上接收数据。我在json
上发布mosquitto
信息的部分工作正常。我订阅的部分如下:
import time
import paho.mqtt.client as mqtt
broker="test.mosquitto.org"
#define callback
def on_message(client, userdata, message):
time.sleep(1)
try:
print("received message =", str(message.payload.decode("utf-8")))
except None:
print("")
client=mqtt.Client()
client.on_message = on_message
#####
print("connecting to broker ",broker)
client.connect(broker)
client.loop_start() #start loop to process received messages
print("subscribing ")
client.subscribe("DHT22_cimti_project_pe") #subscribe
client.loop_forever()
问题是,当我在MacBooks Terminal上运行此程序时,它正在工作,但最终总是因以下错误而崩溃:
Traceback (most recent call last):
File "mqtt2.py", line 26, in <module>
client.loop_forever()
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 1481, in loop_forever
rc = self.loop(timeout, max_packets)
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 1003, in loop
rc = self.loop_read(max_packets)
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 1284, in loop_read
rc = self._packet_read()
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 1849, in _packet_read
rc = self._packet_handle()
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 2305, in _packet_handle
return self._handle_publish()
File "/anaconda3/lib/python3.6/site-packages/paho/mqtt/client.py", line 2464, in _handle_publish
(slen, packet) = struct.unpack(pack_format, self._in_packet['packet'])
struct.error: bad char in struct format
我试图做一个try
except
方法,但是它没有用,所以我决定在Windows计算机上使用。但是,这甚至更糟,因为该程序甚至没有给我发送到mqtt服务器的数据。我直接收到以下错误:
[WinError 10038] An operation was attempted on something that is not a socket.
所以我的问题是。为什么在Windows上Mac可以正常工作(即使它崩溃了)时却出现此错误?我该如何解决此问题(在Windows上,如果可能的话在Mac上为什么不可以)。
答案 0 :(得分:0)
首先,您尝试两次启动网络循环,但永远无法进行。
接下来,您真的应该在订阅之前等待连接确认,因此添加on_connect
回调是一个好主意。
import paho.mqtt.client as mqtt
broker="test.mosquitto.org"
#define callback
def on_message(client, userdata, message):
try:
print("received message =", str(message.payload.decode("utf-8")))
except None:
print("")
def on_connect(client, userdata, flags, rc):
print("Connection returned result: "+connack_string(rc))
print("subscribing ")
client.subscribe("DHT22_cimti_project_pe") #subscribe
client=mqtt.Client()
client.on_message = on_message
client.on_connect = on_connect
#####
print("connecting to broker ",broker)
client.connect(broker)
client.loop_forever() #start loop to process received messages
最后,实际上您不应该阻止on_message
回调,因此请删除time.sleep(1)