blob: c23d837728fc99f4a70271c5a9abe2a3b1717a3f [file] [log] [blame]
cliechtic1c37602009-07-21 01:34:57 +00001==============
2 pySerial API
3==============
4
5.. module:: serial
6
7Classes
8=======
9
cliechti7aed8332009-08-05 14:19:31 +000010Native ports
11------------
12
cliechtic1c37602009-07-21 01:34:57 +000013.. class:: Serial
14
Chris Liechti518b0d32015-08-30 02:20:39 +020015 .. method:: __init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None)
cliechtic1c37602009-07-21 01:34:57 +000016
17 :param port:
Chris Liechti518b0d32015-08-30 02:20:39 +020018 Device name or :const:`None`.
cliechtic1c37602009-07-21 01:34:57 +000019
Chris Liechtice621882015-08-06 19:29:31 +020020 :param int baudrate:
cliechtic1c37602009-07-21 01:34:57 +000021 Baud rate such as 9600 or 115200 etc.
22
23 :param bytesize:
cliechti4a567a02009-07-27 22:09:31 +000024 Number of data bits. Possible values:
25 :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`,
26 :const:`EIGHTBITS`
cliechtic1c37602009-07-21 01:34:57 +000027
28 :param parity:
cliechti4a567a02009-07-27 22:09:31 +000029 Enable parity checking. Possible values:
cliechti87686242009-08-18 00:58:31 +000030 :const:`PARITY_NONE`, :const:`PARITY_EVEN`, :const:`PARITY_ODD`
31 :const:`PARITY_MARK`, :const:`PARITY_SPACE`
cliechtic1c37602009-07-21 01:34:57 +000032
33 :param stopbits:
cliechti4a567a02009-07-27 22:09:31 +000034 Number of stop bits. Possible values:
cliechti87686242009-08-18 00:58:31 +000035 :const:`STOPBITS_ONE`, :const:`STOPBITS_ONE_POINT_FIVE`,
cliechti4a567a02009-07-27 22:09:31 +000036 :const:`STOPBITS_TWO`
cliechtic1c37602009-07-21 01:34:57 +000037
Chris Liechtice621882015-08-06 19:29:31 +020038 :param float timeout:
cliechtic1c37602009-07-21 01:34:57 +000039 Set a read timeout value.
40
Chris Liechtice621882015-08-06 19:29:31 +020041 :param bool xonxoff:
cliechtic1c37602009-07-21 01:34:57 +000042 Enable software flow control.
43
Chris Liechtice621882015-08-06 19:29:31 +020044 :param bool rtscts:
cliechtic1c37602009-07-21 01:34:57 +000045 Enable hardware (RTS/CTS) flow control.
46
Chris Liechtice621882015-08-06 19:29:31 +020047 :param bool dsrdtr:
cliechti07709e42010-05-21 00:30:09 +000048 Enable hardware (DSR/DTR) flow control.
49
Chris Liechti589c92a2015-09-04 23:04:34 +020050 :param float write_timeout:
cliechti07709e42010-05-21 00:30:09 +000051 Set a write timeout value.
52
Chris Liechti589c92a2015-09-04 23:04:34 +020053 :param float inter_byte_timeout:
cliechti4a567a02009-07-27 22:09:31 +000054 Inter-character timeout, :const:`None` to disable (default).
cliechtic1c37602009-07-21 01:34:57 +000055
cliechti6066f842009-07-24 00:05:45 +000056 :exception ValueError:
cliechti4a567a02009-07-27 22:09:31 +000057 Will be raised when parameter are out of range, e.g. baud rate, data bits.
cliechti6066f842009-07-24 00:05:45 +000058
59 :exception SerialException:
60 In case the device can not be found or can not be configured.
61
62
cliechti4a567a02009-07-27 22:09:31 +000063 The port is immediately opened on object creation, when a *port* is
64 given. It is not opened when *port* is :const:`None` and a successive call
65 to :meth:`open` will be needed.
66
Chris Liechti518b0d32015-08-30 02:20:39 +020067 *port* is a device name: depending on operating system. e.g.
68 ``/dev/ttyUSB0`` on GNU/Linux or ``COM3`` on Windows.
cliechtic1c37602009-07-21 01:34:57 +000069
cliechti25375b52010-07-21 23:27:13 +000070 The parameter *baudrate* can be one of the standard values:
71 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
72 9600, 19200, 38400, 57600, 115200.
cliechti28b8fd02011-12-28 21:39:42 +000073 These are well supported on all platforms.
74
75 Standard values above 115200, such as: 230400, 460800, 500000, 576000,
76 921600, 1000000, 1152000, 1500000, 2000000, 2500000, 3000000, 3500000,
77 4000000 also work on many platforms and devices.
cliechti25375b52010-07-21 23:27:13 +000078
cliechti06281be2011-08-25 23:08:29 +000079 Non-standard values are also supported on some platforms (GNU/Linux, MAC
cliechti25375b52010-07-21 23:27:13 +000080 OSX >= Tiger, Windows). Though, even on these platforms some serial
81 ports may reject non-standard values.
82
cliechti4a567a02009-07-27 22:09:31 +000083 Possible values for the parameter *timeout*:
cliechti5134aab2009-07-21 19:47:59 +000084
cliechtibb5c3c52009-07-23 02:29:27 +000085 - ``timeout = None``: wait forever
86 - ``timeout = 0``: non-blocking mode (return immediately on read)
cliechtif81362e2009-07-25 03:44:33 +000087 - ``timeout = x``: set timeout to ``x`` seconds (float allowed)
cliechtic1c37602009-07-21 01:34:57 +000088
Chris Liechti518b0d32015-08-30 02:20:39 +020089 Writes are blocking by default, unless *write_imeout* is set. For
cliechti25375b52010-07-21 23:27:13 +000090 possible values refer to the list for *timeout* above.
cliechti07709e42010-05-21 00:30:09 +000091
cliechti8611bf42009-08-03 00:34:03 +000092 Note that enabling both flow control methods (*xonxoff* and *rtscts*)
93 together may not be supported. It is common to use one of the methods
94 at once, not both.
cliechtic1c37602009-07-21 01:34:57 +000095
cliechti07709e42010-05-21 00:30:09 +000096 *dsrdtr* is not supported by all platforms (silently ignored). Setting
97 it to ``None`` has the effect that its state follows *rtscts*.
98
cliechti25375b52010-07-21 23:27:13 +000099 Also consider using the function :func:`serial_for_url` instead of
100 creating Serial instances directly.
101
cliechti5c72e4d2010-07-21 14:04:54 +0000102 .. versionchanged:: 2.5
cliechti06281be2011-08-25 23:08:29 +0000103 *dsrdtr* now defaults to ``False`` (instead of *None*)
cliechti5c72e4d2010-07-21 14:04:54 +0000104
cliechtic1c37602009-07-21 01:34:57 +0000105 .. method:: open()
106
107 Open port.
108
109 .. method:: close()
110
111 Close port immediately.
112
cliechti25375b52010-07-21 23:27:13 +0000113 .. method:: __del__()
114
115 Destructor, close port when serial port instance is freed.
116
cliechtic1c37602009-07-21 01:34:57 +0000117
Chris Liechti256ea212015-08-29 23:57:00 +0200118 The following methods may raise :exc:`SerialException` when applied to a closed
cliechti4a567a02009-07-27 22:09:31 +0000119 port.
cliechtic1c37602009-07-21 01:34:57 +0000120
121 .. method:: read(size=1)
122
cliechtibb5c3c52009-07-23 02:29:27 +0000123 :param size: Number of bytes to read.
124 :return: Bytes read from the port.
cliechtic1c37602009-07-21 01:34:57 +0000125
cliechti4a567a02009-07-27 22:09:31 +0000126 Read *size* bytes from the serial port. If a timeout is set it may
cliechtibb5c3c52009-07-23 02:29:27 +0000127 return less characters as requested. With no timeout it will block
128 until the requested number of bytes is read.
cliechtic1c37602009-07-21 01:34:57 +0000129
cliechti4a567a02009-07-27 22:09:31 +0000130 .. versionchanged:: 2.5
131 Returns an instance of :class:`bytes` when available (Python 2.6
cliechti8611bf42009-08-03 00:34:03 +0000132 and newer) and :class:`str` otherwise.
cliechti4a567a02009-07-27 22:09:31 +0000133
cliechtibb5c3c52009-07-23 02:29:27 +0000134 .. method:: write(data)
135
136 :param data: Data to send.
cliechti4a567a02009-07-27 22:09:31 +0000137 :return: Number of bytes written.
cliechti6066f842009-07-24 00:05:45 +0000138 :exception SerialTimeoutException:
139 In case a write timeout is configured for the port and the time is
140 exceeded.
141
cliechti4a567a02009-07-27 22:09:31 +0000142 Write the string *data* to the port.
cliechtic1c37602009-07-21 01:34:57 +0000143
cliechti4a567a02009-07-27 22:09:31 +0000144 .. versionchanged:: 2.5
cliechtiddd78132009-07-28 01:13:28 +0000145 Accepts instances of :class:`bytes` and :class:`bytearray` when
cliechti8611bf42009-08-03 00:34:03 +0000146 available (Python 2.6 and newer) and :class:`str` otherwise.
cliechti4a567a02009-07-27 22:09:31 +0000147
cliechti9a1c6952009-10-20 22:18:28 +0000148 .. versionchanged:: 2.5
149 Write returned ``None`` in previous versions.
150
Chris Liechti518b0d32015-08-30 02:20:39 +0200151 .. method:: flush()
152
153 Flush of file like objects. In this case, wait until all data is
154 written.
155
Chris Liechti256ea212015-08-29 23:57:00 +0200156 .. attribute:: in_waiting
cliechti4a567a02009-07-27 22:09:31 +0000157
Chris Liechti256ea212015-08-29 23:57:00 +0200158 :getter: Get the number of bytes in the input buffer
159 :type: int
160
161 Return the number of bytes in the receive buffer.
cliechti4a567a02009-07-27 22:09:31 +0000162
Chris Liechti518b0d32015-08-30 02:20:39 +0200163 .. versionchanged:: 3.0 changed to property from ``inWaiting()``
cliechtic1c37602009-07-21 01:34:57 +0000164
Chris Liechti518b0d32015-08-30 02:20:39 +0200165 .. attribute:: out_waiting
166
167 :getter: Get the number of bytes in the output buffer
168 :platform: Posix
169 :platform: Windows
170
171 Return the number of bytes in the output buffer.
172
173 .. versionchanged:: 2.7 (Posix support added)
174 .. versionchanged:: 3.0 changed to property from ``outWaiting()``
cliechtic1c37602009-07-21 01:34:57 +0000175
Chris Liechti256ea212015-08-29 23:57:00 +0200176 .. method:: reset_input_buffer()
cliechtic1c37602009-07-21 01:34:57 +0000177
178 Flush input buffer, discarding all it's contents.
179
Chris Liechti518b0d32015-08-30 02:20:39 +0200180 .. versionchanged:: 3.0 renamed from ``flushInput()``
181
Chris Liechti256ea212015-08-29 23:57:00 +0200182 .. method:: reset_output_buffer()
cliechtic1c37602009-07-21 01:34:57 +0000183
184 Clear output buffer, aborting the current output and
185 discarding all that is in the buffer.
186
Chris Liechti518b0d32015-08-30 02:20:39 +0200187 .. versionchanged:: 3.0 renamed from ``flushOutput()``
188
Chris Liechti256ea212015-08-29 23:57:00 +0200189 .. method:: send_break(duration=0.25)
cliechtic1c37602009-07-21 01:34:57 +0000190
cliechtibb5c3c52009-07-23 02:29:27 +0000191 :param duration: Time (float) to activate the BREAK condition.
192
cliechtic1c37602009-07-21 01:34:57 +0000193 Send break condition. Timed, returns to idle state after given
194 duration.
195
cliechtic1c37602009-07-21 01:34:57 +0000196
Chris Liechti256ea212015-08-29 23:57:00 +0200197 .. attribute:: break_condition
cliechtibb5c3c52009-07-23 02:29:27 +0000198
Chris Liechti256ea212015-08-29 23:57:00 +0200199 :getter: Get the current BREAK state
200 :setter: Control the BREAK state
201 :type: bool
cliechtic1c37602009-07-21 01:34:57 +0000202
Chris Liechti256ea212015-08-29 23:57:00 +0200203 When set to ``True`` activate BREAK condition, else disable.
204 Controls TXD. When active, no transmitting is possible.
cliechtic1c37602009-07-21 01:34:57 +0000205
Chris Liechti256ea212015-08-29 23:57:00 +0200206 .. attribute:: rts
cliechtibb5c3c52009-07-23 02:29:27 +0000207
Chris Liechti256ea212015-08-29 23:57:00 +0200208 :setter: Set the state of the RTS line
209 :getter: Return the state of the RTS line
210 :type: bool
cliechtic1c37602009-07-21 01:34:57 +0000211
Chris Liechti256ea212015-08-29 23:57:00 +0200212 Set RTS line to specified logic level. It is possible to assign this
213 value before opening the serial port, then the value is applied uppon
214 :meth:`open`.
cliechtic1c37602009-07-21 01:34:57 +0000215
Chris Liechti256ea212015-08-29 23:57:00 +0200216 .. attribute:: dtr
cliechtibb5c3c52009-07-23 02:29:27 +0000217
Chris Liechti256ea212015-08-29 23:57:00 +0200218 :setter: Set the state of the DTR line
219 :getter: Return the state of the DTR line
220 :type: bool
cliechtic1c37602009-07-21 01:34:57 +0000221
Chris Liechti256ea212015-08-29 23:57:00 +0200222 Set DTR line to specified logic level. It is possible to assign this
223 value before opening the serial port, then the value is applied uppon
224 :meth:`open`.
cliechtic1c37602009-07-21 01:34:57 +0000225
Chris Liechti518b0d32015-08-30 02:20:39 +0200226 Read-only attributes:
227
228 .. attribute:: name
229
230 :getter: Device name.
231
232 .. versionadded:: 2.5
233
Chris Liechti256ea212015-08-29 23:57:00 +0200234 .. attribute:: cts
235
236 :getter: Get the state of the CTS line
237 :type: bool
cliechtibb5c3c52009-07-23 02:29:27 +0000238
cliechtic1c37602009-07-21 01:34:57 +0000239 Return the state of the CTS line.
240
Chris Liechti256ea212015-08-29 23:57:00 +0200241 .. attribute:: dsr
cliechtic1c37602009-07-21 01:34:57 +0000242
Chris Liechti256ea212015-08-29 23:57:00 +0200243 :getter: Get the state of the DSR line
244 :type: bool
cliechtibb5c3c52009-07-23 02:29:27 +0000245
cliechtic1c37602009-07-21 01:34:57 +0000246 Return the state of the DSR line.
247
Chris Liechti256ea212015-08-29 23:57:00 +0200248 .. attribute:: ri
cliechtic1c37602009-07-21 01:34:57 +0000249
Chris Liechti256ea212015-08-29 23:57:00 +0200250 :getter: Get the state of the RI line
251 :type: bool
cliechtibb5c3c52009-07-23 02:29:27 +0000252
cliechtic1c37602009-07-21 01:34:57 +0000253 Return the state of the RI line.
254
Chris Liechti256ea212015-08-29 23:57:00 +0200255 .. attribute:: cd
cliechtic1c37602009-07-21 01:34:57 +0000256
Chris Liechti256ea212015-08-29 23:57:00 +0200257 :getter: Get the state of the CD line
258 :type: bool
cliechtibb5c3c52009-07-23 02:29:27 +0000259
cliechtic1c37602009-07-21 01:34:57 +0000260 Return the state of the CD line
261
cliechtif81362e2009-07-25 03:44:33 +0000262
cliechti25375b52010-07-21 23:27:13 +0000263 New values can be assigned to the following attributes (properties), the
264 port will be reconfigured, even if it's opened at that time:
cliechtic1c37602009-07-21 01:34:57 +0000265
cliechtiedcdbe42009-07-22 00:48:34 +0000266
267 .. attribute:: port
268
269 Read or write port. When the port is already open, it will be closed
270 and reopened with the new setting.
271
272 .. attribute:: baudrate
273
Chris Liechti518b0d32015-08-30 02:20:39 +0200274 :getter: Get current baud rate
275 :setter: Set new baud rate
276 :type: int
277
cliechti6066f842009-07-24 00:05:45 +0000278 Read or write current baud rate setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000279
280 .. attribute:: bytesize
281
Chris Liechti518b0d32015-08-30 02:20:39 +0200282 :getter: Get current byte size
283 :setter: Set new byte size. Possible values:
284 :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`,
285 :const:`EIGHTBITS`
286 :type: int
287
cliechti6066f842009-07-24 00:05:45 +0000288 Read or write current data byte size setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000289
290 .. attribute:: parity
291
Chris Liechti518b0d32015-08-30 02:20:39 +0200292 :getter: Get current parity setting
293 :setter: Set new parity mode. Possible values:
294 :const:`PARITY_NONE`, :const:`PARITY_EVEN`, :const:`PARITY_ODD`
295 :const:`PARITY_MARK`, :const:`PARITY_SPACE`
296
cliechti6066f842009-07-24 00:05:45 +0000297 Read or write current parity setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000298
299 .. attribute:: stopbits
300
Chris Liechti518b0d32015-08-30 02:20:39 +0200301 :getter: Get current stop bit setting
302 :setter: Set new stop bit setting. Possible values:
303 :const:`STOPBITS_ONE`, :const:`STOPBITS_ONE_POINT_FIVE`,
304 :const:`STOPBITS_TWO`
305
cliechti6066f842009-07-24 00:05:45 +0000306 Read or write current stop bit width setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000307
308 .. attribute:: timeout
309
Chris Liechti518b0d32015-08-30 02:20:39 +0200310 :getter: Get current read timeout setting
311 :setter: Set read timeout
312 :type: float (seconds)
313
cliechti6066f842009-07-24 00:05:45 +0000314 Read or write current read timeout setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000315
Chris Liechti518b0d32015-08-30 02:20:39 +0200316 .. attribute:: write_timeout
317
318 :getter: Get current write timeout setting
319 :setter: Set write timeout
320 :type: float (seconds)
cliechtiedcdbe42009-07-22 00:48:34 +0000321
cliechti6066f842009-07-24 00:05:45 +0000322 Read or write current write timeout setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000323
Chris Liechti518b0d32015-08-30 02:20:39 +0200324 .. versionchanged:: 3.0 renamed from ``writeTimeout``
325
326 .. attribute:: inter_byte_timeout
327
328 :getter: Get current inter byte timeout setting
329 :setter: Disable (``None``) or enable the inter byte timeout
330 :type: float or None
331
332 Read or write current inter byte timeout setting.
333
334 .. versionchanged:: 3.0 renamed from ``interCharTimeout``
335
cliechtiedcdbe42009-07-22 00:48:34 +0000336 .. attribute:: xonxoff
337
Chris Liechti518b0d32015-08-30 02:20:39 +0200338 :getter: Get current software flow control setting
339 :setter: Enable or disable software flow control
340 :type: bool
341
cliechti6066f842009-07-24 00:05:45 +0000342 Read or write current software flow control rate setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000343
344 .. attribute:: rtscts
345
Chris Liechti518b0d32015-08-30 02:20:39 +0200346 :getter: Get current hardware flow control setting
347 :setter: Enable or disable hardware flow control
348 :type: bool
349
cliechti6066f842009-07-24 00:05:45 +0000350 Read or write current hardware flow control setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000351
352 .. attribute:: dsrdtr
353
Chris Liechti518b0d32015-08-30 02:20:39 +0200354 :getter: Get current hardware flow control setting
355 :setter: Enable or disable hardware flow control
356 :type: bool
357
cliechti6066f842009-07-24 00:05:45 +0000358 Read or write current hardware flow control setting.
cliechtiedcdbe42009-07-22 00:48:34 +0000359
Chris Liechtice621882015-08-06 19:29:31 +0200360 .. attribute:: rs485_mode
361
Chris Liechti518b0d32015-08-30 02:20:39 +0200362 :getter: Get the current RS485 settings
363 :setter: Disable (``None``) or enable the RS485 settings
364 :type: :class:`rs485.RS485Settings` or ``None``
365 :platform: Posix (Linux, limited set of hardware)
366 :platform: Windows (RTS on TX only possible)
Chris Liechtice621882015-08-06 19:29:31 +0200367
368 Attribute to configure RS485 support. When set to an instance of
369 :class:`rs485.RS485Settings` and supported by OS, RTS will be active
370 when data is sent and inactive otherwise (for reception). The
371 :class:`rs485.RS485Settings` class provides additional settings
372 supported on some platforms.
373
374 .. versionadded:: 3.0
375
376
cliechtiedcdbe42009-07-22 00:48:34 +0000377 The following constants are also provided:
378
379 .. attribute:: BAUDRATES
380
cliechti25375b52010-07-21 23:27:13 +0000381 A list of valid baud rates. The list may be incomplete such that higher
382 baud rates may be supported by the device and that values in between the
383 standard baud rates are supported. (Read Only).
cliechtiedcdbe42009-07-22 00:48:34 +0000384
385 .. attribute:: BYTESIZES
386
cliechti25375b52010-07-21 23:27:13 +0000387 A list of valid byte sizes for the device (Read Only).
cliechtiedcdbe42009-07-22 00:48:34 +0000388
389 .. attribute:: PARITIES
390
cliechti25375b52010-07-21 23:27:13 +0000391 A list of valid parities for the device (Read Only).
cliechtiedcdbe42009-07-22 00:48:34 +0000392
393 .. attribute:: STOPBITS
394
cliechti25375b52010-07-21 23:27:13 +0000395 A list of valid stop bit widths for the device (Read Only).
cliechtiedcdbe42009-07-22 00:48:34 +0000396
cliechti4a567a02009-07-27 22:09:31 +0000397
cliechti25375b52010-07-21 23:27:13 +0000398 The following methods are for compatibility with the :mod:`io` library.
cliechti4a567a02009-07-27 22:09:31 +0000399
400 .. method:: readable()
401
402 :return: True
cliechtif4566342009-08-04 00:07:19 +0000403
cliechti4a567a02009-07-27 22:09:31 +0000404 .. versionadded:: 2.5
405
406 .. method:: writable()
407
408 :return: True
cliechtif4566342009-08-04 00:07:19 +0000409
cliechti4a567a02009-07-27 22:09:31 +0000410 .. versionadded:: 2.5
411
412 .. method:: seekable()
413
414 :return: False
cliechtif4566342009-08-04 00:07:19 +0000415
cliechti4a567a02009-07-27 22:09:31 +0000416 .. versionadded:: 2.5
417
418 .. method:: readinto(b)
419
cliechti8611bf42009-08-03 00:34:03 +0000420 :param b: bytearray or array instance
cliechti4a567a02009-07-27 22:09:31 +0000421 :return: Number of byte read
422
cliechtid7e7ce22009-08-03 02:01:07 +0000423 Read up to len(b) bytes into :class:`bytearray` *b* and return the
424 number of bytes read.
cliechti4a567a02009-07-27 22:09:31 +0000425
426 .. versionadded:: 2.5
427
cliechti25375b52010-07-21 23:27:13 +0000428 The port settings can be read and written as dictionary.
429
Chris Liechti256ea212015-08-29 23:57:00 +0200430 .. method:: get_settings()
cliechti4065dce2009-08-10 00:55:46 +0000431
432 :return: a dictionary with current port settings.
433
434 Get a dictionary with port settings. This is useful to backup the
435 current settings so that a later point in time they can be restored
Chris Liechti518b0d32015-08-30 02:20:39 +0200436 using :meth:`apply_settings`.
cliechti4065dce2009-08-10 00:55:46 +0000437
438 Note that control lines (RTS/DTR) are part of the settings.
439
440 .. versionadded:: 2.5
441
Chris Liechti256ea212015-08-29 23:57:00 +0200442 .. method:: apply_settings(d)
cliechti4065dce2009-08-10 00:55:46 +0000443
444 :param d: a dictionary with port settings.
445
Chris Liechti518b0d32015-08-30 02:20:39 +0200446 Applies a dictionary that was created by :meth:`get_settings`. Only
cliechti4065dce2009-08-10 00:55:46 +0000447 changes are applied and when a key is missing it means that the setting
448 stays unchanged.
449
450 Note that control lines (RTS/DTR) are not changed.
451
452 .. versionadded:: 2.5
453
cliechti25375b52010-07-21 23:27:13 +0000454 Platform specific methods.
455
cliechtic648da92011-12-29 01:17:51 +0000456 .. warning:: Programs using the following methods and attributes are not
457 portable to other platforms!
cliechti25375b52010-07-21 23:27:13 +0000458
459 .. method:: nonblocking()
460
Chris Liechtice621882015-08-06 19:29:31 +0200461 :platform: Posix
cliechti25375b52010-07-21 23:27:13 +0000462
463 Configure the device for nonblocking operation. This can be useful if
Chris Liechti518b0d32015-08-30 02:20:39 +0200464 the port is used with :mod:`select`. Note that :attr:`timeout` must
465 also be set to ``0``
cliechti25375b52010-07-21 23:27:13 +0000466
467 .. method:: fileno()
468
Chris Liechtice621882015-08-06 19:29:31 +0200469 :platform: Posix
cliechti25375b52010-07-21 23:27:13 +0000470 :return: File descriptor.
471
472 Return file descriptor number for the port that is opened by this object.
473 It is useful when serial ports are used with :mod:`select`.
474
Chris Liechti518b0d32015-08-30 02:20:39 +0200475 .. method:: set_input_flow_control(enable)
cliechti25375b52010-07-21 23:27:13 +0000476
cliechti2f0f8a32011-12-28 22:10:00 +0000477 :platform: Posix
Chris Liechti518b0d32015-08-30 02:20:39 +0200478 :param enable: Set flow control state.
cliechti25375b52010-07-21 23:27:13 +0000479
cliechti2f0f8a32011-12-28 22:10:00 +0000480 Manually control flow - when software flow control is enabled.
481
482 This will send XON (true) and XOFF (false) to the other device.
483
Chris Liechti518b0d32015-08-30 02:20:39 +0200484 .. versionadded:: 2.7 (Posix support added)
485 .. versionchanged:: 3.0 renamed from ``flowControlOut``
cliechti2f0f8a32011-12-28 22:10:00 +0000486
Chris Liechti518b0d32015-08-30 02:20:39 +0200487 .. method:: set_output_flow_control(enable)
cliechti2f0f8a32011-12-28 22:10:00 +0000488
Chris Liechti518b0d32015-08-30 02:20:39 +0200489 :platform: Posix (HW and SW flow control)
490 :platform: Windows (SW flow control only)
cliechti2f0f8a32011-12-28 22:10:00 +0000491 :param enable: Set flow control state.
492
493 Manually control flow of outgoing data - when hardware or software flow
494 control is enabled.
495
496 Sending will be suspended when called with ``False`` and enabled when
497 called with ``True``.
498
Chris Liechti518b0d32015-08-30 02:20:39 +0200499 .. versionchanged:: 2.7 (renamed on Posix, function was called ``flowControl``)
500 .. versionchanged:: 3.0 renamed from ``setXON``
Chris Liechti256ea212015-08-29 23:57:00 +0200501
502
Chris Liechti518b0d32015-08-30 02:20:39 +0200503
Chris Liechti9a99cb22015-08-30 22:16:50 +0200504 .. note:: The following members are deprecated and will be removed in a
Chris Liechti518b0d32015-08-30 02:20:39 +0200505 future release.
Chris Liechti256ea212015-08-29 23:57:00 +0200506
507 .. attribute:: portstr
508
Chris Liechti518b0d32015-08-30 02:20:39 +0200509 .. deprecated:: 2.5 use :attr:`name` instead
Chris Liechti256ea212015-08-29 23:57:00 +0200510
511 .. method:: inWaiting()
512
Chris Liechti518b0d32015-08-30 02:20:39 +0200513 .. deprecated:: 3.0 see :attr:`in_waiting`
514
515 .. attribute:: writeTimeout
516
517 .. deprecated:: 3.0 see :attr:`write_timeout`
Chris Liechti256ea212015-08-29 23:57:00 +0200518
519 .. attribute:: interCharTimeout
520
Chris Liechti518b0d32015-08-30 02:20:39 +0200521 .. deprecated:: 3.0 see :attr:`inter_byte_timeout`
Chris Liechti256ea212015-08-29 23:57:00 +0200522
523 .. method:: sendBreak(duration=0.25)
524
Chris Liechti518b0d32015-08-30 02:20:39 +0200525 .. deprecated:: 3.0 see :meth:`send_break`
Chris Liechti256ea212015-08-29 23:57:00 +0200526
527 .. method:: flushInput()
528
Chris Liechti518b0d32015-08-30 02:20:39 +0200529 .. deprecated:: 3.0 see :meth:`reset_input_buffer`
Chris Liechti256ea212015-08-29 23:57:00 +0200530
531 .. method:: flushOutput()
532
Chris Liechti518b0d32015-08-30 02:20:39 +0200533 .. deprecated:: 3.0 see :meth:`reset_output_buffer`
Chris Liechti256ea212015-08-29 23:57:00 +0200534
535 .. method:: setBreak(level=True)
536
Chris Liechti518b0d32015-08-30 02:20:39 +0200537 .. deprecated:: 3.0 see :attr:`break_condition`
Chris Liechti256ea212015-08-29 23:57:00 +0200538
539 .. method:: setRTS(level=True)
540
Chris Liechti518b0d32015-08-30 02:20:39 +0200541 .. deprecated:: 3.0 see :attr:`rts`
Chris Liechti256ea212015-08-29 23:57:00 +0200542
543 .. method:: setDTR(level=True)
544
Chris Liechti518b0d32015-08-30 02:20:39 +0200545 .. deprecated:: 3.0 see :attr:`dtr`
Chris Liechti256ea212015-08-29 23:57:00 +0200546
547 .. method:: getCTS()
548
Chris Liechti518b0d32015-08-30 02:20:39 +0200549 .. deprecated:: 3.0 see :attr:`cts`
Chris Liechti256ea212015-08-29 23:57:00 +0200550
551 .. method:: getDSR()
552
Chris Liechti518b0d32015-08-30 02:20:39 +0200553 .. deprecated:: 3.0 see :attr:`dsr`
Chris Liechti256ea212015-08-29 23:57:00 +0200554
555 .. method:: getRI()
556
Chris Liechti518b0d32015-08-30 02:20:39 +0200557 .. deprecated:: 3.0 see :attr:`ri`
Chris Liechti256ea212015-08-29 23:57:00 +0200558
559 .. method:: getCD()
560
Chris Liechti518b0d32015-08-30 02:20:39 +0200561 .. deprecated:: 3.0 see :attr:`cd`
Chris Liechti256ea212015-08-29 23:57:00 +0200562
563 .. method:: getSettingsDict()
564
Chris Liechti518b0d32015-08-30 02:20:39 +0200565 .. deprecated:: 3.0 see :meth:`get_settings`
Chris Liechti256ea212015-08-29 23:57:00 +0200566
567 .. method:: applySettingsDict(d)
568
Chris Liechti518b0d32015-08-30 02:20:39 +0200569 .. deprecated:: 3.0 see :meth:`apply_settings`
Chris Liechti256ea212015-08-29 23:57:00 +0200570
571 .. method:: outWaiting()
572
Chris Liechti518b0d32015-08-30 02:20:39 +0200573 .. deprecated:: 3.0 see :attr:`out_waiting`
Chris Liechti256ea212015-08-29 23:57:00 +0200574
575 .. method:: setXON(level=True)
576
Chris Liechti518b0d32015-08-30 02:20:39 +0200577 .. deprecated:: 3.0 see :meth:`set_output_flow_control`
Chris Liechti256ea212015-08-29 23:57:00 +0200578
579 .. method:: flowControlOut(enable)
580
Chris Liechti518b0d32015-08-30 02:20:39 +0200581 .. deprecated:: 3.0 see :meth:`set_input_flow_control`
cliechtif4566342009-08-04 00:07:19 +0000582
cliechtic648da92011-12-29 01:17:51 +0000583 .. attribute:: rtsToggle
584
585 :platform: Windows
586
587 Attribute to configure RTS toggle control setting. When enabled and
588 supported by OS, RTS will be active when data is available and inactive
589 if no data is available.
590
591 .. versionadded:: 2.6
Chris Liechti518b0d32015-08-30 02:20:39 +0200592 .. versionchanged:: 3.0 (removed, see :attr:`rs485_mode` instead)
cliechtic648da92011-12-29 01:17:51 +0000593
594
cliechtic56e41d2011-08-25 22:06:38 +0000595Implementation detail: some attributes and functions are provided by the
596class :class:`SerialBase` and some by the platform specific class and
597others by the base class mentioned above.
cliechti25375b52010-07-21 23:27:13 +0000598
Chris Liechtice621882015-08-06 19:29:31 +0200599RS485 support
600-------------
601The :class:`Serial` class has a :attr:`Serial.rs485_mode` attribute which allows to
602enable RS485 specific support on some platforms. Currently Windows and Linux
603(only a small number of devices) are supported.
cliechti4a567a02009-07-27 22:09:31 +0000604
Chris Liechtice621882015-08-06 19:29:31 +0200605:attr:`Serial.rs485_mode` needs to be set to an instance of
606:class:`rs485.RS485Settings` to enable or to ``None`` to disable this feature.
cliechti4a567a02009-07-27 22:09:31 +0000607
Chris Liechtice621882015-08-06 19:29:31 +0200608Usage::
cliechti4a567a02009-07-27 22:09:31 +0000609
Chris Liechtice621882015-08-06 19:29:31 +0200610 ser = serial.Serial(...)
611 ser.rs485_mode = serial.rs485.RS485Settings(...)
612 ser.write(b'hello')
cliechti4a567a02009-07-27 22:09:31 +0000613
Chris Liechtice621882015-08-06 19:29:31 +0200614There is a subclass :class:`rs485.RS485` available to emulate the RS485 support
615on regular serial ports.
cliechti4a567a02009-07-27 22:09:31 +0000616
cliechti4a567a02009-07-27 22:09:31 +0000617
Chris Liechtice621882015-08-06 19:29:31 +0200618.. class:: rs485.RS485Settings
cliechti4a567a02009-07-27 22:09:31 +0000619
Chris Liechtice621882015-08-06 19:29:31 +0200620 A class that holds RS485 specific settings which are supported on
621 some platforms.
cliechti4a567a02009-07-27 22:09:31 +0000622
Chris Liechtice621882015-08-06 19:29:31 +0200623 .. versionadded:: 3.0
cliechti4a567a02009-07-27 22:09:31 +0000624
Chris Liechtice621882015-08-06 19:29:31 +0200625 .. method:: __init__(rts_level_for_tx=True, rts_level_for_rx=False, loopback=False, delay_before_tx=None, delay_before_rx=None):
cliechti4a567a02009-07-27 22:09:31 +0000626
Chris Liechtice621882015-08-06 19:29:31 +0200627 :param bool rts_level_for_tx:
628 RTS level for transmission
cliechti4a567a02009-07-27 22:09:31 +0000629
Chris Liechtice621882015-08-06 19:29:31 +0200630 :param bool rts_level_for_rx:
631 RTS level for reception
cliechti4a567a02009-07-27 22:09:31 +0000632
Chris Liechtice621882015-08-06 19:29:31 +0200633 :param bool loopback:
634 When set to ``True`` transmitted data is also received.
cliechti4a567a02009-07-27 22:09:31 +0000635
Chris Liechtice621882015-08-06 19:29:31 +0200636 :param float delay_before_tx:
637 Delay after setting RTS but before transmission starts
638
639 :param float delay_before_rx:
640 Delay after transmission ends and resetting RTS
641
642 .. attribute:: rts_level_for_tx
643
644 RTS level for transmission.
645
646 .. attribute:: rts_level_for_rx
647
648 RTS level for reception.
649
650 .. attribute:: loopback
651
652 When set to ``True`` transmitted data is also received.
653
654 .. attribute:: delay_before_tx
655
656 Delay after setting RTS but before transmission starts (seconds as float).
657
658 .. attribute:: delay_before_rx
659
660 Delay after transmission ends and resetting RTS (seconds as float).
cliechti4a567a02009-07-27 22:09:31 +0000661
662
Chris Liechtice621882015-08-06 19:29:31 +0200663.. class:: rs485.RS485
cliechti4a567a02009-07-27 22:09:31 +0000664
Chris Liechtice621882015-08-06 19:29:31 +0200665 A subclass that replaces the :meth:`Serial.write` method with one that toggles RTS
666 according to the RS485 settings.
cliechti4a567a02009-07-27 22:09:31 +0000667
Chris Liechti518b0d32015-08-30 02:20:39 +0200668 Usage::
669
670 ser = serial.rs485.RS485(...)
671 ser.rs485_mode = serial.rs485.RS485Settings(...)
672 ser.write(b'hello')
673
Chris Liechtice621882015-08-06 19:29:31 +0200674 .. warning:: This may work unreliably on some serial ports (control signals not
675 synchronized or delayed compared to data). Using delays may be unreliable
676 (varying times, larger than expected) as the OS may not support very fine
677 grained delays (no smaller than in the order of tens of milliseconds).
cliechti4a567a02009-07-27 22:09:31 +0000678
Chris Liechtice621882015-08-06 19:29:31 +0200679 .. note:: Some implementations support this natively in the class
680 :class:`Serial`. Better performance can be expected when the native version
681 is used.
cliechti4a567a02009-07-27 22:09:31 +0000682
Chris Liechtice621882015-08-06 19:29:31 +0200683 .. note:: The loopback property is ignored by this implementation. The actual
684 behavior depends on the used hardware.
cliechti4a567a02009-07-27 22:09:31 +0000685
cliechti4a567a02009-07-27 22:09:31 +0000686
cliechtie214ff82010-07-21 15:48:47 +0000687
cliechti25375b52010-07-21 23:27:13 +0000688
cliechti7aed8332009-08-05 14:19:31 +0000689:rfc:`2217` Network ports
690-------------------------
691
692.. warning:: This implementation is currently in an experimental state. Use
693 at your own risk.
cliechtiedcdbe42009-07-22 00:48:34 +0000694
cliechtiec4ac1b2009-08-02 00:47:21 +0000695.. class:: rfc2217.Serial
696
cliechtif4566342009-08-04 00:07:19 +0000697 This implements a :rfc:`2217` compatible client. Port names are URLs_ in the
Chris Liechti518b0d32015-08-30 02:20:39 +0200698 form: ``rfc2217://<host>:<port>[?<option>[&<option>]]``
cliechtiec4ac1b2009-08-02 00:47:21 +0000699
cliechtiec4ac1b2009-08-02 00:47:21 +0000700 This class API is compatible to :class:`Serial` with a few exceptions:
701
Chris Liechti518b0d32015-08-30 02:20:39 +0200702 - write_timeout is not implemented
cliechtiec4ac1b2009-08-02 00:47:21 +0000703 - The current implementation starts a thread that keeps reading from the
704 (internal) socket. The thread is managed automatically by the
705 :class:`rfc2217.Serial` port object on :meth:`open`/:meth:`close`.
706 However it may be a problem for user applications that like to use select
707 instead of threads.
708
709 Due to the nature of the network and protocol involved there are a few
710 extra points to keep in mind:
711
712 - All operations have an additional latency time.
713 - Setting control lines (RTS/CTS) needs more time.
714 - Reading the status lines (DSR/DTR etc.) returns a cached value. When that
715 cache is updated depends entirely on the server. The server itself may
716 implement a polling at a certain rate and quick changes may be invisible.
717 - The network layer also has buffers. This means that :meth:`flush`,
Chris Liechti518b0d32015-08-30 02:20:39 +0200718 :meth:`reset_input_buffer` and :meth:`reset_output_buffer` may work with
719 additional delay. Likewise :attr:`in_waiting` returns the size of the
720 data arrived at the object internal buffer and excludes any bytes in the
721 network buffers or any server side buffer.
cliechtiec4ac1b2009-08-02 00:47:21 +0000722 - Closing and immediately reopening the same port may fail due to time
723 needed by the server to get ready again.
724
725 Not implemented yet / Possible problems with the implementation:
726
cliechti8611bf42009-08-03 00:34:03 +0000727 - :rfc:`2217` flow control between client and server (objects internal
728 buffer may eat all your memory when never read).
cliechtid7e7ce22009-08-03 02:01:07 +0000729 - No authentication support (servers may not prompt for a password etc.)
730 - No encryption.
731
732 Due to lack of authentication and encryption it is not suitable to use this
733 client for connections across the internet and should only be used in
734 controlled environments.
cliechtiec4ac1b2009-08-02 00:47:21 +0000735
cliechti7c640ed2009-08-02 00:54:51 +0000736 .. versionadded:: 2.5
cliechtiec4ac1b2009-08-02 00:47:21 +0000737
cliechti7aed8332009-08-05 14:19:31 +0000738
739.. class:: rfc2217.PortManager
740
741 This class provides helper functions for implementing :rfc:`2217`
742 compatible servers.
743
Chris Liechti518b0d32015-08-30 02:20:39 +0200744 Basically, it implements everything needed for the :rfc:`2217` protocol.
cliechti7aed8332009-08-05 14:19:31 +0000745 It just does not open sockets and read/write to serial ports (though it
746 changes other port settings). The user of this class must take care of the
747 data transmission itself. The reason for that is, that this way, this class
748 supports all programming models such as threads and select.
749
750 Usage examples can be found in the examples where two TCP/IP - serial
751 converters are shown, one using threads (the single port server) and an
752 other using select (the multi port server).
753
754 .. note:: Each new client connection must create a new instance as this
755 object (and the :rfc:`2217` protocol) has internal state.
756
757 .. method:: __init__(serial_port, connection, debug_output=False)
758
759 :param serial_port: a :class:`Serial` instance that is managed.
760 :param connection: an object implementing :meth:`write`, used to write
761 to the network.
cliechti86844e82009-08-12 00:05:33 +0000762 :param debug_output: enables debug messages: a :class:`logging.Logger`
763 instance or None.
cliechti7aed8332009-08-05 14:19:31 +0000764
765 Initializes the Manager and starts negotiating with client in Telnet
766 and :rfc:`2217` protocol. The negotiation starts immediately so that
767 the class should be instantiated in the moment the client connects.
768
769 The *serial_port* can be controlled by :rfc:`2217` commands. This
cliechti06281be2011-08-25 23:08:29 +0000770 object will modify the port settings (baud rate etc.) and control lines
cliechti7aed8332009-08-05 14:19:31 +0000771 (RTS/DTR) send BREAK etc. when the corresponding commands are found by
772 the :meth:`filter` method.
773
774 The *connection* object must implement a :meth:`write(data)` function.
775 This function must ensure that *data* is written at once (no user data
776 mixed in, i.e. it must be thread-safe). All data must be sent in its
777 raw form (:meth:`escape` must not be used) as it is used to send Telnet
778 and :rfc:`2217` control commands.
779
cliechti86844e82009-08-12 00:05:33 +0000780 For diagnostics of the connection or the implementation, *debug_output*
781 can be set to an instance of a :class:`logging.Logger` (e.g.
782 ``logging.getLogger('rfc2217.server')``). The caller should configure
783 the logger using ``setLevel`` for the desired detail level of the logs.
784
cliechti7aed8332009-08-05 14:19:31 +0000785 .. method:: escape(data)
786
787 :param data: data to be sent over the network.
788 :return: data, escaped for Telnet/:rfc:`2217`
789
790 A generator that escapes all data to be compatible with :rfc:`2217`.
791 Implementors of servers should use this function to process all data
792 sent over the network.
793
794 The function returns a generator which can be used in ``for`` loops.
cliechtie214ff82010-07-21 15:48:47 +0000795 It can be converted to bytes using :func:`serial.to_bytes`.
cliechti7aed8332009-08-05 14:19:31 +0000796
797 .. method:: filter(data)
798
799 :param data: data read from the network, including Telnet and
800 :rfc:`2217` controls.
801 :return: data, free from Telnet and :rfc:`2217` controls.
802
803 A generator that filters and processes all data related to :rfc:`2217`.
804 Implementors of servers should use this function to process all data
805 received from the network.
806
807 The function returns a generator which can be used in ``for`` loops.
cliechtie214ff82010-07-21 15:48:47 +0000808 It can be converted to bytes using :func:`serial.to_bytes`.
cliechti7aed8332009-08-05 14:19:31 +0000809
cliechti7cb78e82009-08-05 15:47:57 +0000810 .. method:: check_modem_lines(force_notification=False)
811
812 :param force_notification: Set to false. Parameter is for internal use.
cliechti7aed8332009-08-05 14:19:31 +0000813
814 This function needs to be called periodically (e.g. every second) when
815 the server wants to send NOTIFY_MODEMSTATE messages. This is required
816 to support the client for reading CTS/DSR/RI/CD status lines.
817
818 The function reads the status line and issues the notifications
819 automatically.
820
821 .. versionadded:: 2.5
822
cliechtiec4ac1b2009-08-02 00:47:21 +0000823.. seealso::
824
825 :rfc:`2217` - Telnet Com Port Control Option
826
827
cliechtic1c37602009-07-21 01:34:57 +0000828Exceptions
829==========
830
831.. exception:: SerialException
832
833 Base class for serial port exceptions.
834
cliechti4a567a02009-07-27 22:09:31 +0000835 .. versionchanged:: 2.5
cliechti4cb94662013-10-17 03:17:50 +0000836 Now derives from :exc:`IOError` instead of :exc:`Exception`
cliechti4a567a02009-07-27 22:09:31 +0000837
cliechtic1c37602009-07-21 01:34:57 +0000838.. exception:: SerialTimeoutException
839
840 Exception that is raised on write timeouts.
841
842
843Constants
844=========
845
cliechti87686242009-08-18 00:58:31 +0000846*Parity*
847
cliechtic1c37602009-07-21 01:34:57 +0000848.. data:: PARITY_NONE
849.. data:: PARITY_EVEN
850.. data:: PARITY_ODD
851.. data:: PARITY_MARK
852.. data:: PARITY_SPACE
853
cliechti87686242009-08-18 00:58:31 +0000854*Stop bits*
855
cliechtic1c37602009-07-21 01:34:57 +0000856.. data:: STOPBITS_ONE
857.. data:: STOPBITS_ONE_POINT_FIVE
858.. data:: STOPBITS_TWO
859
cliechti06281be2011-08-25 23:08:29 +0000860Note that 1.5 stop bits are not supported on POSIX. It will fall back to 2 stop
cliechti41be0392010-01-02 03:02:38 +0000861bits.
862
cliechti87686242009-08-18 00:58:31 +0000863*Byte size*
864
cliechtic1c37602009-07-21 01:34:57 +0000865.. data:: FIVEBITS
866.. data:: SIXBITS
867.. data:: SEVENBITS
868.. data:: EIGHTBITS
cliechti5b7d16a2009-07-21 21:53:59 +0000869
cliechti87686242009-08-18 00:58:31 +0000870
871*Others*
872
cliechti8611bf42009-08-03 00:34:03 +0000873Default control characters (instances of :class:`bytes` for Python 3.0+) for
cliechtidaf47ba2009-07-28 01:28:16 +0000874software flow control:
cliechti6066f842009-07-24 00:05:45 +0000875
cliechti5b7d16a2009-07-21 21:53:59 +0000876.. data:: XON
877.. data:: XOFF
cliechtif81362e2009-07-25 03:44:33 +0000878
cliechti4a567a02009-07-27 22:09:31 +0000879Module version:
cliechtif81362e2009-07-25 03:44:33 +0000880
881.. data:: VERSION
882
Chris Liechti518b0d32015-08-30 02:20:39 +0200883 A string indicating the pySerial version, such as ``3.0``.
cliechtif81362e2009-07-25 03:44:33 +0000884
cliechti87686242009-08-18 00:58:31 +0000885 .. versionadded:: 2.3
886
cliechti44eb98f2011-03-21 21:41:10 +0000887
cliechtie542b362011-03-18 00:49:16 +0000888Module functions and attributes
889===============================
cliechtif81362e2009-07-25 03:44:33 +0000890
891.. function:: device(number)
892
Chris Liechti518b0d32015-08-30 02:20:39 +0200893 .. versionchanged:: 3.0 removed, use ``serial.tools.list_ports`` instead
894
cliechti7c640ed2009-08-02 00:54:51 +0000895
cliechtie3ab3532009-08-05 12:40:38 +0000896.. function:: serial_for_url(url, \*args, \*\*kwargs)
cliechti7c640ed2009-08-02 00:54:51 +0000897
cliechti86844e82009-08-12 00:05:33 +0000898 :param url: Device name, number or :ref:`URL <URLs>`
cliechti7c640ed2009-08-02 00:54:51 +0000899 :param do_not_open: When set to true, the serial port is not opened.
900 :return: an instance of :class:`Serial` or a compatible object.
901
902 Get a native or a :rfc:`2217` implementation of the Serial class, depending
cliechtid7e7ce22009-08-03 02:01:07 +0000903 on port/url. This factory function is useful when an application wants
cliechti25375b52010-07-21 23:27:13 +0000904 to support both, local ports and remote ports. There is also support
Chris Liechti589c92a2015-09-04 23:04:34 +0200905 for other types, see :ref:`URL <URLs>` section.
cliechti7c640ed2009-08-02 00:54:51 +0000906
cliechtid7e7ce22009-08-03 02:01:07 +0000907 The port is not opened when a keyword parameter called *do_not_open* is
908 given and true, by default it is opened.
cliechti7c640ed2009-08-02 00:54:51 +0000909
910 .. versionadded:: 2.5
cliechtif4566342009-08-04 00:07:19 +0000911
cliechti87686242009-08-18 00:58:31 +0000912
cliechtie542b362011-03-18 00:49:16 +0000913.. attribute:: protocol_handler_packages
914
915 This attribute is a list of package names (strings) that is searched for
916 protocol handlers.
917
918 e.g. we want to support a URL ``foobar://``. A module
919 ``my_handlers.protocol_foobar`` is provided by the user::
920
921 serial.protocol_handler_packages.append("my_handlers")
922 s = serial.serial_for_url("foobar://")
923
924 For an URL starting with ``XY://`` is the function :func:`serial_for_url`
925 attempts to import ``PACKAGE.protocol_XY`` with each candidate for
926 ``PACKAGE`` from this list.
927
928 .. versionadded:: 2.6
929
930
cliechti25375b52010-07-21 23:27:13 +0000931.. function:: to_bytes(sequence)
cliechtie214ff82010-07-21 15:48:47 +0000932
933 :param sequence: String or list of integers
cliechti25375b52010-07-21 23:27:13 +0000934 :returns: an instance of ``bytes``
cliechtie214ff82010-07-21 15:48:47 +0000935
cliechtie542b362011-03-18 00:49:16 +0000936 Convert a sequence to a ``bytes`` type. This is used to write code that is
cliechtie214ff82010-07-21 15:48:47 +0000937 compatible to Python 2.x and 3.x.
938
cliechtie542b362011-03-18 00:49:16 +0000939 In Python versions prior 3.x, ``bytes`` is a subclass of str. They convert
cliechti25375b52010-07-21 23:27:13 +0000940 ``str([17])`` to ``'[17]'`` instead of ``'\x11'`` so a simple
cliechtie542b362011-03-18 00:49:16 +0000941 ``bytes(sequence)`` doesn't work for all versions of Python.
cliechtie214ff82010-07-21 15:48:47 +0000942
943 This function is used internally and in the unit tests.
944
cliechtie542b362011-03-18 00:49:16 +0000945 .. versionadded:: 2.5
946
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200947.. function:: iterbytes(b)
948
949 :param b: bytes, bytearray or memoryview
950 :returns: a generator that yields bytes
951
952 Some versions of Python (3.x) would return integers instead of bytes when
953 looping over an instance of ``bytes``. This helper function ensures that
954 bytes are returned.
955
956 .. versionadded:: 3.0
957
cliechtie214ff82010-07-21 15:48:47 +0000958
Chris Liechti811bf382015-10-10 00:54:47 +0200959Threading
960=========
961
962.. module:: serial.threaded
963.. versionadded:: 3.0
964
965.. warning:: This implementation is currently in an experimental state. Use
966 at your own risk.
967
968This module provides classes to simplify working with threads and protocols.
969
970.. class:: Protocol
971
972 Protocol as used by the :class:`SerialPortWorker`. This base class provides empty
973 implementations of all methods.
974
975
976 .. method:: connection_made(transport)
977
978 :param transport: instance used to write to serial port.
979
980 Called when reader thread is started.
981
982 .. method:: data_received(data)
983
984 :param data: received bytes
985
986 Called with snippets received from the serial port.
987
988 .. method:: connection_lost(exc)
989
990 :param exc: Exception if connection was terminated by error else ``None``
991
992 Called when the serial port is closed or the reader loop terminated
993 otherwise.
994
995.. class:: Packetizer(Protocol)
996
997 Read binary packets from serial port. Packets are expected to be terminated
998 with a ``TERMINATOR`` byte (null byte by default).
999
1000 The class also keeps track of the transport.
1001
1002 .. attribute:: TERMINATOR = b'\\0'
1003
1004 .. method:: __init__()
1005
1006 .. method:: connection_made(transport)
1007
1008 Store transport
1009
1010 .. method:: connection_lost(exc)
1011
1012 Forget transport
1013
1014 .. method:: data_received(data)
1015
1016 Buffer received data and search for ``TERMINATOR``, when found,
1017 call :meth:`handle_packet`.
1018
1019 .. method:: handle_packet(packet)
1020
1021 Process packets - to be overridden by subclassing.
1022
1023
1024.. class:: LineReader(Packetizer)
1025
1026 Read and write (Unicode) lines from/to serial port.
1027 The encoding is applied.
1028
1029
1030 .. attribute:: TERMINATOR = b'\\r\\n'
1031 .. attribute:: ENCODING = 'utf-8'
1032 .. attribute:: UNICODE_HANDLING = 'replace'
1033
1034 .. method:: handle_packet(packet)
1035
1036 .. method:: handle_line(line)
1037
1038 :param line: Unicode string with one line (excluding line terminator)
1039
1040 Process one line - to be overridden by subclassing.
1041
1042 .. method:: write_line(text)
1043
1044 :param text: Unicode string with one line (excluding line terminator)
1045
1046 Write text to the transport. ``text`` is a Unicode string and the encoding
1047 is applied before sending ans also the newline is append.
1048
1049
1050.. class:: SerialPortWorker(threading.Thread)
1051
1052 Implement a serial port read loop and dispatch to a Protocol instance (like
1053 the :class:`asyncio.Protocol`) but do it with threads.
1054
1055 Calls to :meth:`close` will close the serial port but it is also possible to just
1056 :meth:`stop` this thread and continue the serial port instance otherwise.
1057
1058 .. method:: __init__(serial_instance, protocol_factory)
1059
1060 :param serial_instance: serial port instance (opened) to be used.
1061 :param protocol_factory: a callable that returns a Protocol instance
1062
1063 Initialize thread.
1064
1065 Note that the ``serial_instance`` timeout is set to one second!
1066 Other settings are not changed.
1067
1068 .. method:: stop()
1069
1070 Stop the reader thread.
1071
1072 .. method:: run()
1073
1074 The actual reader loop driven by the thread. It calls
1075 :meth:`Protocol.connection_made`, reads from the serial port calling
1076 :meth:`Protocol.data_received` and finally calling :meth:`Protocol.connection_lost`
1077 when :meth:`close` is called or an error occurs.
1078
1079 .. method:: write(data)
1080
1081 Thread safe writing (uses lock).
1082
1083 .. method:: close()
1084
1085 Close the serial port and exit reader thread, calls :meth:`stop` (uses lock).
1086
1087 .. method:: connect()
1088
1089 Wait until connection is set up and return the transport and protocol
1090 instances.
1091
1092
1093 This class can be used as context manager, in this case it starts
1094 the thread and connects automatically. The serial port is closed
1095 when the context is left.
1096
1097 .. method:: __enter__()
1098
1099 :returns: protocol
1100
1101 Connect and return protocol instance.
1102
1103 .. method:: __exit__(exc_type, exc_val, exc_tb)
1104
1105 Closes serial port.
1106
Chris Liechtia1436b12015-10-12 23:19:04 +02001107Example::
1108
1109 class PrintLines(LineReader):
1110 def connection_made(self, transport):
1111 super(PrintLines, self).connection_made(transport)
1112 sys.stdout.write('port opened\n')
1113 self.write_line('hello world')
1114
1115 def handle_line(self, data):
1116 sys.stdout.write('line received: {}\n'.format(repr(data)))
1117
1118 def connection_lost(self, exc):
1119 if exc:
1120 traceback.print_exc(exc)
1121 sys.stdout.write('port closed\n')
1122
1123 ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1)
1124 with SerialPortWorker(ser, PrintLines) as protocol:
1125 protocol.write_line('hello')
1126 time.sleep(2)
1127
Chris Liechti811bf382015-10-10 00:54:47 +02001128
Chris Liechti1f0c9b42015-09-03 23:49:48 +02001129asyncio
1130=======
1131
Chris Liechti589c92a2015-09-04 23:04:34 +02001132.. module:: serial.aio
1133
Chris Liechti1f0c9b42015-09-03 23:49:48 +02001134.. warning:: This implementation is currently in an experimental state. Use
1135 at your own risk.
1136
Chris Liechti589c92a2015-09-04 23:04:34 +02001137Experimental asyncio support is available for Python 3.4 and newer. The module
Chris Liechti1f0c9b42015-09-03 23:49:48 +02001138:mod:`serial.aio` provides a :class:`asyncio.Transport`:
1139``SerialTransport``.
1140
1141
1142A factory function (`asyncio.coroutine`) is provided:
1143
1144.. function:: create_serial_connection(loop, protocol_factory, \*args, \*\*kwargs)
1145
1146 :param loop: The event handler
1147 :param protocol_factory: Factory function for a :class:`asyncio.Protocol`
1148 :param args: Passed to the :class:`serial.Serial` init function
1149 :param kwargs: Passed to the :class:`serial.Serial` init function
1150 :platform: Posix
1151
1152 Get a connection making coroutine.
1153
1154Example::
1155
1156 class Output(asyncio.Protocol):
1157 def connection_made(self, transport):
1158 self.transport = transport
1159 print('port opened', transport)
Chris Liechti589c92a2015-09-04 23:04:34 +02001160 transport.serial.rts = False
Chris Liechti1f0c9b42015-09-03 23:49:48 +02001161 transport.write(b'hello world\n')
1162
1163 def data_received(self, data):
1164 print('data received', repr(data))
1165 self.transport.close()
1166
1167 def connection_lost(self, exc):
1168 print('port closed')
1169 asyncio.get_event_loop().stop()
1170
1171 loop = asyncio.get_event_loop()
Chris Liechti589c92a2015-09-04 23:04:34 +02001172 coro = serial.aio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
Chris Liechti1f0c9b42015-09-03 23:49:48 +02001173 loop.run_until_complete(coro)
1174 loop.run_forever()
1175 loop.close()
1176