Skip to content

Instantly share code, notes, and snippets.

@coderbyheart
Created August 19, 2019 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderbyheart/34a8e71ffe30af882407544567971efb to your computer and use it in GitHub Desktop.
Save coderbyheart/34a8e71ffe30af882407544567971efb to your computer and use it in GitHub Desktop.
protobuf example
package gps;
syntax = "proto3";
message gps {
message V {
double lng = 0;
double lat = 1;
double acc = 2;
double alt = 3;
double spd = 4;
double hdg = 5;
}
V v = 0;
double ts = 1;
}
var protobuf = require("protobufjs");
protobuf.load("gps.proto", function(err, root) {
if (err)
throw err;
// Obtain a message type
var GpsMessage = root.lookupType("gps.gps");
// Exemplary payload
var payload = {
"v": {
"lng": 10.414394,
"lat": 63.430588,
"acc": 17.127758,
"alt": 221.639832,
"spd": 0.320966,
"hdg": 0
},
"ts": 1566042672382
};
// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
var errMsg = GpsMessage.verify(payload);
if (errMsg)
throw Error(errMsg);
// Create a new message
var message = GpsMessage.create(payload); // or use .fromObject if conversion is necessary
// Encode a message to an Uint8Array (browser) or Buffer (node)
var buffer = GpsMessage.encode(message).finish();
// ... do something with buffer
console.log(buffer.toString().length) // 62
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment