Created
May 20, 2014 22:07
-
-
Save brandoaire/3595e06a5a58f2514af6 to your computer and use it in GitHub Desktop.
JS listener for local control of an RC Car with a Spark Core
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 dgram = require("dgram"); | |
var os = require('os'); | |
var getIPAddresses = function () { | |
var nics = os.networkInterfaces(); | |
var results = []; | |
for (var name in nics) { | |
if (!nics.hasOwnProperty(name)) { continue; } | |
var nic = nics[name]; | |
for (var i = 0; i < nic.length; i++) { | |
var addy = nic[i]; | |
if ((addy.family == "IPv4") | |
&& (addy.address != "127.0.0.1")) { | |
results.push(addy.address); | |
} | |
} | |
} | |
return results; | |
}; | |
var server = dgram.createSocket("udp4"); | |
server.on("error", function (err) { | |
console.log("server error:\n" + err.stack); | |
server.close(); | |
}); | |
server.on("message", function (msg, rinfo) { | |
var hex = msg.toString('hex'); | |
var idx = hex.indexOf('ff'); | |
var id = hex.substring(idx + 2); | |
console.log("a core just announced itself! core id:" + id + " ip address: " + rinfo.address); | |
}); | |
server.on("listening", function () { | |
var address = server.address(); | |
console.log("server listening " + address.address + ":" + address.port); | |
}); | |
var ips = getIPAddresses(); | |
if (!ips || (ips.length == 0)) { | |
console.error("error getting IP address!"); | |
} | |
server.bind(5683, '0.0.0.0', function () { | |
for(var i=0;i<ips.length;i++) { | |
server.addMembership('224.0.1.187', ips[i]); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment