UNPKG

@growbox/sensors

Version:

An abstraction layer for a selection of raspberry-compatible sensors

60 lines (52 loc) 1.72 kB
/** * @author nstCactus * @date 06/12/2017 13:13 */ //@formatter:off const ds18b20 = require('ds18b20-raspi'); const AbstractSensor = require('./AbstractSensor'); const SensorValue = require('../SensorValue'); const SensorError = require('../errors/SensorError'); //@formatter:on /** * A ds18b20 temperature sensor */ class Ds18b20Sensor extends AbstractSensor { /** * Read from the sensor to get the current temperature * @returns {Promise<SensorValue[]>} A promise that, when fulfilled, contains an array which consists of a single * SensorValue: the current temperature */ async read() { const ds18b20Sensors = ds18b20.list(); return new Promise((resolve, reject) => { if (ds18b20Sensors.indexOf(this.uid) >= 0) { const value = ds18b20.readC(this.uid, 2); resolve([new SensorValue(SensorValue.TypeEnum.TEMPERATURE, value)]); } else { reject(new ReferenceError(`Skipping ds18b20 sensor "${this.name}" as no sensor with this id was found`)); } }); } /** * @returns {Promise<string[]>} A Promise that, when fulfilled, contains an array of the ids of all ds18b20 sensors * connected to the 1-wire bus. */ static async list() { return new Promise((resolve, reject) => { ds18b20.list((err, deviceIds) => { if (err) { // No, no sensor found isn't an error! if (err.indexOf('any 1-Wire sensors to list') > -1) { resolve([]); } else { reject (new SensorError(err)); } } else { resolve(deviceIds); } }); }); } } module.exports = Ds18b20Sensor;