Хранилища Subversion pytwidcpp

Редакция

Редакция 2 | Редакция 4 | К новейшей редакции | Авторство | Сравнить с предыдущей | Последнее изменение | Открыть журнал | RSS

# -*- coding: utf-8 -*-
""" PyCODC NMDC/ADC Client """
from twisted.internet import protocol
from twisted.protocols import basic
from twisted.python import log

import socket
import re

class NMDC(protocol.Protocol):
    """
    NMDC Protocol implementation
    """


    buffer = ""
    encoding = None
    hostname = None

    def dataReceived(self, data):
        print "Data: %s" % data
        lines = (self.buffer + data).split("|")
        print self.buffer
        for line in lines:
            if len(line) <= 2:
                continue
            print "Line: %s" % line
            command, params = self.parseLine(line)
        self.handleCommand(command, params)

    def connectionLost(self, reason):
        print "Conlost: %s" %self
        pass

    def connectionMade(self):
        print "Made connect"
        if self.hostname is None:
            self.hostname = socket.getfqdn()

    def sendLine(self, line):
        _to_send = line.encode('utf-8')
        self.transport.write(_to_send)

    def parseLine(self, line):
        """
        Returns NMDC command and params
        """

        print "parse: %s" % line
        if line.startswith("$"):
            try:
                m = re.match("^\$(?P<command>[a-zA-Z]+)[ ](?P<params>.+$)", line)

                command = m.group("command")
                params = m.group("params")
                print "NMDC Command: %s; Params: %s" %(command, params)
            except:
                print "Exception: %s"% line
            return command, params
        else:
            return "", ""

    def handleCommand(self, command, params):
        print "handleCommand: %s %s" % (command, params)
        method = getattr(self, "nmdc_%s" % command, None)
        try:
            if method is not None:
                method(params)
            else: self.nmdc_unknown(command, params)
        except:
            print "handleCommand except"
            log.deferr()
        pass

    def makeAnswer(self, command, params):
        if params is not "":
            answer = "$%s %s|" % (command, params)
        else:
            answer = "$%s|"% command

        self.sendLine(answer)
        print "makeAnswer: %s" % answer

    def nmdc_unknown(self, command, params):
        print "nmdc_%s doesn't exist. Called with params: %s" % (command,params)