Python Library Stringtools
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

csp.py 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. 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. logger_name = 'STRINGTOOLS'
  19. logger = logging.getLogger(logger_name)
  20. DATA_SEPERATOR = b'\n'
  21. class csp(object):
  22. """This class extracts messages from an "csp-stream".
  23. **Example:**
  24. .. literalinclude:: ../examples/csp.csp.py
  25. Will result to the following output:
  26. .. literalinclude:: ../examples/csp.csp.log
  27. """
  28. LOG_PREFIX = 'CSP:'
  29. def __init__(self, seperator=DATA_SEPERATOR):
  30. self.__buffer__ = b''
  31. self.__seperator__ = seperator
  32. def process(self, data):
  33. """
  34. This processes a byte out of a "stp-stream".
  35. :param bytes data: A byte stream
  36. :returns: A list of the extracted message(s)
  37. :rtype: list
  38. """
  39. if sys.version_info < (3, 0):
  40. if type(data) is unicode:
  41. raise TypeError
  42. #
  43. rv = (self.__buffer__ + data).split(self.__seperator__)
  44. self.__buffer__ = rv.pop()
  45. if len(self.__buffer__) != 0:
  46. logger.debug('%s Leaving data in buffer (to be processed next time): %s', self.LOG_PREFIX, stringtools.hexlify(self.__buffer__))
  47. for msg in rv:
  48. logger.info('%s message identified - %s', self.LOG_PREFIX, stringtools.hexlify(msg))
  49. return rv
  50. def build_frame(msg, seperator=DATA_SEPERATOR):
  51. """This Method builds an "csp-frame" to be transfered via a stream.
  52. :param str data: A String (Bytes) to be framed
  53. :returns: The "csp-framed" message to be sent
  54. :rtype: str
  55. **Example:**
  56. .. literalinclude:: ../examples/csp.build_frame.py
  57. Will result to the following output:
  58. .. literalinclude:: ../examples/csp.build_frame.log
  59. """
  60. if seperator in msg:
  61. raise ValueError
  62. else:
  63. return msg + seperator