Skip to content

Commit

Permalink
ambientlight: Relocate controller creation in start
Browse files Browse the repository at this point in the history
to use onerror

Change-Id: I04d2e9910d3f4b69dd2eb5fce30c90f5fa3b0462
Signed-off-by: Philippe Coval <p.coval@samsung.com>
  • Loading branch information
rzr committed Feb 27, 2019
1 parent f380fdb commit 3f329a2
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions lib/ambientlight/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@

'use strict';

var console = require('console');
var BH1750 = require('bh1750');

/**
* Class inspired by W3C's generic-sensor
* @related: https://www.w3.org/TR/ambient-light/
**/
function AmbientLight(options) {
this.state = 'construct';

this.state = 'idle';
this.type = 'ambientlight';
this.illuminance = 0;

Expand All @@ -42,12 +42,6 @@ function AmbientLight(options) {
this.options = options || {};
this.options.frequency = this.options.frequency || 1;
this.options.controller = this.options.controller || 'bh1750';
if (this.options.controller === 'bh1750') {
this.sensor = new BH1750(this.options.sensor);
} else {
throw new Error("TODO: unsupported controller:" + this.options.controller);
}
this.state = 'idle';

return this;
}
Expand Down Expand Up @@ -80,7 +74,21 @@ AmbientLight.prototype.stop = function stop() {

AmbientLight.prototype.start = function start() {
var self = this;
self.state = 'activating';
this.state = 'activating';
if (!this.sensor) {
try {
if (this.options.controller === 'bh1750') {
this.sensor = new BH1750(this.options.sensor);
} else {
throw new Error("TODO: unsupported controller:" + this.options.controller);
}
} catch (err) {
if (this.onerror) {
return this.onerror(err)
}
}
}

try {
if (!self.interval) {
self.interval = setInterval(function() { self.update(); },
Expand All @@ -95,3 +103,12 @@ AmbientLight.prototype.start = function start() {

module.exports = AmbientLight;


if (module.parent === null) {
var sensor = new AmbientLight();
sensor.onreading = function() {
console.log('log: ' + this.illuminance)
this.stop();
}
sensor.start();
}

0 comments on commit 3f329a2

Please sign in to comment.