Created
January 19, 2017 08:46
-
-
Save q-depot/0cc9cc411191b8ac34f228ad4765c352 to your computer and use it in GitHub Desktop.
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 mav = require("./mavlink_v10_ardupilotmega.js"); | |
var mavProtocol = new MAVLink( null, 252, 1 ); | |
var serverPort = 6000; // local sever listening port | |
var remotePort = -1; // this is set by the first HEARBEAT msg received from the drone | |
var remoteIp = '192.168.1.200'; // drone IP | |
var dgram = require('dgram'); | |
var server = dgram.createSocket('udp4'); | |
// Server | |
// ---------------------------------------------------------------- // | |
server.on('listening', function () { | |
var address = server.address(); | |
console.log('UDP Server listening on ' + address.address + ":" + address.port); | |
}); | |
server.on('message', function (message, remote) { | |
// decode the MAVLink msg, this function should return the msg or null | |
decodedMsg = mavProtocol.decode(message); | |
// wait for the first HEARTBEAT message to send the remotePort | |
// this is used to send back messages to the drone | |
if ( decodedMsg && decodedMsg.name == "HEARTBEAT" ) | |
{ | |
// this is the first HEARTBEAT msg received | |
// log and send a test message to the drone | |
if ( remotePort < 0 ) | |
{ | |
remotePort = remote.port; | |
console.log('set udp port: ' + remote.port ); | |
sendMAVLink( new mav.messages.autopilot_version_request(1, 1) ); | |
} | |
else | |
remotePort = remote.port; | |
} | |
// Log incoming messages except HEARTBEAT | |
if ( decodedMsg && decodedMsg.name != "HEARTBEAT" ) | |
console.log( decodedMsg ); | |
else if ( !decodedMsg ) | |
console.log( 'Decode Error: '); | |
}); | |
server.bind(serverPort); | |
// MAVLink | |
// ---------------------------------------------------------------- // | |
function sendMAVLink( msg ) | |
{ | |
buff = new Buffer(msg.pack(mavProtocol)); | |
mavProtocol.seq = (mavProtocol.seq + 1) % 256; | |
mavProtocol.total_packets_sent +=1; | |
mavProtocol.total_bytes_sent += buff.length; | |
if ( remotePort > 0 ) // wait for the drone to send the HEARTBEAT | |
{ | |
server.send( buff, remotePort, remoteIp, function(err, bytes) { | |
if (err) { | |
console.log('ERROR! ' + err ); | |
throw err; | |
} | |
}); | |
} | |
else | |
{ | |
console.log('MAV not ready!'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment