Implementation of the MAVLink protocol
In your main node script, you need to include the generated parser and instantiate it; you also need some kind of binary stream library that can read/write binary data and emit an event when new data is ready to be parsed (TCP, UDP, serial port all have appropriate libraries in the npm-o-sphere). The connection's "data is ready" event is bound to invoke the MAVLink parser to try and extract a valid message.
// requires Underscore.js, can use Winston for logging ,// see package.json for dependencies for the implementationvar mavlink = require'mavlink_ardupilotmega_v1.0'net = require'net';// Instantiate the parsermavlinkParser = ;// Create a connection -- can be anything that can receive/send binaryconnection = netcreateConnection5760 '127.0.0.1';// Provision the instantiated mavlinkParser object with the connectionmavlinkParsersetConnectionconnection;// When the connection issues a "got data" event, try and parse itconnectionon'data'mavlinkParserparseBufferdata;;
If the serial buffer has a valid MAVLink message, the message is removed from the buffer and parsed. Upon parsing a valid message, the MAVLink implementation emits two events:
message (for any message) and the specific message name that was parsed, so you can listen for specific messages and handle them.
// Attach an event handler for any valid MAVLink messagemavlinkParseron'message'console.log'Got a message of any type!';console.logmessage;;// Attach an event handler for a specific MAVLink messagemavlinkParseron'HEARTBEAT'console.log'Got a heartbeat message!';console.logmessage; // message is a HEARTBEAT message;
See the gotcha's and todo's section below for some important caveats. The below code is preliminary and will change to be more direct. At this point, the MAVLink parser doesn't manage any state information about the UAV or the connection itself, so a few fields need to be fudged, as indicated below.
Sending a MAVLink message is done by creating the message object, populating its fields, and packing/sending it across the wire. Messages are defined in the generated code, and you can look up the parameter list/docs for each message type there. For example, the message
REQUEST_DATA_STREAM has this signature:
Creating the message is done like this:
request = request_data_stream1 1 mavlinkMAV_DATA_STREAM_ALL 1 1;mavlinkParsersendrequest;