Skip to content

Instantly share code, notes, and snippets.

@brycejohnston
Last active January 16, 2019 14:32
Show Gist options
  • Save brycejohnston/6fc08b626f8396c41a699e4f747d8cd2 to your computer and use it in GitHub Desktop.
Save brycejohnston/6fc08b626f8396c41a699e4f747d8cd2 to your computer and use it in GitHub Desktop.
Node.js script to read DHT22 sensor and post readings to API. Run in background with forever / forever-service node libraries.
/***
forever-service version 0.5.4
Platform - Raspbian GNU/Linux 7 (wheezy)
update-rc.d: using dependency based boot sequencing
sensors provisioned successfully
Commands to interact with service sensors
Start - "sudo service sensors start"
Stop - "sudo service sensors stop"
Status - "sudo service sensors status"
Restart - "sudo service sensors restart"
***/
var sensorLib = require('node-dht-sensor');
var unirest = require('unirest');
var apiHost = "https://yourapiurlhere/api/v1/";
function getFahr(tempC) {
var p = Math.pow(10, 1);
tempF = tempC * 9 / 5 + 32;
return Math.round(tempF * p) / p;
}
function apiPost(tempC, humidity) {
unirest.post(apiHost + 'syour_sensor_endpoint')
.type('json')
.headers({
'Accept': 'application/json',
'Authorization': 'Token token=yourapitokenhere'
})
.send({
sensor_reading: {
temp_c: tempC,
temp_f: getFahr(tempC),
humidity: humidity
}
})
.end(function (response) {
console.log(response.body);
});
}
var dht_sensor = {
initialize: function () {
return sensorLib.initialize(22, 4);
},
read: function () {
var readout = sensorLib.read();
apiPost(readout.temperature.toFixed(2), readout.humidity.toFixed(2));
console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
'humidity: ' + readout.humidity.toFixed(2) + '%');
setTimeout(function () {
dht_sensor.read();
}, 1200000);
}
};
if (dht_sensor.initialize()) {
dht_sensor.read();
} else {
console.warn('Failed to initialize sensor');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment