Skip to content

Instantly share code, notes, and snippets.

@obiltschnig
Last active March 8, 2019 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obiltschnig/f010981e18dceaedaf2e9eaae8958971 to your computer and use it in GitHub Desktop.
Save obiltschnig/f010981e18dceaedaf2e9eaae8958971 to your computer and use it in GitHub Desktop.
Sending sensor data to ThingSpeak from macchina.io (now with outlier detection).
var net = require('net');
var sensors = [
{
name: 'temperature',
id: 'io.macchina.bluePillar.temperature#lamp1',
sensor: null,
validRange: { min: -40, max: 50 }
},
{
name: 'humidity',
id: 'io.macchina.bluePillar.humidity#lamp1',
sensor: null,
validRange: { min: 0, max: 100 }
},
{
name: 'pressure',
id: 'io.macchina.bluePillar.pressure#lamp1',
sensor: null,
validRange: { min: 500, max: 1100 }
},
{
name: 'windspeed',
id: 'io.macchina.bluePillar.wind.speed#lamp1',
sensor: null,
validRange: { min: 0, max: 40 }
},
{
name: 'pm25',
id: 'io.macchina.bluePillar.pm25#lamp1',
sensor: null,
validRange: { min: 0, max: 50 }
},
{
name: 'noise',
id: 'io.macchina.bluePillar.noise#lamp1',
sensor: null,
validRange: { min: 0, max: 180 }
}
];
var history = {};
for (var i = 0; i < sensors.length; i++)
{
var s = sensors[i];
var ref = serviceRegistry.findByName(s.id);
if (ref)
{
s.sensor = ref.instance();
history[s.name] = [];
}
}
setInterval(() => {
for (var i = 0; i < sensors.length; i++)
{
var s = sensors[i];
var value = s.sensor.value();
history[s.name].push(value);
console.debug('%s: %f', s.name, value);
}
}, 5000);
setInterval(() => {
var uri = 'https://api.thingspeak.com/update';
var params = 'api_key=R49TZ8UI7M94LE4B';
for (var i = 0; i < sensors.length; i++)
{
var s = sensors[i];
var range = s.validRange;
var arr = history[s.name];
var filtered = arr.filter(v => (v >= range.min && v <= range.max));
var max = filtered.reduce((a, b) => Math.max(a, b));
history[s.name] = [];
console.log('%s max: %f (%d outliers)', s.name, max, arr.length - filtered.length);
params += '&field' + (i + 1) + '=' + max;
}
var httpRequest = new net.HTTPRequest(
'POST',
uri
);
httpRequest.contentType = 'application/x-www-form-urlencoded';
httpRequest.content = params;
httpRequest.send((result) => {
console.log('ThingSpeak HTTP response: %d %s', result.response.status, result.response.content);
});
}, 60000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment