[Twisted-Python] serial communication - getting started

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Mon Oct 21 14:21:27 MDT 2013


On 07:42 pm, ltaylor.volks at gmail.com wrote:
>
>On Oct 21, 2013, at 6:57 AM, Robert Voigtländer wrote:
>>Thanks for the fast reply.
>>I don't yet understand your answer. I may have to dig more into 
>>Python.
>>
>>On 21 October 2013 13:45, Itamar Turner-Trauring <itamar at itamarst.org> 
>>wrote:
>
><snip guidance to avoid threads>
>>
>>3. A reasonable place for the write() might be in your Protocol's 
>>connectionMade method.
>
>The Protocol has access to a .transport attribute, which is the 
>SerialPort() instance.
>
>Therefore, you can write to the serial port (the transport) from within 
>your protocol:
>
>
>class Echo(LineReceiver):
>
>    def connectionMade(self):
>        self.transport.write('HELLO\n')
>
>    def lineReceived(self, line):
>        self.transport.write(line + '\n')

Additionally, since the serial transport tries hard to look just like a 
tcp transport or an ssl transport, the generic protocol code in 
LineReceiver.sendLine will work just fine with it.  So in addition to 
using the `lineReceived` callback to handle lines that arrive you can 
use `sendLine` to write lines out to the serial port:

    class Echo(LineReceiver):
        delimiter = b"\n"

        def connectionMade(self):
            self.sendLine(b"HELLO")

        def lineReceived(self, line):
            self.sendLine(line)

This is part of the power of the transport/protocol separation: reusable 
protocol logic. :)

Jean-Paul
>
>The connectionMade method will be called once the transport (the 
>SerialPort instance) is ready (the serial port is open), making it an 
>appropriate place to kick off an init sequence or similar.
>
>
>Lucas



More information about the Twisted-Python mailing list