diff --git a/lib/temperature/index.js b/lib/temperature/index.js index 98d7cfe..ce0ed24 100644 --- a/lib/temperature/index.js +++ b/lib/temperature/index.js @@ -19,9 +19,11 @@ var console = require('console'); var BMP085 = null; +var HTU21D = null; try { BMP085 = require('@abandonware/bmp085-sensor'); + HTU21D = require('htu21d-i2c'); } catch (err){ // console.log(err); } @@ -59,20 +61,37 @@ TemperatureSensor.prototype.update = function update() { var self = this; try { self.hasReading = false; - self.sensor.read(function (err, data) { - if (err) { - return self.onerror(err); - } - if ((data === null) || (typeof data === 'undefined')) { - return self.onerror("Invalid data"); - } else { - self.timestamp = new Date(); - self.celsius = Number(data.temperature); - self.hasReading = true; - self.onreading(); - self.hasReading = false; - } - }); + if (typeof self.sensor.readTemperature === 'function') { + self.sensor.readTemperature(function (err, data) { + if (err) { + return self.onerror(err); + } + if ((data === null) || (typeof data === 'undefined')) { + return self.onerror("Invalid data"); + } else { + self.timestamp = new Date(); + self.celsius = data; + self.hasReading = true; + self.onreading(); + self.hasReading = false; + } + }); + } else { + self.sensor.read(function (err, data) { + if (err) { + return self.onerror(err); + } + if ((data === null) || (typeof data === 'undefined')) { + return self.onerror("Invalid data"); + } else { + self.timestamp = new Date(); + self.celsius = Number(data.temperature); + self.hasReading = true; + self.onreading(); + self.hasReading = false; + } + }); + } } catch (err) { self.onerror(err); } @@ -96,6 +115,11 @@ TemperatureSensor.prototype.start = function start() { (this.options.controller === 'bmp180') ) { this.sensor = new BMP085(this.options.sensor); + } else if ((this.options.controller === 'htu21d') || + (this.options.controller === 'node-htu21d') || + (this.options.controller === 'htu21d-i2c') + ) { + this.sensor = new HTU21D(this.options.sensor); } else { throw new Error("TODO: unsupported controller:" + this.options.controller); } @@ -107,18 +131,24 @@ TemperatureSensor.prototype.start = function start() { } try { - self.sensor.calibrate(function (err /* , data*/) { - if (err) { - throw err; - } - if (!self.interval) { - self.interval = setInterval(function() { self.update(); }, - 1000. / self.options.frequency); - self.onactivate(); - self.state = 'activated'; - } - }); - + if (typeof self.sensor.calibrate !== 'function') { + self.interval = setInterval(function() { self.update(); }, + 1000. / self.options.frequency); + self.onactivate(); + self.state = 'activated'; + } else { + self.sensor.calibrate(function (err /* , data*/) { + if (err) { + throw err; + } + if (!self.interval) { + self.interval = setInterval(function() { self.update(); }, + 1000. / self.options.frequency); + self.onactivate(); + self.state = 'activated'; + } + }); + } } catch(err) { self.onerror(err); }