Example #1
0
 def open(self):
     self.id = uuid.uuid4()
     MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     # Ping to make sure the agent is alive.
     self.io_loop.add_timeout(datetime.timedelta(seconds=random.randint(5,30)), self.send_ping)
     global ws_list
     ws_list.add({"id" : self.id, "ws" : self, "open" : True})
Example #2
0
    def __init__(self,
                 name,
                 stop_cb=None,
                 is_manager=False,
                 parser=None,
                 daemonize=True,
                 log_prefix="interface_",
                 log_on_stdout=True,
                 test=False,
                 source=None):
        '''
        Create Interface instance, which defines system handlers
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self,
                        name,
                        type="interface",
                        stop_cb=stop_cb,
                        is_manager=is_manager,
                        parser=parser,
                        daemonize=daemonize,
                        log_prefix=log_prefix,
                        log_on_stdout=log_on_stdout,
                        test=test)

        self.log.info(u"Start of the interface init")
        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(INTERFACE_VENDOR_ID,
                                               self.get_plugin_name(),
                                               self.get_sanitized_hostname())
        # in case we overwrite the source :
        else:
            self.source = source

        ### MQ
        self._mq_name = self.source
        #self.zmq = zmq.Context()
        self.mq_pub = MQPub(self.zmq, self._mq_name)
        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.output'])

        ### Context
        # set the context
        # All elements that may be added in the request sent over MQ
        # * media (irc, audio, sms, ...)
        # * text (from voice recognition)
        # * location (the input element location : this is configured on the input element : kitchen, garden, bedroom, ...)
        # * identity (from face recognition)
        # * mood (from kinect or anything else)
        # * sex (from voice recognition and post processing on the voice)
        self.butler_context = {
            "media": None,
            "location": None,
            "identity": None,
            "mood": None,
            "sex": None
        }
        self.log.info(u"End of the interface init")
Example #3
0
 def __init__(self, name, host):
     """ Constructor
         @param name: plugin name
         @param host: plugin host
     """
     self.name = name
     self.host = host
     self.type = "plugin"
     self.plugin_status = None
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['plugin.status'])
Example #4
0
 def __init__(self, name, host):
     """ Constructor
         @param name: plugin name
         @param host: plugin host
     """
     self.name = name
     self.host = host
     self.type = "plugin"
     self.plugin_status = None
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['plugin.status'])
Example #5
0
 def __init__(self):
     self.ctx = zmq.Context()
     self.WSmessages = Queue()
     self.MQmessages = Queue()
     self.sub = MQAsyncSub.__init__(self, self.ctx, 'admin', [])
     self.pub = MQPub(self.ctx, 'admin-ws')
     self.subscribers = set()
Example #6
0
    def _instanciate(self):
        """ parse the json and load all needed components
        """
        try:
            self._parsed_condition = self.__parse_part(self._json)

            # Set the trigger to the last test of each kind of test
            # Only SensorTest class receive generic_trigger
            self._log.info(u"Scenario '{0}' : configure the trigger to the last item of each test instance".format(remove_accents(self._name)))
            for a_kind_of_test in self._test_instances:
                if a_kind_of_test.startswith("sensor.SensorTest"):
                    self._log.debug(u"Scenario '{0}' : test instance : {1} ({2} items)".format(remove_accents(self._name), a_kind_of_test, len(self._test_instances[a_kind_of_test])))
                    for idx, val in enumerate(self._test_instances[a_kind_of_test]):
                        if val.__class__.__name__ == 'SensorTest':
                            self._log.debug("Set trigger for item '{0}' to generic_trigger".format(idx))
                            val.set_trigger(self.generic_trigger)
                        else:
                            self._log.debug("Set trigger for item '{0}' to dummy".format(idx))
                            val.set_trigger(self._dummy)

            self._log.debug(u"Scenario '{0}' python generated code : \n{1}".format(remove_accents(self._name), self._parsed_condition))
            # this line is to decomment only for debug purpose
            # it will display the evaluated if conditions
            # but so, it will evaluate all sensors, so it may trigger some scenarios on startup in double
            #self._log.debug(u"Now, the python code evaluated is : \n{0}".format(self.__parse_part(self._json, debug = True)))
            tmp = ast.parse(self._parsed_condition)
            #self._compiled_condition = compile(tmp, "Scenario {0}".format(remove_accents(self._name)), 'exec')
            buf = remove_accents(self._name)
            buf = ucode(buf)
            self._compiled_condition = compile(tmp, "Scenario {0}".format(buf), 'exec')
            if len(self._subList) > 0:
                self._sub = MQAsyncSub.__init__(self, zmq.Context(), 'scenario-sensor', set(self._subList))
        except:
            raise
Example #7
0
    def __init__(self):
        """ Initiate DbHelper, Logs and config
        """
        XplPlugin.__init__(self, 'xplgw', log_prefix = "")
        MQAsyncSub.__init__(self, self.zmq, 'xplgw', ['client.conversion', 'client.list'])

        self.log.info(u"XPL manager initialisation...")
        self._db = DbHelper()
        self.pub = MQPub(zmq.Context(), 'xplgw')
        self.stats = None
        self.client_xpl_map = {}
        self.client_conversion_map = {}
        self._load_client_to_xpl_target()
        self._load_conversions()
        self.load()
        self.ready()
Example #8
0
 def __init__(self):
     self.ctx = zmq.Context()
     self.WSmessages = Queue()
     self.MQmessages = Queue()
     self.sub = MQAsyncSub.__init__(self, self.ctx, 'admin', [])
     self.pub = MQPub(self.ctx, 'admin-ws')
     self.subscribers = set()
Example #9
0
    def __init__(self):
        """ Initiate DbHelper, Logs and config
        """
        XplPlugin.__init__(self, 'xplgw', log_prefix="")
        MQAsyncSub.__init__(\
            self, self.zmq, 'xplgw', \
            ['client.conversion', 'client.list'])

        self.log.info(u"XPL manager initialisation...")
        self._db = DbHelper()
        self.pub = MQPub(zmq.Context(), 'xplgw')
        # some initial data sets
        self.client_xpl_map = {}
        self.client_conversion_map = {}
        self._db_sensors = {}
        self._db_xplstats = {}
        # queue to store the message that needs to be ahndled for sensor checking
        self._sensor_queue = Queue.Queue()
        # all command handling params
        # _lock => to be sure to be thread safe
        # _dict => uuid to xplstat translationg
        # _pkt => received messages to check
        self._cmd_lock_d = threading.Lock()
        self._cmd_dict = {}
        self._cmd_lock_p = threading.Lock()
        self._cmd_pkt = {}
        # load some initial data from manager and db
        self._load_client_to_xpl_target()
        self._load_conversions()
        # create a general listener
        self._create_xpl_trigger()
        # start handling the xplmessages
        self._s_thread = self._SensorThread(\
            self.log, self._sensor_queue, \
            self.client_conversion_map, self.pub)
        self._s_thread.start()
        # start handling the command reponses in a thread
        self._c_thread = self._CommandThread(\
            self.log, self._db, self._cmd_lock_d, \
            self._cmd_lock_p, self._cmd_dict, self._cmd_pkt, self.pub)
        self._c_thread.start()
        # start the sensorthread
        self.ready()
Example #10
0
    def __init__(self, name, stop_cb = None, is_manager = False, parser = None,
                 daemonize = True, log_prefix = "interface_", log_on_stdout = True, test = False, source = None):
        '''
        Create Interface instance, which defines system handlers
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self, name, type = "interface", stop_cb = stop_cb, is_manager = is_manager, parser = parser, daemonize = daemonize, log_prefix = log_prefix, log_on_stdout = log_on_stdout, test = test)

        self.log.info(u"Start of the interface init")
        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(INTERFACE_VENDOR_ID, self.get_plugin_name(), self.get_sanitized_hostname())
        # in case we overwrite the source : 
        else:
            self.source = source

        ### MQ
        self._mq_name = self.source
        #self.zmq = zmq.Context()
        self.mq_pub = MQPub(self.zmq, self._mq_name)
        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.output'])

        ### Context
        # set the context
        # All elements that may be added in the request sent over MQ
        # * media (irc, audio, sms, ...)
        # * text (from voice recognition)
        # * location (the input element location : this is configured on the input element : kitchen, garden, bedroom, ...)
        # * identity (from face recognition)
        # * mood (from kinect or anything else) 
        # * sex (from voice recognition and post processing on the voice)
        self.butler_context = {"media" : None,
                               "location" : None,
                               "identity" : None,
                               "mood" : None,
                               "sex" : None
                              }
        self.log.info(u"End of the interface init")
Example #11
0
    def _instanciate(self):
        """ parse the json and load all needed components
        """
        try:
            self._parsed_condition = self.__parse_part(self._json)

            # Set the trigger to the last test of each kind of test
            # Only SensorTest class receive generic_trigger
            self._log.info(
                u"Scenario '{0}' : configure the trigger to the last item of each test instance"
                .format(remove_accents(self._name)))
            for a_kind_of_test in self._test_instances:
                if a_kind_of_test.startswith("sensor.SensorTest"):
                    self._log.debug(
                        u"Scenario '{0}' : test instance : {1} ({2} items)".
                        format(remove_accents(self._name), a_kind_of_test,
                               len(self._test_instances[a_kind_of_test])))
                    for idx, val in enumerate(
                            self._test_instances[a_kind_of_test]):
                        if val.__class__.__name__ == 'SensorTest':
                            self._log.debug(
                                "Set trigger for item '{0}' to generic_trigger"
                                .format(idx))
                            val.set_trigger(self.generic_trigger)
                        else:
                            self._log.debug(
                                "Set trigger for item '{0}' to dummy".format(
                                    idx))
                            val.set_trigger(self._dummy)

            self._log.debug(
                u"Scenario '{0}' python generated code : \n{1}".format(
                    remove_accents(self._name), self._parsed_condition))
            # this line is to decomment only for debug purpose
            # it will display the evaluated if conditions
            # but so, it will evaluate all sensors, so it may trigger some scenarios on startup in double
            #self._log.debug(u"Now, the python code evaluated is : \n{0}".format(self.__parse_part(self._json, debug = True)))
            tmp = ast.parse(self._parsed_condition)
            #self._compiled_condition = compile(tmp, "Scenario {0}".format(remove_accents(self._name)), 'exec')
            buf = remove_accents(self._name)
            buf = ucode(buf)
            self._compiled_condition = compile(tmp, "Scenario {0}".format(buf),
                                               'exec')
            if len(self._subList) > 0:
                self._sub = MQAsyncSub.__init__(self, zmq.Context(),
                                                'scenario-sensor',
                                                set(self._subList))
        except:
            raise
Example #12
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['metrics.browser'])
     IOLoop.instance().start()
Example #13
0
    def __init__(self):

        ### Option parser
        parser = ArgumentParser()
        parser.add_argument("-i",
                          action="store_true",
                          dest="interactive",
                          default=False, \
                          help="Butler interactive mode (must be used WITH -f).")

        Plugin.__init__(self, name='butler', parser=parser)

        ### MQ
        # MQ publisher
        #self._mq_name = "interface-{0}.{1}".format(self._name, self.get_sanitized_hostname())
        self._mq_name = "butler"
        #self.zmq = zmq.Context()
        self.pub = MQPub(self.zmq, self._mq_name)

        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.input'])

        ### Configuration elements
        try:
            cfg = Loader('butler')
            config = cfg.load()
            conf = dict(config[1])

            self.lang = conf['lang']
            self.butler_name = conf['name']
            self.butler_sex = conf['sex']
            self.butler_mood = None
            if self.butler_sex not in SEX_ALLOWED:
                self.log.error(
                    u"Exiting : the butler sex configured is not valid : '{0}'. Expecting : {1}"
                    .format(self.butler_sex, SEX_ALLOWED))
                self.force_leave()
                return

        except:
            self.log.error(
                u"Exiting : error while reading the configuration file '{0}' : {1}"
                .format(CONFIG_FILE, traceback.format_exc()))
            self.force_leave()
            return
        # user name (default is 'localuser')
        # this is not used for now on Domogik side
        self.user_name = "localuser"

        ### Prepare the brain
        # - validate packages

        # Start the brain :)
        self.brain = RiveScript(utf8=True)

        # set rivescript variables

        # Configure bot variables
        # all must be lower case....
        self.log.info("Configuring name and sex : {0}, {1}".format(
            self.butler_name.lower(), self.butler_sex.lower()))
        self.brain.set_variable("name", self.butler_name.lower())
        self.brain.set_variable("fullname", self.butler_name.lower())
        self.brain.set_variable("sex", self.butler_sex.lower())

        # set the PYTHONPATH
        sys.path.append(self.get_libraries_directory())

        # load the brain
        self.brain_content = None
        self.learn_content = None
        self.not_understood_content = None
        self.load_all_brain()

        # shortcut to allow the core brain package to reload the brain for learning
        self.brain.reload_butler = self.reload

        # history
        self.history = []

        print(u"*** Welcome in {0} world, your digital assistant! ***".format(
            self.butler_name))
        print(u"You may type /quit to let {0} have a break".format(
            self.butler_name))

        ### Interactive mode
        if self.options.interactive:
            self.log.info(u"Launched in interactive mode : running the chat!")
            # TODO : run as a thread
            #self.run_chat()
            thr_run_chat = Thread(None, self.run_chat, "run_chat", (), {})
            thr_run_chat.start()
        else:
            self.log.info(u"Not launched in interactive mode")

        ### TODO
        #self.add_stop_cb(self.shutdown)

        self.log.info(u"Butler initialized")
        self.ready()
Example #14
0
    def __init__(self):

        ### Option parser
        parser = ArgumentParser()
        parser.add_argument("-i", 
                          action="store_true", 
                          dest="interactive", 
                          default=False, \
                          help="Butler interactive mode (must be used WITH -f).")

        Plugin.__init__(self, name = 'butler', parser = parser)

        ### MQ
        # MQ publisher
        #self._mq_name = "interface-{0}.{1}".format(self._name, self.get_sanitized_hostname())
        self._mq_name = "butler"
        #self.zmq = zmq.Context()
        self.pub = MQPub(self.zmq, self._mq_name)

        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.input'])


        ### Configuration elements
        try:
            cfg = Loader('butler')
            config = cfg.load()
            conf = dict(config[1])

            self.lang = conf['lang']
            self.butler_name = conf['name']
            self.butler_sex = conf['sex']
            self.butler_mood = None
            if self.butler_sex not in SEX_ALLOWED:
                self.log.error(u"Exiting : the butler sex configured is not valid : '{0}'. Expecting : {1}".format(self.butler_sex, SEX_ALLOWED))
                self.force_leave()
                return
       
        except:
            self.log.error(u"Exiting : error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
            self.force_leave()
            return
        # user name (default is 'localuser')
        # this is not used for now on Domogik side
        self.user_name = "localuser"

        ### Prepare the brain
        # - validate packages

        # Start the brain :)
        self.brain = RiveScript(utf8=True)

        # set rivescript variables

        # Configure bot variables
        # all must be lower case....
        self.log.info("Configuring name and sex : {0}, {1}".format(self.butler_name.lower(), self.butler_sex.lower()))
        self.brain.set_variable("name", self.butler_name.lower())
        self.brain.set_variable("fullname", self.butler_name.lower())
        self.brain.set_variable("sex", self.butler_sex.lower())

        # set the PYTHONPATH
        sys.path.append(self.get_libraries_directory())

        # load the brain
        self.brain_content = None
        self.learn_content = None
        self.not_understood_content = None
        self.load_all_brain()

        # shortcut to allow the core brain package to reload the brain for learning
        self.brain.reload_butler = self.reload


        # history
        self.history = []

        print(u"*** Welcome in {0} world, your digital assistant! ***".format(self.butler_name))
        print(u"You may type /quit to let {0} have a break".format(self.butler_name))


        ### Interactive mode
        if self.options.interactive:
            self.log.info(u"Launched in interactive mode : running the chat!")
            # TODO : run as a thread
            #self.run_chat()
            thr_run_chat = Thread(None,
                                  self.run_chat,
                                  "run_chat",
                                  (),
                                  {})
            thr_run_chat.start()
        else:
            self.log.info(u"Not launched in interactive mode")
        

        ### TODO
        #self.add_stop_cb(self.shutdown)

        self.log.info(u"Butler initialized")
        self.ready()
Example #15
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['device-stats'])
Example #16
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['device.new'])
     IOLoop.instance().start()
Example #17
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['metrics.browser'])
     IOLoop.instance().start()
Example #18
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['package.detail'])
     IOLoop.instance().start()
Example #19
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['package.detail'])
     IOLoop.instance().start()
Example #20
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['client.sensor'])
     IOLoop.instance().start()
Example #21
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['helper.publish'])
     IOLoop.instance().start()
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['metrics.processinfo'])
     IOLoop.instance().start()
Example #23
0
 def __init__(self):
     self.WSmessages = Queue()
     self.MQmessages = Queue()
     self.sub = MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     self.subscribers = set()
Example #24
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test',
                         ['metrics.processinfo'])
     IOLoop.instance().start()
Example #25
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['device.new'])
     IOLoop.instance().start()
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['plugin.configuration'])
     IOLoop.instance().start()
Example #27
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['plugin.status'])
     IOLoop.instance().start()
Example #28
0
 def open(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     # Ping to make sure the agent is alive.
     self.io_loop.add_timeout(datetime.timedelta(seconds=random.randint(5,30)), self.send_ping)
     AdminWebSocket.clients.add(self)
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['interface.input'])
     IOLoop.instance().start()
Example #30
0
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['device-stats'])
Example #31
0
 def open(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     AdminWebSocket.clients.add(self)
Example #32
0
 def open(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     AdminWebSocket.clients.add(self)
 def __init__(self):
     MQAsyncSub.__init__(self, zmq.Context(), 'test', ['client.conversion'])
     IOLoop.instance().start()
Example #34
0
 def __init__(self):
     self.WSmessages = Queue()
     self.MQmessages = Queue()
     self.sub = MQAsyncSub.__init__(self, zmq.Context(), 'admin', [])
     self.subscribers = set()