Example #1
0
    def loadHandler(self, r_type, h_type, h_name):
        """
        Load the handler config object from the file based on the given info
        """
        # create a handler config object first
        handler_config = HandlerConfig()

        if r_type in ['share']:
            # this is a shared handler, we will require a handler type
            # if the h_type is a handler type class object, translate it into a str
            if h_type is None:
                h_type = self.findHandlerTypeStringFromName(h_name)
            if not isinstance(h_type, basestring):
                h_type = ht.getHandlerTypeName(h_type)
            handler_module = '.'.join(
                ['lib', 'handlers', r_type, h_type, h_name])
        else:
            # this is a robot handler, no handler type required
            handler_module = '.'.join(['lib', 'handlers', r_type, h_name])

        try:
            if h_type in ("Sensor", "Actuator"):
                handler_config.loadHandlerMethod(handler_module)
            else:
                handler_config.loadHandlerMethod(handler_module,
                                                 onlyLoadInit=True)

            handler_config.robot_type = r_type
        except ImportError as import_error:
            # TODO: Log an error here if the handler is necessary
            handler_config = None

        return handler_config
Example #2
0
    def getHandlerConfigDefault(self, r_type, h_type, h_name):
        """
        Get default handler config object from handler_configs if exists
        Or load it from corresponding file if not exits
        given rtype (str: share or robot type (str)), htype (class), h_name (str). NOT yet overridden by .robot defaults
        """

        default_handler_config = None

        if self.handler_configs == {}:
            # if no handler has been loaded yet we will load the handler from file
            default_handler_config = self.loadHandler(r_type, h_type, h_name)
        else:
            # fetch it from the exiting handler_configs dictionary
            if r_type not in self.handler_configs.keys():
                # robot type is not recognized
                logging.warning("Cannot find handler config with robot type {!r}.".format(r_type))
            elif h_type not in self.handler_configs[r_type].keys():
                # handler type is not recognized
                logging.warning("Cannot find handler config with handler type {!r} for robot {!r}.\n \
                                It is possible the handler config was not successfully loaded." \
                                .format(ht.getHandlerTypeName(h_type), r_type))
            else:
                for handler_config in self.handler_configs[r_type][h_type]:
                    if handler_config.name == h_name:
                        # we found the handler config object
                        default_handler_config = deepcopy(handler_config)
                        break

                if default_handler_config is None:
                    # Cannot find handler config object with given name
                    logging.warning("Cannot find handler config with handler name {!r}.".format(h_name))

        return default_handler_config
Example #3
0
    def loadHandler(self, r_type, h_type, h_name):
        """
        Load the handler config object from the file based on the given info
        """
        # create a handler config object first
        handler_config = HandlerConfig()

        if r_type in ['share']:
            # this is a shared handler, we will require a handler type
            # if the h_type is a handler type class object, translate it into a str
            if h_type is None:
                h_type =  self.findHandlerTypeStringFromName(h_name)
            if not isinstance(h_type, basestring):
                h_type = ht.getHandlerTypeName(h_type)
            handler_module = '.'.join(['lib', 'handlers', r_type, h_type, h_name])
        else:
            # this is a robot handler, no handler type required
            handler_module = '.'.join(['lib', 'handlers', r_type, h_name])

        try:
            if h_type in ("Sensor", "Actuator"):
                handler_config.loadHandlerMethod(handler_module)
            else:
                handler_config.loadHandlerMethod(handler_module, onlyLoadInit=True)

            handler_config.robot_type = r_type
        except ImportError as import_error:
            # TODO: Log an error here if the handler is necessary
            handler_config = None

        return handler_config
Example #4
0
    def toString(self):
        """
        Return the string representation of the handler object
        """
        # prepare the input for initiation
        init_method_config = self.getMethodByName('__init__')

        method_input = []
        for para_config in init_method_config.para:
            if para_config.para_type.lower() in ['str', 'string', 'region']:
                if para_config.value is not None:
                    method_input.append(
                        '%s=%s' %
                        (para_config.name, '\"' + para_config.value + '\"'))
            else:
                method_input.append('%s=%s' %
                                    (para_config.name, str(para_config.value)))

        # build the string starting from the type of the robot
        method_string = self.robot_type
        if self.robot_type == 'share':
            # only add the handler type if the robot type is `share`
            method_string += '.' + ht.getHandlerTypeName(self.h_type)

        method_string += ('.' + self.name + '(' + ','.join(method_input) + ')')

        return method_string
Example #5
0
    def prepareHandler(self, handler_config):
        """
        Instantiate the handler object of the given handler config if it is not already instantiated
        Return the handler instance
        """

        # Check if we alreay instantiated the handler
        handler_name = handler_config.name
        h = self.getHandlerInstanceByName(handler_name)

        if h is None:
            # we need to instantiate the handler
            robot_type = handler_config.robot_type

            # construct the handler module path for importing
            if robot_type == "share":
                handler_type_string = ht.getHandlerTypeName(
                    handler_config.h_type)
                handler_module_path = ".".join([
                    "lib", "handlers", robot_type, handler_type_string,
                    handler_name
                ])
            else:
                handler_module_path = ".".join(
                    ["lib", "handlers", robot_type, handler_name])

            # find the handler class object
            h_name, h_type, handler_class = HandlerConfig.loadHandlerClass(
                handler_module_path)

            # get the HMC for the init_method
            init_method_config = handler_config.getMethodByName("__init__")

            # construct the arguments list; everyone gets a reference to executor
            arg_dict = {"executor": self.executor}

            # everyone except for InitHandler gets shared_data too
            if h_type is not ht.InitHandler:
                arg_dict.update(
                    {"shared_data": self.executor.proj.shared_data})

            # add any arguments specific to this method
            arg_dict.update(init_method_config.getArgDict())

            # instantiate the handler
            try:
                h = handler_class(**arg_dict)
            except Exception:
                logging.exception(
                    "Failed during handler {} instantiation".format(
                        handler_module_path))
            else:
                self.handler_instance.append(h)
        return h
Example #6
0
    def prepareHandler(self, handler_config):
        """
        Instantiate the handler object of the given handler config if it is not already instantiated
        Return the handler instance
        """

        # Check if we alreay instantiated the handler
        handler_name = handler_config.name
        h = self.getHandlerInstanceByName(handler_name)

        if h is None:
            # we need to instantiate the handler
            robot_type = handler_config.robot_type

            # construct the handler module path for importing
            if robot_type == "share":
                handler_type_string = ht.getHandlerTypeName(handler_config.h_type)
                handler_module_path = ".".join(["lib", "handlers", robot_type, handler_type_string,  handler_name])
            else:
                handler_module_path = ".".join(["lib", "handlers", robot_type, handler_name])

            # find the handler class object
            h_name, h_type, handler_class = HandlerConfig.loadHandlerClass(handler_module_path)

            # get the HMC for the init_method
            init_method_config = handler_config.getMethodByName("__init__")

            # construct the arguments list; everyone gets a reference to executor
            arg_dict = {"executor": self.executor}

            # everyone except for InitHandler gets shared_data too
            if h_type is not ht.InitHandler:
                arg_dict.update({"shared_data":self.executor.proj.shared_data})

            # add any arguments specific to this method
            arg_dict.update(init_method_config.getArgDict())

            # instantiate the handler
            try:
                h = handler_class(**arg_dict)
            except Exception:
                logging.exception("Failed during handler {} instantiation".format(handler_module_path))
            else:
                self.handler_instance.append(h)
        return h
Example #7
0
 def __repr__(self):
     """
     Overwrite string representation function
     """
     strRepr = ""
     # Only show the atrributes we are interested in
     keyList = ['name', 'r_type', 'handlers']
     for key in keyList:
         if key == 'handlers':
             handler_configs = getattr(self, key, {})
             temp_str_list = []
             for h_type in handler_configs.keys():
                 temp_str_list.append("{0:13}{1:23}{2}".format('', ht.getHandlerTypeName(h_type) + ':', \
                                                          handler_configs[h_type].name))
             strRepr = strRepr + ("{0}{1}\n".format("<"+key+">:\n", '\n'.join(temp_str_list)))
         else:
             strRepr = strRepr + ("{0:13}{1}\n".format("<"+key+">:", getattr(self, key, 'NOT DEFINED')))
     reprString = "\n --Robot <{0}> -- \n".format(self.name) + \
                 strRepr + " -- End of Robot <{0}> -- \n".format(self.name)
     return reprString
Example #8
0
    def getHandlerConfigDefault(self, r_type, h_type, h_name):
        """
        Get default handler config object from handler_configs if exists
        Or load it from corresponding file if not exits
        given rtype (str: share or robot type (str)), htype (class), h_name (str). NOT yet overridden by .robot defaults
        """

        default_handler_config = None

        if self.handler_configs == {}:
            # if no handler has been loaded yet we will load the handler from file
            default_handler_config = self.loadHandler(r_type, h_type, h_name)
        else:
            # fetch it from the exiting handler_configs dictionary
            if r_type not in self.handler_configs.keys():
                # robot type is not recognized
                logging.warning(
                    "Cannot find handler config with robot type {!r}.".format(
                        r_type))
            elif h_type not in self.handler_configs[r_type].keys():
                # handler type is not recognized
                logging.warning("Cannot find handler config with handler type {!r} for robot {!r}.\n \
                                It is possible the handler config was not successfully loaded." \
                                .format(ht.getHandlerTypeName(h_type), r_type))
            else:
                for handler_config in self.handler_configs[r_type][h_type]:
                    if handler_config.name == h_name:
                        # we found the handler config object
                        default_handler_config = deepcopy(handler_config)
                        break

                if default_handler_config is None:
                    # Cannot find handler config object with given name
                    logging.warning(
                        "Cannot find handler config with handler name {!r}.".
                        format(h_name))

        return default_handler_config
Example #9
0
    def toString(self):
        """
        Return the string representation of the handler object
        """
        # prepare the input for initiation
        init_method_config = self.getMethodByName('__init__')

        method_input = []
        for para_config in init_method_config.para:
            if para_config.para_type.lower() in ['str', 'string', 'region']:
                if para_config.value is not None:
                    method_input.append('%s=%s'%(para_config.name, '\"'+para_config.value+'\"'))
            else:
                method_input.append('%s=%s'%(para_config.name, str(para_config.value)))

        # build the string starting from the type of the robot
        method_string = self.robot_type
        if self.robot_type == 'share':
            # only add the handler type if the robot type is `share`
            method_string += '.' + ht.getHandlerTypeName(self.h_type)

        method_string += ('.' + self.name + '(' + ','.join(method_input) + ')')

        return method_string