[Twisted-Python] how to create state machines?
Doug Farrell
dfarrell at mypublisher.com
Thu Mar 26 12:26:17 MDT 2009
Hi all,
I'm still getting my 'sea legs' with Twisted, so this may be a novice
question, but I'm wondering what would be a good way to create a state
machine with Twisted? For instance I've written quite a bit of code in
different languages that creates co-operative, context switching schemes
using state machines. Here would be a primative example in psuedocode:
Switch(state):
Case INIT:
Initialize()
state = CMD1
Case CMD1:
CommandOne()
state = WAITCMD1
Case WAITCMD1:
If CommandOneDone()
state = DONE
Else
state = WAITCMD1
Case DONE:
state = EXIT
This state machine initializes a system, issues an asynchronous command
that takes time to complete (say a motor move command) and then waits
for that command to be done before exiting. In the context of a
framework that is calling this state machine, the WAITCMD1 is executed
repeatedly (polling) while the asynchronous command completes. A system
can be constructed with lots of little state machines like this and be
made to look like it is doing many things at once even though the
execution of the program is single threaded.
I understand (pretty much) the Twisted framework is like this and
implmenting event handlers like connectionMade(), etc., is a state
machine, but I'm wondering how to implement what I've outlined above in
one of Twisted's state event handlers, or inside something like
callLater(). For example, let's say I want to use Twisted to run a long
running daemon process that has an XMLRPC interface. That XMLRPC
interface is an interface to a state machine inside Twisted that allows
the caller to change state, or start new state machines, or get the
status of a running state machine. In that case I'm thinking I want a
state machine the runs continuously in the Twisted loop, structured like
the example above; co-operatively yielding back to Twisted, but running
non-stop. Something like callLater(1, stateMachine), but non-stop,
without even the 1 second call loop.
Is this something I can do with callLater()? Would using a deferred be a
better option? I see deferred's callBack() system as a connecting states
together, but I'm not sure how a WAITONCMD1 kind of thing would work,
where the deferred callBack(d, waitTillDone) would have to keep coming
back to itself till some condition is met?
Thanks in advance for your help,
Doug
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20090326/ded4ec4d/attachment.html>
More information about the Twisted-Python
mailing list