serialutil.py 19 KB

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