chaosc-fetcher/cosmfetcher.js

65 lines
2.3 KiB
JavaScript

// this is a json fetcher for streams from cosm.com
// to use, simply start "node cosmfetcher.js <hubAddress> <hubPort>"
// configuration
var streams = [ 91755, 70632, 53146, 45582, 64590 ]; // configure which cosm streams to fetch
var pollingInterval = 1000; // in ms
var sendAlways = false; // if set to true, fetcher will always send osc messages
// regardless if value changed
// end configuration
var restify = require('restify'), osc = require('node-osc');
var hubAddress = process.argv.length > 2 ? process.argv[2] : '192.168.23.43';
var hubPort = process.argv.length > 3 ? process.argv[3] : 7110;
console.log("using " + hubAddress + ":" + hubPort + " as hub");
var oscClient = new osc.Client(hubAddress, hubPort);
var cosmClient = restify.createJsonClient({
url: 'http://api.cosm.com',
headers: { 'X-ApiKey':'orKBBdLAKuKJU-RxqmZpZB6q0baSAKxBTVhKdjhUNkdyVT0g' },
version:'*'
});
var recentvalues = {};
setInterval(function() {
for(var i=0; i<streams.length; i++) {
cosmClient.get('/v2/feeds/' + streams[i] + ".json", function(err, req, res, obj) {
if(err || obj.datastreams == null) return;
for(var i=0; i<obj.datastreams.length; i++) {
var dataStream = obj.datastreams[i];
if(dataStream.id == null) continue;
var streamName = dataStream.id;
if(streamName.length < 2 && dataStream.tags != null) {
streamName = dataStream.tags[0] + streamName;
}
var address = '/cosm/' + obj.id + "/" + streamName;
var currentValue = dataStream.current_value;
if(isNumber(currentValue)) currentValue = parseFloat(currentValue);
if(sendAlways || recentvalues[address] != currentValue) {
oscClient.send(address, currentValue);
console.log(address + "," + currentValue);
}
recentvalues[address] = currentValue;
}
});
}
}, pollingInterval);
function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}