blob: e568aa139c29560107c830055cc8394f442674fd [file] [log] [blame]
cliechtid6bf52c2003-10-01 02:28:12 +00001#! python
cliechtic54b2c82008-06-21 01:59:08 +00002# Python Serial Port Extension for Win32, Linux, BSD, Jython
3# see __init__.py
cliechtid6bf52c2003-10-01 02:28:12 +00004#
cliechti14b274a2009-02-07 00:27:05 +00005# (C) 2001-2009 Chris Liechti <cliechti@gmx.net>
cliechtid6bf52c2003-10-01 02:28:12 +00006# this is distributed under a free software license, see license.txt
7
cliechti4a567a02009-07-27 22:09:31 +00008# compatibility folder Python < 2.6
9try:
10 bytes
11 bytearray
cliechtia3a811f2009-07-29 21:59:03 +000012except (NameError, AttributeError):
cliechti4a567a02009-07-27 22:09:31 +000013 # Python older than 2.6 do not have these types. Like for Python 2.6 they
cliechti2750b832009-07-28 00:13:52 +000014 # should behave like str. For Python older than 3.0 we want to work with
15 # strings anyway, only later versions have a true bytes type.
cliechti4a567a02009-07-27 22:09:31 +000016 bytes = str
17 # bytearray is a mutable type that is easily turned into an instance of
18 # bytes
19 class bytearray(list):
20 # for bytes(bytearray()) usage
21 def __str__(self): return ''.join(self)
22 # append automatically converts integers to characters
23 def append(self, item):
24 if isinstance(item, str):
25 list.append(self, item)
26 else:
27 list.append(self, chr(item))
cliechti0bbebbf2009-07-30 17:23:42 +000028
29# create control bytes, depending on true type of bytes
30# all Python versions prior 3.x convert str([17]) to '[17]' instead of '\x11'
31if bytes is str:
cliechti2750b832009-07-28 00:13:52 +000032 XON = chr(17)
33 XOFF = chr(19)
34else:
35 XON = bytes([17])
36 XOFF = bytes([19])
cliechti4a567a02009-07-27 22:09:31 +000037
cliechtia3a811f2009-07-29 21:59:03 +000038
cliechti0d6029a2008-06-21 01:28:46 +000039PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
cliechti58b481c2009-02-16 20:42:32 +000040STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
cliechti14b274a2009-02-07 00:27:05 +000041FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
cliechtid6bf52c2003-10-01 02:28:12 +000042
43PARITY_NAMES = {
cliechti4a567a02009-07-27 22:09:31 +000044 PARITY_NONE: 'None',
45 PARITY_EVEN: 'Even',
46 PARITY_ODD: 'Odd',
47 PARITY_MARK: 'Mark',
48 PARITY_SPACE: 'Space',
cliechtid6bf52c2003-10-01 02:28:12 +000049}
50
cliechti1dbe4b62002-02-14 02:49:25 +000051
cliechti4a567a02009-07-27 22:09:31 +000052class SerialException(IOError):
cliechtid6bf52c2003-10-01 02:28:12 +000053 """Base class for serial port related exceptions."""
cliechti7fe54d52002-03-03 20:11:47 +000054
cliechtid6bf52c2003-10-01 02:28:12 +000055
cliechti62611612004-04-20 01:55:43 +000056class SerialTimeoutException(SerialException):
57 """Write timeouts give an exception"""
58
cliechti4a567a02009-07-27 22:09:31 +000059
cliechti62611612004-04-20 01:55:43 +000060writeTimeoutError = SerialTimeoutException("Write timeout")
cliechti4a567a02009-07-27 22:09:31 +000061portNotOpenError = ValueError('Attempting to use a port that is not open')
cliechti62611612004-04-20 01:55:43 +000062
cliechtif81362e2009-07-25 03:44:33 +000063
cliechtid6bf52c2003-10-01 02:28:12 +000064class FileLike(object):
cliechti1dbe4b62002-02-14 02:49:25 +000065 """An abstract file like class.
cliechti14b274a2009-02-07 00:27:05 +000066
cliechti1dbe4b62002-02-14 02:49:25 +000067 This class implements readline and readlines based on read and
68 writelines based on write.
69 This class is used to provide the above functions for to Serial
70 port objects.
cliechti14b274a2009-02-07 00:27:05 +000071
cliechti1dbe4b62002-02-14 02:49:25 +000072 Note that when the serial port was opened with _NO_ timeout that
73 readline blocks until it sees a newline (or the specified size is
74 reached) and that readlines would never return and therefore
75 refuses to work (it raises an exception in this case)!
76 """
77
cliechtif81362e2009-07-25 03:44:33 +000078 def __init__(self):
79 self.closed = True
80
81 def close(self):
82 self.closed = True
83
84 # so that ports are closed when objects are discarded
85 def __del__(self):
86 """Destructor. Calls close()."""
87 # The try/except block is in case this is called at program
88 # exit time, when it's possible that globals have already been
89 # deleted, and then the close() call might fail. Since
90 # there's nothing we can do about such failures and they annoy
91 # the end users, we suppress the traceback.
92 try:
93 self.close()
94 except:
95 pass
96
cliechti1dbe4b62002-02-14 02:49:25 +000097 def writelines(self, sequence):
98 for line in sequence:
99 self.write(line)
100
101 def flush(self):
cliechti1bb1bb22002-08-18 00:43:58 +0000102 """flush of file like objects"""
103 pass
cliechti1dbe4b62002-02-14 02:49:25 +0000104
cliechti980e4b02005-12-20 23:19:58 +0000105 # iterator for e.g. "for line in Serial(0): ..." usage
106 def next(self):
107 line = self.readline()
108 if not line: raise StopIteration
109 return line
110
111 def __iter__(self):
112 return self
113
cliechtif81362e2009-07-25 03:44:33 +0000114 # other functions of file-likes - not used by pySerial
cliechti980e4b02005-12-20 23:19:58 +0000115
cliechtif81362e2009-07-25 03:44:33 +0000116 #~ readinto(b)
117
118 def seek(self, pos, whence=0):
119 raise IOError("file is not seekable")
120
121 def tell(self):
122 raise IOError("file is not seekable")
123
124 def truncate(self, n=None):
125 raise IOError("file is not seekable")
126
127 def isatty(self):
128 return False
129
130
131class SerialBase(object):
cliechtid6bf52c2003-10-01 02:28:12 +0000132 """Serial port base class. Provides __init__ function and properties to
133 get/set port settings."""
cliechti14b274a2009-02-07 00:27:05 +0000134
cliechtidfec0c82009-07-21 01:35:41 +0000135 # default values, may be overridden in subclasses that do not support all values
cliechtif81362e2009-07-25 03:44:33 +0000136 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
137 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
138 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
139 3000000, 3500000, 4000000)
cliechtid6bf52c2003-10-01 02:28:12 +0000140 BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
cliechti14b274a2009-02-07 00:27:05 +0000141 PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
cliechti6ffdb8f2009-07-22 00:48:57 +0000142 STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
cliechti14b274a2009-02-07 00:27:05 +0000143
cliechtid6bf52c2003-10-01 02:28:12 +0000144 def __init__(self,
cliechti14b274a2009-02-07 00:27:05 +0000145 port = None, # number of device, numbering starts at
146 # zero. if everything fails, the user
147 # can specify a device string, note
148 # that this isn't portable anymore
149 # port will be opened if one is specified
cliechtidfec0c82009-07-21 01:35:41 +0000150 baudrate=9600, # baud rate
151 bytesize=EIGHTBITS, # number of data bits
cliechti14b274a2009-02-07 00:27:05 +0000152 parity=PARITY_NONE, # enable parity checking
cliechtidfec0c82009-07-21 01:35:41 +0000153 stopbits=STOPBITS_ONE, # number of stop bits
cliechti14b274a2009-02-07 00:27:05 +0000154 timeout=None, # set a timeout value, None to wait forever
155 xonxoff=0, # enable software flow control
156 rtscts=0, # enable RTS/CTS flow control
157 writeTimeout=None, # set a timeout for writes
158 dsrdtr=None, # None: use rtscts setting, dsrdtr override if true or false
159 interCharTimeout=None # Inter-character timeout, None to disable
cliechtid6bf52c2003-10-01 02:28:12 +0000160 ):
161 """Initialize comm port object. If a port is given, then the port will be
cliechti02f7c992004-02-02 19:48:27 +0000162 opened immediately. Otherwise a Serial port object in closed state
cliechtid6bf52c2003-10-01 02:28:12 +0000163 is returned."""
164
165 self._isOpen = False
cliechti4a567a02009-07-27 22:09:31 +0000166 self._port = None # correct value is assigned below through properties
167 self._baudrate = None # correct value is assigned below through properties
168 self._bytesize = None # correct value is assigned below through properties
169 self._parity = None # correct value is assigned below through properties
170 self._stopbits = None # correct value is assigned below through properties
171 self._timeout = None # correct value is assigned below through properties
172 self._writeTimeout = None # correct value is assigned below through properties
173 self._xonxoff = None # correct value is assigned below through properties
174 self._rtscts = None # correct value is assigned below through properties
175 self._dsrdtr = None # correct value is assigned below through properties
176 self._interCharTimeout = None # correct value is assigned below through properties
cliechti14b274a2009-02-07 00:27:05 +0000177
178 # assign values using get/set methods using the properties feature
cliechtid6bf52c2003-10-01 02:28:12 +0000179 self.port = port
180 self.baudrate = baudrate
181 self.bytesize = bytesize
182 self.parity = parity
183 self.stopbits = stopbits
184 self.timeout = timeout
cliechti62611612004-04-20 01:55:43 +0000185 self.writeTimeout = writeTimeout
cliechtid6bf52c2003-10-01 02:28:12 +0000186 self.xonxoff = xonxoff
187 self.rtscts = rtscts
cliechtif46e0a82005-05-19 15:24:57 +0000188 self.dsrdtr = dsrdtr
cliechti679bfa62008-06-20 23:58:15 +0000189 self.interCharTimeout = interCharTimeout
cliechti14b274a2009-02-07 00:27:05 +0000190
cliechtid6bf52c2003-10-01 02:28:12 +0000191 if port is not None:
192 self.open()
193
194 def isOpen(self):
195 """Check if the port is opened."""
196 return self._isOpen
197
198 # - - - - - - - - - - - - - - - - - - - - - - - -
199
cliechti9147c442009-07-21 22:12:16 +0000200 # TODO: these are not really needed as the is the BAUDRATES etc. attribute...
cliechti14b274a2009-02-07 00:27:05 +0000201 # maybe i remove them before the final release...
202
cliechtid6bf52c2003-10-01 02:28:12 +0000203 def getSupportedBaudrates(self):
204 return [(str(b), b) for b in self.BAUDRATES]
205
206 def getSupportedByteSizes(self):
207 return [(str(b), b) for b in self.BYTESIZES]
cliechti14b274a2009-02-07 00:27:05 +0000208
cliechtid6bf52c2003-10-01 02:28:12 +0000209 def getSupportedStopbits(self):
210 return [(str(b), b) for b in self.STOPBITS]
211
212 def getSupportedParities(self):
213 return [(PARITY_NAMES[b], b) for b in self.PARITIES]
214
215 # - - - - - - - - - - - - - - - - - - - - - - - -
216
217 def setPort(self, port):
218 """Change the port. The attribute portstr is set to a string that
219 contains the name of the port."""
cliechti14b274a2009-02-07 00:27:05 +0000220
cliechtid6bf52c2003-10-01 02:28:12 +0000221 was_open = self._isOpen
222 if was_open: self.close()
223 if port is not None:
cliechtif81362e2009-07-25 03:44:33 +0000224 if isinstance(port, basestring):
cliechtid6bf52c2003-10-01 02:28:12 +0000225 self.portstr = port
226 else:
227 self.portstr = self.makeDeviceName(port)
228 else:
229 self.portstr = None
230 self._port = port
cliechtif81362e2009-07-25 03:44:33 +0000231 self.name = self.portstr
cliechtid6bf52c2003-10-01 02:28:12 +0000232 if was_open: self.open()
cliechti14b274a2009-02-07 00:27:05 +0000233
cliechtid6bf52c2003-10-01 02:28:12 +0000234 def getPort(self):
cliechti107db8d2004-01-15 01:20:23 +0000235 """Get the current port setting. The value that was passed on init or using
cliechtid6bf52c2003-10-01 02:28:12 +0000236 setPort() is passed back. See also the attribute portstr which contains
237 the name of the port as a string."""
238 return self._port
239
cliechti0276f5e2004-11-13 03:14:11 +0000240 port = property(getPort, setPort, doc="Port setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000241
242
243 def setBaudrate(self, baudrate):
cliechti4a567a02009-07-27 22:09:31 +0000244 """Change baud rate. It raises a ValueError if the port is open and the
cliechti2750b832009-07-28 00:13:52 +0000245 baud rate is not possible. If the port is closed, then the value is
cliechti107db8d2004-01-15 01:20:23 +0000246 accepted and the exception is raised when the port is opened."""
cliechti107db8d2004-01-15 01:20:23 +0000247 try:
248 self._baudrate = int(baudrate)
249 except TypeError:
cliechti93db61b2006-08-26 19:16:18 +0000250 raise ValueError("Not a valid baudrate: %r" % (baudrate,))
cliechti107db8d2004-01-15 01:20:23 +0000251 else:
252 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000253
cliechtid6bf52c2003-10-01 02:28:12 +0000254 def getBaudrate(self):
cliechti4a567a02009-07-27 22:09:31 +0000255 """Get the current baud rate setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000256 return self._baudrate
cliechti14b274a2009-02-07 00:27:05 +0000257
cliechti4a567a02009-07-27 22:09:31 +0000258 baudrate = property(getBaudrate, setBaudrate, doc="Baud rate setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000259
260
261 def setByteSize(self, bytesize):
262 """Change byte size."""
cliechti93db61b2006-08-26 19:16:18 +0000263 if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % (bytesize,))
cliechtid6bf52c2003-10-01 02:28:12 +0000264 self._bytesize = bytesize
265 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000266
cliechtid6bf52c2003-10-01 02:28:12 +0000267 def getByteSize(self):
268 """Get the current byte size setting."""
269 return self._bytesize
cliechti14b274a2009-02-07 00:27:05 +0000270
cliechti0276f5e2004-11-13 03:14:11 +0000271 bytesize = property(getByteSize, setByteSize, doc="Byte size setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000272
273
274 def setParity(self, parity):
275 """Change parity setting."""
cliechti93db61b2006-08-26 19:16:18 +0000276 if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % (parity,))
cliechtid6bf52c2003-10-01 02:28:12 +0000277 self._parity = parity
278 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000279
cliechtid6bf52c2003-10-01 02:28:12 +0000280 def getParity(self):
281 """Get the current parity setting."""
282 return self._parity
cliechti14b274a2009-02-07 00:27:05 +0000283
cliechti0276f5e2004-11-13 03:14:11 +0000284 parity = property(getParity, setParity, doc="Parity setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000285
286
287 def setStopbits(self, stopbits):
cliechti4a567a02009-07-27 22:09:31 +0000288 """Change stop bits size."""
289 if stopbits not in self.STOPBITS: raise ValueError("Not a valid stop bit size: %r" % (stopbits,))
cliechtid6bf52c2003-10-01 02:28:12 +0000290 self._stopbits = stopbits
291 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000292
cliechtid6bf52c2003-10-01 02:28:12 +0000293 def getStopbits(self):
cliechti4a567a02009-07-27 22:09:31 +0000294 """Get the current stop bits setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000295 return self._stopbits
cliechti14b274a2009-02-07 00:27:05 +0000296
cliechti4a567a02009-07-27 22:09:31 +0000297 stopbits = property(getStopbits, setStopbits, doc="Stop bits setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000298
299
300 def setTimeout(self, timeout):
301 """Change timeout setting."""
302 if timeout is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000303 try:
cliechti14b274a2009-02-07 00:27:05 +0000304 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechtid6bf52c2003-10-01 02:28:12 +0000305 except TypeError:
cliechti93db61b2006-08-26 19:16:18 +0000306 raise ValueError("Not a valid timeout: %r" % (timeout,))
cliechti2750b832009-07-28 00:13:52 +0000307 if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
cliechtid6bf52c2003-10-01 02:28:12 +0000308 self._timeout = timeout
309 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000310
cliechtid6bf52c2003-10-01 02:28:12 +0000311 def getTimeout(self):
312 """Get the current timeout setting."""
313 return self._timeout
cliechti14b274a2009-02-07 00:27:05 +0000314
cliechti0276f5e2004-11-13 03:14:11 +0000315 timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")
cliechti62611612004-04-20 01:55:43 +0000316
317
318 def setWriteTimeout(self, timeout):
319 """Change timeout setting."""
320 if timeout is not None:
cliechti93db61b2006-08-26 19:16:18 +0000321 if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
cliechti62611612004-04-20 01:55:43 +0000322 try:
323 timeout + 1 #test if it's a number, will throw a TypeError if not...
324 except TypeError:
325 raise ValueError("Not a valid timeout: %r" % timeout)
cliechti14b274a2009-02-07 00:27:05 +0000326
cliechti62611612004-04-20 01:55:43 +0000327 self._writeTimeout = timeout
328 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000329
cliechti62611612004-04-20 01:55:43 +0000330 def getWriteTimeout(self):
331 """Get the current timeout setting."""
332 return self._writeTimeout
cliechti14b274a2009-02-07 00:27:05 +0000333
cliechti0276f5e2004-11-13 03:14:11 +0000334 writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")
cliechtid6bf52c2003-10-01 02:28:12 +0000335
336
337 def setXonXoff(self, xonxoff):
cliechti4a567a02009-07-27 22:09:31 +0000338 """Change XON/XOFF setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000339 self._xonxoff = xonxoff
340 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000341
cliechtid6bf52c2003-10-01 02:28:12 +0000342 def getXonXoff(self):
cliechti4a567a02009-07-27 22:09:31 +0000343 """Get the current XON/XOFF setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000344 return self._xonxoff
cliechti14b274a2009-02-07 00:27:05 +0000345
cliechti4a567a02009-07-27 22:09:31 +0000346 xonxoff = property(getXonXoff, setXonXoff, doc="XON/XOFF setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000347
348 def setRtsCts(self, rtscts):
cliechti4a567a02009-07-27 22:09:31 +0000349 """Change RTS/CTS flow control setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000350 self._rtscts = rtscts
351 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000352
cliechtid6bf52c2003-10-01 02:28:12 +0000353 def getRtsCts(self):
cliechti4a567a02009-07-27 22:09:31 +0000354 """Get the current RTS/CTS flow control setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000355 return self._rtscts
cliechti14b274a2009-02-07 00:27:05 +0000356
cliechtif46e0a82005-05-19 15:24:57 +0000357 rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")
cliechtid6bf52c2003-10-01 02:28:12 +0000358
cliechtif46e0a82005-05-19 15:24:57 +0000359 def setDsrDtr(self, dsrdtr=None):
360 """Change DsrDtr flow control setting."""
361 if dsrdtr is None:
cliechti14b274a2009-02-07 00:27:05 +0000362 # if not set, keep backwards compatibility and follow rtscts setting
cliechtif46e0a82005-05-19 15:24:57 +0000363 self._dsrdtr = self._rtscts
364 else:
cliechti14b274a2009-02-07 00:27:05 +0000365 # if defined independently, follow its value
cliechtif46e0a82005-05-19 15:24:57 +0000366 self._dsrdtr = dsrdtr
367 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000368
cliechtif46e0a82005-05-19 15:24:57 +0000369 def getDsrDtr(self):
cliechti4a567a02009-07-27 22:09:31 +0000370 """Get the current DSR/DTR flow control setting."""
cliechtif46e0a82005-05-19 15:24:57 +0000371 return self._dsrdtr
cliechti14b274a2009-02-07 00:27:05 +0000372
cliechtif46e0a82005-05-19 15:24:57 +0000373 dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
cliechti679bfa62008-06-20 23:58:15 +0000374
375 def setInterCharTimeout(self, interCharTimeout):
376 """Change inter-character timeout setting."""
377 if interCharTimeout is not None:
378 if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
379 try:
cliechti14b274a2009-02-07 00:27:05 +0000380 interCharTimeout + 1 # test if it's a number, will throw a TypeError if not...
cliechti679bfa62008-06-20 23:58:15 +0000381 except TypeError:
382 raise ValueError("Not a valid timeout: %r" % interCharTimeout)
cliechti14b274a2009-02-07 00:27:05 +0000383
cliechti679bfa62008-06-20 23:58:15 +0000384 self._interCharTimeout = interCharTimeout
385 if self._isOpen: self._reconfigurePort()
cliechti14b274a2009-02-07 00:27:05 +0000386
cliechti679bfa62008-06-20 23:58:15 +0000387 def getInterCharTimeout(self):
388 """Get the current inter-character timeout setting."""
389 return self._interCharTimeout
cliechti14b274a2009-02-07 00:27:05 +0000390
cliechti679bfa62008-06-20 23:58:15 +0000391 interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")
392
393
cliechtid6bf52c2003-10-01 02:28:12 +0000394 # - - - - - - - - - - - - - - - - - - - - - - - -
395
396 def __repr__(self):
397 """String representation of the current port settings and its state."""
cliechtif46e0a82005-05-19 15:24:57 +0000398 return "%s<id=0x%x, open=%s>(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
cliechtid6bf52c2003-10-01 02:28:12 +0000399 self.__class__.__name__,
400 id(self),
401 self._isOpen,
402 self.portstr,
403 self.baudrate,
404 self.bytesize,
405 self.parity,
406 self.stopbits,
407 self.timeout,
408 self.xonxoff,
409 self.rtscts,
cliechtif46e0a82005-05-19 15:24:57 +0000410 self.dsrdtr,
cliechtid6bf52c2003-10-01 02:28:12 +0000411 )
412
cliechti4a567a02009-07-27 22:09:31 +0000413 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechtif81362e2009-07-25 03:44:33 +0000414
cliechti4a567a02009-07-27 22:09:31 +0000415 def readline(self, size=None, eol='\n'):
416 """read a line which is terminated with end-of-line (eol) character
417 ('\n' by default) or until timeout"""
418 line = ''
419 while 1:
420 c = self.read(1)
421 if c:
422 line += c # not very efficient but lines are usually not that long
423 if c == eol:
424 break
425 if size is not None and len(line) >= size:
426 break
427 else:
428 break
429 return bytes(line)
cliechtif81362e2009-07-25 03:44:33 +0000430
cliechti4a567a02009-07-27 22:09:31 +0000431 def readlines(self, sizehint=None, eol='\n'):
432 """read a list of lines, until timeout
433 sizehint is ignored"""
434 if self.timeout is None:
435 raise ValueError("Serial port MUST have enabled timeout for this function!")
436 lines = []
437 while 1:
438 line = self.readline(eol=eol)
439 if line:
440 lines.append(line)
441 if line[-1] != eol: # was the line received with a timeout?
442 break
443 else:
444 break
445 return lines
cliechtif81362e2009-07-25 03:44:33 +0000446
cliechti4a567a02009-07-27 22:09:31 +0000447 def xreadlines(self, sizehint=None):
448 """just call readlines - here for compatibility"""
449 return self.readlines()
450
451 # - - - - - - - - - - - - - - - - - - - - - - - -
452 # compatibility with io library
453
454 def readable(self): return True
455 def writable(self): return True
456 def seekable(self): return False
457 def readinto(self, b):
458 data = self.read(len(b))
459 n = len(data)
460 try:
461 b[:n] = data
462 except TypeError, err:
463 import array
464 if not isinstance(b, array.array):
465 raise err
466 b[:n] = array.array('b', data)
467 return n
cliechtif81362e2009-07-25 03:44:33 +0000468
469
cliechtid6bf52c2003-10-01 02:28:12 +0000470if __name__ == '__main__':
cliechtif81362e2009-07-25 03:44:33 +0000471 import sys
cliechtid6bf52c2003-10-01 02:28:12 +0000472 s = SerialBase()
cliechtif81362e2009-07-25 03:44:33 +0000473 sys.stdout.write('port name: %s\n' % s.portstr)
474 sys.stdout.write('baud rates: %s\n' % s.getSupportedBaudrates())
475 sys.stdout.write('byte sizes: %s\n' % s.getSupportedByteSizes())
476 sys.stdout.write('parities: %s\n' % s.getSupportedParities())
477 sys.stdout.write('stop bits: %s\n' % s.getSupportedStopbits())
478 sys.stdout.write('%s\n' % s)