Exemple #1
0
    def on_mdp_request(self, msg):
        """ Handle Requests over MQ
            @param msg : MQ req message
        """
        try:
            with self._db.session_scope():
                # XplPlugin handles MQ Req/rep also
                XplPlugin.on_mdp_request(self, msg)

                # configuration
                if msg.get_action() == "config.get":
                    self._mdp_reply_config_get(msg)
                elif msg.get_action() == "config.set":
                    self._mdp_reply_config_set(msg)
                elif msg.get_action() == "config.delete":
                    self._mdp_reply_config_delete(msg)
                # devices list
                elif msg.get_action() == "device.get":
                    self._mdp_reply_devices_result(msg)
                # device get params
                elif msg.get_action() == "device.params":
                    self._mdp_reply_devices_params_result(msg)
                # device create
                elif msg.get_action() == "device.create":
                    self._mdp_reply_devices_create_result(msg)
        except exception as e:
            msg = "Exception in on_mdp_request: {0}".format(e)
            self.log.error(msg)
            self.log.error(traceback.format_exc())
            print msg
Exemple #2
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='cidmodem')

        # Configuration
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('cidmodem', 'device')

        cid_command = self._config.query('cidmodem', 'cid-command')

        # Init Modem
        cid = CallerIdModem(self.log, self.send_xpl)

        # Open Modem
        try:
            cid.open(device, cid_command)
        except CallerIdModemException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # Start reading Modem
        cid_process = threading.Thread(None, cid.listen, "listen_cid", (), {})
        cid_process.start()
        self.enable_hbeat()
Exemple #3
0
    def __init__(self, proxy_ip, proxy_port):
        """
        Initiate properties
        Then, start HTTP server and give it initialized data
        @param proxy_ip :  ip of the proxy server
        @param proxy_port :  port of proxy server
        """

        XplPlugin.__init__(self, name='proxy', reload_cb=self.reload_config)
        # logging initialization
        self.log.info("Proxy initialisation ...")
        self.log.debug("locale : %s %s" % locale.getdefaultlocale())
        self._config = Query(self.myxpl, self.log)
        self.server = None
        self.server_process = None
        self.proxy_ip = None
        self.proxy_port = None
        self.use_ssl = False
        self.ssl_certificate = None
        self.server_ip = None
        self.server_port = None
        self.auth_method = None
        self.username = None
        self.password = None
        self.add_stop_cb(self.stop_http)
        self.enable_hbeat()
        self.reload_config()
Exemple #4
0
 def __init__(self):
     """
     Create the X10Main class
     This class is used to connect x10 (through heyu) to the xPL Network
     """
     XplPlugin.__init__(self, name = 'x10_heyu')
     self._heyu_cfg_path_res = ""
     self._config = Query(self.myxpl, self.log)
     self._heyu_cfg_path_res = self._config.query('x10_heyu', 'heyu-cfg-path')
     try:
         self.__myx10 = X10API(self._heyu_cfg_path_res, self.log)
     except Exception:
         self.log.error("Something went wrong during heyu init, check logs")
         self.log.error("Exception : %s" % traceback.format_exc())
         exit(1)
     #Create listeners
     Listener(self.x10_cmnd_cb, self.myxpl, {'schema': 'x10.basic', 'xpltype': 'xpl-cmnd'})
     #One listener for system schema, allowing to reload config
     #Listener(self.heyu_reload_config, self.myxpl, {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
     #                                                'command': 'reload', 'plugin': 'x10'})
     #One listener for system schema, allowing to dump config
     #Listener(self.heyu_dump_config, self.myxpl, {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
     #                                              'command': 'push_config', 'plugin': 'x10'})
     self.log.debug("before start X10monitor")
     self._monitor = X10Monitor(self._heyu_cfg_path_res)
     self._monitor.get_monitor().add_cb(self.x10_monitor_cb)
     self._monitor.get_monitor().start()
     self.enable_hbeat()
     self.log.debug("Heyu correctly started")
Exemple #5
0
    def __init__(self):
        """
        Create the bluez plugin.
        """
        XplPlugin.__init__(self, name='bluez')
        self.log.info("__init__ : Start ...")
        self.config = Query(self.myxpl, self.log)

        self.log.debug("__init__ : Try to start the bluez API")
        try:
            self._bluez = BluezAPI(self.log, self.config, self.myxpl, \
                self.get_stop())
        except:
            error = "Something went wrong during bluezAPI init : %s" %  \
                     (traceback.format_exc())
            self.log.error("__init__ : " + error)

        self.log.debug("__init__ : Try to create listeners")
        Listener(self.basic_cmnd_cb, self.myxpl, {
            'schema': 'bluez.basic',
            'xpltype': 'xpl-cmnd'
        })

        self.add_stop_cb(self._bluez.stop_all)

        #self.enable_helper()
        self.enable_hbeat()
        self._bluez.start_adaptator()
        self.log.info("Plugin bluez correctly started.")
Exemple #6
0
    def __init__(self):
        """
        Create the X10Main class
        This class is used to connect x10 (through cm15a) to the xPL Network
        """
        XplPlugin.__init__(self, name = 'x10cm15a')
        self.log.error("Cm15a correctly started")
        self._device = "/dev/cm15a0"
#        self._config = Query(self.myxpl, self.log)
#        self._device = self._config.query('cm15a', 'cm15a-path')
        if not os.path.exists(self._device):
            self.log.error(self._device + " is not present")
        else:
            self.log.debug("device present as "+self._device)
        self._config = Query(self.myxpl, self.log)
        try:
            self.__myx10 = X10API(self._device, self.log)
        except Exception:
            self.log.error("Something went wrong during cm15a init, check logs")
            self.log.error("Exception : %s" % traceback.format_exc())
            exit(1)
        #Create listeners
        Listener(self.x10_cmnd_cb, self.myxpl, 
                 {'schema': 'x10.basic', 'xpltype': 'xpl-cmnd'})
        self.log.debug("Sending hbeat")
        self.enable_hbeat()
        self.log.debug("Cm15a correctly started")
Exemple #7
0
    def on_mdp_request(self, msg):
        """ Handle Requests over MQ 
            @param msg : MQ req message
        """
        # XplPlugin handles MQ Req/rep also
        XplPlugin.on_mdp_request(self, msg)

        ### packages details
        # retrieve the packages details
        if msg.get_action() == "package.detail.get":
            self.log.info(u"Packages details request : {0}".format(msg))
            self._mdp_reply_packages_detail()

        ### device_types
        # retrieve the device_types
        elif msg.get_action() == "device_types.get":
            self.log.info(u"Device types request : {0}".format(msg))
            self._mdp_reply_device_types(msg)

        ### clients list and details
        # retrieve the clients list
        elif msg.get_action() == "client.list.get":
            self.log.info(u"Clients list request : {0}".format(msg))
            self._mdp_reply_clients_list()

        # retrieve the clients details
        elif msg.get_action() == "client.detail.get":
            self.log.info(u"Clients details request : {0}".format(msg))
            self._mdp_reply_clients_detail()

        # start clients
        elif msg.get_action() == "plugin.start.do":
            self.log.info(u"Plugin startup request : {0}".format(msg))
            self._mdp_reply_plugin_start(msg)
Exemple #8
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='k8056')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # Configuration
        device = self.get_config("k8056_device")                         # Serial port
        if device is None:
            self.log.error('### Device is not configured, exitting')
            self.force_leave()
            return

        # Init relayboard
        self.k8056_board = K8056(self.log)

        # Open serial port
        try:
            self.k8056_board.open(device)
        except K8056Exception as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # Create listeners
        self.log.info("### Creating listener for K8056")
        Listener(self.k8056_cmnd_cb, self.myxpl, {'xpltype': 'xpl-cmnd', 'schema': 'ac.basic'})    # ac.basic { address=0 unit=1 command=off }

        self.ready()
Exemple #9
0
 def __init__(self):
     """
     Create the X10Main class
     This class is used to connect x10 (through heyu) to the xPL Network
     """
     XplPlugin.__init__(self, name='x10_heyu')
     self._heyu_cfg_path_res = ""
     self._config = Query(self.myxpl, self.log)
     self._heyu_cfg_path_res = self._config.query('x10_heyu',
                                                  'heyu-cfg-path')
     try:
         self.__myx10 = X10API(self._heyu_cfg_path_res, self.log)
     except Exception:
         self.log.error("Something went wrong during heyu init, check logs")
         self.log.error("Exception : %s" % traceback.format_exc())
         exit(1)
     #Create listeners
     Listener(self.x10_cmnd_cb, self.myxpl, {
         'schema': 'x10.basic',
         'xpltype': 'xpl-cmnd'
     })
     #One listener for system schema, allowing to reload config
     #Listener(self.heyu_reload_config, self.myxpl, {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
     #                                                'command': 'reload', 'plugin': 'x10'})
     #One listener for system schema, allowing to dump config
     #Listener(self.heyu_dump_config, self.myxpl, {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
     #                                              'command': 'push_config', 'plugin': 'x10'})
     self.log.debug("before start X10monitor")
     self._monitor = X10Monitor(self._heyu_cfg_path_res)
     self._monitor.get_monitor().add_cb(self.x10_monitor_cb)
     self._monitor.get_monitor().start()
     self.enable_hbeat()
     self.log.debug("Heyu correctly started")
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='weather')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        # get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device = True)


        self.weather_manager = Weather(self.log, 
                                       self.send_xpl_sensor_basic, 
                                       self.send_xpl_weather_forecast, 
                                       self.get_stop(), 
                                       self.get_parameter_for_feature)
        # Start getting weather informations
        weather_process = threading.Thread(None,
                                    self.weather_manager.start_loop,
                                    "weather-process",
                                    (self.devices,),
                                    {})
        self.register_thread(weather_process)
        weather_process.start()

        self.ready()
Exemple #11
0
    def __init__(self):
        """
        Create the bluez plugin.
        """
        XplPlugin.__init__(self, name = 'bluez')
        self.log.info("__init__ : Start ...")
        self.config = Query(self.myxpl, self.log)

        self.log.debug("__init__ : Try to start the bluez API")
        try:
            self._bluez = BluezAPI(self.log, self.config, self.myxpl, \
                self.get_stop())
        except:
            error = "Something went wrong during bluezAPI init : %s" %  \
                     (traceback.format_exc())
            self.log.error("__init__ : "+error)

        self.log.debug("__init__ : Try to create listeners")
        Listener(self.basic_cmnd_cb, self.myxpl,
                 {'schema': 'bluez.basic', 'xpltype': 'xpl-cmnd'})

        self.add_stop_cb(self._bluez.stop_all)

        #self.enable_helper()
        self.enable_hbeat()
        self._bluez.start_adaptator()
        self.log.info("Plugin bluez correctly started.")
Exemple #12
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='cidmodem')

        # Configuration
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('cidmodem', 'device')

        cid_command = self._config.query('cidmodem', 'cid-command')

        # Init Modem
        cid  = CallerIdModem(self.log, self.send_xpl)
        
        # Open Modem
        try:
            cid.open(device, cid_command)
        except CallerIdModemException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return
            
        # Start reading Modem
        cid_process = threading.Thread(None,
                                   cid.listen,
                                   "listen_cid",
                                   (),
                                   {})                                  
        cid_process.start()                              
        self.enable_hbeat()
Exemple #13
0
    def __init__(self):
        """ Create lister for google agenda requets
        """
        XplPlugin.__init__(self, name = 'gagenda')

        # Create logger
        self.log.debug("Listener for Google agenda created")

        # Get config
        self._config = Query(self.myxpl, self.log)
        self._email = self._config.query('gagenda', 'email')
        self._password = self._config.query('gagenda', 'password')
        self._calendar_name = self._config.query('gagenda', 'calendarname')

        # Create object
        self._gagenda_manager = GAgenda(self.log, \
                                       self._email, \
                                       self._password, \
                                       self._calendar_name, \
                                       self._broadcast_events)

        # Create listener for today
        Listener(self.gagenda_cb, self.myxpl, {'schema': 'calendar.request',
                'xpltype': 'xpl-cmnd', 'command': 'REQUEST'})
        self.enable_hbeat()
Exemple #14
0
 def __init__(self):
     parser = ArgumentParser()
     parser.add_argument(dest="type", help="XPL message type.")
     parser.add_argument(dest="schema", help="XPL message schema.")
     parser.add_argument(
         dest="message",
         help="XPL message data, comma seperated list (key=val,key2=val2).")
     parser.add_argument("-t",
                         "--target",
                         dest="target",
                         default=None,
                         help="XPL message target.")
     parser.add_argument("-s",
                         "--source",
                         dest="source",
                         default=None,
                         help="XPL message source.")
     XplPlugin.__init__(self,
                        name='send',
                        daemonize=False,
                        parser=parser,
                        nohub=True)
     mess = self.forge_message()
     self.log.debug(u"Send message : %s" % mess)
     self.myxpl.send(mess)
     self.force_leave()
Exemple #15
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='mirror')
        # Get config
        #   - device
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('mirror', 'device')

        # Init Mir:ror
        mirror  = Mirror(self.log, self.send_xpl)
        
        # Open Mir:ror
        try:
            mirror.open(device)
        except MirrorException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return
            
        # Start reading Mir:ror
        mirror_process = threading.Thread(None,
                                   mirror.listen,
                                   "mirror-process-reader",
                                   (self.get_stop(),),
                                   {})
        self.register_thread(mirror_process)
        mirror_process.start()
        self.enable_hbeat()
Exemple #16
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='weather')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        # get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=True)

        self.weather_manager = Weather(self.log, self.send_xpl_sensor_basic,
                                       self.send_xpl_weather_forecast,
                                       self.get_stop(),
                                       self.get_parameter_for_feature)
        # Start getting weather informations
        weather_process = threading.Thread(None,
                                           self.weather_manager.start_loop,
                                           "weather-process", (self.devices, ),
                                           {})
        self.register_thread(weather_process)
        weather_process.start()

        self.ready()
Exemple #17
0
    def __init__(self):
        '''
        Create the plcbusMain class
        This class is used to connect PLCBUS to the xPL Network
        '''
        # Load config
        XplPlugin.__init__(self, name='plcbus')
        # Create listeners
        Listener(self._plcbus_cmnd_cb, self.myxpl, {
            'schema': 'plcbus.basic',
            'xpltype': 'xpl-cmnd',
        })
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('plcbus', 'device')
        self._usercode = self._config.query('plcbus', 'usercode')
        self._probe_inter = int(self._config.query('plcbus', 'probe-interval'))
        self._probe_list = self._config.query('plcbus', 'probe-list')

        # Create log instance
        self.api = PLCBUSAPI(self.log, device, self._command_cb,
                             self._message_cb)
        self.add_stop_cb(self.api.stop)
        if self._probe_inter == 0:
            self.log.warning(
                "The probe interval has been set to 0. This is not correct. The plugin will use a probe interval of 5 seconds"
            )
            self._probe_inter = 5
        self._probe_status = {}
        self._probe_thr = XplTimer(self._probe_inter, self._send_probe,
                                   self.myxpl)
        self._probe_thr.start()
        #       self.register_timer(self._probe_thr)
        self.enable_hbeat()
Exemple #18
0
 def __init__(self):
     XplPlugin.__init__(self, name="scenario")
     self._backend = ScenarioManager(self.log)
     self.add_stop_cb(self.end)
     self.add_stop_cb(self.shutdown)
     self.log.info(u"Scenario Frontend and Manager initialized, let's wait for some work.")
     self.ready()
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='rfxbnz')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # Configuration
        host = self.get_config("host")                         # host where rfxcomrx run
        if host is None:
            self.log.error('### Host is not configured, exiting')
            self.force_leave()
            return

        self.lastTimestampHbeat = time.time()

        # Create listeners
        self.log.info("==>  Creating listener for rfxbnz")
        Listener(self.rfxbnz_stat_cb, self.myxpl, {'xplsource': 'bnz-rfxcomrx.' + host, 'xpltype': 'xpl-stat', 'schema': 'hbeat.app'})

        self.log.info("==> Launch thread to rfxbnz_chk_hbeat")
        threads = {}
        thr_name = "rfxbnz_chk"
        threads[thr_name] = threading.Thread(None,
                                            self.rfxbnz_chk_hbeat,
                                            thr_name,
                                            (self.log,
                                                self.get_stop()),
                                            {})
        threads[thr_name].start()
        self.register_thread(threads[thr_name])

        self.ready()
Exemple #20
0
    def __init__(self):
        """ Create lister for google agenda requets
        """
        XplPlugin.__init__(self, name='gagenda')

        # Create logger
        self.log.debug("Listener for Google agenda created")

        # Get config
        self._config = Query(self.myxpl, self.log)
        self._email = self._config.query('gagenda', 'email')
        self._password = self._config.query('gagenda', 'password')
        self._calendar_name = self._config.query('gagenda', 'calendarname')

        # Create object
        self._gagenda_manager = GAgenda(self.log, \
                                       self._email, \
                                       self._password, \
                                       self._calendar_name, \
                                       self._broadcast_events)

        # Create listener for today
        Listener(
            self.gagenda_cb, self.myxpl, {
                'schema': 'calendar.request',
                'xpltype': 'xpl-cmnd',
                'command': 'REQUEST'
            })
        self.enable_hbeat()
Exemple #21
0
    def __init__(self):
        '''
        Create the plcbusMain class
        This class is used to connect PLCBUS to the xPL Network
        '''
        # Load config
        XplPlugin.__init__(self, name = 'plcbus')
        # Create listeners
        Listener(self._plcbus_cmnd_cb, self.myxpl, {
            'schema': 'plcbus.basic',
            'xpltype': 'xpl-cmnd',
        })
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('plcbus', 'device')
        self._usercode = self._config.query('plcbus', 'usercode')
        self._probe_inter = int( self._config.query('plcbus', 'probe-interval'))
        self._probe_list = self._config.query('plcbus', 'probe-list')

        # Create log instance
        self.api = PLCBUSAPI(self.log, device, self._command_cb, self._message_cb)
        self.add_stop_cb(self.api.stop)
        if self._probe_inter == 0:
            self.log.warning("The probe interval has been set to 0. This is not correct. The plugin will use a probe interval of 5 seconds")
            self._probe_inter = 5 
        self._probe_status = {}
        self._probe_thr = XplTimer(self._probe_inter, self._send_probe, self.myxpl)
        self._probe_thr.start()
#       self.register_timer(self._probe_thr)
        self.enable_hbeat()
Exemple #22
0
    def __init__(self):
        """ Create lister and launch bg listening
        """
        try:
            XplPlugin.__init__(self, name = 'karotz')
        except:
            self.log.error("Error to create Karotz Xplplugin=%s" % (traceback.format_exc()))
            return
            
        self._config = Query(self.myxpl, self.log)

        self.instid = self._config.query('karotz', 'installid')
        self.lang = self._config.query('karotz', 'language')
        
        try:
            self.log.info("Starting library")
            self.karotz=Karotz(self.log,self.instid)
            self.log.info("Started")
        except:
            self.log.error("Error to create Karotz object=%s" % (traceback.format_exc()))
            return

                
        self.log.info("Creating listener for Karotz")
        Listener(self.xpl_command, self.myxpl, {'schema': 'karotz.basic', 'xpltype': 'xpl-cmnd'})
        

        #self.add_stop_cb(self.stop)
        self.enable_hbeat()

        self.log.info("Plugin ready :)")
Exemple #23
0
    def __init__(self):
        parser = OptionParser()
        parser.add_option("-c", action="store_true", dest="compress", \
		default=False, help="Diaply data in a compress way")
        parser.add_option("-t", action="store", dest="xpltype", \
                default=None, type="string", \
                help="Filter messages on XPL message type")
        parser.add_option("-s", action="store", dest="xplsource", \
                default=None, type="string", \
                help="Filter messages on XPL source field")
        parser.add_option("-S", action="store", dest="xplschema", \
                default=None, type="string", \
                help="Filter messages on XPL schema field")
        parser.add_option("-i", action="store", dest="xplinstance", \
                default=None, type="string", \
                help="Filter messages on XPL instance")
        XplPlugin.__init__(self, name='dump_xpl', daemonize=False, \
                parser=parser)
        fil = {}
        if self.options.xpltype != None:
            fil['xpltype'] = self.options.xpltype
        if self.options.xplsource != None:
            fil['xplsource'] = self.options.xplsource
        if self.options.xplschema != None:
            fil['schema'] = self.options.xplschema
        if self.options.xplinstance != None:
            fil['xplinstance'] = self.options.xplinstance
        Listener(self._sniffer_cb, self.myxpl, filter=fil)
        self.enable_hbeat()
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='irtrans')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device = False)
        # get the config values
        self.managerClients = ManagerClients(self,  self.send_xplTrig)
        for a_device in self.devices :
            try :
                if (a_device['device_type_id'] != 'irtrans.irtrans_lan') and (a_device['device_type_id'] != 'irtrans.irwsserver') :
                    self.log.error(u"No a device type reconized : {0}".format(a_device['device_type_id']))
                    break
                else :
                    if self.managerClients.addClient(a_device) :
                        self.log.info("Ready to work with device {0}".format(getIRTransId(a_device)))
                    else : self.log.info("Device parameters not configured, can't create IRTrans Client : {0}".format(getIRTransId(a_device)))
            except:
                self.log.error(traceback.format_exc())
                # we don't quit plugin if an error occured
                #self.force_leave()
                #return
        # Create the xpl listeners
        Listener(self.handle_xpl_cmd, self.myxpl,{'schema': 'irtrans.basic',
                                                                        'xpltype': 'xpl-cmnd'})
        print "Plugin ready :)"
        self.log.info("Plugin ready :)")
        self.ready()
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='daikcode')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device = False)
        # get the config values
        self.remoteManager = RemoteManager(self, self.send_xpl)
        for a_device in self.devices :
            try :
                if a_device['device_type_id'] != 'daikcode.remotearc' :
                #if device_name == None  or irtransmitter == None or options == None :
                    self.log.error(u"No daikcode.remotearc device type")
                    break
                else :
                    self.remoteManager.addRemote(a_device)
                    self.log.debug("Ready to work with device {0}".format(getRemoteId(a_device)))
            except:
                self.log.error(traceback.format_exc())
                # we don't quit plugin if an error occured
                #self.force_leave()
                #return
         # Create the xpl listeners
        Listener(self.handle_xpl_cmd, self.myxpl,{'schema': 'daikin.basic',
                                                                        'xpltype': 'xpl-cmnd'})
        Listener(self.handle_xpl_trig, self.myxpl,{'schema': 'ir.basic',
                                                                        'xpltype': 'xpl-trig'})
        print "Plugin ready :)"
        self.log.info("Plugin ready :)")
        self.ready()
Exemple #26
0
 def __init__(self):
     """
     Create the tsChacon class
     This class is used to connect chacon devices (through TellSitck) to the xPL Network
     """
     XplPlugin.__init__(self, name='tschacon')
     self.log.debug("tschacon correctly started")
     self._device = "/dev/tellstick"
     #Check if the device exists
     if not os.path.exists(self._device):
         self.log.error(self._device + " is not present")
     else:
         self.log.debug("device present as " + self._device)
     self._config = Query(self.myxpl, self.log)
     try:
         self.__mytellstick = TellStick()
     except Exception:
         self.log.error(
             "Something went wrong during TellStick init, check logs")
         self.log.error("Exception : %s" % traceback.format_exc())
         exit(1)
     #Create listeners
     Listener(self.tsChacon_cmnd_cb, self.myxpl, {
         'schema': 'ts.arctech',
         'xpltype': 'xpl-cmnd'
     })
     self.enable_hbeat()
     self.log.debug("tschacon plugin correctly started")
Exemple #27
0
   def __init__(self):
       parser = OptionParser()
       parser.add_option("-c", action="store_true", dest="compress", \
 default=False, help="Diaply data in a compress way")
       parser.add_option("-t", action="store", dest="xpltype", \
               default=None, type="string", \
               help="Filter messages on XPL message type")
       parser.add_option("-s", action="store", dest="xplsource", \
               default=None, type="string", \
               help="Filter messages on XPL source field")
       parser.add_option("-S", action="store", dest="xplschema", \
               default=None, type="string", \
               help="Filter messages on XPL schema field")
       parser.add_option("-i", action="store", dest="xplinstance", \
               default=None, type="string", \
               help="Filter messages on XPL instance")
       XplPlugin.__init__(self, name='dump_xpl', daemonize=False, \
               parser=parser)
       fil = {}
       if self.options.xpltype != None:
           fil['xpltype'] = self.options.xpltype
       if self.options.xplsource != None:
           fil['xplsource'] = self.options.xplsource
       if self.options.xplschema != None:
           fil['schema'] = self.options.xplschema
       if self.options.xplinstance != None:
           fil['xplinstance'] = self.options.xplinstance
       Listener(self._sniffer_cb, self.myxpl, filter=fil)
       self.enable_hbeat()
Exemple #28
0
    def __init__(self):
        """
        Create the tsChacon class
        This class is used to connect chacon devices (through TellSitck) to the xPL Network
        """
        XplPlugin.__init__(self, name = 'tschacon')
        self.log.debug("tschacon correctly started")
        self._device = "/dev/tellstick"
	#Check if the device exists
        if not os.path.exists(self._device):
            self.log.error(self._device + " is not present")
        else:
            self.log.debug("device present as "+self._device)
        self._config = Query(self.myxpl, self.log)
        try:
            self.__mytellstick = TellStick()
        except Exception:
            self.log.error("Something went wrong during TellStick init, check logs")
            self.log.error("Exception : %s" % traceback.format_exc())
            exit(1)
        #Create listeners
        Listener(self.tsChacon_cmnd_cb, self.myxpl, 
                 {'schema': 'ts.arctech', 'xpltype': 'xpl-cmnd'})
        self.enable_hbeat()
        self.log.debug("tschacon plugin correctly started")
Exemple #29
0
    def __init__(self):
        '''
        Start teleinfo device handler
        '''
        XplPlugin.__init__(self, name='teleinfo')
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('teleinfo', 'device')
        interval = self._config.query('teleinfo', 'interval')

        # Init Teleinfo
        teleinfo  = Teleinfo(self.log, self.send_xpl)
        
        # Open Teleinfo modem
        try:
            teleinfo.open(device)
        except TeleinfoException as err:
            self.log.error(err.value)
            print(err.value)
            self.force_leave()
            return
            
        self.add_stop_cb(teleinfo.close)
        # Start reading Teleinfo
        teleinfo_process = threading.Thread(None,
                                   teleinfo.listen,
                                   'teleinfo-listen',
                                   (float(interval),),
                                   {})                                  
        teleinfo_process.start()                              
        self.enable_hbeat()
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        XplPlugin.on_mdp_request(self, msg)
        if msg.get_action() == "client.cmd":
            print(msg)
            reason = None
            status = True
            data = msg.get_data()
            if 'blacklist' in data:
                bl = data['blacklist']
            else:
                reason = u"Invalid command : no blacklist key in message"
                status = False

            if status == True:
                try:
                    with open(self.blacklist_file, 'ab') as fp_blacklist:
                        fp_blacklist.write("\n{0};{1}".format("manual blacklisting", bl))
                except:
                    reason = u"Error while completing blacklist file : {0}. Error is : {1}".format(self.blacklist_file, traceback.format_exc())
                    self.log.error(reason)
                    status = False
                self.load_blacklist()


            self.log.info("Reply to command")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())

            if status == True:
                thread.start_new_thread(self.open_modems, ())
Exemple #31
0
    def __init__(self):
        """ Create lister for XBMC notifications
        """
        XplPlugin.__init__(self, name='xbmc_not')
        # Create logger
        self.log.debug("Listener for XBMC notifications created")

        # Get configuration
        self._config = Query(self.myxpl, self.log)
        address = self._config.query('xbmc_not', 'address')
        delay = self._config.query('xbmc_not', 'delay')
        maxdelay = self._config.query('xbmc_not', 'maxdelay')

        self.log.debug("Config : address = " + address)
        self.log.debug("Config : delay = " + delay)
        self.log.debug("Config : maxdelay = " + maxdelay)

        # Create XBMCNotification object
        self.xbmc_notification_manager = XBMCNotification(self.log, address, delay, \
                                                         maxdelay)

        # Create listeners
        Listener(self.xbmc_notification_cb, self.myxpl, {
            'schema': 'osd.basic',
            'xpltype': 'xpl-cmnd'
        })
        self.enable_hbeat()

        self.enable_hbeat()
Exemple #32
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='mirror')
        # Get config
        #   - device
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('mirror', 'device')

        # Init Mir:ror
        mirror = Mirror(self.log, self.send_xpl)

        # Open Mir:ror
        try:
            mirror.open(device)
        except MirrorException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # Start reading Mir:ror
        mirror_process = threading.Thread(None, mirror.listen,
                                          "mirror-process-reader",
                                          (self.get_stop(), ), {})
        self.register_thread(mirror_process)
        mirror_process.start()
        self.enable_hbeat()
Exemple #33
0
    def __init__(self):
        # Connect to the socket

        XplPlugin.__init__(self, name = 'mochad')

        self.mochad_socket = None

        self._config = Query(self.myxpl, self.log)
        self.__host = self._config.query('mochad','mochad-host')
        self.__port = self._config.query('mochad','mochad-port')
        if self._config.query('mochad','cm15') == "True":
            self.__cm15 = True
        else:
            self.__cm15 = False
        if self._config.query('mochad','cm19') == "True":
            self.__cm19 = True
        else:
            self.__cm19 = False

        if self.__cm15:
            self.__itf = "pl"
        elif self.__cm19:
            self.__itf = "rf"

        self.connect()

        child_pid = os.fork()
        if child_pid == 0:
            self.listener()
        else:
            return None
Exemple #34
0
    def __init__(self):
        """ Init manager
        """
        XplPlugin.__init__(self, name = 'sms')

        # Configuration

        self._config = Query(self.myxpl, self.log)
        login = self._config.query('sms', 'login')
        password = self._config.query('sms', 'password')
        phone = self._config.query('sms', 'phone')
	operator = self._config.query('sms', 'operator')
	operator = operator.lower()

        if (operator == "orange"):
		from domogik_packages.xpl.lib.sms_orange import Sms
	if (operator == "sfr"):
		from domogik_packages.xpl.lib.sms_sfr import Sms
	if (operator == "bouygues"):
		from domogik_packages.xpl.lib.sms_bouygues import Sms		
        self.log.debug("Init info for sms created")
        ### Create Sms objects
        self.my_sms = Sms(self.log,login,password,phone)
	self.log.debug("Create object for sms created")
        # Create listener
        Listener(self.sms_cb, self.myxpl, {'schema': 'sendmsg.basic','xpltype': 'xpl-cmnd'})
        self.log.debug("Listener for sms created")

        self.enable_hbeat()
Exemple #35
0
 def __init__(self):
     """
     Create the X10Main class
     This class is used to connect x10 (through cm15a) to the xPL Network
     """
     XplPlugin.__init__(self, name='x10cm15a')
     self.log.error("Cm15a correctly started")
     self._device = "/dev/cm15a0"
     #        self._config = Query(self.myxpl, self.log)
     #        self._device = self._config.query('cm15a', 'cm15a-path')
     if not os.path.exists(self._device):
         self.log.error(self._device + " is not present")
     else:
         self.log.debug("device present as " + self._device)
     self._config = Query(self.myxpl, self.log)
     try:
         self.__myx10 = X10API(self._device, self.log)
     except Exception:
         self.log.error(
             "Something went wrong during cm15a init, check logs")
         self.log.error("Exception : %s" % traceback.format_exc())
         exit(1)
     #Create listeners
     Listener(self.x10_cmnd_cb, self.myxpl, {
         'schema': 'x10.basic',
         'xpltype': 'xpl-cmnd'
     })
     self.log.debug("Sending hbeat")
     self.enable_hbeat()
     self.log.debug("Cm15a correctly started")
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='test', test = True, source='arduino-co2.myarduino')

        self.send_xpl(schema = "sensor.basic", data = {"current" : 213, "device" : "co2sensor1", "type" : "co2"})
        self.ready()
Exemple #37
0
    def __init__(self, proxy_ip, proxy_port):
        """
        Initiate properties
        Then, start HTTP server and give it initialized data
        @param proxy_ip :  ip of the proxy server
        @param proxy_port :  port of proxy server
        """

        XplPlugin.__init__(self, name = 'proxy',
            reload_cb = self.reload_config)
        # logging initialization
        self.log.info("Proxy initialisation ...")
        self.log.debug("locale : %s %s" % locale.getdefaultlocale())
        self._config = Query(self.myxpl, self.log)
        self.server = None
        self.server_process = None
        self.proxy_ip = None
        self.proxy_port = None
        self.use_ssl = False
        self.ssl_certificate = None
        self.server_ip = None
        self.server_port = None
        self.auth_method = None
        self.username = None
        self.password = None
        self.add_stop_cb(self.stop_http)
        self.enable_hbeat()
        self.reload_config()
Exemple #38
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='velbus')
        self._config = Query(self.myxpl, self.log)
        # get the config values
        device_type = self._config.query('velbus', 'connection-type')
        if device_type == None:
            self.log.error('Devicetype is not configured, exitting') 
            print('Devicetype is not configured, exitting')
            self.force_leave()
            return
        device = self._config.query('velbus', 'device')
        #device = '192.168.1.101:3788'
        if device == None:
            self.log.error('Device is not configured, exitting') 
            print('Device is not configured, exitting')
            self.force_leave()
            return
        # validate the config vars
        if (device_type != 'serial') and (device_type != 'socket'):
            self.log.error('Devicetype must be socket or serial, exitting') 
            print('Devicetype must be socket or serial, exitting')
            self.force_leave()
            return
        if device_type == 'socket' and not re.match('[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]+', device):
            self.log.error('A socket device is in the form of <ip>:<port>, exitting') 
            print('A socket device is in the form of <ip>:<port>, exitting')
            self.force_leave()
            return

        # Init RFXCOM
        self.manager  = VelbusDev(self.log, self.send_xpl,
			self.send_trig, self.get_stop())
        self.add_stop_cb(self.manager.close)
        
        # Create a listener for all messages used by RFXCOM
        Listener(self.process_lighting_basic, self.myxpl,
                 {'xpltype': 'xpl-cmnd', 'schema': 'lighting.basic'})
        Listener(self.process_shutter_basic, self.myxpl,
                 {'xpltype': 'xpl-cmnd', 'schema': 'shutter.basic'})
        # Create listeners
        try:
            self.manager.open(device, device_type)
        except VelbusException as ex:
            self.log.error(ex.value)
            self.force_leave()
            return
        self.manager.scan()
            
        # Start reading RFXCOM
        listenthread = threading.Thread(None,
                                   self.manager.listen,
                                   "velbus-process-reader",
                                   (self.get_stop(),),
                                   {})
        self.register_thread(listenthread)
        listenthread.start()
        self.enable_hbeat()
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='script')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=True)
        # print(self.devices)        # List devices créés dans plugin ?

        # Init script functions
        self.script = Script(self.log)

        # ### For each device
        for a_device in self.devices:
            # self.log.info(u"a_device:   %s" % format(a_device))

            device_name = a_device["name"]                                      # Ex.: "Conso Elec Jour"
            device_typeid = a_device["device_type_id"]                          # Ex.: "script.info_number | script.info_binary | script.info_string | script.action"
            device_statname = device_typeid.replace('.', '_')                   # Ex.: "script_info_number | script_info_binary | script_info_string | script_action"
            command_script = self.get_parameter_for_feature(a_device, "xpl_stats", "stat_" + device_statname, "command")    # Ex.: "/home/user/getElec.sh -jour"
            if device_typeid != "script.action":                                # Shedule only script_info_* scripts
                command_interval = self.get_parameter(a_device, "interval")     # Ex.: "60" in secondes
                self.log.info(u"==> Device '{0}' ({1}) to call = '{2}' with interval = {3}s".format(device_name, device_typeid, command_script, command_interval))
                if command_interval > 0:
                    thr_name = "dev_{0}-{1}".format(a_device['id'], "script_info")
                    self.log.info(u"==> Launch script thread '%s' for '%s' device !" % (thr_name, device_name))
                    threads = {}
                    threads[thr_name] = threading.Thread(None,
                                                        self.script.runScheduledCmd,
                                                        thr_name,
                                                        (self.log,
                                                            device_name,
                                                            device_statname,
                                                            command_script,
                                                            command_interval,
                                                            self.send_xpl,
                                                            self.get_stop()
                                                        ),
                                                    {})
                    threads[thr_name].start()
                    self.register_thread(threads[thr_name])
                    self.log.info(u"==> Wait some time before running the next scheduled script ...")
                    time.sleep(5)        # Wait some time to not start the script with the same interval et the same time.
                else:
                    self.log.info(u"==> Script thread '%s' for '%s' device is DISABLED (interval < 0) !" % (thr_name, device_name))

            else:
                self.log.info(u"==> Device '{0}' ({1}) to call = '{2}'".format(device_name, device_typeid, command_script))

        # Create listeners
        self.log.info(u"==> Creating listener for Script")
        Listener(self.scriptCmnd_cb, self.myxpl, {'xpltype': 'xpl-cmnd', 'schema': 'exec.basic'})

        self.ready()
Exemple #40
0
 def __init__(self):
     XplPlugin.__init__(self, name = 'xpl_time')
     
     self._listen_thr = XplTimer(TIME_BETWEEN_EACH_MESSAGE, \
                                 self._send_datetime,
                                 self.myxpl)
     self._listen_thr.start()
     self.enable_hbeat()
Exemple #41
0
 def __init__(self, name, stop_cb=None, is_manager=False, reload_cb=None, \
     dump_cb=None, parser=None, daemonize = True):
     """
     Initialize the class
     """
     XplPlugin.__init__(self, name, stop_cb, is_manager, reload_cb, \
         dump_cb, parser, daemonize)
     self.__helper = PluginHelper(self)
Exemple #42
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='yweather')

        # Get config
        self._config = Query(self.myxpl, self.log)
        unit = self._config.query('yweather', 'unit' )
        if unit == None:
            self.log.error("Unit not configured : exiting")
            print("Unit not configured : exiting")
            self.force_leave()
            return
        unit = unit.lower()
        
        self.enable_current = self._config.query('yweather', 'en-current' )
        self.enable_previsionnal = self._config.query('yweather', 'en-prev' )

        self.cities = {}
        num = 1
        loop = True
        while loop == True:
            city_code = self._config.query('yweather', 'city-%s' % str(num))
            device = self._config.query('yweather', 'device-%s' % str(num))
            if city_code != None:
                self.cities[city_code] = { "device" : device }
                num = num + 1
            else:
                loop = False

        # Open weather for cities
        for city in self.cities:
            self.cities[city]["obj"] = YWeather(self.log, self.send_xpl)
            try:
                self.log.info("Init weather for '%s'" % city)
                self.cities[city]["obj"].open(city, unit,
                                              self.cities[city]["device"])
            except YWeatherException as err:
                self.log.error(err.value)
                print(err.value)
                self.force_leave()
                return

        # Start listening for weather
        for city in self.cities:
            try:
                self.log.info("Start listening weather for '%s'" % city)
                self._listen_thr = XplTimer(TIME_BETWEEN_EACH_WEATHER_READ, \
                                            self.cities[city]["obj"].get, \
                                            self.myxpl)
                self._listen_thr.start()
                self.enable_hbeat()
            except YWeatherException as err:
                self.log.error(err.value)
                print(err.value)
                self.force_leave()
                return
        self.enable_hbeat()
Exemple #43
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='rfxcom')
        # Get config
        #   - device
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('rfxcom', 'device')
        if device == None:
            self.log.error('Device is not configured, exiting')
            print('Device is not configured, exiting')
            self.force_leave()
            return

        # Init RFXCOM
        self.rfxcom = RfxcomUsb(self.log, self.send_xpl, self.send_trig,
                                self.get_stop())

        # Create a listener for all messages used by RFXCOM
        # TODO !!!!!
        # Create listeners
        Listener(self.process_x10_basic, self.myxpl, {
            'schema': 'x10.basic',
            'xpltype': 'xpl-cmnd'
        })
        Listener(self.process_x10_security, self.myxpl, {
            'schema': 'x10.securiy',
            'xpltype': 'xpl-cmnd'
        })
        Listener(self.process_ac_basic, self.myxpl, {
            'schema': 'ac.basic',
            'xpltype': 'xpl-cmnd'
        })
        Listener(self.process_remote_basic, self.myxpl, {
            'schema': 'remote.basic',
            'xpltype': 'xpl-cmnd'
        })
        Listener(self.process_control_basic, self.myxpl, {
            'schema': 'control.basic',
            'xpltype': 'xpl-cmnd'
        })

        # Open RFXCOM
        try:
            self.rfxcom.open(device)
        except RfxcomException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # Start reading RFXCOM
        rfxcom_process = threading.Thread(None, self.rfxcom.listen,
                                          "rfxcom-process-reader",
                                          (self.get_stop(), ), {})
        self.register_thread(rfxcom_process)
        rfxcom_process.start()
        self.enable_hbeat()
Exemple #44
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='yweather')

        # Get config
        self._config = Query(self.myxpl, self.log)
        unit = self._config.query('yweather', 'unit')
        if unit == None:
            self.log.error("Unit not configured : exiting")
            print("Unit not configured : exiting")
            self.force_leave()
            return
        unit = unit.lower()

        self.enable_current = self._config.query('yweather', 'en-current')
        self.enable_previsionnal = self._config.query('yweather', 'en-prev')

        self.cities = {}
        num = 1
        loop = True
        while loop == True:
            city_code = self._config.query('yweather', 'city-%s' % str(num))
            device = self._config.query('yweather', 'device-%s' % str(num))
            if city_code != None:
                self.cities[city_code] = {"device": device}
                num = num + 1
            else:
                loop = False

        # Open weather for cities
        for city in self.cities:
            self.cities[city]["obj"] = YWeather(self.log, self.send_xpl)
            try:
                self.log.info("Init weather for '%s'" % city)
                self.cities[city]["obj"].open(city, unit,
                                              self.cities[city]["device"])
            except YWeatherException as err:
                self.log.error(err.value)
                print(err.value)
                self.force_leave()
                return

        # Start listening for weather
        for city in self.cities:
            try:
                self.log.info("Start listening weather for '%s'" % city)
                self._listen_thr = XplTimer(TIME_BETWEEN_EACH_WEATHER_READ, \
                                            self.cities[city]["obj"].get, \
                                            self.myxpl)
                self._listen_thr.start()
                self.enable_hbeat()
            except YWeatherException as err:
                self.log.error(err.value)
                print(err.value)
                self.force_leave()
                return
        self.enable_hbeat()
Exemple #45
0
    def __init__(self):
        """ Init 
        """
        XplPlugin.__init__(self, name='ping')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        # but.... if we stop the plugin right now, we won't be able to detect existing device and send events about them
        # so we don't stop the plugin if no devices are created
        self.devices = self.get_device_list(quit_if_no_device = False)

        ### get all config keys
        # n/a

        ### For each device
        threads = {}
        for a_device in self.devices:
            try:
                interval = self.get_parameter(a_device, "interval")
                address = self.get_parameter_for_feature(a_device, "xpl_stats", "ping", "device")
                self.log.info(u"Launch thread to ping {0}. Address = {1}, interval = {2} seconds".format(a_device["name"], address, interval))
                thr_name = "dev_{0}".format(a_device['id'])
                threads[thr_name] = threading.Thread(None, 
                                           Ping,
                                           thr_name,
                                           (self.log,
                                            address, 
                                            interval,
                                            self.send_xpl,
                                            self.get_stop()),
                                           {})
                threads[thr_name].start()
                self.register_thread(threads[thr_name])
            except:
                self.log.error(u"{0}".format(traceback.format_exc()))

        ### Devices autodetection with nmap
        try:
            self.log.info(u"Launch thread For devices autodetection")
            thr_nmap = threading.Thread(None, 
                                       Nmap,
                                       "nmap",
                                       (self.log,
                                        self.device_detected,
                                        self.get_stop()),
                                       {})
            thr_nmap.start()
            self.register_thread(thr_nmap)
        except:
            self.log.error(u"{0}".format(traceback.format_exc()))

        # notify ready
        self.ready()
Exemple #46
0
    def __init__(self):
        """ Initiate DbHelper, Logs and config
        """
        XplPlugin.__init__(self, 'xplgw', log_prefix="core_")
        self.add_mq_sub('client.conversion')
        self.add_mq_sub('client.list')
        self.add_mq_sub('client.sensor')
        self.add_mq_sub('device.update')

        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 = {}

        # load devices informations
        self._reload_devices()
        self._reload_commands()
        self._reload_xpl_stats()

        # queue to store the message that needs to be ahndled for sensor checking
        self._sensor_queue = queue.Queue()
        # queue to handle the sensor storage
        self._sensor_store_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._x_thread = self._XplSensorThread(\
            self.log, self._sensor_queue, \
            self._sensor_store_queue)
        self._x_thread.start()
        # start handling the command reponses in a thread
        self._c_thread = self._XplCommandThread(\
            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 sensor storage thread
        self._s_thread = self._SensorStoreThread(\
                self._sensor_store_queue, self.log, \
                self._get_conversion_map, self.pub)
        self._s_thread.start()
        # start the sensorthread
        self.ready()
Exemple #47
0
 def __init__(self):
     XplPlugin.__init__(self, name='scenario')
     self._backend = ScenarioManager(self.log)
     self.add_stop_cb(self.end)
     self.add_stop_cb(self.shutdown)
     self.log.info(
         u"Scenario Frontend and Manager initialized, let's wait for some work."
     )
     self.ready()
Exemple #48
0
    def __init__(self):
        """ Initiate DbHelper, Logs and config
        """
        XplPlugin.__init__(self, 'xplgw', log_prefix="core_")
        self.add_mq_sub('client.conversion')
        self.add_mq_sub('client.list')
        self.add_mq_sub('client.sensor')
        self.add_mq_sub('device.update')

        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 = {}

        # load devices informations
        self._reload_devices()
        self._reload_commands()
        self._reload_xpl_stats()

        # queue to store the message that needs to be ahndled for sensor checking
        self._sensor_queue = queue.Queue()
        # queue to handle the sensor storage
        self._sensor_store_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._x_thread = self._XplSensorThread(\
            self.log, self._sensor_queue, \
            self._sensor_store_queue)
        self._x_thread.start()
        # start handling the command reponses in a thread
        self._c_thread = self._XplCommandThread(\
            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 sensor storage thread
        self._s_thread = self._SensorStoreThread(\
                self._sensor_store_queue, self.log, \
                self._get_conversion_map, self.pub)
        self._s_thread.start()
        # start the sensorthread
        self.ready()
Exemple #49
0
    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='water')
        # Get config
        #self._config = Query(self.myxpl, self.log)
        #device = self._config.query('water', device')

        ### Define listener for temperatures
        self.temperatures = {}  # {"device1" : value, "device2" : value2}
        Listener(self.update_temperature_values, self.myxpl, {
            'schema': 'sensor.basic',
            'xpltype': 'xpl-stat',
            'type': 'temp'
        })

        ### Define "crontab like" events

        # kill legionella
        # TODO : get config param
        cron_expr = '0 0 1 * * *'
        cron_data = re.sub(" +", " ", cron_expr).split(" ")
        self.cron_kill_legionella = TimeCond(cron_data[0], cron_data[1],
                                             cron_data[2], cron_data[3],
                                             cron_data[4], cron_data[5])
        Listener(self.kill_legionella, self.myxpl, {
            'schema': 'datetime.basic',
            'xpltype': 'xpl-trig'
        })

        # water heating
        # TODO : get config param
        cron_expr = '0 4 * * * *'
        cron_data = re.sub(" +", " ", cron_expr).split(" ")
        self.cron_heat_water = TimeCond(cron_data[0], cron_data[1],
                                        cron_data[2], cron_data[3],
                                        cron_data[4], cron_data[5])
        Listener(self.heat_water, self.myxpl, {
            'schema': 'datetime.basic',
            'xpltype': 'xpl-trig'
        })

        # consumption analysis
        # TODO : get config param
        cron_expr = '55 23 * * * *'
        cron_data = re.sub(" +", " ", cron_expr).split(" ")
        self.cron_consumption_analysis = TimeCond(cron_data[0], cron_data[1],
                                                  cron_data[2], cron_data[3],
                                                  cron_data[4], cron_data[5])
        Listener(self.consumption_analysis, self.myxpl, {
            'schema': 'datetime.basic',
            'xpltype': 'xpl-trig'
        })

        # plugin ready
        self.enable_hbeat()
Exemple #50
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        XplPlugin.__init__(self, name = 'admin', nohub = True)
        # logging initialization
        self.log.info(u"Admin Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

	try:
            try:
                cfg_rest = Loader('admin')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.interfaces = conf_rest['interfaces']
                self.port = conf_rest['port']
                # if rest_use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_rest['use_ssl']
                self.key_file = conf_rest['ssl_certificate']
                self.cert_file = conf_rest['ssl_key']
            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
		self.use_ssl = False
		self.key_file = ""
		self.cert_file = ""
                self.clean_json = False
            self.log.info(u"Configuration : interfaces:port = %s:%s" % (self.interfaces, self.port))
	    
	    # get all datatypes
            cli = MQSyncReq(self.zmq)
            msg = MQMessage()
            msg.set_action('datatype.get')
            res = cli.request('manager', msg.get(), timeout=10)
            if res is not None:
                self.datatypes = res.get_data()['datatypes']
            else:
                self.datatypes = {}

 	    # Launch server, stats
            self.log.info(u"Admin Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
	    self.start_http()
            # calls the tornado.ioloop.instance().start()
            
            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except :
            self.log.error(u"%s" % self.get_exception())
Exemple #51
0
    def on_mdp_request(self, msg):
        # XplPlugin handles MQ Req/rep also
        XplPlugin.on_mdp_request(self, msg)

        if msg.get_action() == "reload":
            self.load()
            msg = MQMessage()
            msg.set_action('reload.result')
            self.reply(msg.get())
        elif msg.get_action() == "cmd.send":
            self._send_xpl_command(msg)
Exemple #52
0
 def on_mdp_request(self, msg):
     """ Method called when an mq request comes in
     XplPlugin also needs this info, so we need to do a passthrough
     """
     try:
         XplPlugin.on_mdp_request(self, msg)
         if msg.get_action() == "test":
             pass
         if msg.get_action() == "cmd.send":
             self._send_xpl_command(msg)
     except Exception as exp:
         self.log.error(traceback.format_exc())
Exemple #53
0
    def __init__(self):
        """ Create listener for Foscam Relay
        """
        XplPlugin.__init__(self, name='foscam')

        self._config = Query(self.myxpl, self.log)
        # Configuration : list of cameras
        self.cameras = {}
        num = 1
        loop = True
        while loop == True:
            #Get each camera settings
            name = self._config.query('foscam', 'name-%s' % str(num))
            ip = self._config.query('foscam', 'ip-%s' % str(num))
            port = self._config.query('foscam', 'port-%s' % str(num))
            user = self._config.query('foscam', 'user-%s' % str(num))
            password = self._config.query('foscam', 'password-%s' % str(num))
            delay = self._config.query('foscam', 'delay-%s' % str(num))
            if port == None:
                port = 80
            if user == None:
                user = ""
            if password == None:
                password = ""
            if delay == None:
                delay = 0
            if name != None:
                self.log.info(
                    "Configuration : name=%s, ip=%s, port=%s, user=%s, password=No_Log, delay=%s"
                    % (name, ip, port, user, delay))
                self.cameras[name] = {
                    "ip": ip,
                    "port": port,
                    "user": user,
                    "password": password,
                    "delay": delay
                }
            else:
                loop = False
            num += 1

        ### Create FOSCAM object
        self._foscammanager = RELAY(self.log)
        # Create listeners
        Listener(self.foscam_command, self.myxpl, {
            'schema': 'control.basic',
            'xpltype': 'xpl-cmnd',
            'type': 'output'
        })
        self.log.info("Listener for Foscam relay created")
        #print ("Listener for Foscam relay created")
        self.enable_hbeat()
Exemple #54
0
    def __init__(self):
        '''
        Initialize database and xPL connection
        '''
        XplPlugin.__init__(self, 'dbmgr')
        MQRep.__init__(self, zmq.Context(), 'dbmgr')
        self.log.debug("Init database_manager instance")

        # Check for database connexion
        self._db = DbHelper()
        nb_test = 0
        db_ok = False
        while not db_ok and nb_test < DATABASE_CONNECTION_NUM_TRY:
            nb_test += 1
            try:
                self._db.list_user_accounts()
                db_ok = True
            except:
                msg = "The database is not responding. Check your configuration of if the database is up. Test %s/%s" % (
                    nb_test, DATABASE_CONNECTION_NUM_TRY)
                print(msg)
                self.log.error(msg)
                msg = "Waiting for %s seconds" % DATABASE_CONNECTION_WAIT
                print(msg)
                self.log.info(msg)
                time.sleep(DATABASE_CONNECTION_WAIT)

        if nb_test >= DATABASE_CONNECTION_NUM_TRY:
            msg = "Exiting dbmgr!"
            print(msg)
            self.log.error(msg)
            self.force_leave()
            return

        msg = "Connected to the database"
        print(msg)
        self.log.info(msg)
        try:
            self._engine = self._db.get_engine()
        except:
            self.log.error("Error while starting database engine : %s" %
                           traceback.format_exc())
            self.force_leave()
            return

        Listener(self._request_config_cb, self.myxpl, {
            'schema': 'domogik.config',
            'xpltype': 'xpl-cmnd'
        })
        self.enable_hbeat()
        IOLoop.instance().start()
Exemple #55
0
    def __init__(self):
        """ Init 
        """
        XplPlugin.__init__(self, name='ping')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        # but.... if we stop the plugin right now, we won't be able to detect existing device and send events about them
        # so we don't stop the plugin if no devices are created
        self.devices = self.get_device_list(quit_if_no_device=False)

        ### get all config keys
        # n/a

        ### For each device
        threads = {}
        for a_device in self.devices:
            try:
                interval = self.get_parameter(a_device, "interval")
                address = self.get_parameter_for_feature(
                    a_device, "xpl_stats", "ping", "device")
                self.log.info(
                    u"Launch thread to ping {0}. Address = {1}, interval = {2} seconds"
                    .format(a_device["name"], address, interval))
                thr_name = "dev_{0}".format(a_device['id'])
                threads[thr_name] = threading.Thread(
                    None, Ping, thr_name, (self.log, address, interval,
                                           self.send_xpl, self.get_stop()), {})
                threads[thr_name].start()
                self.register_thread(threads[thr_name])
            except:
                self.log.error(u"{0}".format(traceback.format_exc()))

        ### Devices autodetection with nmap
        try:
            self.log.info(u"Launch thread For devices autodetection")
            thr_nmap = threading.Thread(
                None, Nmap, "nmap",
                (self.log, self.device_detected, self.get_stop()), {})
            thr_nmap.start()
            self.register_thread(thr_nmap)
        except:
            self.log.error(u"{0}".format(traceback.format_exc()))

        # notify ready
        self.ready()