Created
August 19, 2019 10:55
-
-
Save coderbyheart/34a8e71ffe30af882407544567971efb to your computer and use it in GitHub Desktop.
protobuf example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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