On 21 February 2011 22:45, Jason Rennie <[email protected]> wrote:
> Sounds like you just need a queue of pending commands and a state object for
> the currently executing command.
Just for the sake of completeness, this is what I've ended up with. No
explicit queues, and the state is kept with a lock:
--------
class CommandProtocol(LineOnlyReceiver, TimeoutMixin):
def __init__(self):
self.lock = defer.DeferredLock()
self.deferred = None
def runCommand(self, command, payload=None):
result = self.lock.run(self.sendCommand, command, payload)
return result
def sendCommand(self, command, payload=None):
assert self.deferred is None, "Already waiting for reply!"
# The parser uses these
self.command = command
self.sent = msg
self.deferred = defer.Deferred()
self.deferred.addCallback(self.parseReply)
self.deferred.addBoth(self.cleanup)
self.setTimeout(self.DEFAULT_TIMEOUT)
self.sendLine(msg)
return self.deferred
def cleanup(self, res):
self.deferred = None
del self.command
del self.sent
return res
def lineReceived(self, line):
if self.deferred:
self.setTimeout(None)
self.deferred.callback(line)
# If not, we've timed out or this is a spurious line
def timeoutConnection(self):
self.deferred.errback(
Timeout("The device took too long to respond"))
def parseReply(self, line):
# Do parsing, raise synchronous errors if bad
return reply
--------
Technically, things like self.command, self.sent, self.deferred etc.
could be closed over by nested functions, which could be set as the
callbacks, but that's just down to where and how you prefer to store
state. Besides, we all know that flat > nested ;)
Thanks for everyone's help!
— Jason
_______________________________________________
Twisted-Python mailing list
[email protected]
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python