serialposix.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. # if exclusive lock is requested, create it before we modify anything else
  266. if self._exclusive is not None:
  267. if self._exclusive:
  268. try:
  269. fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  270. except IOError as msg:
  271. raise SerialException(msg.errno, "Could not exclusively lock port {}: {}".format(self._port, msg))
  272. else:
  273. fcntl.flock(self.fd, fcntl.LOCK_UN)
  274. custom_baud = None
  275. vmin = vtime = 0 # timeout is done via select
  276. if self._inter_byte_timeout is not None:
  277. vmin = 1
  278. vtime = int(self._inter_byte_timeout * 10)
  279. try:
  280. orig_attr = termios.tcgetattr(self.fd)
  281. iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
  282. except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
  283. raise SerialException("Could not configure port: {}".format(msg))
  284. # set up raw mode / no echo / binary
  285. cflag |= (termios.CLOCAL | termios.CREAD)
  286. lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
  287. termios.ECHOK | termios.ECHONL |
  288. termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
  289. for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
  290. if hasattr(termios, flag):
  291. lflag &= ~getattr(termios, flag)
  292. oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
  293. iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
  294. if hasattr(termios, 'IUCLC'):
  295. iflag &= ~termios.IUCLC
  296. if hasattr(termios, 'PARMRK'):
  297. iflag &= ~termios.PARMRK
  298. # setup baud rate
  299. try:
  300. ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
  301. except AttributeError:
  302. try:
  303. ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
  304. except KeyError:
  305. #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
  306. # may need custom baud rate, it isn't in our list.
  307. ispeed = ospeed = getattr(termios, 'B38400')
  308. try:
  309. custom_baud = int(self._baudrate) # store for later
  310. except ValueError:
  311. raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
  312. else:
  313. if custom_baud < 0:
  314. raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
  315. # setup char len
  316. cflag &= ~termios.CSIZE
  317. if self._bytesize == 8:
  318. cflag |= termios.CS8
  319. elif self._bytesize == 7:
  320. cflag |= termios.CS7
  321. elif self._bytesize == 6:
  322. cflag |= termios.CS6
  323. elif self._bytesize == 5:
  324. cflag |= termios.CS5
  325. else:
  326. raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
  327. # setup stop bits
  328. if self._stopbits == serial.STOPBITS_ONE:
  329. cflag &= ~(termios.CSTOPB)
  330. elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
  331. cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
  332. elif self._stopbits == serial.STOPBITS_TWO:
  333. cflag |= (termios.CSTOPB)
  334. else:
  335. raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
  336. # setup parity
  337. iflag &= ~(termios.INPCK | termios.ISTRIP)
  338. if self._parity == serial.PARITY_NONE:
  339. cflag &= ~(termios.PARENB | termios.PARODD | CMSPAR)
  340. elif self._parity == serial.PARITY_EVEN:
  341. cflag &= ~(termios.PARODD | CMSPAR)
  342. cflag |= (termios.PARENB)
  343. elif self._parity == serial.PARITY_ODD:
  344. cflag &= ~CMSPAR
  345. cflag |= (termios.PARENB | termios.PARODD)
  346. elif self._parity == serial.PARITY_MARK and CMSPAR:
  347. cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
  348. elif self._parity == serial.PARITY_SPACE and CMSPAR:
  349. cflag |= (termios.PARENB | CMSPAR)
  350. cflag &= ~(termios.PARODD)
  351. else:
  352. raise ValueError('Invalid parity: {!r}'.format(self._parity))
  353. # setup flow control
  354. # xonxoff
  355. if hasattr(termios, 'IXANY'):
  356. if self._xonxoff:
  357. iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
  358. else:
  359. iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
  360. else:
  361. if self._xonxoff:
  362. iflag |= (termios.IXON | termios.IXOFF)
  363. else:
  364. iflag &= ~(termios.IXON | termios.IXOFF)
  365. # rtscts
  366. if hasattr(termios, 'CRTSCTS'):
  367. if self._rtscts:
  368. cflag |= (termios.CRTSCTS)
  369. else:
  370. cflag &= ~(termios.CRTSCTS)
  371. elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
  372. if self._rtscts:
  373. cflag |= (termios.CNEW_RTSCTS)
  374. else:
  375. cflag &= ~(termios.CNEW_RTSCTS)
  376. # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
  377. # buffer
  378. # vmin "minimal number of characters to be read. 0 for non blocking"
  379. if vmin < 0 or vmin > 255:
  380. raise ValueError('Invalid vmin: {!r}'.format(vmin))
  381. cc[termios.VMIN] = vmin
  382. # vtime
  383. if vtime < 0 or vtime > 255:
  384. raise ValueError('Invalid vtime: {!r}'.format(vtime))
  385. cc[termios.VTIME] = vtime
  386. # activate settings
  387. if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
  388. termios.tcsetattr(
  389. self.fd,
  390. termios.TCSANOW,
  391. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  392. # apply custom baud rate, if any
  393. if custom_baud is not None:
  394. self._set_special_baudrate(custom_baud)
  395. if self._rs485_mode is not None:
  396. self._set_rs485_mode(self._rs485_mode)
  397. def close(self):
  398. """Close port"""
  399. if self.is_open:
  400. if self.fd is not None:
  401. os.close(self.fd)
  402. self.fd = None
  403. os.close(self.pipe_abort_read_w)
  404. os.close(self.pipe_abort_read_r)
  405. os.close(self.pipe_abort_write_w)
  406. os.close(self.pipe_abort_write_r)
  407. self.pipe_abort_read_r, self.pipe_abort_read_w = None, None
  408. self.pipe_abort_write_r, self.pipe_abort_write_w = None, None
  409. self.is_open = False
  410. # - - - - - - - - - - - - - - - - - - - - - - - -
  411. @property
  412. def in_waiting(self):
  413. """Return the number of bytes currently in the input buffer."""
  414. #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
  415. s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
  416. return struct.unpack('I', s)[0]
  417. # select based implementation, proved to work on many systems
  418. def read(self, size=1):
  419. """\
  420. Read size bytes from the serial port. If a timeout is set it may
  421. return less characters as requested. With no timeout it will block
  422. until the requested number of bytes is read.
  423. """
  424. if not self.is_open:
  425. raise portNotOpenError
  426. read = bytearray()
  427. timeout = Timeout(self._timeout)
  428. while len(read) < size:
  429. try:
  430. ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout.time_left())
  431. if self.pipe_abort_read_r in ready:
  432. os.read(self.pipe_abort_read_r, 1000)
  433. break
  434. # If select was used with a timeout, and the timeout occurs, it
  435. # returns with empty lists -> thus abort read operation.
  436. # For timeout == 0 (non-blocking operation) also abort when
  437. # there is nothing to read.
  438. if not ready:
  439. break # timeout
  440. buf = os.read(self.fd, size - len(read))
  441. # read should always return some data as select reported it was
  442. # ready to read when we get to this point.
  443. if not buf:
  444. # Disconnected devices, at least on Linux, show the
  445. # behavior that they are always ready to read immediately
  446. # but reading returns nothing.
  447. raise SerialException(
  448. 'device reports readiness to read but returned no data '
  449. '(device disconnected or multiple access on port?)')
  450. read.extend(buf)
  451. except OSError as e:
  452. # this is for Python 3.x where select.error is a subclass of
  453. # OSError ignore BlockingIOErrors and EINTR. other errors are shown
  454. # https://www.python.org/dev/peps/pep-0475.
  455. if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
  456. raise SerialException('read failed: {}'.format(e))
  457. except select.error as e:
  458. # this is for Python 2.x
  459. # ignore BlockingIOErrors and EINTR. all errors are shown
  460. # see also http://www.python.org/dev/peps/pep-3151/#select
  461. if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
  462. raise SerialException('read failed: {}'.format(e))
  463. if timeout.expired():
  464. break
  465. return bytes(read)
  466. def cancel_read(self):
  467. if self.is_open:
  468. os.write(self.pipe_abort_read_w, b"x")
  469. def cancel_write(self):
  470. if self.is_open:
  471. os.write(self.pipe_abort_write_w, b"x")
  472. def write(self, data):
  473. """Output the given byte string over the serial port."""
  474. if not self.is_open:
  475. raise portNotOpenError
  476. d = to_bytes(data)
  477. tx_len = length = len(d)
  478. timeout = Timeout(self._write_timeout)
  479. while tx_len > 0:
  480. try:
  481. n = os.write(self.fd, d)
  482. if timeout.is_non_blocking:
  483. # Zero timeout indicates non-blocking - simply return the
  484. # number of bytes of data actually written
  485. return n
  486. elif not timeout.is_infinite:
  487. # when timeout is set, use select to wait for being ready
  488. # with the time left as timeout
  489. if timeout.expired():
  490. raise writeTimeoutError
  491. abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left())
  492. if abort:
  493. os.read(self.pipe_abort_write_r, 1000)
  494. break
  495. if not ready:
  496. raise writeTimeoutError
  497. else:
  498. assert timeout.time_left() is None
  499. # wait for write operation
  500. abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
  501. if abort:
  502. os.read(self.pipe_abort_write_r, 1)
  503. break
  504. if not ready:
  505. raise SerialException('write failed (select)')
  506. d = d[n:]
  507. tx_len -= n
  508. except SerialException:
  509. raise
  510. except OSError as e:
  511. # this is for Python 3.x where select.error is a subclass of
  512. # OSError ignore BlockingIOErrors and EINTR. other errors are shown
  513. # https://www.python.org/dev/peps/pep-0475.
  514. if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
  515. raise SerialException('write failed: {}'.format(e))
  516. except select.error as e:
  517. # this is for Python 2.x
  518. # ignore BlockingIOErrors and EINTR. all errors are shown
  519. # see also http://www.python.org/dev/peps/pep-3151/#select
  520. if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
  521. raise SerialException('write failed: {}'.format(e))
  522. if not timeout.is_non_blocking and timeout.expired():
  523. raise writeTimeoutError
  524. return length - len(d)
  525. def flush(self):
  526. """\
  527. Flush of file like objects. In this case, wait until all data
  528. is written.
  529. """
  530. if not self.is_open:
  531. raise portNotOpenError
  532. termios.tcdrain(self.fd)
  533. def reset_input_buffer(self):
  534. """Clear input buffer, discarding all that is in the buffer."""
  535. if not self.is_open:
  536. raise portNotOpenError
  537. termios.tcflush(self.fd, termios.TCIFLUSH)
  538. def reset_output_buffer(self):
  539. """\
  540. Clear output buffer, aborting the current output and discarding all
  541. that is in the buffer.
  542. """
  543. if not self.is_open:
  544. raise portNotOpenError
  545. termios.tcflush(self.fd, termios.TCOFLUSH)
  546. def send_break(self, duration=0.25):
  547. """\
  548. Send break condition. Timed, returns to idle state after given
  549. duration.
  550. """
  551. if not self.is_open:
  552. raise portNotOpenError
  553. termios.tcsendbreak(self.fd, int(duration / 0.25))
  554. def _update_break_state(self):
  555. """\
  556. Set break: Controls TXD. When active, no transmitting is possible.
  557. """
  558. if self._break_state:
  559. fcntl.ioctl(self.fd, TIOCSBRK)
  560. else:
  561. fcntl.ioctl(self.fd, TIOCCBRK)
  562. def _update_rts_state(self):
  563. """Set terminal status line: Request To Send"""
  564. if self._rts_state:
  565. fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
  566. else:
  567. fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
  568. def _update_dtr_state(self):
  569. """Set terminal status line: Data Terminal Ready"""
  570. if self._dtr_state:
  571. fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
  572. else:
  573. fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
  574. @property
  575. def cts(self):
  576. """Read terminal status line: Clear To Send"""
  577. if not self.is_open:
  578. raise portNotOpenError
  579. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  580. return struct.unpack('I', s)[0] & TIOCM_CTS != 0
  581. @property
  582. def dsr(self):
  583. """Read terminal status line: Data Set Ready"""
  584. if not self.is_open:
  585. raise portNotOpenError
  586. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  587. return struct.unpack('I', s)[0] & TIOCM_DSR != 0
  588. @property
  589. def ri(self):
  590. """Read terminal status line: Ring Indicator"""
  591. if not self.is_open:
  592. raise portNotOpenError
  593. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  594. return struct.unpack('I', s)[0] & TIOCM_RI != 0
  595. @property
  596. def cd(self):
  597. """Read terminal status line: Carrier Detect"""
  598. if not self.is_open:
  599. raise portNotOpenError
  600. s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
  601. return struct.unpack('I', s)[0] & TIOCM_CD != 0
  602. # - - platform specific - - - -
  603. @property
  604. def out_waiting(self):
  605. """Return the number of bytes currently in the output buffer."""
  606. #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
  607. s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
  608. return struct.unpack('I', s)[0]
  609. def fileno(self):
  610. """\
  611. For easier use of the serial port instance with select.
  612. WARNING: this function is not portable to different platforms!
  613. """
  614. if not self.is_open:
  615. raise portNotOpenError
  616. return self.fd
  617. def set_input_flow_control(self, enable=True):
  618. """\
  619. Manually control flow - when software flow control is enabled.
  620. This will send XON (true) or XOFF (false) to the other device.
  621. WARNING: this function is not portable to different platforms!
  622. """
  623. if not self.is_open:
  624. raise portNotOpenError
  625. if enable:
  626. termios.tcflow(self.fd, termios.TCION)
  627. else:
  628. termios.tcflow(self.fd, termios.TCIOFF)
  629. def set_output_flow_control(self, enable=True):
  630. """\
  631. Manually control flow of outgoing data - when hardware or software flow
  632. control is enabled.
  633. WARNING: this function is not portable to different platforms!
  634. """
  635. if not self.is_open:
  636. raise portNotOpenError
  637. if enable:
  638. termios.tcflow(self.fd, termios.TCOON)
  639. else:
  640. termios.tcflow(self.fd, termios.TCOOFF)
  641. def nonblocking(self):
  642. """DEPRECATED - has no use"""
  643. import warnings
  644. warnings.warn("nonblocking() has no effect, already nonblocking", DeprecationWarning)
  645. class PosixPollSerial(Serial):
  646. """\
  647. Poll based read implementation. Not all systems support poll properly.
  648. However this one has better handling of errors, such as a device
  649. disconnecting while it's in use (e.g. USB-serial unplugged).
  650. """
  651. def read(self, size=1):
  652. """\
  653. Read size bytes from the serial port. If a timeout is set it may
  654. return less characters as requested. With no timeout it will block
  655. until the requested number of bytes is read.
  656. """
  657. if not self.is_open:
  658. raise portNotOpenError
  659. read = bytearray()
  660. poll = select.poll()
  661. poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
  662. if size > 0:
  663. while len(read) < size:
  664. # print "\tread(): size",size, "have", len(read) #debug
  665. # wait until device becomes ready to read (or something fails)
  666. for fd, event in poll.poll(self._timeout * 1000):
  667. if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
  668. raise SerialException('device reports error (poll)')
  669. # we don't care if it is select.POLLIN or timeout, that's
  670. # handled below
  671. buf = os.read(self.fd, size - len(read))
  672. read.extend(buf)
  673. if ((self._timeout is not None and self._timeout >= 0) or
  674. (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf:
  675. break # early abort on timeout
  676. return bytes(read)
  677. class VTIMESerial(Serial):
  678. """\
  679. Implement timeout using vtime of tty device instead of using select.
  680. This means that no inter character timeout can be specified and that
  681. the error handling is degraded.
  682. Overall timeout is disabled when inter-character timeout is used.
  683. """
  684. def _reconfigure_port(self, force_update=True):
  685. """Set communication parameters on opened port."""
  686. super(VTIMESerial, self)._reconfigure_port()
  687. fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
  688. if self._inter_byte_timeout is not None:
  689. vmin = 1
  690. vtime = int(self._inter_byte_timeout * 10)
  691. elif self._timeout is None:
  692. vmin = 1
  693. vtime = 0
  694. else:
  695. vmin = 0
  696. vtime = int(self._timeout * 10)
  697. try:
  698. orig_attr = termios.tcgetattr(self.fd)
  699. iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
  700. except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
  701. raise serial.SerialException("Could not configure port: {}".format(msg))
  702. if vtime < 0 or vtime > 255:
  703. raise ValueError('Invalid vtime: {!r}'.format(vtime))
  704. cc[termios.VTIME] = vtime
  705. cc[termios.VMIN] = vmin
  706. termios.tcsetattr(
  707. self.fd,
  708. termios.TCSANOW,
  709. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  710. def read(self, size=1):
  711. """\
  712. Read size bytes from the serial port. If a timeout is set it may
  713. return less characters as requested. With no timeout it will block
  714. until the requested number of bytes is read.
  715. """
  716. if not self.is_open:
  717. raise portNotOpenError
  718. read = bytearray()
  719. while len(read) < size:
  720. buf = os.read(self.fd, size - len(read))
  721. if not buf:
  722. break
  723. read.extend(buf)
  724. return bytes(read)
  725. # hack to make hasattr return false
  726. cancel_read = property()