serialutil.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. #! python
  2. # Python Serial Port Extension for Win32, Linux, BSD, Jython
  3. # see __init__.py
  4. #
  5. # (C) 2001-2010 Chris Liechti <cliechti@gmx.net>
  6. # this is distributed under a free software license, see license.txt
  7. # compatibility for older Python < 2.6
  8. try:
  9. bytes
  10. bytearray
  11. except (NameError, AttributeError):
  12. # Python older than 2.6 do not have these types. Like for Python 2.6 they
  13. # should behave like str. For Python older than 3.0 we want to work with
  14. # strings anyway, only later versions have a true bytes type.
  15. bytes = str
  16. # bytearray is a mutable type that is easily turned into an instance of
  17. # bytes
  18. class bytearray(list):
  19. # for bytes(bytearray()) usage
  20. def __str__(self): return ''.join(self)
  21. def __repr__(self): return 'bytearray(%r)' % ''.join(self)
  22. # append automatically converts integers to characters
  23. def append(self, item):
  24. if isinstance(item, str):
  25. list.append(self, item)
  26. else:
  27. list.append(self, chr(item))
  28. # +=
  29. def __iadd__(self, other):
  30. for byte in other:
  31. self.append(byte)
  32. return self
  33. def __getslice__(self, i, j):
  34. return bytearray(list.__getslice__(self, i, j))
  35. def __getitem__(self, item):
  36. if isinstance(item, slice):
  37. return bytearray(list.__getitem__(self, item))
  38. else:
  39. return ord(list.__getitem__(self, item))
  40. def __eq__(self, other):
  41. if isinstance(other, basestring):
  42. other = bytearray(other)
  43. return list.__eq__(self, other)
  44. # ``memoryview`` was introduced in Python 2.7 and ``bytes(some_memoryview)``
  45. # isn't returning the contents (very unfortunate). Therefore we need special
  46. # cases and test for it. Ensure that there is a ``memoryview`` object for older
  47. # Python versions. This is easier than making every test dependent on its
  48. # existence.
  49. try:
  50. memoryview
  51. except (NameError, AttributeError):
  52. # implementation does not matter as we do not realy use it.
  53. # it just must not inherit from something else we might care for.
  54. class memoryview:
  55. pass
  56. # all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11'
  57. # so a simple ``bytes(sequence)`` doesn't work for all versions
  58. def to_bytes(seq):
  59. """convert a sequence to a bytes type"""
  60. if isinstance(seq, bytes):
  61. return seq
  62. elif isinstance(seq, bytearray):
  63. return bytes(seq)
  64. elif isinstance(seq, memoryview):
  65. return seq.tobytes()
  66. else:
  67. b = bytearray()
  68. for item in seq:
  69. b.append(item) # this one handles int and str for our emulation and ints for Python 3.x
  70. return bytes(b)
  71. # create control bytes
  72. XON = to_bytes([17])
  73. XOFF = to_bytes([19])
  74. CR = to_bytes([13])
  75. LF = to_bytes([10])
  76. PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
  77. STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
  78. FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
  79. PARITY_NAMES = {
  80. PARITY_NONE: 'None',
  81. PARITY_EVEN: 'Even',
  82. PARITY_ODD: 'Odd',
  83. PARITY_MARK: 'Mark',
  84. PARITY_SPACE: 'Space',
  85. }
  86. class SerialException(IOError):
  87. """Base class for serial port related exceptions."""
  88. class SerialTimeoutException(SerialException):
  89. """Write timeouts give an exception"""
  90. writeTimeoutError = SerialTimeoutException('Write timeout')
  91. portNotOpenError = SerialException('Attempting to use a port that is not open')
  92. class FileLike(object):
  93. """An abstract file like class.
  94. This class implements readline and readlines based on read and
  95. writelines based on write.
  96. This class is used to provide the above functions for to Serial
  97. port objects.
  98. Note that when the serial port was opened with _NO_ timeout that
  99. readline blocks until it sees a newline (or the specified size is
  100. reached) and that readlines would never return and therefore
  101. refuses to work (it raises an exception in this case)!
  102. """
  103. def __init__(self):
  104. self.closed = True
  105. def close(self):
  106. self.closed = True
  107. # so that ports are closed when objects are discarded
  108. def __del__(self):
  109. """Destructor. Calls close()."""
  110. # The try/except block is in case this is called at program
  111. # exit time, when it's possible that globals have already been
  112. # deleted, and then the close() call might fail. Since
  113. # there's nothing we can do about such failures and they annoy
  114. # the end users, we suppress the traceback.
  115. try:
  116. self.close()
  117. except:
  118. pass
  119. def writelines(self, sequence):
  120. for line in sequence:
  121. self.write(line)
  122. def flush(self):
  123. """flush of file like objects"""
  124. pass
  125. # iterator for e.g. "for line in Serial(0): ..." usage
  126. def next(self):
  127. line = self.readline()
  128. if not line: raise StopIteration
  129. return line
  130. def __iter__(self):
  131. return self
  132. def readline(self, size=None, eol=LF):
  133. """read a line which is terminated with end-of-line (eol) character
  134. ('\n' by default) or until timeout."""
  135. leneol = len(eol)
  136. line = bytearray()
  137. while True:
  138. c = self.read(1)
  139. if c:
  140. line += c
  141. if line[-leneol:] == eol:
  142. break
  143. if size is not None and len(line) >= size:
  144. break
  145. else:
  146. break
  147. return bytes(line)
  148. def readlines(self, sizehint=None, eol=LF):
  149. """read a list of lines, until timeout.
  150. sizehint is ignored."""
  151. if self.timeout is None:
  152. raise ValueError("Serial port MUST have enabled timeout for this function!")
  153. leneol = len(eol)
  154. lines = []
  155. while True:
  156. line = self.readline(eol=eol)
  157. if line:
  158. lines.append(line)
  159. if line[-leneol:] != eol: # was the line received with a timeout?
  160. break
  161. else:
  162. break
  163. return lines
  164. def xreadlines(self, sizehint=None):
  165. """Read lines, implemented as generator. It will raise StopIteration on
  166. timeout (empty read). sizehint is ignored."""
  167. while True:
  168. line = self.readline()
  169. if not line: break
  170. yield line
  171. # other functions of file-likes - not used by pySerial
  172. #~ readinto(b)
  173. def seek(self, pos, whence=0):
  174. raise IOError("file is not seekable")
  175. def tell(self):
  176. raise IOError("file is not seekable")
  177. def truncate(self, n=None):
  178. raise IOError("file is not seekable")
  179. def isatty(self):
  180. return False
  181. class SerialBase(object):
  182. """Serial port base class. Provides __init__ function and properties to
  183. get/set port settings."""
  184. # default values, may be overridden in subclasses that do not support all values
  185. BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
  186. 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
  187. 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
  188. 3000000, 3500000, 4000000)
  189. BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
  190. PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
  191. STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
  192. def __init__(self,
  193. port = None, # number of device, numbering starts at
  194. # zero. if everything fails, the user
  195. # can specify a device string, note
  196. # that this isn't portable anymore
  197. # port will be opened if one is specified
  198. baudrate=9600, # baud rate
  199. bytesize=EIGHTBITS, # number of data bits
  200. parity=PARITY_NONE, # enable parity checking
  201. stopbits=STOPBITS_ONE, # number of stop bits
  202. timeout=None, # set a timeout value, None to wait forever
  203. xonxoff=False, # enable software flow control
  204. rtscts=False, # enable RTS/CTS flow control
  205. writeTimeout=None, # set a timeout for writes
  206. dsrdtr=False, # None: use rtscts setting, dsrdtr override if True or False
  207. interCharTimeout=None # Inter-character timeout, None to disable
  208. ):
  209. """Initialize comm port object. If a port is given, then the port will be
  210. opened immediately. Otherwise a Serial port object in closed state
  211. is returned."""
  212. self._isOpen = False
  213. self._port = None # correct value is assigned below through properties
  214. self._baudrate = None # correct value is assigned below through properties
  215. self._bytesize = None # correct value is assigned below through properties
  216. self._parity = None # correct value is assigned below through properties
  217. self._stopbits = None # correct value is assigned below through properties
  218. self._timeout = None # correct value is assigned below through properties
  219. self._writeTimeout = None # correct value is assigned below through properties
  220. self._xonxoff = None # correct value is assigned below through properties
  221. self._rtscts = None # correct value is assigned below through properties
  222. self._dsrdtr = None # correct value is assigned below through properties
  223. self._interCharTimeout = None # correct value is assigned below through properties
  224. # assign values using get/set methods using the properties feature
  225. self.port = port
  226. self.baudrate = baudrate
  227. self.bytesize = bytesize
  228. self.parity = parity
  229. self.stopbits = stopbits
  230. self.timeout = timeout
  231. self.writeTimeout = writeTimeout
  232. self.xonxoff = xonxoff
  233. self.rtscts = rtscts
  234. self.dsrdtr = dsrdtr
  235. self.interCharTimeout = interCharTimeout
  236. if port is not None:
  237. self.open()
  238. def isOpen(self):
  239. """Check if the port is opened."""
  240. return self._isOpen
  241. # - - - - - - - - - - - - - - - - - - - - - - - -
  242. # TODO: these are not really needed as the is the BAUDRATES etc. attribute...
  243. # maybe i remove them before the final release...
  244. def getSupportedBaudrates(self):
  245. return [(str(b), b) for b in self.BAUDRATES]
  246. def getSupportedByteSizes(self):
  247. return [(str(b), b) for b in self.BYTESIZES]
  248. def getSupportedStopbits(self):
  249. return [(str(b), b) for b in self.STOPBITS]
  250. def getSupportedParities(self):
  251. return [(PARITY_NAMES[b], b) for b in self.PARITIES]
  252. # - - - - - - - - - - - - - - - - - - - - - - - -
  253. def setPort(self, port):
  254. """Change the port. The attribute portstr is set to a string that
  255. contains the name of the port."""
  256. was_open = self._isOpen
  257. if was_open: self.close()
  258. if port is not None:
  259. if isinstance(port, basestring):
  260. self.portstr = port
  261. else:
  262. self.portstr = self.makeDeviceName(port)
  263. else:
  264. self.portstr = None
  265. self._port = port
  266. self.name = self.portstr
  267. if was_open: self.open()
  268. def getPort(self):
  269. """Get the current port setting. The value that was passed on init or using
  270. setPort() is passed back. See also the attribute portstr which contains
  271. the name of the port as a string."""
  272. return self._port
  273. port = property(getPort, setPort, doc="Port setting")
  274. def setBaudrate(self, baudrate):
  275. """Change baud rate. It raises a ValueError if the port is open and the
  276. baud rate is not possible. If the port is closed, then the value is
  277. accepted and the exception is raised when the port is opened."""
  278. try:
  279. b = int(baudrate)
  280. except TypeError:
  281. raise ValueError("Not a valid baudrate: %r" % (baudrate,))
  282. else:
  283. if b <= 0:
  284. raise ValueError("Not a valid baudrate: %r" % (baudrate,))
  285. self._baudrate = b
  286. if self._isOpen: self._reconfigurePort()
  287. def getBaudrate(self):
  288. """Get the current baud rate setting."""
  289. return self._baudrate
  290. baudrate = property(getBaudrate, setBaudrate, doc="Baud rate setting")
  291. def setByteSize(self, bytesize):
  292. """Change byte size."""
  293. if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % (bytesize,))
  294. self._bytesize = bytesize
  295. if self._isOpen: self._reconfigurePort()
  296. def getByteSize(self):
  297. """Get the current byte size setting."""
  298. return self._bytesize
  299. bytesize = property(getByteSize, setByteSize, doc="Byte size setting")
  300. def setParity(self, parity):
  301. """Change parity setting."""
  302. if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % (parity,))
  303. self._parity = parity
  304. if self._isOpen: self._reconfigurePort()
  305. def getParity(self):
  306. """Get the current parity setting."""
  307. return self._parity
  308. parity = property(getParity, setParity, doc="Parity setting")
  309. def setStopbits(self, stopbits):
  310. """Change stop bits size."""
  311. if stopbits not in self.STOPBITS: raise ValueError("Not a valid stop bit size: %r" % (stopbits,))
  312. self._stopbits = stopbits
  313. if self._isOpen: self._reconfigurePort()
  314. def getStopbits(self):
  315. """Get the current stop bits setting."""
  316. return self._stopbits
  317. stopbits = property(getStopbits, setStopbits, doc="Stop bits setting")
  318. def setTimeout(self, timeout):
  319. """Change timeout setting."""
  320. if timeout is not None:
  321. try:
  322. timeout + 1 # test if it's a number, will throw a TypeError if not...
  323. except TypeError:
  324. raise ValueError("Not a valid timeout: %r" % (timeout,))
  325. if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
  326. self._timeout = timeout
  327. if self._isOpen: self._reconfigurePort()
  328. def getTimeout(self):
  329. """Get the current timeout setting."""
  330. return self._timeout
  331. timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")
  332. def setWriteTimeout(self, timeout):
  333. """Change timeout setting."""
  334. if timeout is not None:
  335. if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
  336. try:
  337. timeout + 1 #test if it's a number, will throw a TypeError if not...
  338. except TypeError:
  339. raise ValueError("Not a valid timeout: %r" % timeout)
  340. self._writeTimeout = timeout
  341. if self._isOpen: self._reconfigurePort()
  342. def getWriteTimeout(self):
  343. """Get the current timeout setting."""
  344. return self._writeTimeout
  345. writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")
  346. def setXonXoff(self, xonxoff):
  347. """Change XON/XOFF setting."""
  348. self._xonxoff = xonxoff
  349. if self._isOpen: self._reconfigurePort()
  350. def getXonXoff(self):
  351. """Get the current XON/XOFF setting."""
  352. return self._xonxoff
  353. xonxoff = property(getXonXoff, setXonXoff, doc="XON/XOFF setting")
  354. def setRtsCts(self, rtscts):
  355. """Change RTS/CTS flow control setting."""
  356. self._rtscts = rtscts
  357. if self._isOpen: self._reconfigurePort()
  358. def getRtsCts(self):
  359. """Get the current RTS/CTS flow control setting."""
  360. return self._rtscts
  361. rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")
  362. def setDsrDtr(self, dsrdtr=None):
  363. """Change DsrDtr flow control setting."""
  364. if dsrdtr is None:
  365. # if not set, keep backwards compatibility and follow rtscts setting
  366. self._dsrdtr = self._rtscts
  367. else:
  368. # if defined independently, follow its value
  369. self._dsrdtr = dsrdtr
  370. if self._isOpen: self._reconfigurePort()
  371. def getDsrDtr(self):
  372. """Get the current DSR/DTR flow control setting."""
  373. return self._dsrdtr
  374. dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
  375. def setInterCharTimeout(self, interCharTimeout):
  376. """Change inter-character timeout setting."""
  377. if interCharTimeout is not None:
  378. if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
  379. try:
  380. interCharTimeout + 1 # test if it's a number, will throw a TypeError if not...
  381. except TypeError:
  382. raise ValueError("Not a valid timeout: %r" % interCharTimeout)
  383. self._interCharTimeout = interCharTimeout
  384. if self._isOpen: self._reconfigurePort()
  385. def getInterCharTimeout(self):
  386. """Get the current inter-character timeout setting."""
  387. return self._interCharTimeout
  388. interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")
  389. # - - - - - - - - - - - - - - - - - - - - - - - -
  390. _SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
  391. 'dsrdtr', 'rtscts', 'timeout', 'writeTimeout', 'interCharTimeout')
  392. def getSettingsDict(self):
  393. """Get current port settings as a dictionary. For use with
  394. applySettingsDict"""
  395. return dict([(key, getattr(self, '_'+key)) for key in self._SETTINGS])
  396. def applySettingsDict(self, d):
  397. """apply stored settings from a dictionary returned from
  398. getSettingsDict. it's allowed to delete keys from the dictionary. these
  399. values will simply left unchanged."""
  400. for key in self._SETTINGS:
  401. if d[key] != getattr(self, '_'+key): # check against internal "_" value
  402. setattr(self, key, d[key]) # set non "_" value to use properties write function
  403. # - - - - - - - - - - - - - - - - - - - - - - - -
  404. def __repr__(self):
  405. """String representation of the current port settings and its state."""
  406. 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)" % (
  407. self.__class__.__name__,
  408. id(self),
  409. self._isOpen,
  410. self.portstr,
  411. self.baudrate,
  412. self.bytesize,
  413. self.parity,
  414. self.stopbits,
  415. self.timeout,
  416. self.xonxoff,
  417. self.rtscts,
  418. self.dsrdtr,
  419. )
  420. # - - - - - - - - - - - - - - - - - - - - - - - -
  421. # compatibility with io library
  422. def readable(self): return True
  423. def writable(self): return True
  424. def seekable(self): return False
  425. def readinto(self, b):
  426. data = self.read(len(b))
  427. n = len(data)
  428. try:
  429. b[:n] = data
  430. except TypeError, err:
  431. import array
  432. if not isinstance(b, array.array):
  433. raise err
  434. b[:n] = array.array('b', data)
  435. return n
  436. if __name__ == '__main__':
  437. import sys
  438. s = SerialBase()
  439. sys.stdout.write('port name: %s\n' % s.portstr)
  440. sys.stdout.write('baud rates: %s\n' % s.getSupportedBaudrates())
  441. sys.stdout.write('byte sizes: %s\n' % s.getSupportedByteSizes())
  442. sys.stdout.write('parities: %s\n' % s.getSupportedParities())
  443. sys.stdout.write('stop bits: %s\n' % s.getSupportedStopbits())
  444. sys.stdout.write('%s\n' % s)