Subversion Repositories pytwidcpp

Rev

Rev 3 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

# -*- 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(basic.LineReceiver):
    """
    NMDC Protocol implementation
    """


    delimiter = "|"

    buffer = ""
    encoding = None
    hostname = None

    def lineReceived(self, line):
        print "Line Received: %s" % line
        command, params = self.parseLine(line)
        self.handleCommand(command, params)

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

    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)