#!/usr/bin/env python # -*- coding: utf-8 -*- # """ csp (Carriage-Return seperation protocol) ========================================= **Author:** * Dirk Alders **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 logger_name = 'STRINGTOOLS' logger = logging.getLogger(logger_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