Skip to content

Instantly share code, notes, and snippets.

@Tirael
Created November 25, 2016 01:00
Show Gist options
  • Save Tirael/68e5da1f32451e12e7241309e8c2c7f8 to your computer and use it in GitHub Desktop.
Save Tirael/68e5da1f32451e12e7241309e8c2c7f8 to your computer and use it in GitHub Desktop.
machine-test
var machina = require('machina');
var vehicleSignal = new machina.BehavioralFsm( {
initialize: function( options ) {
// your setup code goes here...
},
namespace: "vehicle-signal",
initialState: "uninitialized",
states: {
uninitialized: {
"*": function( client ) {
this.deferUntilTransition( client );
this.transition( client, "green" );
}
},
green: {
_onEnter: function( client ) {
console.log('1');
client.timer = setTimeout( function() {
this.handle( client, "timeout" );
}.bind( this ), 30000 );
this.emit( "vehicles", { client: client, status: 'GREEN' } );
},
timeout: "green-interruptible",
pedestrianWaiting: function( client ) {
console.log('2');
this.deferUntilTransition( client, "green-interruptible" );
},
_onExit: function( client ) {
console.log('3');
clearTimeout( client.timer );
}
},
"green-interruptible": {
pedestrianWaiting: "yellow"
},
yellow: {
_onEnter: function( client ) {
console.log('4');
client.timer = setTimeout( function() {
this.handle( client, "timeout" );
}.bind( this ), 5000 );
this.emit( "vehicles", { client: client, status: 'YELLOW' } );
},
timeout: "red",
_onExit: function( client ) {
console.log('5');
clearTimeout( client.timer );
}
},
red: {
_onEnter: function( client ) {
console.log('6');
client.timer = setTimeout( function() {
this.handle( client, "timeout" );
}.bind( this ), 1000 );
},
_reset: "green",
_onExit: function( client ) {
console.log('7');
clearTimeout( client.timer );
}
}
},
reset: function( client ) {
console.log('8');
this.handle( client, "_reset" );
},
pedestrianWaiting: function( client ) {
console.log('9');
this.handle( client, "pedestrianWaiting" );
}
} );
console.log('***');
// Now we can have multiple 'instances' of traffic lights that all share the same FSM:
var light1 = { location: "Dijsktra Ave & Hunt Blvd", direction: "north-south" };
var light2 = { location: "Dijsktra Ave & Hunt Blvd", direction: "east-west" };
// to use the behavioral fsm, we pass the "client" in as the first arg to API calls:
vehicleSignal.pedestrianWaiting( light1 );
// Now let's signal a pedestrian waiting at light2
vehicleSignal.pedestrianWaiting( light2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment