local.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. def connect(self):
  16. """Establish connection to the device.
  17. """
  18. # TODO(ms): these settings can probably be tweaked and still support most of
  19. # the devices.
  20. self._conn = serial.Serial(port=self.device,
  21. baudrate=4800,
  22. parity=serial.PARITY_EVEN,
  23. stopbits=serial.STOPBITS_TWO,
  24. timeout=1,
  25. xonxoff=0,
  26. rtscts=0)
  27. def disconnect(self):
  28. """Disconnect from the device.
  29. """
  30. if self._conn:
  31. self._conn.close()
  32. def write(self, packet):
  33. """Write packet to the serial interface.
  34. :param packet: packet to write
  35. :type packet: :class:`alphasign.packet.Packet`
  36. """
  37. if not self._conn:
  38. return
  39. if self.debug:
  40. print "Writing packet: %s" % repr(packet)
  41. self._conn.write(str(packet))
  42. class DebugInterface(base.BaseInterface):
  43. """Dummy interface used only for debugging.
  44. This does nothing except print the contents of written packets.
  45. """
  46. def __init__(self):
  47. self.debug = True
  48. def connect(self):
  49. pass
  50. def disconnect(self):
  51. pass
  52. def write(self, packet):
  53. if self.debug:
  54. print "Writing packet: %s" % repr(packet)