serialutil.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. #! python
  2. #
  3. # Base class and support functions used by various backends.
  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. import io
  10. import time
  11. # ``memoryview`` was introduced in Python 2.7 and ``bytes(some_memoryview)``
  12. # isn't returning the contents (very unfortunate). Therefore we need special
  13. # cases and test for it. Ensure that there is a ``memoryview`` object for older
  14. # Python versions. This is easier than making every test dependent on its
  15. # existence.
  16. try:
  17. memoryview
  18. except (NameError, AttributeError):
  19. # implementation does not matter as we do not really use it.
  20. # it just must not inherit from something else we might care for.
  21. class memoryview(object): # pylint: disable=redefined-builtin,invalid-name
  22. pass
  23. try:
  24. unicode
  25. except (NameError, AttributeError):
  26. unicode = str # for Python 3, pylint: disable=redefined-builtin,invalid-name
  27. try:
  28. basestring
  29. except (NameError, AttributeError):
  30. basestring = (str,) # for Python 3, pylint: disable=redefined-builtin,invalid-name
  31. # "for byte in data" fails for python3 as it returns ints instead of bytes
  32. def iterbytes(b):
  33. """Iterate over bytes, returning bytes instead of ints (python3)"""
  34. if isinstance(b, memoryview):
  35. b = b.tobytes()
  36. i = 0
  37. while True:
  38. a = b[i:i + 1]
  39. i += 1
  40. if a:
  41. yield a
  42. else:
  43. break
  44. # all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11'
  45. # so a simple ``bytes(sequence)`` doesn't work for all versions
  46. def to_bytes(seq):
  47. """convert a sequence to a bytes type"""
  48. if isinstance(seq, bytes):
  49. return seq
  50. elif isinstance(seq, bytearray):
  51. return bytes(seq)
  52. elif isinstance(seq, memoryview):
  53. return seq.tobytes()
  54. elif isinstance(seq, unicode):
  55. raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
  56. else:
  57. # handle list of integers and bytes (one or more items) for Python 2 and 3
  58. return bytes(bytearray(seq))
  59. # create control bytes
  60. XON = to_bytes([17])
  61. XOFF = to_bytes([19])
  62. CR = to_bytes([13])
  63. LF = to_bytes([10])
  64. PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
  65. STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
  66. FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
  67. PARITY_NAMES = {
  68. PARITY_NONE: 'None',
  69. PARITY_EVEN: 'Even',
  70. PARITY_ODD: 'Odd',
  71. PARITY_MARK: 'Mark',
  72. PARITY_SPACE: 'Space',
  73. }
  74. class SerialException(IOError):
  75. """Base class for serial port related exceptions."""
  76. class SerialTimeoutException(SerialException):
  77. """Write timeouts give an exception"""
  78. writeTimeoutError = SerialTimeoutException('Write timeout')
  79. portNotOpenError = SerialException('Attempting to use a port that is not open')
  80. class Timeout(object):
  81. """\
  82. Abstraction for timeout operations. Using time.monotonic() if available
  83. or time.time() in all other cases.
  84. The class can also be initialized with 0 or None, in order to support
  85. non-blocking and fully blocking I/O operations. The attributes
  86. is_non_blocking and is_infinite are set accordingly.
  87. """
  88. if hasattr(time, 'monotonic'):
  89. # Timeout implementation with time.monotonic(). This function is only
  90. # supported by Python 3.3 and above. It returns a time in seconds
  91. # (float) just as time.time(), but is not affected by system clock
  92. # adjustments.
  93. TIME = time.monotonic
  94. else:
  95. # Timeout implementation with time.time(). This is compatible with all
  96. # Python versions but has issues if the clock is adjusted while the
  97. # timeout is running.
  98. TIME = time.time
  99. def __init__(self, duration):
  100. """Initialize a timeout with given duration"""
  101. self.is_infinite = (duration is None)
  102. self.is_non_blocking = (duration == 0)
  103. self.duration = duration
  104. if duration is not None:
  105. self.target_time = self.TIME() + duration
  106. else:
  107. self.target_time = None
  108. def expired(self):
  109. """Return a boolean, telling if the timeout has expired"""
  110. return self.target_time is not None and self.time_left() <= 0
  111. def time_left(self):
  112. """Return how many seconds are left until the timeout expires"""
  113. if self.is_non_blocking:
  114. return 0
  115. elif self.is_infinite:
  116. return None
  117. else:
  118. delta = self.target_time - self.TIME()
  119. if delta > self.duration:
  120. # clock jumped, recalculate
  121. self.target_time = self.TIME() + self.duration
  122. return self.duration
  123. else:
  124. return max(0, delta)
  125. def restart(self, duration):
  126. """\
  127. Restart a timeout, only supported if a timeout was already set up
  128. before.
  129. """
  130. self.duration = duration
  131. self.target_time = self.TIME() + duration
  132. class SerialBase(io.RawIOBase):
  133. """\
  134. Serial port base class. Provides __init__ function and properties to
  135. get/set port settings.
  136. """
  137. # default values, may be overridden in subclasses that do not support all values
  138. BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
  139. 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
  140. 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
  141. 3000000, 3500000, 4000000)
  142. BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
  143. PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
  144. STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
  145. def __init__(self,
  146. port=None,
  147. baudrate=9600,
  148. bytesize=EIGHTBITS,
  149. parity=PARITY_NONE,
  150. stopbits=STOPBITS_ONE,
  151. timeout=None,
  152. xonxoff=False,
  153. rtscts=False,
  154. write_timeout=None,
  155. dsrdtr=False,
  156. inter_byte_timeout=None,
  157. exclusive=None,
  158. **kwargs):
  159. """\
  160. Initialize comm port object. If a "port" is given, then the port will be
  161. opened immediately. Otherwise a Serial port object in closed state
  162. is returned.
  163. """
  164. self.is_open = False
  165. self.portstr = None
  166. self.name = None
  167. # correct values are assigned below through properties
  168. self._port = None
  169. self._baudrate = None
  170. self._bytesize = None
  171. self._parity = None
  172. self._stopbits = None
  173. self._timeout = None
  174. self._write_timeout = None
  175. self._xonxoff = None
  176. self._rtscts = None
  177. self._dsrdtr = None
  178. self._inter_byte_timeout = None
  179. self._rs485_mode = None # disabled by default
  180. self._rts_state = True
  181. self._dtr_state = True
  182. self._break_state = False
  183. self._exclusive = None
  184. # assign values using get/set methods using the properties feature
  185. self.port = port
  186. self.baudrate = baudrate
  187. self.bytesize = bytesize
  188. self.parity = parity
  189. self.stopbits = stopbits
  190. self.timeout = timeout
  191. self.write_timeout = write_timeout
  192. self.xonxoff = xonxoff
  193. self.rtscts = rtscts
  194. self.dsrdtr = dsrdtr
  195. self.inter_byte_timeout = inter_byte_timeout
  196. self.exclusive = exclusive
  197. # watch for backward compatible kwargs
  198. if 'writeTimeout' in kwargs:
  199. self.write_timeout = kwargs.pop('writeTimeout')
  200. if 'interCharTimeout' in kwargs:
  201. self.inter_byte_timeout = kwargs.pop('interCharTimeout')
  202. if kwargs:
  203. raise ValueError('unexpected keyword arguments: {!r}'.format(kwargs))
  204. if port is not None:
  205. self.open()
  206. # - - - - - - - - - - - - - - - - - - - - - - - -
  207. # to be implemented by subclasses:
  208. # def open(self):
  209. # def close(self):
  210. # - - - - - - - - - - - - - - - - - - - - - - - -
  211. @property
  212. def port(self):
  213. """\
  214. Get the current port setting. The value that was passed on init or using
  215. setPort() is passed back.
  216. """
  217. return self._port
  218. @port.setter
  219. def port(self, port):
  220. """\
  221. Change the port.
  222. """
  223. if port is not None and not isinstance(port, basestring):
  224. raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
  225. was_open = self.is_open
  226. if was_open:
  227. self.close()
  228. self.portstr = port
  229. self._port = port
  230. self.name = self.portstr
  231. if was_open:
  232. self.open()
  233. @property
  234. def baudrate(self):
  235. """Get the current baud rate setting."""
  236. return self._baudrate
  237. @baudrate.setter
  238. def baudrate(self, baudrate):
  239. """\
  240. Change baud rate. It raises a ValueError if the port is open and the
  241. baud rate is not possible. If the port is closed, then the value is
  242. accepted and the exception is raised when the port is opened.
  243. """
  244. try:
  245. b = int(baudrate)
  246. except TypeError:
  247. raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
  248. else:
  249. if b < 0:
  250. raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
  251. self._baudrate = b
  252. if self.is_open:
  253. self._reconfigure_port()
  254. @property
  255. def bytesize(self):
  256. """Get the current byte size setting."""
  257. return self._bytesize
  258. @bytesize.setter
  259. def bytesize(self, bytesize):
  260. """Change byte size."""
  261. if bytesize not in self.BYTESIZES:
  262. raise ValueError("Not a valid byte size: {!r}".format(bytesize))
  263. self._bytesize = bytesize
  264. if self.is_open:
  265. self._reconfigure_port()
  266. @property
  267. def exclusive(self):
  268. """Get the current exclusive access setting."""
  269. return self._exclusive
  270. @exclusive.setter
  271. def exclusive(self, exclusive):
  272. """Change the exclusive access setting."""
  273. self._exclusive = exclusive
  274. if self.is_open:
  275. self._reconfigure_port()
  276. @property
  277. def parity(self):
  278. """Get the current parity setting."""
  279. return self._parity
  280. @parity.setter
  281. def parity(self, parity):
  282. """Change parity setting."""
  283. if parity not in self.PARITIES:
  284. raise ValueError("Not a valid parity: {!r}".format(parity))
  285. self._parity = parity
  286. if self.is_open:
  287. self._reconfigure_port()
  288. @property
  289. def stopbits(self):
  290. """Get the current stop bits setting."""
  291. return self._stopbits
  292. @stopbits.setter
  293. def stopbits(self, stopbits):
  294. """Change stop bits size."""
  295. if stopbits not in self.STOPBITS:
  296. raise ValueError("Not a valid stop bit size: {!r}".format(stopbits))
  297. self._stopbits = stopbits
  298. if self.is_open:
  299. self._reconfigure_port()
  300. @property
  301. def timeout(self):
  302. """Get the current timeout setting."""
  303. return self._timeout
  304. @timeout.setter
  305. def timeout(self, timeout):
  306. """Change timeout setting."""
  307. if timeout is not None:
  308. try:
  309. timeout + 1 # test if it's a number, will throw a TypeError if not...
  310. except TypeError:
  311. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  312. if timeout < 0:
  313. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  314. self._timeout = timeout
  315. if self.is_open:
  316. self._reconfigure_port()
  317. @property
  318. def write_timeout(self):
  319. """Get the current timeout setting."""
  320. return self._write_timeout
  321. @write_timeout.setter
  322. def write_timeout(self, timeout):
  323. """Change timeout setting."""
  324. if timeout is not None:
  325. if timeout < 0:
  326. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  327. try:
  328. timeout + 1 # test if it's a number, will throw a TypeError if not...
  329. except TypeError:
  330. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  331. self._write_timeout = timeout
  332. if self.is_open:
  333. self._reconfigure_port()
  334. @property
  335. def inter_byte_timeout(self):
  336. """Get the current inter-character timeout setting."""
  337. return self._inter_byte_timeout
  338. @inter_byte_timeout.setter
  339. def inter_byte_timeout(self, ic_timeout):
  340. """Change inter-byte timeout setting."""
  341. if ic_timeout is not None:
  342. if ic_timeout < 0:
  343. raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
  344. try:
  345. ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
  346. except TypeError:
  347. raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
  348. self._inter_byte_timeout = ic_timeout
  349. if self.is_open:
  350. self._reconfigure_port()
  351. @property
  352. def xonxoff(self):
  353. """Get the current XON/XOFF setting."""
  354. return self._xonxoff
  355. @xonxoff.setter
  356. def xonxoff(self, xonxoff):
  357. """Change XON/XOFF setting."""
  358. self._xonxoff = xonxoff
  359. if self.is_open:
  360. self._reconfigure_port()
  361. @property
  362. def rtscts(self):
  363. """Get the current RTS/CTS flow control setting."""
  364. return self._rtscts
  365. @rtscts.setter
  366. def rtscts(self, rtscts):
  367. """Change RTS/CTS flow control setting."""
  368. self._rtscts = rtscts
  369. if self.is_open:
  370. self._reconfigure_port()
  371. @property
  372. def dsrdtr(self):
  373. """Get the current DSR/DTR flow control setting."""
  374. return self._dsrdtr
  375. @dsrdtr.setter
  376. def dsrdtr(self, dsrdtr=None):
  377. """Change DsrDtr flow control setting."""
  378. if dsrdtr is None:
  379. # if not set, keep backwards compatibility and follow rtscts setting
  380. self._dsrdtr = self._rtscts
  381. else:
  382. # if defined independently, follow its value
  383. self._dsrdtr = dsrdtr
  384. if self.is_open:
  385. self._reconfigure_port()
  386. @property
  387. def rts(self):
  388. return self._rts_state
  389. @rts.setter
  390. def rts(self, value):
  391. self._rts_state = value
  392. if self.is_open:
  393. self._update_rts_state()
  394. @property
  395. def dtr(self):
  396. return self._dtr_state
  397. @dtr.setter
  398. def dtr(self, value):
  399. self._dtr_state = value
  400. if self.is_open:
  401. self._update_dtr_state()
  402. @property
  403. def break_condition(self):
  404. return self._break_state
  405. @break_condition.setter
  406. def break_condition(self, value):
  407. self._break_state = value
  408. if self.is_open:
  409. self._update_break_state()
  410. # - - - - - - - - - - - - - - - - - - - - - - - -
  411. # functions useful for RS-485 adapters
  412. @property
  413. def rs485_mode(self):
  414. """\
  415. Enable RS485 mode and apply new settings, set to None to disable.
  416. See serial.rs485.RS485Settings for more info about the value.
  417. """
  418. return self._rs485_mode
  419. @rs485_mode.setter
  420. def rs485_mode(self, rs485_settings):
  421. self._rs485_mode = rs485_settings
  422. if self.is_open:
  423. self._reconfigure_port()
  424. # - - - - - - - - - - - - - - - - - - - - - - - -
  425. _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
  426. 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
  427. 'inter_byte_timeout')
  428. def get_settings(self):
  429. """\
  430. Get current port settings as a dictionary. For use with
  431. apply_settings().
  432. """
  433. return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
  434. def apply_settings(self, d):
  435. """\
  436. Apply stored settings from a dictionary returned from
  437. get_settings(). It's allowed to delete keys from the dictionary. These
  438. values will simply left unchanged.
  439. """
  440. for key in self._SAVED_SETTINGS:
  441. if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
  442. setattr(self, key, d[key]) # set non "_" value to use properties write function
  443. # - - - - - - - - - - - - - - - - - - - - - - - -
  444. def __repr__(self):
  445. """String representation of the current port settings and its state."""
  446. return '{name}<id=0x{id:x}, open={p.is_open}>(port={p.portstr!r}, ' \
  447. 'baudrate={p.baudrate!r}, bytesize={p.bytesize!r}, parity={p.parity!r}, ' \
  448. 'stopbits={p.stopbits!r}, timeout={p.timeout!r}, xonxoff={p.xonxoff!r}, ' \
  449. 'rtscts={p.rtscts!r}, dsrdtr={p.dsrdtr!r})'.format(
  450. name=self.__class__.__name__, id=id(self), p=self)
  451. # - - - - - - - - - - - - - - - - - - - - - - - -
  452. # compatibility with io library
  453. # pylint: disable=invalid-name,missing-docstring
  454. def readable(self):
  455. return True
  456. def writable(self):
  457. return True
  458. def seekable(self):
  459. return False
  460. def readinto(self, b):
  461. data = self.read(len(b))
  462. n = len(data)
  463. try:
  464. b[:n] = data
  465. except TypeError as err:
  466. import array
  467. if not isinstance(b, array.array):
  468. raise err
  469. b[:n] = array.array('b', data)
  470. return n
  471. # - - - - - - - - - - - - - - - - - - - - - - - -
  472. # context manager
  473. def __enter__(self):
  474. if not self.is_open:
  475. self.open()
  476. return self
  477. def __exit__(self, *args, **kwargs):
  478. self.close()
  479. # - - - - - - - - - - - - - - - - - - - - - - - -
  480. def send_break(self, duration=0.25):
  481. """\
  482. Send break condition. Timed, returns to idle state after given
  483. duration.
  484. """
  485. if not self.is_open:
  486. raise portNotOpenError
  487. self.break_condition = True
  488. time.sleep(duration)
  489. self.break_condition = False
  490. # - - - - - - - - - - - - - - - - - - - - - - - -
  491. # backwards compatibility / deprecated functions
  492. def flushInput(self):
  493. self.reset_input_buffer()
  494. def flushOutput(self):
  495. self.reset_output_buffer()
  496. def inWaiting(self):
  497. return self.in_waiting
  498. def sendBreak(self, duration=0.25):
  499. self.send_break(duration)
  500. def setRTS(self, value=1):
  501. self.rts = value
  502. def setDTR(self, value=1):
  503. self.dtr = value
  504. def getCTS(self):
  505. return self.cts
  506. def getDSR(self):
  507. return self.dsr
  508. def getRI(self):
  509. return self.ri
  510. def getCD(self):
  511. return self.cd
  512. def setPort(self, port):
  513. self.port = port
  514. @property
  515. def writeTimeout(self):
  516. return self.write_timeout
  517. @writeTimeout.setter
  518. def writeTimeout(self, timeout):
  519. self.write_timeout = timeout
  520. @property
  521. def interCharTimeout(self):
  522. return self.inter_byte_timeout
  523. @interCharTimeout.setter
  524. def interCharTimeout(self, interCharTimeout):
  525. self.inter_byte_timeout = interCharTimeout
  526. def getSettingsDict(self):
  527. return self.get_settings()
  528. def applySettingsDict(self, d):
  529. self.apply_settings(d)
  530. def isOpen(self):
  531. return self.is_open
  532. # - - - - - - - - - - - - - - - - - - - - - - - -
  533. # additional functionality
  534. def read_all(self):
  535. """\
  536. Read all bytes currently available in the buffer of the OS.
  537. """
  538. return self.read(self.in_waiting)
  539. def read_until(self, terminator=LF, size=None):
  540. """\
  541. Read until a termination sequence is found ('\n' by default), the size
  542. is exceeded or until timeout occurs.
  543. """
  544. lenterm = len(terminator)
  545. line = bytearray()
  546. timeout = Timeout(self._timeout)
  547. while True:
  548. c = self.read(1)
  549. if c:
  550. line += c
  551. if line[-lenterm:] == terminator:
  552. break
  553. if size is not None and len(line) >= size:
  554. break
  555. else:
  556. break
  557. if timeout.expired():
  558. break
  559. return bytes(line)
  560. def iread_until(self, *args, **kwargs):
  561. """\
  562. Read lines, implemented as generator. It will raise StopIteration on
  563. timeout (empty read).
  564. """
  565. while True:
  566. line = self.read_until(*args, **kwargs)
  567. if not line:
  568. break
  569. yield line
  570. # - - - - - - - - - - - - - - - - - - - - - - - - -
  571. if __name__ == '__main__':
  572. import sys
  573. s = SerialBase()
  574. sys.stdout.write('port name: {}\n'.format(s.name))
  575. sys.stdout.write('baud rates: {}\n'.format(s.BAUDRATES))
  576. sys.stdout.write('byte sizes: {}\n'.format(s.BYTESIZES))
  577. sys.stdout.write('parities: {}\n'.format(s.PARITIES))
  578. sys.stdout.write('stop bits: {}\n'.format(s.STOPBITS))
  579. sys.stdout.write('{}\n'.format(s))