我目前正在实现在两个树莓pi之间使用的MQTT协议。第一个是Pi 0,并将连接有pi摄像机。它将把每个捕获的帧转换为一个numpy数组,然后将其发布到主控Pi,然后再使用PIL将numpy数组转换为图像。我这样做是因为我希望在主Pi上执行主要图像处理操作。
我的问题是主Pi没有收到任何消息。我已经执行了调试,并且在servant脚本上一切正常。但是由于某些原因,主Pi却什么也没收到。
这是两个脚本:
servant.py:
import paho.mqtt.client as mqtt
import time
import cv2
import numpy
import json
MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"
mqttc = mqtt.Client()
mqttc.connect(MQTT_SERVER, 1883, 60)
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
frame_list = frame.tolist()
MQTT_MESSAGE = json.dumps(frame_list)
mqttc.publish(MQTT_PATH, MQTT_MESSAGE)
time.sleep(1)
master.py:
import paho.mqtt.client as mqtt
import numpy as np
import json
import PIL
MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"
def on_connect(client, userdata, flags, rc):
print("connected with result code " + str(rc))
client.subscribe(MQTT_PATH)
def on_message(client, userdata, msg):
data = json.loads(msg.payload)
array = np.array(data)
img = PIL.Image.fromarray(array)
cv2.imshow('image', img)
cv2.waitKey()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, 1883, 60)
client.loop_forever()
答案 0 :(得分:0)
在您的发布代码中,您实际上没有给客户任何时间来处理它尝试发送的消息。这甚至是一个更大的问题,因为该消息可能大于单个网络数据包(作为图像)。要解决此问题,您必须调用MQTT客户端循环函数(或在b
中启动循环import paho.mqtt.client as mqtt
import time
import cv2
import numpy
import json
MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"
mqttc = mqtt.Client()
mqttc.connect(MQTT_SERVER, 1883, 60)
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
frame_list = frame.tolist()
MQTT_MESSAGE = json.dumps(frame_list)
mqttc.publish(MQTT_PATH, MQTT_MESSAGE)
mqttc.loop()
time.sleep(1)
或类似这样:
import paho.mqtt.client as mqtt
import time
import cv2
import numpy
import json
MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"
mqttc = mqtt.Client()
mqttc.connect(MQTT_SERVER, 1883, 60)
cap = cv2.VideoCapture(0)
mqttc.start_loop()
while True:
ret, frame = cap.read()
frame_list = frame.tolist()
MQTT_MESSAGE = json.dumps(frame_list)
mqttc.publish(MQTT_PATH, MQTT_MESSAGE)
time.sleep(1)