serialutil.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. **kwargs):
  158. """\
  159. Initialize comm port object. If a "port" is given, then the port will be
  160. opened immediately. Otherwise a Serial port object in closed state
  161. is returned.
  162. """
  163. self.is_open = False
  164. self.portstr = None
  165. self.name = None
  166. # correct values are assigned below through properties
  167. self._port = None
  168. self._baudrate = None
  169. self._bytesize = None
  170. self._parity = None
  171. self._stopbits = None
  172. self._timeout = None
  173. self._write_timeout = None
  174. self._xonxoff = None
  175. self._rtscts = None
  176. self._dsrdtr = None
  177. self._inter_byte_timeout = None
  178. self._rs485_mode = None # disabled by default
  179. self._rts_state = True
  180. self._dtr_state = True
  181. self._break_state = False
  182. # assign values using get/set methods using the properties feature
  183. self.port = port
  184. self.baudrate = baudrate
  185. self.bytesize = bytesize
  186. self.parity = parity
  187. self.stopbits = stopbits
  188. self.timeout = timeout
  189. self.write_timeout = write_timeout
  190. self.xonxoff = xonxoff
  191. self.rtscts = rtscts
  192. self.dsrdtr = dsrdtr
  193. self.inter_byte_timeout = inter_byte_timeout
  194. # watch for backward compatible kwargs
  195. if 'writeTimeout' in kwargs:
  196. self.write_timeout = kwargs.pop('writeTimeout')
  197. if 'interCharTimeout' in kwargs:
  198. self.inter_byte_timeout = kwargs.pop('interCharTimeout')
  199. if kwargs:
  200. raise ValueError('unexpected keyword arguments: {!r}'.format(kwargs))
  201. if port is not None:
  202. self.open()
  203. # - - - - - - - - - - - - - - - - - - - - - - - -
  204. # to be implemented by subclasses:
  205. # def open(self):
  206. # def close(self):
  207. # - - - - - - - - - - - - - - - - - - - - - - - -
  208. @property
  209. def port(self):
  210. """\
  211. Get the current port setting. The value that was passed on init or using
  212. setPort() is passed back.
  213. """
  214. return self._port
  215. @port.setter
  216. def port(self, port):
  217. """\
  218. Change the port.
  219. """
  220. if port is not None and not isinstance(port, basestring):
  221. raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
  222. was_open = self.is_open
  223. if was_open:
  224. self.close()
  225. self.portstr = port
  226. self._port = port
  227. self.name = self.portstr
  228. if was_open:
  229. self.open()
  230. @property
  231. def baudrate(self):
  232. """Get the current baud rate setting."""
  233. return self._baudrate
  234. @baudrate.setter
  235. def baudrate(self, baudrate):
  236. """\
  237. Change baud rate. It raises a ValueError if the port is open and the
  238. baud rate is not possible. If the port is closed, then the value is
  239. accepted and the exception is raised when the port is opened.
  240. """
  241. try:
  242. b = int(baudrate)
  243. except TypeError:
  244. raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
  245. else:
  246. if b < 0:
  247. raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
  248. self._baudrate = b
  249. if self.is_open:
  250. self._reconfigure_port()
  251. @property
  252. def bytesize(self):
  253. """Get the current byte size setting."""
  254. return self._bytesize
  255. @bytesize.setter
  256. def bytesize(self, bytesize):
  257. """Change byte size."""
  258. if bytesize not in self.BYTESIZES:
  259. raise ValueError("Not a valid byte size: {!r}".format(bytesize))
  260. self._bytesize = bytesize
  261. if self.is_open:
  262. self._reconfigure_port()
  263. @property
  264. def parity(self):
  265. """Get the current parity setting."""
  266. return self._parity
  267. @parity.setter
  268. def parity(self, parity):
  269. """Change parity setting."""
  270. if parity not in self.PARITIES:
  271. raise ValueError("Not a valid parity: {!r}".format(parity))
  272. self._parity = parity
  273. if self.is_open:
  274. self._reconfigure_port()
  275. @property
  276. def stopbits(self):
  277. """Get the current stop bits setting."""
  278. return self._stopbits
  279. @stopbits.setter
  280. def stopbits(self, stopbits):
  281. """Change stop bits size."""
  282. if stopbits not in self.STOPBITS:
  283. raise ValueError("Not a valid stop bit size: {!r}".format(stopbits))
  284. self._stopbits = stopbits
  285. if self.is_open:
  286. self._reconfigure_port()
  287. @property
  288. def timeout(self):
  289. """Get the current timeout setting."""
  290. return self._timeout
  291. @timeout.setter
  292. def timeout(self, timeout):
  293. """Change timeout setting."""
  294. if timeout is not None:
  295. try:
  296. timeout + 1 # test if it's a number, will throw a TypeError if not...
  297. except TypeError:
  298. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  299. if timeout < 0:
  300. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  301. self._timeout = timeout
  302. if self.is_open:
  303. self._reconfigure_port()
  304. @property
  305. def write_timeout(self):
  306. """Get the current timeout setting."""
  307. return self._write_timeout
  308. @write_timeout.setter
  309. def write_timeout(self, timeout):
  310. """Change timeout setting."""
  311. if timeout is not None:
  312. if timeout < 0:
  313. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  314. try:
  315. timeout + 1 # test if it's a number, will throw a TypeError if not...
  316. except TypeError:
  317. raise ValueError("Not a valid timeout: {!r}".format(timeout))
  318. self._write_timeout = timeout
  319. if self.is_open:
  320. self._reconfigure_port()
  321. @property
  322. def inter_byte_timeout(self):
  323. """Get the current inter-character timeout setting."""
  324. return self._inter_byte_timeout
  325. @inter_byte_timeout.setter
  326. def inter_byte_timeout(self, ic_timeout):
  327. """Change inter-byte timeout setting."""
  328. if ic_timeout is not None:
  329. if ic_timeout < 0:
  330. raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
  331. try:
  332. ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
  333. except TypeError:
  334. raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
  335. self._inter_byte_timeout = ic_timeout
  336. if self.is_open:
  337. self._reconfigure_port()
  338. @property
  339. def xonxoff(self):
  340. """Get the current XON/XOFF setting."""
  341. return self._xonxoff
  342. @xonxoff.setter
  343. def xonxoff(self, xonxoff):
  344. """Change XON/XOFF setting."""
  345. self._xonxoff = xonxoff
  346. if self.is_open:
  347. self._reconfigure_port()
  348. @property
  349. def rtscts(self):
  350. """Get the current RTS/CTS flow control setting."""
  351. return self._rtscts
  352. @rtscts.setter
  353. def rtscts(self, rtscts):
  354. """Change RTS/CTS flow control setting."""
  355. self._rtscts = rtscts
  356. if self.is_open:
  357. self._reconfigure_port()
  358. @property
  359. def dsrdtr(self):
  360. """Get the current DSR/DTR flow control setting."""
  361. return self._dsrdtr
  362. @dsrdtr.setter
  363. def dsrdtr(self, dsrdtr=None):
  364. """Change DsrDtr flow control setting."""
  365. if dsrdtr is None:
  366. # if not set, keep backwards compatibility and follow rtscts setting
  367. self._dsrdtr = self._rtscts
  368. else:
  369. # if defined independently, follow its value
  370. self._dsrdtr = dsrdtr
  371. if self.is_open:
  372. self._reconfigure_port()
  373. @property
  374. def rts(self):
  375. return self._rts_state
  376. @rts.setter
  377. def rts(self, value):
  378. self._rts_state = value
  379. if self.is_open:
  380. self._update_rts_state()
  381. @property
  382. def dtr(self):
  383. return self._dtr_state
  384. @dtr.setter
  385. def dtr(self, value):
  386. self._dtr_state = value
  387. if self.is_open:
  388. self._update_dtr_state()
  389. @property
  390. def break_condition(self):
  391. return self._break_state
  392. @break_condition.setter
  393. def break_condition(self, value):
  394. self._break_state = value
  395. if self.is_open:
  396. self._update_break_state()
  397. # - - - - - - - - - - - - - - - - - - - - - - - -
  398. # functions useful for RS-485 adapters
  399. @property
  400. def rs485_mode(self):
  401. """\
  402. Enable RS485 mode and apply new settings, set to None to disable.
  403. See serial.rs485.RS485Settings for more info about the value.
  404. """
  405. return self._rs485_mode
  406. @rs485_mode.setter
  407. def rs485_mode(self, rs485_settings):
  408. self._rs485_mode = rs485_settings
  409. if self.is_open:
  410. self._reconfigure_port()
  411. # - - - - - - - - - - - - - - - - - - - - - - - -
  412. _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
  413. 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
  414. 'inter_byte_timeout')
  415. def get_settings(self):
  416. """\
  417. Get current port settings as a dictionary. For use with
  418. apply_settings().
  419. """
  420. return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
  421. def apply_settings(self, d):
  422. """\
  423. Apply stored settings from a dictionary returned from
  424. get_settings(). It's allowed to delete keys from the dictionary. These
  425. values will simply left unchanged.
  426. """
  427. for key in self._SAVED_SETTINGS:
  428. if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
  429. setattr(self, key, d[key]) # set non "_" value to use properties write function
  430. # - - - - - - - - - - - - - - - - - - - - - - - -
  431. def __repr__(self):
  432. """String representation of the current port settings and its state."""
  433. return '{name}<id=0x{id:x}, open={p.is_open}>(port={p.portstr!r}, ' \
  434. 'baudrate={p.baudrate!r}, bytesize={p.bytesize!r}, parity={p.parity!r}, ' \
  435. 'stopbits={p.stopbits!r}, timeout={p.timeout!r}, xonxoff={p.xonxoff!r}, ' \
  436. 'rtscts={p.rtscts!r}, dsrdtr={p.dsrdtr!r})'.format(
  437. name=self.__class__.__name__, id=id(self), p=self)
  438. # - - - - - - - - - - - - - - - - - - - - - - - -
  439. # compatibility with io library
  440. # pylint: disable=invalid-name,missing-docstring
  441. def readable(self):
  442. return True
  443. def writable(self):
  444. return True
  445. def seekable(self):
  446. return False
  447. def readinto(self, b):
  448. data = self.read(len(b))
  449. n = len(data)
  450. try:
  451. b[:n] = data
  452. except TypeError as err:
  453. import array
  454. if not isinstance(b, array.array):
  455. raise err
  456. b[:n] = array.array('b', data)
  457. return n
  458. # - - - - - - - - - - - - - - - - - - - - - - - -
  459. # context manager
  460. def __enter__(self):
  461. return self
  462. def __exit__(self, *args, **kwargs):
  463. self.close()
  464. # - - - - - - - - - - - - - - - - - - - - - - - -
  465. def send_break(self, duration=0.25):
  466. """\
  467. Send break condition. Timed, returns to idle state after given
  468. duration.
  469. """
  470. if not self.is_open:
  471. raise portNotOpenError
  472. self.break_condition = True
  473. time.sleep(duration)
  474. self.break_condition = False
  475. # - - - - - - - - - - - - - - - - - - - - - - - -
  476. # backwards compatibility / deprecated functions
  477. def flushInput(self):
  478. self.reset_input_buffer()
  479. def flushOutput(self):
  480. self.reset_output_buffer()
  481. def inWaiting(self):
  482. return self.in_waiting
  483. def sendBreak(self, duration=0.25):
  484. self.send_break(duration)
  485. def setRTS(self, value=1):
  486. self.rts = value
  487. def setDTR(self, value=1):
  488. self.dtr = value
  489. def getCTS(self):
  490. return self.cts
  491. def getDSR(self):
  492. return self.dsr
  493. def getRI(self):
  494. return self.ri
  495. def getCD(self):
  496. return self.cd
  497. def setPort(self, port):
  498. self.port = port
  499. @property
  500. def writeTimeout(self):
  501. return self.write_timeout
  502. @writeTimeout.setter
  503. def writeTimeout(self, timeout):
  504. self.write_timeout = timeout
  505. @property
  506. def interCharTimeout(self):
  507. return self.inter_byte_timeout
  508. @interCharTimeout.setter
  509. def interCharTimeout(self, interCharTimeout):
  510. self.inter_byte_timeout = interCharTimeout
  511. def getSettingsDict(self):
  512. return self.get_settings()
  513. def applySettingsDict(self, d):
  514. self.apply_settings(d)
  515. def isOpen(self):
  516. return self.is_open
  517. # - - - - - - - - - - - - - - - - - - - - - - - -
  518. # additional functionality
  519. def read_all(self):
  520. """\
  521. Read all bytes currently available in the buffer of the OS.
  522. """
  523. return self.read(self.in_waiting)
  524. def read_until(self, terminator=LF, size=None):
  525. """\
  526. Read until a termination sequence is found ('\n' by default), the size
  527. is exceeded or until timeout occurs.
  528. """
  529. lenterm = len(terminator)
  530. line = bytearray()
  531. while True:
  532. c = self.read(1)
  533. if c:
  534. line += c
  535. if line[-lenterm:] == terminator:
  536. break
  537. if size is not None and len(line) >= size:
  538. break
  539. else:
  540. break
  541. return bytes(line)
  542. def iread_until(self, *args, **kwargs):
  543. """\
  544. Read lines, implemented as generator. It will raise StopIteration on
  545. timeout (empty read).
  546. """
  547. while True:
  548. line = self.read_until(*args, **kwargs)
  549. if not line:
  550. break
  551. yield line
  552. # - - - - - - - - - - - - - - - - - - - - - - - - -
  553. if __name__ == '__main__':
  554. import sys
  555. s = SerialBase()
  556. sys.stdout.write('port name: {}\n'.format(s.name))
  557. sys.stdout.write('baud rates: {}\n'.format(s.BAUDRATES))
  558. sys.stdout.write('byte sizes: {}\n'.format(s.BYTESIZES))
  559. sys.stdout.write('parities: {}\n'.format(s.PARITIES))
  560. sys.stdout.write('stop bits: {}\n'.format(s.STOPBITS))
  561. sys.stdout.write('{}\n'.format(s))