1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- """
- csp (Carriage-Return seperation protocol)
- =========================================
-
- **Author:**
-
- * Dirk Alders <sudo-dirk@mount-mockery.de>
-
- **Description:**
-
- This module is a submodule of :mod:`stringtools` and creates an frame to transmit and receive messages via an serial interface.
-
- **Submodules:**
-
- * :class:`stringtools.csp.csp`
- * :func:`stringtools.csp.build_frame`
- """
-
- import stringtools
-
- import logging
- import sys
-
- try:
- from config import APP_NAME as ROOT_LOGGER_NAME
- except ImportError:
- ROOT_LOGGER_NAME = 'root'
- logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
-
- DATA_SEPERATOR = b'\n'
-
-
- class csp(object):
- """This class extracts messages from an "csp-stream".
-
- **Example:**
-
- .. literalinclude:: ../examples/csp.csp.py
-
- Will result to the following output:
-
- .. literalinclude:: ../examples/csp.csp.log
- """
- LOG_PREFIX = 'CSP:'
-
- def __init__(self, seperator=DATA_SEPERATOR):
- self.__buffer__ = b''
- self.__seperator__ = seperator
-
- def process(self, data):
- """
- This processes a byte out of a "stp-stream".
-
- :param bytes data: A byte stream
- :returns: A list of the extracted message(s)
- :rtype: list
- """
- if sys.version_info < (3, 0):
- if type(data) is unicode:
- raise TypeError
- #
- rv = (self.__buffer__ + data).split(self.__seperator__)
- self.__buffer__ = rv.pop()
- if len(self.__buffer__) != 0:
- logger.debug('%s Leaving data in buffer (to be processed next time): %s', self.LOG_PREFIX, stringtools.hexlify(self.__buffer__))
- for msg in rv:
- logger.info('%s message identified - %s', self.LOG_PREFIX, stringtools.hexlify(msg))
- return rv
-
-
- def build_frame(msg, seperator=DATA_SEPERATOR):
- """This Method builds an "csp-frame" to be transfered via a stream.
-
- :param str data: A String (Bytes) to be framed
- :returns: The "csp-framed" message to be sent
- :rtype: str
-
- **Example:**
-
- .. literalinclude:: ../examples/csp.build_frame.py
-
- Will result to the following output:
-
- .. literalinclude:: ../examples/csp.build_frame.log
- """
- if seperator in msg:
- raise ValueError
- else:
- return msg + seperator
|