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
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)