chaosc-cosmdisplay/cosm.js

86 lines
2.2 KiB
JavaScript
Raw Normal View History

var restify = require('restify')
, util = require('util')
, EventEmitter = require('events').EventEmitter;
var COSM = function(streams, key) {
var self = this;
var streams = streams;
var interval = 1000;
var jsonClient = restify.createJsonClient({
url: 'http://api.cosm.com',
headers: { 'X-ApiKey': key },
version:'*'
});
var recentvalues = {};
setInterval(function() {
for(var i=0; i<streams.length; i++) {
jsonClient.get('/v2/feeds/' + streams[i] + ".json", function(err, req, res, obj) {
if(err || obj.datastreams == null) {
console.error("error getting stream: " + err)
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 currentValue = dataStream.current_value;
if(isNumber(currentValue)) currentValue = parseFloat(currentValue);
var object = {
'stream': obj.id,
'feed': dataStream.id,
'tags': dataStream.tags,
'displayname': streamName,
'value': currentValue
};
var address = streams[i] + ":" + dataStream.id;
if(recentvalues[address] != currentValue) {
self.emit('changedvalue', object);
}
self.emit('updatevalue', object);
recentvalues[address] = currentValue;
}
});
}
}, interval);
function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}
}
util.inherits(COSM, EventEmitter);
module.exports = COSM;