[Tutor] Serial communication ...

Adam Bark adam.jtm30 at gmail.com
Mon Sep 13 20:33:45 CEST 2010


On 13/09/10 16:36, Markus Hubig wrote:
> Hi @all!
>
> I'm about to write a class for serial communication on Win32 and Linux 
> which
> provides a method called "talk" to send something over the serial 
> line, wait for
> the answer and returns it. My problem is, that I don't know how long 
> the answer
> will be (ok max 260 bytes but most answers are much smaller).
>
> This is what I have now, please leave some comments:
>
>    1. Will this work on Win32 (with select)?
>    2. Should I better use twisted.internet.serialport?
>    3. Will self.read(260)block until it reads the full 260 bytes?
>
> class SerialDevice(Serial):
>
>     def __init__(self,port):
>         Serial.__init__(self)
>         self.port = port
>         self.baudrate = 57600
>         self.bytesize = EIGHTBITS
>         self.parity = PARITY_ODD
>         self.stopbits = STOPBITS_TWO
>         self.timeout = 0
>         self.xonxoff = 0
>         self.rtscts = 0
>         self.dsrdtr = 0
>         self.open()
>         self.flush()
>     def _write(self, packet):
>         fileno = self.fileno()
>         while True:
>             readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>             if fileno in writeable:
>                 time.sleep(0.1)
>                 length = self.write(packet)
>                 break
>         return length
>     def _read(self):
>         fileno = self.fileno()
>         while True:
>             readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>             if fileno in readable:
>                 time.sleep(0.1)
>                 packet = self.read(260)
>                 break
>         return packet
>     def talk(self, packet):
>         self._write(packet)
>         responce = self._read()
>         return responce
>
> Thank you, Markus
>
> -- 
> Can't read my mail? Just don't hold it that way!
Ideally you would send a specific ending packet and you read one byte at 
a time until the right sequence comes up. Alternatively you could have 
the first byte as a length indicator. The only other options I can think 
of are fixed length or a specific timeout.
HTH.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/1c53802a/attachment.html>


More information about the Tutor mailing list