transform.js
var Cylon = require('cylon');
var clients = { }
var prevObj = { };
var simple_moving_averager = function(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1); // remove the first element of the array
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
if (nums.length < period)
n = nums.length;
return (sum/n).toFixed(2);
}
};
var smaTemp = simple_moving_averager(20);
var smaHumid = simple_moving_averager(20);
BOSS_TOPIC = "/nat/sensor/boss"
var topics = {
boss: { "name": BOSS_TOPIC, "subscribe": false, qos: 0 }
};
Cylon.robot({
connections: {
server: { adaptor: 'mqtt', host: 'mqtt://128.199.191.223:1883' },
xively: { adaptor: 'mqtt', host: 'mqtt://api.xively.com:1883',
feed_url: 'oA84T0lCAadH2SE37OejYCtBzrigITu0HKtVHAnPX5EFqdYy/v2/feeds/1092378279.json' },
sense2: { adaptor: 'mqtt', host: 'mqtt://api.xively.com:1883',
feed_url: '1o6ZKIC4MOTMJbxDkNWcB6afnoPNzHqbyE40uiU7uX2BARAu/v2/feeds/469207408.json'},
dragon_eclipse: { adaptor: 'mqtt', host: 'mqtt://iot.eclipse.org:1883',
topic: 'cmmc/Dragon'},
},
work: function(my) {
my.server.subscribe("/nat/sensor/data", function (err, arr) {
console.log("ON subscribe", arguments);
});
var publish_esp8266_channel = function(my, json) {
var chipId = json.clientId;
var ddd = {
"version":"1.0.0",
"datastreams":[
{ "id": "temperature-" +chipId, "current_value": json.temp /10 },
{ "id": "humidity-" +chipId, "current_value": json.humid / 10 },
{ "id": "heap-" +chipId, "current_value": json.heap },
{ "id": "cnt-" +chipId, "current_value": json.cnt }
]
};
var to_be_sent_data = JSON.stringify(ddd);
my.xively.publish(my.xively.details.feed_url, to_be_sent_data);
}
var publish_cmmc_sense = function(my, json) {
////////////////////////////////////////////////////
// TRANSFORM //
////////////////////////////////////////////////////
var chipId = json.clientId.split("-")[1];
chipId = chipId.substr(-3);
console.log(json);
var d2 = {
"version":"1.0.0",
"datastreams":[
{ "id": "temperature-" +chipId, "current_value": json.temp /10 },
{ "id": "humidity-" +chipId, "current_value": json.humid / 10 },
{ "id": "temperature-average", "current_value": smaTemp(json.temp /10) },
{ "id": "humidity-average", "current_value": smaHumid(json.humid /10) }
]
};
console.log(d2);
my.sense2.publish(my.sense2.details.feed_url, JSON.stringify(d2));
}
my.server.on("message", function(topic, msg) {
var json;
try {
json = JSON.parse(msg);
}
catch(e) {
console.log(msg);
console.log(e);
return;
}
publish_esp8266_channel(my, json);
publish_cmmc_sense(my, json);
});
}
}).start();