Last active
September 9, 2015 04:59
-
-
Save kevinswiber/ab8e889f7764b3dbd3c0 to your computer and use it in GitHub Desktop.
Zetta LED state machine that changes at runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var util = require('util'); | |
| var Device = require('zetta').Device; | |
| var LED = module.exports = function() { | |
| Device.call(this); | |
| this.intensity = 0; | |
| var self = this; | |
| // Example of dynamically changing state machine at runtime. | |
| // Measures would have to be taken to ensure these changes are | |
| // loaded at init time after the changes have been made | |
| // dynamically. | |
| setTimeout(function() { | |
| self._allowed['on'] = ['turn-off', 'dim']; | |
| self._allowed['dimmed'] = ['turn-on', 'turn-off']; | |
| self._transitions['dim'] = { | |
| handler: function(intensity, cb) { | |
| intensity = new Number(intensity); | |
| if (!intensity || isNaN(intensity)) { | |
| this.call('turn-off', cb); | |
| return; | |
| } | |
| this.intensity = intensity; | |
| this.state = 'dimmed'; | |
| cb(); | |
| }, | |
| fields: [ { name: 'intensity', type: 'text' } ] | |
| } | |
| }, 5000); | |
| }; | |
| util.inherits(LED, Device); | |
| LED.prototype.init = function(config) { | |
| config | |
| .type('led') | |
| .state('off') | |
| .when('off', { allow: ['turn-on'] }) | |
| .when('on', { allow: ['turn-off'] }) | |
| .map('turn-on', this.turnOn) | |
| .map('turn-off', this.turnOff) | |
| }; | |
| LED.prototype.turnOn = function(cb) { | |
| this.intensity = 100; | |
| this.state = 'on'; | |
| cb(); | |
| }; | |
| LED.prototype.turnOff = function(cb) { | |
| this.intensity = 0; | |
| this.state = 'off'; | |
| cb(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment