-
Notifications
You must be signed in to change notification settings - Fork 0
/
README
419 lines (376 loc) · 13.6 KB
/
README
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
===================================================
A state machine module based on generator functions
===================================================
Introduction
------------
Yet another `state machines with generators` module. It is intended to be a
lightweight collection of useful functions to model state machines and can be
dropped into your project's package.
I wanted something that would be easy to integrate in applications, imposing
as little as possible of the modules's conventions on client code. I also
wanted an implementation that supported hierarchical and sequential
composition of state machines.
Why use generators? Because they are suspend-able functions, they retain
state and support entry/exit actions without requiring an object oriented
abstraction. An application is free to use this module's functions within
classes but it does not (and should not) have to.
The state_machine_from_class() function can be used to create
a state machine instance form a class encapsulating the state factory and
state transition functions.
Get the source `here <http://github.com/dxxb/pystatemachine>`_.
Overview
--------
State and state machines are generator functions. A state is not usually
used directly but rather handled by a state machine like the one implemented
in state_machine(). A state machine is a state that handles state transitions
and dispatches execution to the currently active state. This way states can be
nested.
The skeleton_state() below shows a skeleton implementation
for a typical state. A state accepts 3 parameters: an application specific
context, an unique identifier for the state in the transition table
of the parent state machine and an event. All yield statements in a state
must yield the same 3 parameters and update the 3 parameters with the value
returned by the yield statement like this ``ctx, state_id_vec, evt =
yield (ctx, state_id_vec, evt)``.
>>> def skeleton_state(ctx, state_id, evt):
... # code executed when entering the state
... try:
... while True:
... # return control to the parent state machine
... ctx, state_id_vec, evt = yield ctx, state_id_vec, evt
... #
... # code that executes every time an event is received
... #
...
... finally:
... # code executed when exiting the state
... pass
The state_machine() generator accepts an application specific context which
will be passed to each state, a state factory function called each time
an instance of a state is created (this occurs right before entering the
state) and a transition function called to retrieve the unique ID of
the next state given the current state ID and the event. The transition
function is first called with a (state_id, event) tuple of (None, None)
in order to retrieve the initial state ID. When the transition function
returns None the state machine has reached its final state and stops.
run_sm() is used to run a state machine to completion. The optional callback
function parameter is invoked for each event and the optional val parameter
is useful for resuming execution of a state machine. The callback function
must return a tuple containing the context, state ID and event parameters,
the values returned can be different from the values it was passed.
The callback function can raise StopIteration() to indicate that the run_sm()
should exit. run_sm() returns the last valid context, state ID and event
tuple.
state_machine_from_class() returns a state machine instance initialized using
the ``state_factory`` and ``transition`` methods of the class.
Tutorial
--------
Let's start by looking at a simple usage example. An example state is defined
as follows:
>>> import smachine as smm
>>> def state_ex2(ctx, state_id_vec, evt):
... print "Entering state:", state_id_vec[-1]
... try:
... while True:
... ctx, state_id_vec, evt = yield ctx, state_id_vec, evt
... print "Received event", evt, "while in", state_id_vec[-1]
... finally:
... print "Exiting state:", state_id_vec[-1]
The state factory function always returns an instance of ``state_ex2`` and
the transition function moves between states (identified by increasing
integers) when the ``n`` event is received, stays in the current state when
the ``x`` event is received and terminates when ``e`` is received
>>> s_f = lambda c,n,e: state_ex2(c,n,e)
>>> def t_f(c, t):
... if t[0] is None:
... return 1
... if t[1] == 'x':
... return t[0]
... elif t[1] == 'e':
... return None
... else:
... return t[0] + 1
...
The state machine is created passing a null context
>>> sm = smm.state_machine(s_f, t_f)(None)
and then run using the ``xnxnxne`` sequence of events
>>> l = list(smm.iter_sm(sm, iter('xn'*3+'e')))
Entering state: 1
Received event x while in 1
Exiting state: 1
Entering state: 2
Received event x while in 2
Exiting state: 2
Entering state: 3
Received event x while in 3
Exiting state: 3
Entering state: 4
Exiting state: 4
Define a list of states and some events we want to occur in sequence. The
``test`` event does not effect the state, while ``up`` and ``down`` change the the
state to the next one up or down respectively.
>>> states = ['freezing', 'cold', 'cool', 'warm', 'hot']
>>> event_list = ['up', 'test', 'up', 'up', 'down']
A state implementation that simply prints out the last event and current
state IDs
>>> def state_ex1(ctx, state_id_vec, evt):
... while True:
... ctx, vec, evt = yield ctx, state_id_vec, evt
...
Wrap callback(), state_factory() and transition() in a class to show how to
use state_machine_from_class()
>>> class StateMachineClassEx1(object):
... @staticmethod
... def callback(sm, val):
... # Consume the first event and make it the current event
... ctx, state_id_vec, evt = val
... if len(ctx) > 0:
... return ctx, state_id_vec, ctx.pop(0)
... else:
... raise StopIteration()
...
... @staticmethod
... def state_factory(ctx, state_id_vec, evt):
... # Return the same implementation for every state
... return state_ex1(ctx, state_id_vec, evt)
...
... @staticmethod
... def transition(ctx, t):
... state_id, evt = t
... if t == (None, None):
... # return the initial state
... idx = states.index('cool')
... elif evt == 'test':
... # the 'test' event does not cause a state change
... idx = states.index(state_id)
... else:
... # pick the next state form the list
... idx = states.index(state_id)
... if evt == 'up':
... idx = min(idx+1, len(states)-1)
... else:
... idx = max(idx-1, 0)
... print (state_id, evt), '->', states[idx]
... return states[idx]
...
The event_list is passed as 'context' for the state machine
>>> sm = smm.state_machine_from_class(StateMachineClassEx1)(event_list)
>>> end_state = smm.run_sm(sm, StateMachineClassEx1.callback)
(None, None) -> cool
('cool', 'up') -> warm
('warm', 'test') -> warm
('warm', 'up') -> hot
('hot', 'up') -> hot
('hot', 'down') -> warm
>>> end_state
([], ('warm',), 'down')
============================================================================
>>> class SimpleSM1(object):
... @staticmethod
... def state(ctx, state_id_vec, evt):
... while True:
... ctx, state_id_vec, evt = yield ctx, state_id_vec, evt
... @staticmethod
... def state_factory(ctx, name, evt):
... # Return the same implementation for every state
... return SimpleSM1.state(ctx, name, evt)
... @staticmethod
... def transition(ctx, t):
... s, e = t
... tt = {
... (None, None): 's1',
... ('s1', 'n'): 's2',
... ('s2', 'n'): None,
... }
... return tt.get(t, 's1')
...
>>> m1 = smm.state_machine_from_class(SimpleSM1)
>>> m2 = smm.state_machine_from_class(SimpleSM1)
>>> m3 = smm.state_machine_from_class(SimpleSM1)
>>> tt = {
... (None, None): 'm1',
... ('m1', None): 'm2',
... ('m2', None): 'm3',
... ('m3', None): None,
... }
>>> s = {
... 'm1': m1,
... 'm2': m2,
... 'm3': m3,
... }
>>> s_f = lambda c,n,e: s[n[-1]](c, n, e)
>>> t_f = lambda c,t: tt.get(t, t[0])
>>> sm = smm.state_machine(s_f, t_f)(None)
>>> for val in smm.iter_sm(sm, iter('n'*20)):
... print (val[1], val[2])
...
(('m1', 's1'), None)
(('m1', 's2'), 'n')
(('m2', 's1'), None)
(('m2', 's2'), 'n')
(('m3', 's1'), None)
(('m3', 's2'), 'n')
>>> tt = {
... (None, None): 'closed',
... ('closed', 'open'): 'opened',
... ('opened', 'close'): 'closed',
... ('closed', 'lock'): 'locked',
... ('locked', 'unlock'): 'closed',
... }
>>> s_f = lambda c,n,e: state_ex1(c, n, e)
>>> t_f = lambda c,t: tt.get(t, t[0])
>>> def print_transitions(iter):
... old_s = None
... while True:
... c, s, e = iter.next()
... print (old_s, e), '->', s[-1]
... old_s = s[-1]
... yield c, s, e
...
>>> e = ['lock', 'open', 'unlock', 'open', 'close']
>>> sm = smm.state_machine(s_f, t_f)(None)
>>> l = [val for val in print_transitions(smm.iter_sm(sm, iter(e)))]
(None, None) -> closed
('closed', 'lock') -> locked
('locked', 'open') -> locked
('locked', 'unlock') -> closed
('closed', 'open') -> opened
('opened', 'close') -> closed
# Using run_sm()
>>> def cb(sm, val):
... ctx, state_id, evt = val
... print (ctx['last_state'], evt), '->', state_id[-1]
... ctx['last_state'] = state_id[-1]
... return ctx, state_id, ctx['evt_src'].next()
...
>>> ctx = dict([('evt_src', iter(e)), ('last_state', None)])
>>> sm = smm.state_machine(s_f, t_f)(ctx)
>>> val = smm.run_sm(sm, cb)
(None, None) -> closed
('closed', 'lock') -> locked
('locked', 'open') -> locked
('locked', 'unlock') -> closed
('closed', 'open') -> opened
('opened', 'close') -> closed
# Hierarchical state machine example: pocket calculator
>>> import operator
>>> import sys
>>> def display(str_or_int):
... sys.stdout.write(' ' + str(str_or_int))
...
>>> class PocketCalcInnerSM(object):
...
... tt = {
... ('on', None): 'op_nd1',
... ('op_nd1', '/*+-'): 'op_tor',
... ('op_tor', '0123456789.'): 'op_nd2',
... ('op_nd2', '/*+-'): 'op_tor',
... ('op_nd2', '='): 'result',
... ('result', '/*+-'): 'op_tor',
... ('result', '0123456789.'): 'op_nd1',
... }
...
... @classmethod
... def transition(cls, c, t):
... s_id = cls.tt.get(t, None)
... if s_id is None:
... for k,v in cls.tt.items():
... if k[0] == t[0] and t[1] in k[1]:
... s_id = v
... if s_id is None:
... return t[0]
... return s_id
...
... @classmethod
... def state_factory(cls, c, n, e):
... return getattr(cls, n[-1])(c,n,e)
...
... @staticmethod
... def op_nd1(c, s, e):
... if e is not None:
... c['op_nd1'] = int(e)
... else:
... c['op_nd1'] = 0
... while True:
... display(c['op_nd1'])
... c, s, e = yield c, s, e
... c['op_nd1'] = c['op_nd1']*10 + int(e)
...
... @staticmethod
... def op_nd2(c, s, e):
... c['op_nd2'] = int(e)
... while True:
... display(c['op_nd2'])
... c, s, e = yield c, s, e
... c['op_nd2'] = c['op_nd2']*10 + int(e)
...
... @staticmethod
... def op_tor(c, s, e):
... while True:
... if c['op_tor'] is not None:
... c['op_nd1'] = c['op_tor'](c['op_nd1'], c['op_nd2'])
... display(c['op_nd1'])
... display(e)
... if e == '+':
... c['op_tor'] = operator.add
... elif e == '-':
... c['op_tor'] = operator.sub
... elif e == '/':
... c['op_tor'] = operator.div
... elif e == '*':
... c['op_tor'] = operator.mul
... else:
... raise StopIteration
... c, s, e = yield c, s, e
...
... @staticmethod
... def result(c, s, e):
... c['op_nd1'] = c['op_tor'](c['op_nd1'], c['op_nd2'])
... c['op_tor'] = None
... while True:
... display(c['op_nd1'])
... c, s, e = yield c, s, e
...
...
>>> class PocketCalcOuterSM(object):
...
... tt = {
... (None, None): 'off',
... ('off', 'p-on'): 'reset',
... ('on', 'p-on'): 'reset',
... ('reset', None): 'on',
... ('on', 'p-off'): 'off',
... }
...
... @classmethod
... def transition(cls, c, t):
... return cls.tt.get(t, t[0])
...
... @classmethod
... def state_factory(cls, c, n, e):
... if n[-1] == 'on':
... return smm.state_machine_from_class(PocketCalcInnerSM)(c,n,e)
... return getattr(cls, n[-1])(c,n,e)
...
... @staticmethod
... def off(c, s, e):
... while True:
... c, s, e = yield c, s, e
...
... @staticmethod
... def reset(c, s, e):
... c['op_nd1'] = 0
... c['op_nd2'] = 0
... c['op_tor'] = None
... return
... # yield statement is necessary to make this a generator
... c, s, e = yield c, s, e
...
>>> ctx = dict()
>>> pc_sm = smm.state_machine_from_class(PocketCalcOuterSM)(ctx)
>>> e = ['p-on', '2', '+', '3', '=', '-', '1', '=', 'p-on', 'p-off']
>>> l = [(dict(val[0]),)+val[1:] for val in smm.iter_sm(pc_sm, iter(e))]
0 2 + 3 5 - 1 4 0
>>> e = ['p-on', '2', '*', '3', '/', '2', '+', '1', '3', '=', 'p-off']
>>> l = [val for val in smm.iter_sm(pc_sm, iter(e), val = l[-1])]
0 2 * 3 6 / 2 3 + 1 13 16