用Python寫協議規範

jieforest發表於2012-03-31
This is a writeup of a talk I did recently at Software Passion Summit in Gothenburg, Sweden. For more background info, see the post I did prior to the conference.

Writing a specification in a full-blown programming language like Python has upsides and downsides. On the downside, Python is not designed as a declarative language, so any attempt to make it declarative (apart from just listing native data types) will require some kind of customization and/or tooling to work. On the upside, having a declaration in the language you write your servers in, you can use the specification itself, rather than a generated derivative of that specification, and writing custom - in this case minimal - generators for other languages is simple, since you can you Python introspection to traverse your specification, and the templating logic of your choice to generate source - this makes it possible, for example, to target a J2ME terminal that just won't accept existing solutions, and where dropping a 150K jar file for protocol implementation is not an alternative.

For me, this journey started around 2006 when I started to lose control over protocol documentation and protocol versions for the protocol used between terminals and servers in the fleet management solutionVisual Units Logistics. After looking for, and discarding, several existing tools, and after being inspired by the fact that we usually configure Javascript. in Javascript, I started to sketch (as in, ink on paper) on what a protocol specification in Python would look like. This is a transcription of what I came up with at the time:

CODE:

1.imei = long
2.log_message = string
3.timestamp = long
4.voltage = float
5.log = Message(imei, timestamp,
6.log_message, voltage)
7.protocol = Protocol(log, ...)
8.protocol.parse(data)With this as a target, I created the first version of a protocol implementation. It looked similar to the target version, but suffered from an abundance of repetition:

CODE:

01.#protocol.py
02.LOG = 0x023
03.ALIVE = 0x021
04.message = Token('message', 'String', 'X')
05.timestamp = Token('timestamp', 'long', 'q')
06.signal = Token('signal', 'short', 'h')
07.voltage = Token('voltage', 'short', 'h')
08.msg_log = Message('LOG', LOG, timestamp, signal, voltage)
09.msg_alive = Message('ALIVE', ALIVE, timestamp)
10.protocol = Protocol(version=1.0, messages=[msg_log,msg_alive])
11.#usage
12.from protocol import protocol
13.parsed_data = protocol.parse(data)
14.open('Protocol.java’,'w').write(protocol.java_protocol())

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-720004/,如需轉載,請註明出處,否則將追究法律責任。

相關文章