示例#1
0
    def wait_for_xpl(self, xpltype=None, xplschema=None, xplsource=None, data={}, timeout=10):
        """ Wait for a xpl message for a given time (in seconds)
            @param xpltype: the xpl message type. Possible values are None (all), xpl-cmnd, xpl-stat, xpl-trig
            @param xplschema : the xpl schema (sensor.basic for example)
            @param xplsource : the xpl source of the message
            @param data : the list of keys/values we should find in the message. { 'key1' : 'val1', ... }
            @param timeout : time (in seconds) given to get the message. Once timeout has expired, we return False
        """

        # create the listener to catch the message
        self._xpl_received = Event()
        criteria = {"schema": xplschema, "xpltype": xpltype, "xplsource": xplsource}
        for key in data:
            criteria[key] = str(data[key])
        listener = Listener(self._wait_for_xpl_cb, self.myxpl, criteria)

        # we add 5% to the timeout as some operations may be done in the plugin and so the interval is not totally exact
        timeout = timeout * 1.05
        self._xpl_received.wait(timeout)
        if not self._xpl_received.is_set():
            raise RuntimeError("No xPL message received")
        print(u"xPL message received : {0}".format(self.xpl_data))
        # remove the listener
        listener.unregister()
        return True
示例#2
0
    def wait_for_xpl(self,
                     xpltype=None,
                     xplschema=None,
                     xplsource=None,
                     data={},
                     timeout=10):
        """ Wait for a xpl message for a given time (in seconds)
            @param xpltype: the xpl message type. Possible values are None (all), xpl-cmnd, xpl-stat, xpl-trig
            @param xplschema : the xpl schema (sensor.basic for example)
            @param xplsource : the xpl source of the message
            @param data : the list of keys/values we should find in the message. { 'key1' : 'val1', ... }
            @param timeout : time (in seconds) given to get the message. Once timeout has expired, we return False
        """

        # create the listener to catch the message
        self._xpl_received = Event()
        criteria = {
            'schema': xplschema,
            'xpltype': xpltype,
            'xplsource': xplsource
        }
        for key in data:
            criteria[key] = str(data[key])
        listener = Listener(self._wait_for_xpl_cb, self.myxpl, criteria)

        # we add 5% to the timeout as some operations may be done in the plugin and so the interval is not totally exact
        timeout = timeout * 1.05
        self._xpl_received.wait(timeout)
        if not self._xpl_received.is_set():
            raise RuntimeError("No xPL message received")
        print(u"xPL message received : {0}".format(self.xpl_data))
        # remove the listener
        listener.unregister()
        return True
示例#3
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()
示例#4
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()
示例#5
0
 def enable_helper(self):
     """
     """
     #print("active=%s" % self._helper.isActive())
     if self.__helper.is_active():
         Listener(self.__helper.request_cmnd_listener, self.myxpl,
                 {'schema': 'helper.request', 'xpltype': 'xpl-cmnd'})
         Listener(self.__helper.basic_cmnd_listener, self.myxpl,
                 {'schema': 'helper.basic', 'xpltype': 'xpl-cmnd'})
示例#6
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()
示例#7
0
    def enable_lighting(self):
        """
        Enable the lighting listeners
        @param name : the name of the client
        @param cb_activate_device : the callback method to activate a device
        @param cb_deactivate_device : the callback method to deactivate a device
        @param cb_valid_device : the callback method to validate a device

        """
        if self._started == True or self.cb_activate_device == None \
          or self.cb_deactivate_device == None or self.cb_valid_device == None :
            return False
        else :
            continu = True
            if continu == True:
                try :
                    lis = Listener(self.activate_cmnd_listener, \
                        self._plugin.myxpl, \
                        {'schema': 'lighting.basic', 'xpltype': 'xpl-cmnd', \
                         'command': 'activate'})
                    self._listeners.append(lis)
                    lis = Listener(self.deactivate_cmnd_listener, \
                        self._plugin.myxpl, \
                        {'schema': 'lighting.basic', 'xpltype': 'xpl-cmnd', \
                         'command': 'deactivate'})
                    self._listeners.append(lis)
            #       Listener(self.basic_cmnd_listener, self._plugin.myxpl,
            #           {'schema': 'lighting.basic', 'xpltype': 'xpl-cmnd'})
                    lis = Listener(self.config_stat_listener, \
                        self._plugin.myxpl,
                        {'schema': 'lighting.config', 'xpltype': 'xpl-stat'})
                    self._listeners.append(lis)
                    lis = Listener(self.config_trig_listener, self._plugin.myxpl,
                        {'schema': 'lighting.config', 'xpltype': 'xpl-trig'})
                    self._listeners.append(lis)
                    self._started = True
                    continu = True
                except :
                    error = "Exception : %s" % (traceback.format_exc())
                    self._plugin.log.error("LightingExtension.enable_lighting : " + error)
                    continu = False
            if self._started == True and continu == True:
                try :
                    #request the configuration from the lighting gateway.
                    #print "load configuration"
                    self.load_configuration()
                    continu = True
                except :
                    error = "Exception : %s" % (traceback.format_exc())
                    self._plugin.log.error("LightingExtension.enable_lighting : " + error)
                    continu = False
            if continu :
                self._plugin.log.info("Lighting extensions activated.")
            return continu
示例#8
0
    def __init__(self):
        """
        Create the lighting class
        """
        XplPlugin.__init__(self, name='lighting')
        self.log.debug("lighting.__init__ : Start ...")
        self._config = Query(self.myxpl, self.log)

        self.log.debug("lighting.__init__ : Try to get configuration from XPL")
        try:
            #self.use_cron = bool(self._config.query('lighting', 'usecron'))
            self.broadcast = bool(self._config.query('lighting', 'broadcast'))
            #self.presence = bool(self._config.query('lighting', 'presence'))
        except:
            error = "Can't get configuration from XPL : %s" %  \
                     (traceback.format_exc())
            self.log.exception("lighting.__init__ : " + error)
            #self.use_cron = True
            self.broadcast = True
            #self.presence = True
            raise LightingException(error)

        self.log.debug(
            "lighting.__init__ : Try to start the lighting librairy")
        try:
            self._mylighting = LightingAPI(self.broadcast, \
                self.myxpl, self.log, self.get_data_files_directory())
        except:
            error = "Something went wrong during lightingAPI init : %s" %  \
                     (traceback.format_exc())
            self.log.error("lighting.__init__ : " + error)
            self.force_leave()
            raise LightingException(error)

        self.log.debug("lighting.__init__ : Try to create listeners")
        Listener(self.lighting_config_cmnd, self.myxpl, {
            'schema': 'lighting.config',
            'xpltype': 'xpl-cmnd'
        })
        Listener(self.lighting_basic_cmnd, self.myxpl, {
            'schema': 'lighting.basic',
            'xpltype': 'xpl-cmnd'
        })
        #        Listener(self.lighting_basic_trig, self.myxpl,
        #                 {'schema': 'lighting.basic', 'xpltype': 'xpl-trig'})
        self.enable_hbeat()
        self._mylighting.reload_config()
        self.log.info("Plugin lighting correctly started.")
示例#9
0
    def __init__(self):
        """
        Create the cron class
        """
        XplHlpPlugin.__init__(self, name='cron')
        self.log.debug("__init__ : Start ...")
        self.config = Query(self.myxpl, self.log)

        continue_boot = False
        self.log.debug("__init__ : Try to start the cron API")
        try:
            self._cron = CronAPI(self.log, self.config, self.myxpl, \
                self.get_data_files_directory(), self.get_stop())
        except:
            self.force_leave()
            error = "Something went wrong during cronAPI init : %s" %  \
                     (traceback.format_exc())
            self.log.error("__init__ : " + error)
            return

        self.log.debug("__init__ : Enable heplers")
        self.helpers =   \
           {
             "memory" :
              {
                "cb" : self._cron.helpers.helper_memory,
                "desc" : "Show memory usage of variables. Experimental.",
                "usage" : "memory",
              }
            }
        self.enable_helper()

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

        self.add_stop_cb(self._cron.stop_all)

        self.log.debug("__init__ : Enable the heartbeat")
        self.enable_hbeat()

        self.log.info("Plugin cron correctly started.")
示例#10
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")
示例#11
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 :)")
示例#12
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()
示例#13
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()
示例#14
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()
示例#15
0
文件: xplgw.py 项目: thefrip/domogik
        def __init__(self, xpl, dev, stat, sensor, xpl_type, log_stats, dbh,
                     pub, conversions):
            """ Initialize a stat instance
            @param xpl : A xpl manager instance
            @param dev : A Device reference
            @param stat : A XplStat reference
            @param sensor: A Sensor reference
            @param xpl-type: what xpl-type to listen for
            """
            ### Rest data
            self._db = dbh
            self._log_stats = log_stats
            self._dev = dev
            self._stat = stat
            self._sen = sensor
            self._pub = pub
            self._conv = conversions

            ### build the filter
            params = {'schema': stat.schema, 'xpltype': xpl_type}
            for param in stat.params:
                if param.static:
                    params[param.key] = param.value

            ### start the listener
            self._log_stats.info("creating listener for %s" % (params))
            self._listener = Listener(self._callback, xpl, params)
示例#16
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.")
示例#17
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()
示例#18
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")
示例#19
0
 def buildtimelistener(self, items):
     '''
     Create listener for time conditions
     '''
     self._log.debug("New time listener created")
     Listener(self._parsetimeupdate, self._myxpl,
             {'schema': 'datetime.basic', 'xpltype': 'xpl-trig'})
示例#20
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")
示例#21
0
文件: mvhr.py 项目: wookiesh/domogik
    def __init__(self):
        """
        Create the mvhr class
        """
        XplHlpPlugin.__init__(self, name = 'mvhr')
        self.log.info("mvhr.__init__ : Start ...")
        self.config = Query(self.myxpl, self.log)

        self.log.debug("mvhr.__init__ : Try to start the mvhr library")
        try:
            self._mymvhr = HvacMvhr(self.config, self.log, self.myxpl)
        except:
            error = "Something went wrong during mvhrAPI init : %s" %  \
                (traceback.format_exc())
            self.log.exception("mvhr.__init__ : "+error)

        self.log.debug("mvhr.__init__ : Try to create listeners")
        Listener(self.mvhr_request_cmnd, self.myxpl,
                 {'schema': 'mvhr.request', 'xpltype': 'xpl-cmnd'})
        Listener(self.sensor_basic_trig, self.myxpl,
                 {'schema': 'sensor.basic', 'xpltype': 'xpl-trig'})
#        Listener(self.mvhr_basic_trig, self.myxpl,
#                 {'schema': 'mvhr.basic', 'xpltype': 'xpl-trig'})
#        Listener(self.mvhr_reload_config, self.myxpl,
#                 {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
#                  'command': 'reload', 'plugin': 'mvhr'})
        self.helpers =   \
           { "status" :
              {
                "cb" : self._mymvhr.helper_status,
                "desc" : "Show status of the mvhr",
                "usage" : "status",
                "param-list" : "",
              },
              "reload_config" :
              {
                "cb" : self._mymvhr.helper_reload_config,
                "desc" : "Reload config of the plugin",
                "usage" : "reload_config",
                "param-list" : "",
              },
            }
        self.enable_helper()
        self.enable_hbeat()
        self._mymvhr.reload_config()
        self.log.info("mvhr plugin correctly started")
示例#22
0
    def query(self, plugin, key, element='', nb_test=QUERY_CONFIG_NUM_TRY):
        '''
        Ask the config system for the value. Calling this function will make
        your program wait until it got an answer

        @param plugin : the plugin of the item requesting the value,
        must exists in the config database
        @param element : the name of the element which requests config, None if
        it's a technolgy global parameter
        @param key : the key to fetch corresponding value, if it's an empty string,
        all the config items for this plugin will be fetched
        '''
        if nb_test == 0:
            raise RuntimeError("Maximum tries to get config reached")


        msg = "QC : ask > h=%s, t=%s, k=%s" % \
            (self.__myxpl.p.get_sanitized_hostname(), plugin, key)
        print(msg)
        self.log.debug(msg)
        l = Listener(
            self._query_cb, self.__myxpl, {
                'schema': 'domogik.config',
                'xpltype': 'xpl-stat',
                'plugin': plugin,
                'hostname': self.__myxpl.p.get_sanitized_hostname()
            })
        self._keys[key] = Event()
        self._l[key] = l
        mess = XplMessage()
        mess.set_type('xpl-cmnd')
        mess.set_target(self.target)
        mess.set_schema('domogik.config')
        mess.add_data({'plugin': plugin})
        mess.add_data({'hostname': self.__myxpl.p.get_sanitized_hostname()})
        if element:
            mess.add_data({'element': element})
        mess.add_data({'key': key})

        try:
            self.__myxpl.send(mess)
            self._keys[key].wait(self.query_timeout)
            if not self._keys[key].is_set():
                msg = "No answer received for t = %s, k = %s, check your xpl setup" % \
                    (plugin, key)
                self.log.error(msg)
                #raise RuntimeError(msg)
                self.query(plugin, key, element, nb_test - 1)
        except KeyError:
            pass

        if self._result[key] != "None":
            return self._result[key]
        else:
            return None
示例#23
0
 def buildx10listener(self, items):
     '''
     Create listener for x10 elements
     @param items : items to add listener for
     '''
     for i in items:
         self._log.debug("New  x10 listener created")
         Listener(lambda mess: self.updateList('x10',
                 mess.data['device'],
                 mess.data['command']),
                 self._myxpl,
                 {'schema': 'x10.basic', 'device': i, 'xpltype': 'xpl-cmnd'})
示例#24
0
    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()
示例#25
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()
示例#26
0
文件: dbmgr.py 项目: kopec77/domogik
    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()
示例#27
0
    def query(self, key, testmsg, dictkeys=[], dictkeyvals={}):
        '''
        Send a command and wait for response from the plugin.

        :param key: a key to look for
        :type key: str
        :param testmsg: The message to send
        :param testmsg: XPLMessage
        :param dictkeys: The keys that must exist in the returning message
        :type dictkeys: set()
        :param dictkeyvals: The key:val pairs that must exist ine the returning message
        :param dictkeyvals: disct()

        '''
        liste = Listener(self._query_cb, self.__myxpl, {
            'schema': self.schema,
            'xpltype': self.xpltype
        })
        self._keys[key] = Event()
        self._listens[key] = liste
        self.__myxpl.send(testmsg)
        if key in self._keys:
            try:
                self._keys[key].wait(10)
                if not self._keys[key].is_set():
                    print("No answer received for key %s" % (key))
                    raise RuntimeError(
                        "No answer received for key %s, check your cron xpl setup"
                        % (key))
            except KeyError:
                pass
        res = True
        if 'error' not in self._result:
            if dictkeys != None:
                for mykey in dictkeys:
                    if mykey not in self._result:
                        res = False
            if dictkeyvals != None:
                for mykey in dictkeyvals:
                    if mykey not in self._result:
                        res = False
                    elif self._result[mykey] != dictkeyvals[mykey]:
                        res = False
            return res
        else:
            print("Error %s when communicating key %s" %
                  (self._result['errorcode'], key))
            print("%s : %s" %
                  (self._result['errorcode'], self._result['error']))
            return False
示例#28
0
文件: zwave.py 项目: wookiesh/domogik
 def __init__(self):
     XplPlugin.__init__(self, name='zwave')
     Listener(self.zwave_cmd_cb, self.myxpl, {
         'schema': 'zwave.basic',
         'xpltype': 'xpl-cmnd'
     })
     self._config = Query(self.myxpl, self.log)
     device = self._config.query('zwave', 'device')
     speed = self._config.query('zwave', 'speed')
     print(device, '  ', speed)
     #        device='/dev/ttyUSB0'
     self.myzwave = ZWave(device, speed, self.zwave_cb, self.log)
     self.myzwave.start()
     self.enable_hbeat()
     self.myzwave.send('Network Discovery')
     sleep(3)
示例#29
0
    def __init__(self):
        """ Create listener for Iphone push notification
        """
        XplPlugin.__init__(self, name='ipushnot')
        # Create logger
        self.log.debug("Listener for Iphone push notification created")

        # Create IPushNotification object
        self.ipn_notification_manager = IPushNotification(self.log)

        # Create listeners
        Listener(self.ipn_notification_cb, self.myxpl, {
            'schema': 'sendmsg.push',
            'xpltype': 'xpl-cmnd'
        })
        self.enable_hbeat()
示例#30
0
    def __init__(self):
        """ Init manager
        """
        XplPlugin.__init__(self, name='gceusbrb')

        # Configuration : list of relayboard
        self.relayboards = {}
        num = 1
        loop = True
        self._config = Query(self.myxpl, self.log)
        while loop == True:
            name = self._config.query('gceusbrb', 'rb-%s-name' % str(num))
            device = self._config.query('gceusbrb', 'rb-%s-device' % str(num))
            if name != None:
                self.log.info("Configuration : name=%s, device=%s" %
                              (name, device))
                self.relayboards[name] = {"device": device}
            else:
                loop = False
            num += 1

        ### Create Relayboardusb objects ex.SamsungTV
        for relayboard in self.relayboards:
            self.relayboards[relayboard]['obj'] = Relayboardusb(
                self.log, self.send_xpl)
            try:
                self.log.info(
                    "Opening RelayBoard named '%s' (device : %s)" %
                    (relayboard, self.relayboards[relayboard]['device']))
                self.relayboards[relayboard]['obj'].open(
                    self.relayboards[relayboard]['device'], relayboard)
            except RelayboardusbException as err:
                self.log.error(err.value)
                print err.value
                self.force_leave()
                return

        # Create listener
        Listener(self.relayboard_cb, self.myxpl, {
            'schema': 'control.basic',
            'xpltype': 'xpl-cmnd',
            'type': 'output'
        })
        self.log.debug("Listener for gceusbrb created")

        self.enable_hbeat()
        self.log.info("RB Plugin ready :)")
示例#31
0
    def __init__(self):
        XplPlugin.__init__(self, name='scene')
        print("manager= %s" % self.myxpl)
        self.manager = self.myxpl
        print("manager=%s" % self.manager)

        try:
            self.scene = Scene(self.log, self.send_xpl)
            self.log.info("Start Scene plugin")
            print("Start Scene plugin")
            self.scene.open()

        except SceneException as err:
            self.log.error(err.value)
            print("error value: %s" % err.value)
            self.force_leave()
            return

        ### Start listening
        try:
            self.log.info("Start listening to Scene")
            scene_listen = threading.Thread(None, self.scene.listen, None, (),
                                            {})
            scene_listen.start()
        except SceneException as err:
            self.log.error(err.value)
            print(err.value)
            self.force_leave()
            return

        self.fake_stat = {}
        ### Create listeners for commands
        self.log.info("Creating listener for scene commands")
        Listener(self.scene_cmd, self.myxpl, {'schema': 'scene.basic'})
        self.enable_hbeat()

        self.SceneCount = self.init_file()

        all_scene = self.scene.read_all(self.path)

        for scene in all_scene:
            self.mem_scene(all_scene[scene])

        self.log.info("Plugin ready :)")
        print("Plugin ready :)")