首页 > 解决方案 > 遇到一些问题排队 MQTT 序列化消息

问题描述

我在将 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 从未通过。

蟒蛇代码:

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;
    }
}

标签: pythonc#mqtt

解决方案


推荐阅读