# -*- coding: utf-8 -*-
#
#
# $Id: byteprotocol.py,v 1.3 2004/11/09 05:45:38 xyb Exp $

"""Open Unified Storage System Protocol

Stability: None

@author: U{HD<mailto:hdcola@gmail.com>}

@see: Open Unified Storage System Protocol规范
"""

from twisted.internet import protocol, defer
import struct

class ByteMessageProtocol(protocol.Protocol):
    """二进制流协议处理抽象类"""
    def __init__(self):
        # 接收消息的缓冲区
        self.__buffer = ''

    def dataReceived(self, data):
        """ 查看并解析PDU(protocol data unit)，
        将消息交给rawMessageReceived来进行处理。
        """
        self.__buffer = self.__buffer + data

        while len(self.__buffer) > 3:
            (length,) = struct.unpack('>I', self.__buffer[:4])

            if len(self.__buffer) < length:
                break
            message = self.__buffer[:length]
            self.__buffer = self.__buffer[length:]
            defer.succeed(self.MessageReceived(message))

    def sendData(self, data):
        """将报文发送出去"""
        self.transport.write(data)

    def MessageReceived(self,packet):
        """加载二进制流消息，一定要继承本方法"""
        pass
