serialport.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Serial Port Protocol
  5. """
  6. # http://twistedmatrix.com/trac/ticket/3725#comment:24
  7. # Apparently applications use these names even though they should
  8. # be imported from pyserial
  9. __all__ = [
  10. "serial",
  11. "PARITY_ODD",
  12. "PARITY_EVEN",
  13. "PARITY_NONE",
  14. "STOPBITS_TWO",
  15. "STOPBITS_ONE",
  16. "FIVEBITS",
  17. "EIGHTBITS",
  18. "SEVENBITS",
  19. "SIXBITS",
  20. # Name this module is actually trying to export
  21. "SerialPort",
  22. ]
  23. # all of them require pyserial at the moment, so check that first
  24. import serial
  25. from serial import (
  26. EIGHTBITS,
  27. FIVEBITS,
  28. PARITY_EVEN,
  29. PARITY_NONE,
  30. PARITY_ODD,
  31. SEVENBITS,
  32. SIXBITS,
  33. STOPBITS_ONE,
  34. STOPBITS_TWO,
  35. )
  36. from twisted.python.runtime import platform
  37. class BaseSerialPort:
  38. """
  39. Base class for Windows and POSIX serial ports.
  40. @ivar _serialFactory: a pyserial C{serial.Serial} factory, used to create
  41. the instance stored in C{self._serial}. Overrideable to enable easier
  42. testing.
  43. @ivar _serial: a pyserial C{serial.Serial} instance used to manage the
  44. options on the serial port.
  45. """
  46. _serialFactory = serial.Serial
  47. def setBaudRate(self, baudrate):
  48. if hasattr(self._serial, "setBaudrate"):
  49. self._serial.setBaudrate(baudrate)
  50. else:
  51. self._serial.setBaudRate(baudrate)
  52. def inWaiting(self):
  53. return self._serial.inWaiting()
  54. def flushInput(self):
  55. self._serial.flushInput()
  56. def flushOutput(self):
  57. self._serial.flushOutput()
  58. def sendBreak(self):
  59. self._serial.sendBreak()
  60. def getDSR(self):
  61. return self._serial.getDSR()
  62. def getCD(self):
  63. return self._serial.getCD()
  64. def getRI(self):
  65. return self._serial.getRI()
  66. def getCTS(self):
  67. return self._serial.getCTS()
  68. def setDTR(self, on=1):
  69. self._serial.setDTR(on)
  70. def setRTS(self, on=1):
  71. self._serial.setRTS(on)
  72. # Expert appropriate implementation of SerialPort.
  73. if platform.isWindows():
  74. from twisted.internet._win32serialport import SerialPort
  75. else:
  76. from twisted.internet._posixserialport import SerialPort # type: ignore[assignment]