Python Library Serial Interface
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. serial_interface (Serial Interface Module)
  6. ==========================================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports a common interface for a serial port
  11. **Submodules:**
  12. * :mod:`mmod.module.sub1`
  13. * :class:`mmod.module.sub2`
  14. * :func:`mmod.module.sub2`
  15. **Unittest:**
  16. See also the :download:`unittest <../../serial_interface/_testresults_/unittest.pdf>` documentation.
  17. """
  18. __DEPENDENCIES__ = ['stringtools']
  19. import stringtools
  20. import logging
  21. import serial
  22. import time
  23. try:
  24. from config import APP_NAME as ROOT_LOGGER_NAME
  25. except ImportError:
  26. ROOT_LOGGER_NAME = 'root'
  27. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  28. class serial_interface(object):
  29. """
  30. Class to send and receive data via a serial port.
  31. .. note:: All parameters are given to the standard :py:class:`serial.Serial` library
  32. """
  33. LOG_PREFIX = 'SER:'
  34. def __init__(self, *args, **kwargs):
  35. self._args = args
  36. self._kwargs = kwargs
  37. self.com = None
  38. self.open()
  39. def open(self):
  40. """
  41. This opens the serial port.
  42. :returns: True if the port has been successfully opened
  43. :rtype: bool
  44. """
  45. if self.com is not None:
  46. self.close()
  47. try:
  48. self.com = serial.Serial(*self._args, **self._kwargs)
  49. except:
  50. self.com = None
  51. logger.warning('%s Unable to open comport (%s)', self.LOG_PREFIX, self._args[0])
  52. return False
  53. else:
  54. logger.debug('%s Opening comport (%s)', self.LOG_PREFIX, self._args[0])
  55. return True
  56. def close(self):
  57. """
  58. This closes the serial port.
  59. """
  60. if self.com is not None:
  61. logger.debug('%s Closing comport (%s)', self.LOG_PREFIX, self._args[0])
  62. self.com.close()
  63. self.com = None
  64. def bytes_in_queue(self):
  65. """
  66. This returns the number of available bytes for receiption.
  67. :returns: Number of bytes in queue
  68. :rtype: int
  69. """
  70. if self.com is not None:
  71. return self.com.inWaiting()
  72. else:
  73. return 0
  74. def receive(self, max_length=None):
  75. """
  76. This receives data from the serial interface.
  77. :param int length: An optinal number of bytes to be received. None will return all available bytes.
  78. :returns: The received data
  79. :rtype: str
  80. """
  81. length = self.bytes_in_queue()
  82. if max_length is not None:
  83. length = min(length, max_length)
  84. if self.com is not None and length > 0:
  85. data = self.com.read(length)
  86. self._handle_debug('RX <- ', data)
  87. return data
  88. def send(self, data):
  89. """
  90. This sends data via the serial interface.
  91. :param str data: The data to be send
  92. """
  93. if self.com is not None:
  94. self._handle_debug('TX -> ', data)
  95. self.com.write(data)
  96. def _handle_debug(self, msg, data):
  97. logger.debug('%s ' + msg + stringtools.hexlify(data), self.LOG_PREFIX)
  98. def __del__(self):
  99. self.close()