forked from artcom/hsm-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateMachine.js
468 lines (425 loc) · 17.2 KB
/
StateMachine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/* __ ___ ____ _____ ______ _______ ________ _______ ______ _____ ____ ___ __
The MIT License (MIT)
Copyright (c) 2013 Martin Skinner ART+COM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*globals module*/
/**
* @namespace HSM
*/
var HSM = (function () {
////////////
// Public //
////////////
var Logger = { debug: function(){}, trace: function(){} };
/**
* @callback HSM.State~EntryFunc
* @param {HSM.State} source state
* @param {HSM.State} target state
* @param data - event parameters
*/
/**
* @callback HSM.State~ExitFunc
* @param {HSM.State} source state
* @param {HSM.State} target state
* @param data - event parameters
*/
/**
* A guard function may be attached to any transition. It will be called before the transition is fired. If it doesn't return true,
* the transition will be disabled for the current event.
* @callback HSM.State~GuardFunc
* @param {HSM.State} source - current state
* @param {HSM.State} target - potential next state
* @param data - event parameters
*/
/**
* An action function may be attached to any transition. It will be called after all exit handlers and before all entry handlers are called.
* @callback HSM.State~ActionFunc
* @param {HSM.State} source - current state
* @param {HSM.State} target - next state
* @param data - event parameters
* @see {@link HSM.State~Handler} action
*/
/**
@typedef {Object} HSM.State~Handler
@property {HSM.State} target - target state
@property {HSM.State~GuardFunc=} guard - disables the transition unless returns true.
@property {HSM.State~ActionFunc=} action - called after all state exit handlers and before any state entry handlers are called.
*/
/**
* Represents a State.
* @class HSM.State
* @param {String} theStateID - Identifies the state. Must be unique in the containing state machine.
*/
var State = function (theStateID) {
this._id = theStateID;
this._owner = null; // set to state machine
/** Map of events to handlers.
* Either a single handler or an array of handlers can be given. The guard of each handler will be called
* until a guard returns true (or a handler doesn't have a guard). This handler will then be triggered.
* @memberof! HSM.State#
* @var {(HSM.State~Handler|HSM.State~Handler[])} handler[event]
*/
this.handler = {};
};
/** @memberof! HSM.State#
* @var {HSM.State~EntryFunc}
*/
State.prototype.on_entry = undefined;
/** @memberof! HSM.State#
* @var {HSM.State~ExitFunc}
*/
State.prototype.on_exit = undefined;
State.prototype._enter = function (sourceState, targetState, theData) {
if (this.on_entry !== undefined) {
this.on_entry.apply(this, arguments);
}
};
State.prototype._exit = function (theNextState, theData) {
if (this.on_exit !== undefined) {
this.on_exit.apply(this, arguments);
}
};
State.prototype.toString = function () {
return this._id;
};
State.prototype.__defineGetter__('id', function() {
return this._id;
});
State.prototype.__defineGetter__('owner', function() {
return this._owner;
});
State.prototype.__defineSetter__('owner', function(theOwnerMachine) {
if (this._owner) {
throw ("Invalid Argument - state '"+this._id+"'already owned");
}
this._owner = theOwnerMachine;
});
State.prototype.hasAncestor = function(other) {
if (this._owner.container === null) {
return false;
}
if (this._owner.container === other) {
return true;
}
return this._owner.container.hasAncestor(other);
};
State.prototype.hasAncestorStateMachine = function(stateMachine) {
for (i = 0; i < this.owner.path.length; ++i) {
if (this.owner.path[i] === stateMachine) {
return true;
}
}
return false;
}
/** get the lowest common ancestor state-machine of this
* state and an arbitrary other state
*/
State.prototype.lca = function(state) {
var i;
var thisPath = this._owner.path;
var otherPath = state._owner.path;
for (i = 1; i < thisPath.length; ++i) {
if (otherPath[i] !== thisPath[i]) {
return thisPath[i-1];
}
}
return this._owner;
};
/** Adapter class for nested states
* @class HSM.Sub
* @extends HSM.State
* @param {String} theStateID - Identifies the state. Must be unique in the containing state machine.
* @param {HSM.StateMachine} theSubMachine - the nested state machine.
*/
var Sub = function (theStateID, theSubMachine) {
State.call(this, theStateID);
this._subMachine = theSubMachine;
this._subMachine._container = this;
};
Sub.prototype = Object.create(State.prototype);
Sub.prototype.constructor = Sub;
// old-style inheritance - causes performance warnings in newer JS engines
// Sub.prototype.__proto__ = State.prototype;
Sub.prototype._enter = function (sourceState, targetState, theData) {
State.prototype._enter.apply(this, arguments);
return this._subMachine._enterState(sourceState, targetState, theData);
};
Sub.prototype._exit = function (theNextState, theData) {
this._subMachine.teardown(theNextState, theData);
State.prototype._exit.apply(this, arguments);
};
Sub.prototype._handle = function () {
return this._subMachine._handle.apply(this._subMachine, arguments);
};
Sub.prototype.toString = function toString() {
return this.id + "/(" + this._subMachine + ")";
};
Sub.prototype.__defineGetter__("subMachine", function () {
return this._subMachine;
});
Sub.prototype.__defineGetter__("subState", function () {
return this._subMachine.state;
});
/** Adapter class for parallel states
* @class HSM.Parallel
* @extends HSM.State
* @param {String} theStateID - Identifies the state. Must be unique in the containing state machine.
* @param {HSM.StateMachine[]} theSubMachines - an array of parallel state machines.
*/
var Parallel = function (theStateID, theSubMachines) {
var i;
State.call(this, theStateID);
this._subMachines = theSubMachines || [];
for (i = 0; i < this._subMachines.length; ++i) {
this._subMachines[i]._container = this;
}
};
// inheritance
Parallel.prototype = Object.create(State.prototype);
Parallel.prototype.constructor = Parallel;
// old-style inheritance - causes performance warnings in newer JS engines
// Parallel.prototype.__proto__ = State.prototype;
Parallel.prototype.toString = function toString() {
return this.id + "/(" + this._subMachines.join('|') + ")";
};
Parallel.prototype._enter = function (sourceState, targetState, theData) {
var i;
State.prototype._enter.apply(this, arguments);
for (i = 0; i < this._subMachines.length; ++i) {
var subMachine = this._subMachines[i];
if (targetState.hasAncestorStateMachine(subMachine)) {
subMachine._enterState(sourceState, targetState, theData);
} else {
subMachine.init(theData);
}
}
};
Parallel.prototype._exit = function (theNextState, theData) {
var i;
for (i = 0; i < this._subMachines.length; ++i) {
this._subMachines[i].teardown(theData);
}
State.prototype._exit.apply(this, arguments);
};
Parallel.prototype._handle = function () {
var handled = false;
var i;
for (i = 0; i < this._subMachines.length; ++i) {
if (this._subMachines[i]._handle.apply(this._subMachines[i], arguments)) {
handled = true;
}
}
return handled;
};
Parallel.prototype.__defineGetter__("subMachines", function () {
return this._subMachines;
});
Parallel.prototype.__defineGetter__("parallelStates", function () {
return this._subMachines.map(function(s) { return s.state; });
});
/**
* Represents a State Machine.
* @class HSM.StateMachine
* @param {HSM.State[]} theStates - the states that compose the state machine. The first state is the initial state.
*/
var StateMachine = function(theStates) {
this.states = {};
this._container = null; // set to containing state if part of a composite
this._curState = null;
this._eventInProgress = false;
this._eventQueue = [];
var i;
for (i = 0; i < theStates.length; ++i) {
if (!(theStates[i] instanceof State)) {
throw ("Invalid Argument - not a state");
}
this.states[theStates[i].id] = theStates[i];
theStates[i].owner = this;
}
this.initialState = theStates.length ? theStates[0] : null;
};
StateMachine.prototype.toString = function toString() {
if (this._curState !== null) {
return this._curState.toString();
}
return "_uninitializedStatemachine_";
};
StateMachine.prototype.__defineGetter__('path', function () {
var p = [this];
while (p[0]._container) {
p.unshift(p[0]._container._owner);
}
return p;
});
StateMachine.prototype.__defineGetter__('id', function () {
return this._container ? this._container._id : '_top_';
});
StateMachine.prototype.__defineGetter__('state', function () {
return this._curState;
});
StateMachine.prototype.__defineGetter__('container', function () {
return this._container;
});
/**
* initializes this state machine and set the current state to the initial state.
* Any nested state machines will also be initialized and set to their initial state.
* @memberof! HSM.StateMachine#
* @param [data] event parameters
*/
StateMachine.prototype.init = function (theData) {
Logger.debug("<StateMachine "+this.id+"::init> setting initial state: " + this.initialState.id);
this._enterState(null, this.initialState, theData);
return this;
};
/** Performs a transition between sourceState and targetState. Must only be called
* on the lowest common ancestor of sourceState and targetState
*/
StateMachine.prototype._switchState = function (sourceState, theHandler, theData) {
var targetState = theHandler.target;
Logger.debug("<StateMachine "+this.id+"::_switchState> "+sourceState.id + " => "+targetState.id);
this._exitState(sourceState, targetState, theData);
if (theHandler.action) {
theHandler.action.apply(this, [sourceState, targetState].concat(theData));
}
this._enterState(sourceState, targetState, theData);
};
/** enters targetState. For all nested state machines up to the depth of targetState,
* the state machines are set directly to this state instead of the inital state. For all
* nested state machines beyond the depth of targetState, set to the initial state.
*/
StateMachine.prototype._enterState = function (sourceState, targetState, theData) {
var targetLevel = targetState.owner.path.length;
var thisLevel = this.path.length;
if (targetLevel < thisLevel) {
this._curState = this.initialState;
} else if (targetLevel === thisLevel) {
this._curState = targetState;
} else {
this._curState = targetState._owner.path[thisLevel]._container;
}
Logger.trace("<StateMachine "+this.id+"::_enterState> entering state: " + this._curState.id+", targetState: "+targetState.id);
// call new state's enter handler
this.state._enter(sourceState, targetState, theData);
};
StateMachine.prototype._exitState = function (sourceState, targetState, theData) {
Logger.trace("<StateMachine "+this.id+"::_exitState> exiting state: " + this._curState.id);
this.state._exit(targetState, theData);
};
StateMachine.prototype.teardown = function (targetState, theData) {
this._exitState(this.state, targetState, theData);
};
/** check if this transition's guard passes (if one exists) and
* execute the transition
*/
StateMachine.prototype._tryTransition = function(handler, data) {
var sourceState = this._curState;
var targetState = handler.target;
if ( !('guard' in handler) || handler.guard(sourceState, targetState, data)) {
Logger.trace("<StateMachine "+this.id+"::_tryTransition> guard passed.");
if (handler.kind === 'internal') {
Logger.trace("<StateMachine "+this.id+"::_tryTransition> performing internal transition.");
if(targetState === null || targetState === sourceState) {
if (handler.action) {
handler.action.apply(this, [sourceState, targetState].concat(data));
}
}
} else {
var excecutor = sourceState.lca(targetState);
Logger.trace("<StateMachine "+this.id+"::_tryTransition> passing event to lca: " + excecutor.id);
if (handler.kind === 'local' &&
(sourceState.hasAncestor(targetState) || targetState.hasAncestor(sourceState)))
{
excecutor = excecutor._curState._subMachine;
}
excecutor._switchState(this._curState, handler, data);
}
return true;
}
return false;
};
/**
* Creates a new event an passes it to the top-level state machine for handling. Aliased as handleEvent
* for backwards compatibility.
* @memberof! HSM.StateMachine#
* @param {string} event - event to be handled
* @param [data] event parameters
*/
StateMachine.prototype.emit = function (ev) {
if (this.path.length > 1) {
// if we are not at the top-level state machine,
// call again at the top-level state machine
this.path[0].emit.apply(this.path[0], arguments);
} else {
this._eventQueue.push(arguments);
// we are at the top-level state machine
if (this._eventInProgress === true) {
Logger.trace("<StateMachine "+this.id+">::emit: queuing event "+ev);
} else {
this._eventInProgress = true;
while (this._eventQueue.length > 0) {
this._handle.apply(this, this._eventQueue.shift());
}
this._eventInProgress = false;
}
}
};
StateMachine.prototype.handleEvent = StateMachine.prototype.emit;
StateMachine.prototype._handle = function (ev, data) {
// check if the current state is a (nested) statemachine, if so, give it the event.
// if it handles the event, stop processing it here.
if ('_handle' in this.state) {
Logger.trace("<StateMachine "+this.id+"::_handle> handing down " + ev);
if (this.state._handle.apply(this.state, arguments)) {
return true;
}
}
Logger.trace("<StateMachine "+this.id+"::_handle> handling event " + ev);
if (ev in this.state.handler) {
if (this.state.handler[ev] instanceof Array) {
// we have multiple handlers for this event
// try them all in turn
var handlers = this.state.handler[ev];
var i;
for (i = 0; i < handlers.length; ++i) {
if (this._tryTransition(handlers[i], data)) {
return true;
}
}
return false;
}
// only on handler - try it.
return this._tryTransition(this.state.handler[ev], data);
}
// no handler for this event.
return false;
};
//////////////
// Interface
//////////////
return {
State : State,
Sub : Sub,
Parallel : Parallel,
StateMachine : StateMachine,
Logger : Logger
};
}()); // execute outer function to produce our closure
// nodejs export
if (typeof module === 'object' && module.exports) {
module.exports = HSM;
}