serialutil.py 21 KB

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