serialposix.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. #!/usr/bin/env python
  2. #
  3. # backend for serial IO for POSIX compatible systems, like Linux, OSX
  4. #
  5. # This file is part of pySerial. https://github.com/pyserial/pyserial
  6. # (C) 2001-2016 Chris Liechti <cliechti@gmx.net>
  7. #
  8. # SPDX-License-Identifier: BSD-3-Clause
  9. #
  10. # parts based on code from Grant B. Edwards <grante@visi.com>:
  11. # ftp://ftp.visi.com/users/grante/python/PosixSerial.py
  12. #
  13. # references: http://www.easysw.com/~mike/serial/serial.html
  14. # Collection of port names (was previously used by number_to_device which was
  15. # removed.
  16. # - Linux /dev/ttyS%d (confirmed)
  17. # - cygwin/win32 /dev/com%d (confirmed)
  18. # - openbsd (OpenBSD) /dev/cua%02d
  19. # - bsd*, freebsd* /dev/cuad%d
  20. # - darwin (OS X) /dev/cuad%d
  21. # - netbsd /dev/dty%02d (NetBSD 1.6 testing by Erk)
  22. # - irix (IRIX) /dev/ttyf%d (partially tested) names depending on flow control
  23. # - hp (HP-UX) /dev/tty%dp0 (not tested)
  24. # - sunos (Solaris/SunOS) /dev/tty%c (letters, 'a'..'z') (confirmed)
  25. # - aix (AIX) /dev/tty%d
  26. # pylint: disable=abstract-method
  27. import errno
  28. import fcntl
  29. import os
  30. import select
  31. import struct
  32. import sys
  33. import termios
  34. import serial
  35. from serial.serialutil import SerialBase, SerialException, to_bytes, \
  36. portNotOpenError, writeTimeoutError, Timeout
  37. class PlatformSpecificBase(object):
  38. BAUDRATE_CONSTANTS = {}
  39. def _set_special_baudrate(self, baudrate):
  40. raise NotImplementedError('non-standard baudrates are not supported on this platform')
  41. def _set_rs485_mode(self, rs485_settings):
  42. raise NotImplementedError('RS485 not supported on this platform')
  43. # some systems support an extra flag to enable the two in POSIX unsupported
  44. # paritiy settings for MARK and SPACE
  45. CMSPAR = 0 # default, for unsupported platforms, override below
  46. # try to detect the OS so that a device can be selected...
  47. # this code block should supply a device() and set_special_baudrate() function
  48. # for the platform
  49. plat = sys.platform.lower()
  50. if plat[:5] == 'linux': # Linux (confirmed) # noqa
  51. import array
  52. # extra termios flags
  53. CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
  54. # baudrate ioctls
  55. TCGETS2 = 0x802C542A
  56. TCSETS2 = 0x402C542B
  57. BOTHER = 0o010000
  58. # RS485 ioctls
  59. TIOCGRS485 = 0x542E
  60. TIOCSRS485 = 0x542F
  61. SER_RS485_ENABLED = 0b00000001
  62. SER_RS485_RTS_ON_SEND = 0b00000010
  63. SER_RS485_RTS_AFTER_SEND = 0b00000100
  64. SER_RS485_RX_DURING_TX = 0b00010000
  65. class PlatformSpecific(PlatformSpecificBase):
  66. BAUDRATE_CONSTANTS = {
  67. 0: 0o000000, # hang up
  68. 50: 0o000001,
  69. 75: 0o000002,
  70. 110: 0o000003,
  71. 134: 0o000004,
  72. 150: 0o000005,
  73. 200: 0o000006,
  74. 300: 0o000007,
  75. 600: 0o000010,
  76. 1200: 0o000011,
  77. 1800: 0o000012,
  78. 2400: 0o000013,
  79. 4800: 0o000014,
  80. 9600: 0o000015,
  81. 19200: 0o000016,
  82. 38400: 0o000017,
  83. 57600: 0o010001,
  84. 115200: 0o010002,
  85. 230400: 0o010003,
  86. 460800: 0o010004,
  87. 500000: 0o010005,
  88. 576000: 0o010006,
  89. 921600: 0o010007,
  90. 1000000: 0o010010,
  91. 1152000: 0o010011,
  92. 1500000: 0o010012,
  93. 2000000: 0o010013,
  94. 2500000: 0o010014,
  95. 3000000: 0o010015,
  96. 3500000: 0o010016,
  97. 4000000: 0o010017
  98. }
  99. def _set_special_baudrate(self, baudrate):
  100. # right size is 44 on x86_64, allow for some growth
  101. buf = array.array('i', [0] * 64)
  102. try:
  103. # get serial_struct
  104. fcntl.ioctl(self.fd, TCGETS2, buf)
  105. # set custom speed
  106. buf[2] &= ~termios.CBAUD
  107. buf[2] |= BOTHER
  108. buf[9] = buf[10] = baudrate
  109. # set serial_struct
  110. fcntl.ioctl(self.fd, TCSETS2, buf)
  111. except IOError as e:
  112. raise ValueError('Failed to set custom baud rate ({}): {}'.format(baudrate, e))
  113. def _set_rs485_mode(self, rs485_settings):
  114. buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
  115. try:
  116. fcntl.ioctl(self.fd, TIOCGRS485, buf)
  117. buf[0] |= SER_RS485_ENABLED
  118. if rs485_settings is not None:
  119. if rs485_settings.loopback:
  120. buf[0] |= SER_RS485_RX_DURING_TX
  121. else:
  122. buf[0] &= ~SER_RS485_RX_DURING_TX
  123. if rs485_settings.rts_level_for_tx:
  124. buf[0] |= SER_RS485_RTS_ON_SEND
  125. else:
  126. buf[0] &= ~SER_RS485_RTS_ON_SEND
  127. if rs485_settings.rts_level_for_rx:
  128. buf[0] |= SER_RS485_RTS_AFTER_SEND
  129. else:
  130. buf[0] &= ~SER_RS485_RTS_AFTER_SEND
  131. if rs485_settings.delay_before_tx is not None:
  132. buf[1] = int(rs485_settings.delay_before_tx * 1000)
  133. if rs485_settings.delay_before_rx is not None:
  134. buf[2] = int(rs485_settings.delay_before_rx * 1000)
  135. else:
  136. buf[0] = 0 # clear SER_RS485_ENABLED
  137. fcntl.ioctl(self.fd, TIOCSRS485, buf)
  138. except IOError as e:
  139. raise ValueError('Failed to set RS485 mode: {}'.format(e))
  140. elif plat == 'cygwin': # cygwin/win32 (confirmed)
  141. class PlatformSpecific(PlatformSpecificBase):
  142. BAUDRATE_CONSTANTS = {
  143. 128000: 0x01003,
  144. 256000: 0x01005,
  145. 500000: 0x01007,
  146. 576000: 0x01008,
  147. 921600: 0x01009,
  148. 1000000: 0x0100a,
  149. 1152000: 0x0100b,
  150. 1500000: 0x0100c,
  151. 2000000: 0x0100d,
  152. 2500000: 0x0100e,
  153. 3000000: 0x0100f
  154. }
  155. elif plat[:6] == 'darwin': # OS X
  156. import array
  157. IOSSIOSPEED = 0x80045402 # _IOW('T', 2, speed_t)
  158. class PlatformSpecific(PlatformSpecificBase):
  159. osx_version = os.uname()[2].split('.')
  160. # Tiger or above can support arbitrary serial speeds
  161. if int(osx_version[0]) >= 8:
  162. def _set_special_baudrate(self, baudrate):
  163. # use IOKit-specific call to set up high speeds
  164. buf = array.array('i', [baudrate])
  165. fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
  166. elif plat[:3] == 'bsd' or \
  167. plat[:7] == 'freebsd' or \
  168. plat[:6] == 'netbsd' or \
  169. plat[:7] == 'openbsd':
  170. class ReturnBaudrate(object):
  171. def __getitem__(self, key):
  172. return key
  173. class PlatformSpecific(PlatformSpecificBase):
  174. # Only tested on FreeBSD:
  175. # The baud rate may be passed in as
  176. # a literal value.
  177. BAUDRATE_CONSTANTS = ReturnBaudrate()
  178. else:
  179. class PlatformSpecific(PlatformSpecificBase):
  180. pass
  181. # load some constants for later use.
  182. # try to use values from termios, use defaults from linux otherwise
  183. TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415)
  184. TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416)
  185. TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417)
  186. TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418)
  187. # TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
  188. TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
  189. TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
  190. # TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008)
  191. # TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010)
  192. TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020)
  193. TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040)
  194. TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080)
  195. TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100)
  196. TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR)
  197. TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG)
  198. # TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000)
  199. # TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000)
  200. if hasattr(termios, 'TIOCINQ'):
  201. TIOCINQ = termios.TIOCINQ
  202. else:
  203. TIOCINQ = getattr(termios, 'FIONREAD', 0x541B)
  204. TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411)
  205. TIOCM_zero_str = struct.pack('I', 0)
  206. TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
  207. TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
  208. TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
  209. TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
  210. class Serial(SerialBase, PlatformSpecific):
  211. """\
  212. Serial port class POSIX implementation. Serial port configuration is
  213. done with termios and fcntl. Runs on Linux and many other Un*x like
  214. systems.
  215. """
  216. def open(self):
  217. """\
  218. Open port with current settings. This may throw a SerialException
  219. if the port cannot be opened."""
  220. if self._port is None:
  221. raise SerialException("Port must be configured before it can be used.")
  222. if self.is_open:
  223. raise SerialException("Port is already open.")
  224. self.fd = None
  225. # open
  226. try:
  227. self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
  228. except OSError as msg:
  229. self.fd = None
  230. raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
  231. #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
  232. try:
  233. self._reconfigure_port(force_update=True)
  234. except:
  235. try:
  236. os.close(self.fd)
  237. except:
  238. # ignore any exception when closing the port
  239. # also to keep original exception that happened when setting up
  240. pass
  241. self.fd = None
  242. raise
  243. else:
  244. self.is_open = True
  245. try:
  246. if not self._dsrdtr:
  247. self._update_dtr_state()
  248. if not self._rtscts:
  249. self._update_rts_state()
  250. except IOError as e:
  251. if e.errno in (errno.EINVAL, errno.ENOTTY):
  252. # ignore Invalid argument and Inappropriate ioctl
  253. pass
  254. else:
  255. raise
  256. self.reset_input_buffer()
  257. self.pipe_abort_read_r, self.pipe_abort_read_w = os.pipe()
  258. self.pipe_abort_write_r, self.pipe_abort_write_w = os.pipe()
  259. fcntl.fcntl(self.pipe_abort_read_r, fcntl.F_SETFL, os.O_NONBLOCK)
  260. fcntl.fcntl(self.pipe_abort_write_r, fcntl.F_SETFL, os.O_NONBLOCK)
  261. def _reconfigure_port(self, force_update=False):
  262. """Set communication parameters on opened port."""
  263. if self.fd is None:
  264. raise SerialException("Can only operate on a valid file descriptor")
  265. custom_baud = None
  266. vmin = vtime = 0 # timeout is done via select
  267. if self._inter_byte_timeout is not None:
  268. vmin = 1
  269. vtime = int(self._inter_byte_timeout * 10)
  270. try:
  271. orig_attr = termios.tcgetattr(self.fd)
  272. iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
  273. except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
  274. raise SerialException("Could not configure port: {}".format(msg))
  275. # set up raw mode / no echo / binary
  276. cflag |= (termios.CLOCAL | termios.CREAD)
  277. lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
  278. termios.ECHOK | termios.ECHONL |
  279. termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
  280. for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
  281. if hasattr(termios, flag):
  282. lflag &= ~getattr(termios, flag)
  283. oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
  284. iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
  285. if hasattr(termios, 'IUCLC'):
  286. iflag &= ~termios.IUCLC
  287. if hasattr(termios, 'PARMRK'):
  288. iflag &= ~termios.PARMRK
  289. # setup baud rate
  290. try:
  291. ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
  292. except AttributeError:
  293. try:
  294. ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
  295. except KeyError:
  296. #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
  297. # may need custom baud rate, it isn't in our list.
  298. ispeed = ospeed = getattr(termios, 'B38400')
  299. try:
  300. custom_baud = int(self._baudrate) # store for later
  301. except ValueError:
  302. raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
  303. else:
  304. if custom_baud < 0:
  305. raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
  306. # setup char len
  307. cflag &= ~termios.CSIZE
  308. if self._bytesize == 8:
  309. cflag |= termios.CS8
  310. elif self._bytesize == 7:
  311. cflag |= termios.CS7
  312. elif self._bytesize == 6:
  313. cflag |= termios.CS6
  314. elif self._bytesize == 5:
  315. cflag |= termios.CS5
  316. else:
  317. raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
  318. # setup stop bits
  319. if self._stopbits == serial.STOPBITS_ONE:
  320. cflag &= ~(termios.CSTOPB)
  321. elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
  322. cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
  323. elif self._stopbits == serial.STOPBITS_TWO:
  324. cflag |= (termios.CSTOPB)
  325. else:
  326. raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
  327. # setup parity
  328. iflag &= ~(termios.INPCK | termios.ISTRIP)
  329. if self._parity == serial.PARITY_NONE:
  330. cflag &= ~(termios.PARENB | termios.PARODD | CMSPAR)
  331. elif self._parity == serial.PARITY_EVEN:
  332. cflag &= ~(termios.PARODD | CMSPAR)
  333. cflag |= (termios.PARENB)
  334. elif self._parity == serial.PARITY_ODD:
  335. cflag &= ~CMSPAR
  336. cflag |= (termios.PARENB | termios.PARODD)
  337. elif self._parity == serial.PARITY_MARK and CMSPAR:
  338. cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
  339. elif self._parity == serial.PARITY_SPACE and CMSPAR:
  340. cflag |= (termios.PARENB | CMSPAR)
  341. cflag &= ~(termios.PARODD)
  342. else:
  343. raise ValueError('Invalid parity: {!r}'.format(self._parity))
  344. # setup flow control
  345. # xonxoff
  346. if hasattr(termios, 'IXANY'):
  347. if self._xonxoff:
  348. iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
  349. else:
  350. iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
  351. else:
  352. if self._xonxoff:
  353. iflag |= (termios.IXON | termios.IXOFF)
  354. else:
  355. iflag &= ~(termios.IXON | termios.IXOFF)
  356. # rtscts
  357. if hasattr(termios, 'CRTSCTS'):
  358. if self._rtscts:
  359. cflag |= (termios.CRTSCTS)
  360. else:
  361. cflag &= ~(termios.CRTSCTS)
  362. elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
  363. if self._rtscts:
  364. cflag |= (termios.CNEW_RTSCTS)
  365. else:
  366. cflag &= ~(termios.CNEW_RTSCTS)
  367. # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
  368. # buffer
  369. # vmin "minimal number of characters to be read. 0 for non blocking"
  370. if vmin < 0 or vmin > 255:
  371. raise ValueError('Invalid vmin: {!r}'.format(vmin))
  372. cc[termios.VMIN] = vmin
  373. # vtime
  374. if vtime < 0 or vtime > 255:
  375. raise ValueError('Invalid vtime: {!r}'.format(vtime))
  376. cc[termios.VTIME] = vtime
  377. # activate settings
  378. if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
  379. termios.tcsetattr(
  380. self.fd,
  381. termios.TCSANOW,
  382. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  383. # apply custom baud rate, if any
  384. if custom_baud is not None:
  385. self._set_special_baudrate(custom_baud)
  386. if self._rs485_mode is not None:
  387. self._set_rs485_mode(self._rs485_mode)
  388. def close(self):
  389. """Close port"""
  390. if self.is_open:
  391. if self.fd is not None:
  392. os.close(self.fd)
  393. self.fd = None
  394. os.close(self.pipe_abort_read_w)
  395. os.close(self.pipe_abort_read_r)
  396. os.close(self.pipe_abort_write_w)
  397. os.close(self.pipe_abort_write_r)
  398. self.pipe_abort_read_r, self.pipe_abort_read_w = None, None
  399. self.pipe_abort_write_r, self.pipe_abort_write_w = None, None
  400. self.is_open = False
  401. # - - - - - - - - - - - - - - - - - - - - - - - -
  402. @property
  403. def in_waiting(self):
  404. """Return the number of bytes currently in the input buffer."""
  405. #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
  406. s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
  407. return struct.unpack('I', s)[0]
  408. # select based implementation, proved to work on many systems
  409. def read(self, size=1):
  410. """\
  411. Read size bytes from the serial port. If a timeout is set it may
  412. return less characters as requested. With no timeout it will block
  413. until the requested number of bytes is read.
  414. """
  415. if not self.is_open:
  416. raise portNotOpenError
  417. read = bytearray()
  418. timeout = Timeout(self._timeout)
  419. while len(read) < size:
  420. try:
  421. ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout.time_left())
  422. if self.pipe_abort_read_r in ready:
  423. os.read(self.pipe_abort_read_r, 1000)
  424. break
  425. # If select was used with a timeout, and the timeout occurs, it
  426. # returns with empty lists -> thus abort read operation.
  427. # For timeout == 0 (non-blocking operation) also abort when
  428. # there is nothing to read.
  429. if not ready:
  430. break # timeout
  431. buf = os.read(self.fd, size - len(read))
  432. # read should always return some data as select reported it was
  433. # ready to read when we get to this point.
  434. if not buf:
  435. # Disconnected devices, at least on Linux, show the
  436. # behavior that they are always ready to read immediately
  437. # but reading returns nothing.
  438. raise SerialException(
  439. 'device reports readiness to read but returned no data '
  440. '(device disconnected or multiple access on port?)')
  441. read.extend(buf)
  442. except OSError as e:
  443. # this is for Python 3.x where select.error is a subclass of
  444. # OSError ignore EAGAIN errors. all other errors are shown
  445. if e.errno != errno.EAGAIN and e.errno != errno.EINTR:
  446. raise SerialException('read failed: {}'.format(e))
  447. except select.error as e:
  448. # this is for Python 2.x
  449. # ignore EAGAIN errors. all other errors are shown
  450. # see also http://www.python.org/dev/peps/pep-3151/#select
  451. if e[0] != errno.EAGAIN:
  452. raise SerialException('read failed: {}'.format(e))
  453. if timeout.expired():
  454. break
  455. return bytes(read)
  456. def cancel_read(self):
  457. os.write(self.pipe_abort_read_w, b"x")
  458. def cancel_write(self):
  459. os.write(self.pipe_abort_write_w, b"x")
  460. def write(self, data):
  461. """Output the given byte string over the serial port."""
  462. if not self.is_open:
  463. raise portNotOpenError
  464. d = to_bytes(data)
  465. tx_len = len(d)
  466. timeout = Timeout(self._write_timeout)
  467. while tx_len > 0:
  468. try:
  469. n = os.write(self.fd, d)
  470. if timeout.is_non_blocking:
  471. # Zero timeout indicates non-blocking - simply return the
  472. # number of bytes of data actually written
  473. return n
  474. elif not timeout.is_infinite:
  475. # when timeout is set, use select to wait for being ready
  476. # with the time left as timeout
  477. if timeout.expired():
  478. raise writeTimeoutError
  479. abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left())
  480. if abort:
  481. os.read(self.pipe_abort_write_r, 1000)
  482. break
  483. if not ready:
  484. raise writeTimeoutError
  485. else:
  486. assert timeout.time_left() is None
  487. # wait for write operation
  488. abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
  489. if abort:
  490. os.read(self.pipe_abort_write_r, 1)
  491. break
  492. if not ready:
  493. raise SerialException('write failed (select)')
  494. d = d[n:]
  495. tx_len -= n
  496. except SerialException:
  497. raise
  498. except OSError as v:
  499. if v.errno != errno.EAGAIN:
  500. raise SerialException('write failed: {}'.format(v))
  501. # still calculate and check timeout
  502. if timeout.expired():
  503. raise writeTimeoutError
  504. return len(data)
  505. def flush(self):
  506. """\
  507. Flush of file like objects. In this case, wait until all data
  508. is written.
  509. """
  510. if not self.is_open:
  511. raise portNotOpenError
  512. termios.tcdrain(self.fd)
  513. def reset_input_buffer(self):
  514. """Clear input buffer, discarding all that is in the buffer."""
  515. if not self.is_open:
  516. raise portNotOpenError
  517. termios.tcflush(self.fd, termios.TCIFLUSH)
  518. def reset_output_buffer(self):
  519. """\
  520. Clear output buffer, aborting the current output and discarding all
  521. that is in the buffer.
  522. """
  523. if not self.is_open:
  524. raise portNotOpenError
  525. termios.tcflush(self.fd, termios.TCOFLUSH)
  526. def send_break(self, duration=0.25):
  527. """\
  528. Send break condition. Timed, returns to idle state after given
  529. duration.
  530. """
  531. if not self.is_open:
  532. raise portNotOpenError
  533. termios.tcsendbreak(self.fd, int(duration / 0.25))
  534. def _update_break_state(self):
  535. """\
  536. Set break: Controls TXD. When active, no transmitting is possible.
  537. """
  538. if self._break_state:
  539. fcntl.ioctl(self.fd, TIOCSBRK)
  540. else:
  541. fcntl.ioctl(self.fd, TIOCCBRK)
  542. def _update_rts_state(self):
  543. """Set terminal status line: Request To Send"""
  544. if self._rts_state:
  545. fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
  546. else:
  547. fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
  548. def _update_dtr_state(self):
  549. """Set terminal status line: Data Terminal Ready"""
  550. if self._dtr_state:
  551. fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
  552. else:
  553. fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
  554. @property
  555. def cts(self):
  556. """Read terminal status line: Clear To Send"""
  557. if not self.is_open:
  558. raise portNotOpenError
  559. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  560. return struct.unpack('I', s)[0] & TIOCM_CTS != 0
  561. @property
  562. def dsr(self):
  563. """Read terminal status line: Data Set Ready"""
  564. if not self.is_open:
  565. raise portNotOpenError
  566. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  567. return struct.unpack('I', s)[0] & TIOCM_DSR != 0
  568. @property
  569. def ri(self):
  570. """Read terminal status line: Ring Indicator"""
  571. if not self.is_open:
  572. raise portNotOpenError
  573. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  574. return struct.unpack('I', s)[0] & TIOCM_RI != 0
  575. @property
  576. def cd(self):
  577. """Read terminal status line: Carrier Detect"""
  578. if not self.is_open:
  579. raise portNotOpenError
  580. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  581. return struct.unpack('I', s)[0] & TIOCM_CD != 0
  582. # - - platform specific - - - -
  583. @property
  584. def out_waiting(self):
  585. """Return the number of bytes currently in the output buffer."""
  586. #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
  587. s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
  588. return struct.unpack('I', s)[0]
  589. def fileno(self):
  590. """\
  591. For easier use of the serial port instance with select.
  592. WARNING: this function is not portable to different platforms!
  593. """
  594. if not self.is_open:
  595. raise portNotOpenError
  596. return self.fd
  597. def set_input_flow_control(self, enable=True):
  598. """\
  599. Manually control flow - when software flow control is enabled.
  600. This will send XON (true) or XOFF (false) to the other device.
  601. WARNING: this function is not portable to different platforms!
  602. """
  603. if not self.is_open:
  604. raise portNotOpenError
  605. if enable:
  606. termios.tcflow(self.fd, termios.TCION)
  607. else:
  608. termios.tcflow(self.fd, termios.TCIOFF)
  609. def set_output_flow_control(self, enable=True):
  610. """\
  611. Manually control flow of outgoing data - when hardware or software flow
  612. control is enabled.
  613. WARNING: this function is not portable to different platforms!
  614. """
  615. if not self.is_open:
  616. raise portNotOpenError
  617. if enable:
  618. termios.tcflow(self.fd, termios.TCOON)
  619. else:
  620. termios.tcflow(self.fd, termios.TCOOFF)
  621. def nonblocking(self):
  622. """DEPRECATED - has no use"""
  623. import warnings
  624. warnings.warn("nonblocking() has no effect, already nonblocking", DeprecationWarning)
  625. class PosixPollSerial(Serial):
  626. """\
  627. Poll based read implementation. Not all systems support poll properly.
  628. However this one has better handling of errors, such as a device
  629. disconnecting while it's in use (e.g. USB-serial unplugged).
  630. """
  631. def read(self, size=1):
  632. """\
  633. Read size bytes from the serial port. If a timeout is set it may
  634. return less characters as requested. With no timeout it will block
  635. until the requested number of bytes is read.
  636. """
  637. if not self.is_open:
  638. raise portNotOpenError
  639. read = bytearray()
  640. poll = select.poll()
  641. poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
  642. if size > 0:
  643. while len(read) < size:
  644. # print "\tread(): size",size, "have", len(read) #debug
  645. # wait until device becomes ready to read (or something fails)
  646. for fd, event in poll.poll(self._timeout * 1000):
  647. if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
  648. raise SerialException('device reports error (poll)')
  649. # we don't care if it is select.POLLIN or timeout, that's
  650. # handled below
  651. buf = os.read(self.fd, size - len(read))
  652. read.extend(buf)
  653. if ((self._timeout is not None and self._timeout >= 0) or
  654. (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf:
  655. break # early abort on timeout
  656. return bytes(read)
  657. class VTIMESerial(Serial):
  658. """\
  659. Implement timeout using vtime of tty device instead of using select.
  660. This means that no inter character timeout can be specified and that
  661. the error handling is degraded.
  662. Overall timeout is disabled when inter-character timeout is used.
  663. """
  664. def _reconfigure_port(self, force_update=True):
  665. """Set communication parameters on opened port."""
  666. super(VTIMESerial, self)._reconfigure_port()
  667. fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
  668. if self._inter_byte_timeout is not None:
  669. vmin = 1
  670. vtime = int(self._inter_byte_timeout * 10)
  671. elif self._timeout is None:
  672. vmin = 1
  673. vtime = 0
  674. else:
  675. vmin = 0
  676. vtime = int(self._timeout * 10)
  677. try:
  678. orig_attr = termios.tcgetattr(self.fd)
  679. iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
  680. except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
  681. raise serial.SerialException("Could not configure port: {}".format(msg))
  682. if vtime < 0 or vtime > 255:
  683. raise ValueError('Invalid vtime: {!r}'.format(vtime))
  684. cc[termios.VTIME] = vtime
  685. cc[termios.VMIN] = vmin
  686. termios.tcsetattr(
  687. self.fd,
  688. termios.TCSANOW,
  689. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  690. def read(self, size=1):
  691. """\
  692. Read size bytes from the serial port. If a timeout is set it may
  693. return less characters as requested. With no timeout it will block
  694. until the requested number of bytes is read.
  695. """
  696. if not self.is_open:
  697. raise portNotOpenError
  698. read = bytearray()
  699. while len(read) < size:
  700. buf = os.read(self.fd, size - len(read))
  701. if not buf:
  702. break
  703. read.extend(buf)
  704. return bytes(read)
  705. # hack to make hasattr return false
  706. cancel_read = property()