_posixserialport.py 1.9 KB

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