Python Library Stringtools
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. stringtools.csp (Carriage-Return seperation protocol)
  6. =====================================================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This module is a submodule of :mod:`stringtools` and creates an frame to transmit and receive messages via an serial interface.
  11. **Submodules:**
  12. * :class:`stringtools.csp.csp`
  13. * :func:`stringtools.csp.build_frame`
  14. """
  15. import stringtools
  16. import logging
  17. import sys
  18. try:
  19. from config import APP_NAME as ROOT_LOGGER_NAME
  20. except ImportError:
  21. ROOT_LOGGER_NAME = 'root'
  22. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  23. DATA_SEPERATOR = b'\n'
  24. class csp(object):
  25. """This class extracts messages from an "csp-stream".
  26. **Example:**
  27. .. literalinclude:: stringtools/_examples_/csp.csp.py
  28. Will result to the following output:
  29. .. literalinclude:: stringtools/_examples_/csp.csp.log
  30. """
  31. LOG_PREFIX = 'CSP:'
  32. def __init__(self, seperator=DATA_SEPERATOR):
  33. self.__buffer__ = b''
  34. self.__seperator__ = seperator
  35. def process(self, data):
  36. """
  37. This processes a byte out of a "stp-stream".
  38. :param bytes data: A byte stream
  39. :returns: A list of the extracted message(s)
  40. :rtype: list
  41. """
  42. if sys.version_info < (3, 0):
  43. if type(data) is unicode:
  44. raise TypeError
  45. #
  46. rv = (self.__buffer__ + data).split(self.__seperator__)
  47. self.__buffer__ = rv.pop()
  48. if len(self.__buffer__) != 0:
  49. logger.debug('%s Leaving data in buffer (to be processed next time): %s', self.LOG_PREFIX, stringtools.hexlify(self.__buffer__))
  50. for msg in rv:
  51. logger.info('%s message identified - %s', self.LOG_PREFIX, stringtools.hexlify(msg))
  52. return rv
  53. def build_frame(msg, seperator=DATA_SEPERATOR):
  54. """This Method builds an "csp-frame" to be transfered via a stream.
  55. :param str data: A String (Bytes) to be framed
  56. :returns: The "csp-framed" message to be sent
  57. :rtype: str
  58. **Example:**
  59. .. literalinclude:: stringtools/_examples_/csp.build_frame.py
  60. Will result to the following output:
  61. .. literalinclude:: stringtools/_examples_/csp.build_frame.log
  62. """
  63. if seperator in msg:
  64. raise ValueError
  65. else:
  66. return msg + seperator