Source

protocol-example / protocols.py

Full commit

import imp, os, re, inspect, warnings, struct
import ptypes



class Protocol(object):
    def __init__(self, module, version):
        """Create a protocol implementation from spec"""
        self.version = version
        self._mapping = {}
        self.__doc__ = module.__doc__
        members = inspect.getmembers(module)
        for name, member in members:
            if isinstance(member, tuple) and name == name.upper():
                message = ptypes.Message(name, *member)
                self._mapping[name] = message #by name
                self._mapping[member[1]] = message #by type marker
                
    def parse(self, data):
        return self._mapping[struct.unpack("!b", data[0])[0]].parse(data)
    
    def messages(self):
        return set(self._mapping.values())



PROTOCOL_RE = re.compile('^protocol(\d+\.\d+).py$')
def _getprotocolmodules(path):
    warnings.filterwarnings('ignore') 
    for name in os.listdir(path):
        match = PROTOCOL_RE.match(name)
        if not match: continue
        mod = imp.find_module(name[:-3], [path])
        yield match.group(1), imp.load_module(name, *mod)
    warnings.filterwarnings('always')
    

def load_protocols(path):
    protocols = {}
    for name, proto in _getprotocolmodules(path):
        protocols[float(name)] = Protocol(proto, name)
    return protocols

if __name__ == "__main__":
    import document, makejava
    document.documentation('.')
    for protocol in load_protocols('.').values():
        name, java = makejava.javaprotocol(protocol)
        open(name + '.java', 'w').write(java)