113 lines
3.3 KiB
JavaScript
113 lines
3.3 KiB
JavaScript
var restify = require('restify')
|
|
, util = require('util')
|
|
, EventEmitter = require('events').EventEmitter;
|
|
|
|
// constructor function
|
|
function Cosm(streams, key) {
|
|
var self = this;
|
|
|
|
self._streams = streams;
|
|
self._interval = 5000;
|
|
|
|
self._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++) {
|
|
|
|
self._jsonClient.get('/v2/feeds/' + self._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 = obj.id + ":" + dataStream.id;
|
|
|
|
console.log(recentvalues[address] + " " + currentValue);
|
|
console.log(typeof(recentvalues[address]) + " " + typeof(currentValue));
|
|
if(recentvalues[address] !== currentValue) {
|
|
self.emit('changedvalue', object);
|
|
}
|
|
else
|
|
self.emit('updatevalue', object);
|
|
|
|
|
|
recentvalues[address] = currentValue;
|
|
}
|
|
});
|
|
}
|
|
|
|
}, self._interval);
|
|
}
|
|
|
|
util.inherits(Cosm, EventEmitter);
|
|
|
|
Cosm.prototype.getStreams = function(streams, callback) {
|
|
var self = this;
|
|
|
|
for(var i=0; i<streams.length; i++) {
|
|
|
|
self._jsonClient.get('/v2/feeds/' + streams[i] + ".json", function(err, req, res, obj) {
|
|
if(err || obj.datastreams == null) {
|
|
console.error("error getting stream: " + err)
|
|
return;
|
|
}
|
|
// console.dir(obj);
|
|
var object = {
|
|
id: obj.id,
|
|
description: obj.description,
|
|
lat: typeof obj.location === 'undefined' ? 'undefined' : obj.location.lat,
|
|
lon: typeof obj.location === 'undefined' ? 'undefined' : obj.location.lon,
|
|
location: typeof obj.location === 'undefined' ? 'undefined' :obj.location.name,
|
|
title: obj.title
|
|
};
|
|
|
|
if(callback != 'undefined') callback(object);
|
|
|
|
});
|
|
}
|
|
};
|
|
|
|
|
|
|
|
module.exports = Cosm;
|
|
|
|
|
|
|
|
function isNumber(value) {
|
|
if ((undefined === value) || (null === value)) {
|
|
return false;
|
|
}
|
|
if (typeof value == 'number') {
|
|
return true;
|
|
}
|
|
return !isNaN(value - 0);
|
|
} |