masterblaster
Version:
Scheduling and componsation system for biodome
102 lines (84 loc) • 2.6 kB
JavaScript
var time = require('./time-utils')
, util = require('util')
, biodomeClient = { 'setDeviceState' : function(device, state) {console.log(device, state)} }
, AbstractDeviceEvent = require('./abstract-device-event');
function switchDevice(device, state) {
var e = new TimedDeviceEvent();
e.opts.device = device;
e.opts.scheduledState = state;
return e;
}
function TimedDeviceEvent() {
AbstractDeviceEvent.call(this);
this.opts.endTime = null;
this.opts.endState = null;
this.opts.duration = null;
};
function fromJSON(json) {
var e = new TimedDeviceEvent();
e.opts = (typeof json === Object) ? json : JSON.parse(json);
return e;
}
util.inherits(TimedDeviceEvent, AbstractDeviceEvent);
var def = TimedDeviceEvent.prototype;
def.until = function(when, endState) {
this.opts.endTime = time.validateTimeText(when);
this.opts.endState = endState;
return this;
};
def.for = function(howLong, endState) {
if (!time.parseDuration(howLong)) {
throw Error("Expected format = <number> <second(s)|minute(s)|hour(s)>");
}
this.opts.endState = endState;
this.opts.duration = howLong;
return this;
};
def.execute = function(client) {
var self = this;
client = client || biodomeClient;
this.resolveOptions();
// Go!
self.startTimer = time.singleCallTimer(
self.parsed.startSchedule,
function() {
client.setDeviceState(self.opts.device, self.opts.scheduledState);
}
);
// End!
self.endTimer = time.singleCallTimer(
self.parsed.endSchedule,
function() {
client.setDeviceState(self.opts.device, self.parsed.endState);
self.startTimer.clear();
self.endTimer.clear();
}
);
};
def.resolveOptions = function() {
if (this.resolved) return;
// prepare the things!
this.parsed = {
'device' : this.opts.device,
'scheduledState' : this.opts.scheduledState
};
this.parsed.startSchedule = time.textToSchedule(this.opts.goTime);
this.parsed.endSchedule = this.resolveEndTime();
this.parsed.endState = this.resolveEndState();
this.resolved = true;
};
def.resolveEndTime = function() {
var durationSeconds, startTime, endDate;
if (this.opts.endTime) {
return time.textToSchedule(this.opts.endTime);
} else {
return time.durationToSchedule(this.opts.goTime, this.opts.duration);
}
};
def.resolveEndState = function() {
if (this.opts.endState) return this.opts.endState;
return (this.opts.scheduledState == 'on') ? 'off' : 'on';
};
module.exports = switchDevice;
module.exports.fromJSON = fromJSON;
module.exports.TimedDeviceEvent = TimedDeviceEvent;