protobuf.js icon indicating copy to clipboard operation
protobuf.js copied to clipboard

[Bug]Can not encode the embedded "oneof" keywords issue with sparkplugB schema

Open Hulkman-Tech opened this issue 1 year ago • 0 comments

I try to write the mqtt sparkplugB client to test some payload, but the embedded metrics oneof value can not encode. I found this problem in many place.

its value is differerent with online tools https://www.protobufpal.com/

my mqtt broker side can encode the oneof, and you js lib can not encode it.

here is the log

"Encoded Buffer:" "088ceef7bfed3112140a07746573744b6579100118a8edf7bfed31200a1824" "Decoded Message:" { "metrics": [ { "name": "testKey", "alias": "1", "timestamp": "1713020729000", "datatype": 10, "isHistorical": false, "isTransient": false, "isNull": false } ], "timestamp": "1713020729100", "seq": "36", "uuid": "", "body": "" } run platfom is my macOS, MQTTX, https://npm.runkit.com/protobufjs online platform

here is the code, is that some things wrong with .encode(message).finish()?? or I need to use other function.

`const protobuf = require("protobufjs");

var schema = "syntax = "proto3";
message Payload {
message Metric {
string name = 1;
uint64 alias = 2;
uint64 timestamp = 3;
uint32 datatype = 4;
bool is_historical = 5;
bool is_transient = 6;
bool is_null = 7;
oneof value {
uint32 int_value = 10;
uint64 long_value = 11;
float float_value = 12;
double double_value = 13;
bool boolean_value = 14;
string string_value = 15;
bytes bytes_value = 16;
}
}
uint64 timestamp = 1;
repeated Metric metrics = 2;
uint64 seq = 3;
string uuid = 4;
bytes body = 5;
}"

async function main() { const root = protobuf.parse(schema).root; const Payload = root.lookupType("Payload");

const payloadJson = { timestamp: 1713020729100, metrics: [{ name: "testKey", alias: 1, timestamp: 1713020729000, datatype: 10, int_value: 222 }], seq: 36 };

const message = Payload.create(payloadJson); const buffer = Payload.encode(message).finish(); console.log("Encoded Buffer:", buffer.toString('hex'));

const decodedMessage = Payload.decode(buffer); const object = Payload.toObject(decodedMessage, { longs: String, enums: String, bytes: String, defaults: true, arrays: true // Ensure empty arrays are output });

console.log("Decoded Message:", JSON.stringify(object, null, 2)); }

main().catch(console.error); `

Hulkman-Tech avatar Apr 15 '24 02:04 Hulkman-Tech