Source

imalse / core / cmd / cmd.py

Full commit
"""This file contains the Command Meta Description superclass."""

import jsonpickle
import logging

class UnknownEventException(Exception):
    """Exception for unknown commands."""
    pass

class CMD(object):
    
    """Command Meta Description, a definition of runnable commands."""
    
    name = 'CMD'
    
    def __init__(self, desc=None):
        """Initialize."""
        self.desc = desc
        self.logger = self.set_logger()
        self.node = None

    def set_logger(self):
        """Initialize the logger."""
        logging.basicConfig()
        logger = logging.getLogger(self.name)
        logger.setLevel(logging.DEBUG)
        logger.setLevel(logging.WARNING)
        return logger
    
    def is_okay(self):
        """Check whether this command set is compatible with the node."""
        return True
    
    def trigger(self, event_name, *argv, **kwargv):
        """Trigger an event, the event handler is a class member function"""
        self.logger.debug('%s has been triggered'%(event_name))
        getattr(self, event_name)(*argv, **kwargv)

    def dispatcher(self, sock, data):
        """Execute the commands listed in data
        
        Keyword arguments:
        sock -- the socket that received the data.
        data -- a json encoded object
        
        Raises:
            UnknownEventException
        """
        self.logger.debug('dispatcher recv data' + data)
        if not data:
            return
        
        try:
            unpickled = jsonpickle.decode(data)            
        except ValueError:
            print 'Pickle error'  
            return
                
        self.logger.debug('event_name will be triggered: ' + unpickled.event)        
        self.trigger(unpickled.event, sock, unpickled)

    def install(self, node):
        """Install the command set on the node."""
        if self.is_okay():
            pass
        self.node = node
        node.cmd_set = self

    def start(self):
        """
        
        Start the command set by executing 'start_action' specified in 
        'desc'.
        
        """
        if self.desc != None:
            self.trigger(self.desc.start_action)

    def get_state(self):
        """Get the current state."""
        return self.node.state
    
    def set_state(self, val):
        """Set the current state."""
        self.node.set_state(val)
        
    state = property(get_state, set_state)
    
if __name__ == "__main__":
    import doctest
    doctest.testmod()