排队MQTT序列化消息时遇到一些问题

2024-09-30 22:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将pythons脚本中的一些数据排入c#应用程序时遇到了一些问题。在高层,我有一个python脚本,其中一些硬编码的值被序列化并通过MQTT发送。C#应用程序正在订阅这些消息

在C#端,我订阅了一个主题,该主题将接收这些消息,并在每次收到消息时打印出一些ID值

到目前为止,值并不一致,这意味着从python发送了20条消息,但在C#端,并不是所有消息都被接收到

输出示例:

0
Try deserialize protobuf message
System.IO.MemoryStream
1
Try deserialize protobuf message
System.IO.MemoryStream
2
Try deserialize protobuf message
System.IO.MemoryStream
3
Try deserialize protobuf message
System.IO.MemoryStream
5
Try deserialize protobuf message
System.IO.MemoryStream
7
Try deserialize protobuf message
System.IO.MemoryStream
8
Try deserialize protobuf message
System.IO.MemoryStream
9
Try deserialize protobuf message
System.IO.MemoryStream
10
Try deserialize protobuf message
System.IO.MemoryStream
12
Try deserialize protobuf message
System.IO.MemoryStream
13
Try deserialize protobuf message
System.IO.MemoryStream
14
Try deserialize protobuf message
System.IO.MemoryStream
15
Try deserialize protobuf message
System.IO.MemoryStream
18
Try deserialize protobuf message
System.IO.MemoryStream
19

从上面的输出来看:6、11、16、17从未成功

Python代码:

import paho.mqtt.client as paho import AIML_pb2 import datetime as dt import time

def on_publish(client,userdata,result):                         #create function for callback
    print("data published \n")
    pass

def mqtt(buf):
    broker="127.0.0.1"
    port=1883

    client1= paho.Client("control1")                                #create client object
    client1.on_publish = on_publish                                 #assign function to callback
   
    client1.connect(broker,port)                                    #establish connection
    try:
        ret= client1.publish("/SERVICES/RESPONSE/ECG/UDCMGR/AIML",buf)  #publish
    except:
        print("Waiting to publish!")
    

def main():

    detections = AIML_pb2.ObjectDetectionParametersBroadcast()

    for i in range(0, 20):
        detections.timestamp = dt.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        detections.frameID = i
        detections.objectType = "cell phone"
        detections.conf = 0.90
        detections.top_x = 0.5
        detections.top_y = 0.6
        detections.bottom_x = 0.7
        detections.bottom_y = 0.9
        buf = detections.SerializeToString()
        mqtt(buf)
        print (i)
        time.sleep(1)
main()

C#代码:

if (e.Topic == "/SERVICES/RESPONSE/ECG/UDCMGR/AIML")
{
    Queue <byte[]> objectDetected = new Queue<byte[]>();
                    
    objectDetected.Enqueue(e.Message);

    foreach (var id in objectDetected)
    {
     Console.WriteLine(id);
     ScriptAPIs.aimlStatus = true;
    }
}

Tags: ioimport消息messagesystempublishpahoprotobuf