serialposix.py 29 KB

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