local.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import serial
  2. import time
  3. from alphasign.interfaces import base
  4. class Serial(base.BaseInterface):
  5. """Connect to a sign through a local serial device.
  6. This class uses `pySerial <http://pyserial.sourceforge.net/>`_.
  7. """
  8. def __init__(self, device="/dev/ttyS0"):
  9. """
  10. :param device: character device (default: /dev/ttyS0)
  11. :type device: string
  12. """
  13. self.device = device
  14. self.debug = True
  15. self._conn = None
  16. def connect(self):
  17. """Establish connection to the device.
  18. """
  19. # TODO(ms): these settings can probably be tweaked and still support most of
  20. # the devices.
  21. self._conn = serial.Serial(port=self.device,
  22. baudrate=4800,
  23. parity=serial.PARITY_EVEN,
  24. stopbits=serial.STOPBITS_TWO,
  25. timeout=1,
  26. xonxoff=0,
  27. rtscts=0)
  28. def disconnect(self):
  29. """Disconnect from the device.
  30. """
  31. if self._conn:
  32. self._conn.close()
  33. def write(self, packet):
  34. """Write packet to the serial interface.
  35. :param packet: packet to write
  36. :type packet: :class:`alphasign.packet.Packet`
  37. """
  38. if not self._conn or not self._conn.isOpen():
  39. self.connect()
  40. if self.debug:
  41. print "Writing packet: %s" % repr(packet)
  42. try:
  43. self._conn.write(str(packet))
  44. except OSError:
  45. return False
  46. else:
  47. return True
  48. class DebugInterface(base.BaseInterface):
  49. """Dummy interface used only for debugging.
  50. This does nothing except print the contents of written packets.
  51. """
  52. def __init__(self):
  53. self.debug = True
  54. def connect(self):
  55. pass
  56. def disconnect(self):
  57. pass
  58. def write(self, packet):
  59. if self.debug:
  60. print "Writing packet: %s" % repr(packet)
  61. return True