protobuf python的基本使用

testbed.proto文件,并通过
protoc.exe --python_out=.\ testbed.proto
对其进行编译

syntax = "proto2";

message Addmsgbody {
  repeated Msgbody body = 1;
}

//定义消息头部
message Msgbody{
  required string NodeId = 1;
  required string MsgId = 2;
  required string SendTime = 3;
  repeated AddData Data = 4;
}

//定义消息内容
message AddData{
  //定义设备控制
  repeated AddCMD CMD = 1;
  repeated AddCMDResponse CMDResponse = 2;
}
//设备控制
message AddCMD{
  required int32 MsgCount = 1;
  required int32 ControlType = 2;
  repeated string DUTID = 3;
  repeated string TSBusiNodeIDs = 4;
}
message AddCMDResponse{
  required int32 MsgCount = 1;
  required int32 State = 2;
}

pythond的使用
1、数据的序列化和反序列化

import testbed_pb2
def init_message():
    addmsgbody = testbed_pb2.Addmsgbody()
    msgbody = addmsgbody.body.add()
    msgbody.NodeId = f'{1001}'
    msgbody.MsgId = f'{1}'
    msgbody.SendTime = str(datetime.date.today())
    print(msgbody.SendTime)
    Adddata = msgbody.Data.add()
    AddCMD = Adddata.CMD.add()
    AddCMDResponse = Adddata.CMDResponse.add()
    AddCMD.MsgCount = 1
    AddCMD.ControlType = 2
    for j in range(1, 3):
        #单一属性repeated,通过append不断增加,且每次只能append一个值
        AddCMD.DUTID.append(f'{j*1001}')
    AddCMDResponse.MsgCount = 1
    AddCMDResponse.State = 1
    print(addmsgbody.body)
    #数据序列化
    data = addmsgbody.SerializeToString()
    print(data)
    #数据反序列化
    addmsgbody.ParseFromString(data)
    print(addmsgbody.body)
    for msgbody in addmsgbody.body:
        #数据转换为json格式
        json_body = json_format.MessageToJson(msgbody)
        print(json_body)

一个msgbody
一个msgbody
json格式
在这里插入图片描述

2、同一位置新增protobuf数据时,初始化时应保持不同对象

    add_msgbody = testbed_pb2.Addmsgbody()
    msgbody = add_msgbody.body.add()

3、protobuf数据的获取

    #获取每一个msgbody
    for msgbody in addmsgbody.body:
        c = msgbody.NodeId
        print(c)
        #Data[0]代表的是第一个data
        a = msgbody.Data[0].CMD[0].MsgCount
        d = msgbody.Data[0].CMD[0].DUTID
        print(a, d)
        #获取每一个DUTID
        for DUTID in msgbody.Data[0].CMD[0].DUTID:
            print(DUTID)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值