diff --git a/lib/humidity/index.js b/lib/humidity/index.js index 7100686..cc5aad2 100644 --- a/lib/humidity/index.js +++ b/lib/humidity/index.js @@ -18,7 +18,14 @@ 'use strict'; var console = require('console'); -var Sensor = require('./simulator'); + +var NTU21D = null; +try { + NTU21D = require('htu21d-i2c'); +} catch (err){ + console.log(err); +} +var Simulator = require('./simulator'); /** * Class inspired by W3C's generic-sensor @@ -26,6 +33,7 @@ var Sensor = require('./simulator'); **/ function Humidity(options) { var self = this; + this.state = 'idle'; this.type = 'humidity'; this.properties = ['level']; for (var property in self.properties) { @@ -37,6 +45,7 @@ function Humidity(options) { } this.options = options || {}; this.options.frequency = this.options.frequency || 1; + this.options.controller = this.options.controller || 'simulator'; return this; } @@ -45,7 +54,7 @@ Humidity.prototype.update = function update() { var self = this; try { self.hasReading = false; - self.sensor.read(function(err, data) { + self.sensor.readHumidity(function(err, data) { if (err || data === null || typeof data === 'undefined') { return self.onerror(data); } @@ -75,7 +84,16 @@ Humidity.prototype.start = function start() { this.state = 'activating'; if (!this.sensor) { try { - this.sensor = new Sensor(); + if (this.options.controller === 'simulator') { + this.sensor = new Simulator(); + } else if ((this.options.controller === 'htu21d') || + (this.options.controller === 'node-htu21d') || + (this.options.controller === 'htu21d-i2c') + ) { + this.sensor = new NTU21D(this.options.sensor); + } else { + throw new Error("TODO: unsupported controller:" + this.options.controller); + } } catch (err) { if (this.onerror) { return this.onerror(err) @@ -101,7 +119,10 @@ module.exports = Humidity; if (module.parent === null) { - var sensor = new Humidity(); + var config = process.argv[2] + ? JSON.parse(process.argv[2]) + : null; + var sensor = new Humidity(config); sensor.onreading = function() { console.log('log: level=' + this.level); this.stop(); diff --git a/lib/humidity/simulator.js b/lib/humidity/simulator.js index 2a6f878..fb3e8ce 100644 --- a/lib/humidity/simulator.js +++ b/lib/humidity/simulator.js @@ -24,7 +24,7 @@ function Simulator () { }; } -Simulator.prototype.read = function (callback) { +Simulator.prototype.readHumidity = function (callback) { this.value.level = Math.random(); if (callback) return callback(null, this.value); }; @@ -33,7 +33,7 @@ module.exports = Simulator; if (module.parent === null) { var sensor = new Simulator(); - sensor.read(function (err, value) { + sensor.readHumidity(function (err, value) { if (err) { console.error('error: ' + err); throw err;