@growbox/sensors
Version:
An abstraction layer for a selection of raspberry-compatible sensors
56 lines (46 loc) • 1.55 kB
JavaScript
/**
* @author nstCactus
* @date 06/12/2017 12:45
*/
const dht = require('node-dht-sensor');
const AbstractSensor = require('./AbstractSensor');
const SensorValue = require('../SensorValue');
/** {WeakMap<number>} The GPIO pin the sensor is connected to */
let _gpioPin = new WeakMap();
/**
* A DHT22 temperature and humidity sensor
*/
class Dht22Sensor extends AbstractSensor {
constructor(name, gpioPin) {
super(name, `Dht22_gpio${gpioPin}`);
_gpioPin = gpioPin.set(this, gpioPin);
}
/**
* @returns {number} The GPIO pin the sensor is connected to
*/
get gpioPin() {
return _gpioPin.get(this);
}
/**
* Read form the sensor to get the current temperature and relative humidity.
* @returns {Promise<SensorValue[]>} A promise that, when fulfilled, contains an array of two SensorValues:
* - the current temperature
* - the current relative humidity
*/
read() {
return new Promise((resolve, reject) => {
try {
const reading = dht.read(22, _gpioPin.get(this));
resolve([
new SensorValue(SensorValue.TypeEnum.temperature, reading.temperature),
new SensorValue(SensorValue.TypeEnum.humidity, reading.humidity),
]);
} catch (err) {
console.error(err);
// TODO: pass err as well
reject(new Error(`Skipping dht sensor ${this.name} as an error occurred while reading from it`));
}
});
}
}
module.exports = Dht22Sensor;