_posixserialport.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Serial Port Protocol
  5. """
  6. # dependent on pyserial ( http://pyserial.sf.net/ )
  7. # only tested w/ 1.18 (5 Dec 2002)
  8. from serial import EIGHTBITS, PARITY_NONE, STOPBITS_ONE
  9. from twisted.internet import abstract, fdesc
  10. from twisted.internet.serialport import BaseSerialPort
  11. class SerialPort(BaseSerialPort, abstract.FileDescriptor):
  12. """
  13. A select()able serial device, acting as a transport.
  14. """
  15. connected = 1
  16. def __init__(
  17. self,
  18. protocol,
  19. deviceNameOrPortNumber,
  20. reactor,
  21. baudrate=9600,
  22. bytesize=EIGHTBITS,
  23. parity=PARITY_NONE,
  24. stopbits=STOPBITS_ONE,
  25. timeout=0,
  26. xonxoff=0,
  27. rtscts=0,
  28. ):
  29. abstract.FileDescriptor.__init__(self, reactor)
  30. self._serial = self._serialFactory(
  31. deviceNameOrPortNumber,
  32. baudrate=baudrate,
  33. bytesize=bytesize,
  34. parity=parity,
  35. stopbits=stopbits,
  36. timeout=timeout,
  37. xonxoff=xonxoff,
  38. rtscts=rtscts,
  39. )
  40. self.reactor = reactor
  41. self.flushInput()
  42. self.flushOutput()
  43. self.protocol = protocol
  44. self.protocol.makeConnection(self)
  45. self.startReading()
  46. def fileno(self):
  47. return self._serial.fd
  48. def writeSomeData(self, data):
  49. """
  50. Write some data to the serial device.
  51. """
  52. return fdesc.writeToFD(self.fileno(), data)
  53. def doRead(self):
  54. """
  55. Some data's readable from serial device.
  56. """
  57. return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived)
  58. def connectionLost(self, reason):
  59. """
  60. Called when the serial port disconnects.
  61. Will call C{connectionLost} on the protocol that is handling the
  62. serial data.
  63. """
  64. abstract.FileDescriptor.connectionLost(self, reason)
  65. self._serial.close()
  66. self.protocol.connectionLost(reason)