当前位置: 首页>>代码示例>>Python>>正文


Python Query.query方法代码示例

本文整理汇总了Python中domogik.xpl.common.queryconfig.Query.query方法的典型用法代码示例。如果您正苦于以下问题:Python Query.query方法的具体用法?Python Query.query怎么用?Python Query.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在domogik.xpl.common.queryconfig.Query的用法示例。


在下文中一共展示了Query.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Mochad

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class Mochad(XplPlugin):

    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

    def connect(self):
        for res in socket.getaddrinfo(self.__host, self.__port, socket.AF_UNSPEC, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.mochad_socket = socket.socket(af, socktype, proto)
            except socket.error, msg:
                self.mochad_socket = None
                continue
            try:
                self.mochad_socket.connect(sa)
            except socket.error, msg:
                self.mochad_socket.close()
                self.mochad_socket = None
                continue
            break
开发者ID:capof,项目名称:domogik,代码行数:51,代码来源:mochad.py

示例2: CIDManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class CIDManager(XplPlugin):
    """ Manage the modem to get CID
    """

    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()

    def send_xpl(self, num):
        """ Send xPL message on network
            @param num : call number
        """
        print("Input call : %s " % num)
        msg = XplMessage()
        msg.set_type("xpl-trig")
        msg.set_schema("cid.basic")
        msg.add_data({"calltype" : "INBOUND"})
        msg.add_data({"phone" : num})
        self.myxpl.send(msg)
开发者ID:capof,项目名称:domogik,代码行数:49,代码来源:cidmodem.py

示例3: Zwave

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class Zwave(XplPlugin):
    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)

    def zwave_cmd_cb(self, message):
        if 'command' in message.data:
            cmd = message.data['command']
            node = message.data['node']
            if cmd == 'level':
                lvl = message.data['level']
                self.myzwave.send(cmd, node, lvl)
            else:
                self.myzwave.send(cmd, node)

    def zwave_cb(self, read):
        mess = XplMessage()
        if 'info' in read:
            self.log.error ("Error : Node %s unreponsive" % read['node'])
	elif 'Find' in read:
	    print("node enregistré : %s" % read['Find'])
        elif 'event' in read:
            mess.set_type('xpl-trig')
            mess.set_schema('zwave.basic')
            mess.add_data({'event' : read['event'],
                           'node' : read['node'],
                           'level' : read['level']})
            self.myxpl.send(mess)
        elif 'command' in read and read['command'] == 'Info':
            print("Home ID is %s" % read['Home ID'])
开发者ID:capof,项目名称:domogik,代码行数:43,代码来源:zwave.py

示例4: MirrorManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class MirrorManager(XplPlugin):
    """ Manage the Mir:ror device and connect it to xPL
    """

    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()


    def send_xpl(self, device, type, current):
        """ Send xPL message on network
        """
        print("device:%s, type:%s, current:%s" % (device, type, current))
        msg = XplMessage()
        msg.set_type("xpl-trig")
        msg.set_schema("sensor.basic")
        msg.add_data({"device" : device})
        msg.add_data({"type" : type})
        msg.add_data({"current" : current})
        self.myxpl.send(msg)
开发者ID:capof,项目名称:domogik,代码行数:49,代码来源:mirror.py

示例5: TtsManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class TtsManager(XplPlugin):
    """ Manage Tts
    """

    def __init__(self):
        """ Init manager
        """
        XplPlugin.__init__(self, name = 'tts')

        # Configuration

        self._config = Query(self.myxpl, self.log)
        software = self._config.query('tts', 'software')

        self.log.debug("Init info for tts created")
        ### Create tts objects
        self.my_tts = Tts(self.log, software)
	self.log.debug("Create object for tts created")
        # Create listener
        Listener(self.tts_cb, self.myxpl, {'schema': 'tts.basic','xpltype': 'xpl-cmnd'})
        self.log.debug("Listener for tts created")

        self.enable_hbeat()


    def tts_cb(self, message):
        """ Call tts lib
            @param message : xPL message detected by listener
        """
        # body contains the message
	self.log.debug("Function call back : entry")
        if 'speech' in message.data:
            speech = message.data['speech']
        else:
            self._log.warning("Xpl message : missing 'speech' attribute")
            return

        try:
	    self.log.debug("function call back : before send")
            self.my_tts.send(speech)
	    self.log.debug("function call back : after send")
        except:
	       self.log.error("Error while sending tts : %s" % traceback.format_exc())
              
               return
开发者ID:capof,项目名称:domogik,代码行数:47,代码来源:tts.py

示例6: WolPing

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class WolPing(XplPlugin):
    """ Implements a listener for wol messages on xPL network
    """

    def __init__(self):
        """ Create listener for wake on lan
        """
        XplPlugin.__init__(self, name = 'wol_ping')

        # Configuration : interval between each ping
        self._config = Query(self.myxpl, self.log)
        interval = self._config.query('wol_ping', 'ping-interval')
        if interval == None:
            interval = 60

        # Configuration : list of computers
        self.computers = {}
        num = 1
        loop = True
        while loop == True:
            name = self._config.query('wol_ping', 'name-%s' % str(num))
            ip = self._config.query('wol_ping', 'ip-%s' % str(num))
            mac = self._config.query('wol_ping', 'mac-%s' % str(num))
            mac_port = self._config.query('wol_ping', 'wol-port-%s' % str(num))
            if mac_port == None:
                mac_port = 7
            if name != None:
                self.log.info("Configuration : name=%s, ip=%s, mac=%s, mac port=%s" % (name, ip, mac, mac_port))
                self.computers[name] = {"ip" : ip, "mac" : mac, 
                                        "mac_port" : mac_port}
            else:
                loop = False
            num += 1

        ### Create WOL object
        self._wolmanager = WOL(self.log)
        # Create listeners
        Listener(self.wol_cb, self.myxpl, {'schema': 'control.basic',
                'xpltype': 'xpl-cmnd', 'type': 'wakeonlan', 'current': 'high'})
        self.log.debug("Listener for wake on lan created")

        ### Create Ping object
        self._pingmanager = Ping(self.myxpl, 
                                 self.log, 
                                 self.ping_cb, 
                                 float(interval),
                                 self.computers)
        self.enable_hbeat()
        self._pingmanager.ping()

    def wol_cb(self, message):
        """ Call wake on lan lib
            @param message : xPL message detected by listener
        """
        if 'device' in message.data:
            device = message.data['device']

        try:
            mac = self.computers[device]["mac"]
            port = int(self.computers[device]["mac_port"])
        except KeyError:
            self.log.warning("Computer named '%s' is not defined" % device)
            return
        
        self.log.info("Wake on lan command received for '%s' on port '%s'" %
                       (mac, port))
        #status = self._wolmanager.wake_up(mac, port)
        status = self._wolmanager.wake_up(mac, port)

        # Send xpl-trig to say plugin receive command
        if status == True:
            mess = XplMessage()
            mess.set_type('xpl-trig')
            mess.set_schema('sensor.basic')
            mess.add_data({'device' :  device})
            mess.add_data({'type' :  'wakeonlan'})
            mess.add_data({'current' :  'high'})
            self.myxpl.send(mess)


    def ping_cb(self, type, computer, status):
        # Send xpl-trig to say plugin receive command
        msg = XplMessage()
        msg.set_type(type)
        msg.set_schema('sensor.basic')
        msg.add_data({'device' :  computer})
        msg.add_data({'type' :  'ping'})
        msg.add_data({'current' :  status})
        self.myxpl.send(msg)
开发者ID:capof,项目名称:domogik,代码行数:91,代码来源:wol_ping.py

示例7: ZiBaseMain

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class ZiBaseMain(XplPlugin):
    '''Manage ZiBase
    '''	
    def __init__(self):
        """ Create lister and launch bg listening
        """
        XplPlugin.__init__(self, name = 'zibase')

        self._config = Query(self.myxpl, self.log)

        self.address = self._config.query('zibase', 'ip')
        self.inter = self._config.query('zibase', 'interface')
        self.port = int(self._config.query('zibase', 'port'))
        self.valvar=self._config.query('zibase', 'envar')
        self.interv=int(self._config.query('zibase', 'interv'))

        self.log.info("Creating listener for ZiBase")
        Listener(self.zibase_command, self.myxpl, {'schema': 'zibase.basic',
                'xpltype': 'xpl-cmnd'})
        
        try:
            self.ip_host=get_ip_address(self.inter)
            self.log.debug("Adress IP Host=%s" % (self.ip_host))
        except:
            self.log.error("IP Host not found=%s" % (traceback.format_exc()))
            return

        try:
            self.api = APIZiBase(self.log,self.address)
        except:
            self.log.error("API ZiBase error=%s" % (traceback.format_exc()))
            return

        try:
            self.th=ServerZiBase(self.log,self.ip_host,self.port,self.myxpl)
            self.th.start()
        except:
            self.log.error("Server ZiBase error=%s" % (traceback.format_exc()))
            self.stop()

        try:
            self.api.Connect(self.ip_host,self.port)
        except:
            self.log.error("Connection ZiBase error=%s" % (traceback.format_exc()))
            self.stop()

        if self.valvar=="True" :
            try:
                self.log.info("Start reading internal variables")
                var_read=XplTimer(self.interv,self.zibase_read_var,self.myxpl)
                var_read.start()
            except:
                self.log.error("reading internal variables error")
                return

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

        self.log.info("Plugin ready :)")
        
    def zibase_command(self, message):
        """ Call zibase lib function in function of given xpl message
            @param message : xpl message
        """
        commands = {
            'off': 0,
            'on': 1,
            'preset-dim' : 2,
        }
        protocols = {
            'PRESET': 0,
            'VISONIC433' : 1,
            'VISONIC868' : 2,
            'CHACON' : 3,
            'DOMIA' : 4,
            'X10' : 5,
            'ZWAVE' : 6,
            'RFS10' : 7,
            'XDD433AL' : 8,
            'XDD868AL' : 9,
            'XDD868INSH' : 10,
            'XDD868PILOT' : 11,
            'XDD868BOAC' : 12,
        }

        cmd = None
        dev = None
        protocol = None
        preset_dim = 0
        
        if 'command' in message.data:
            cmd = message.data['command']
        if 'device' in message.data:
            chaine=message.data['device'].split(':')
            try:
                dev = chaine[0].upper()
                protocol=chaine[1].upper()
            except:
                self.log.error("Syntax device not valid")
        if 'preset-dim' in message.data:
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:zibase.py

示例8: DemoDataManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class DemoDataManager(XplPlugin):
    """ Sends demo data over xPL
    """

    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='demodata')

        ### Get config
        self._config = Query(self.myxpl, self.log)
        port = self._config.query('demodata', 'port')
        if port == None:
            port = DEFAULT_PORT 
        else:
            port = int(port)
        self.log.info("Listen port is %s" % port)

        self.log.info("Start creating the listeners")

        ### Create listeners for the fake actuator devices
        # RGB controller
        Listener(self.cmd_arduino_rgb, self.myxpl, {
            'schema': 'arduino.rgb',
            'xpltype': 'xpl-cmnd',
        })

        # Switch
        # Dimmer
        Listener(self.cmd_lighting_basic, self.myxpl, {
            'schema': 'lighting.basic',
            'xpltype': 'xpl-cmnd',
        })

        self.log.info("All listeners are created")

        ### Call the data creators
        self.log.info("Start all the data creator threads")
        demo = DemoData(self.log, self.send_sensor_basic, \
                                  self.send_teleinfo_basic)

        # weather data each minute
        self._weather_thr = XplTimer(60, \
                                     demo.weather_data, \
                                     self.myxpl)
        self._weather_thr.start()

        # teleinfo data each 10min
        self._teleinfo_thr = XplTimer(600, \
                                     demo.teleinfo_data, \
                                     self.myxpl)
        self._teleinfo_thr.start()

        # tank data each 1min
        self._tank_thr = XplTimer(60, \
                                  demo.tank_data, \
                                  self.myxpl)
        self._tank_thr.start()

        # water data each 1min
        self._water_thr = XplTimer(60, \
                                  demo.water_data, \
                                  self.myxpl)
        self._water_thr.start()

        self.log.info("All the data creator threads created")

        self.enable_hbeat()

        # Launch the web UI
        #demo_ui = DemoUI()
        msg = "Launch the Web UI on port %s" % port
        print(msg)
        self.log.info(msg)
        self.add_stop_cb(self.stop_http)
        self.server = None
        self.server_ip = ''
        self.server_port = port
        self.start_http()

    def start_http(self):
        """ Start HTTP Server
        """
        self.server = HTTPServerWithParam((self.server_ip, int(self.server_port)), UIHandler, \
                                         handler_params = [self])
        self.server.serve_forever()

    def stop_http(self):
        """ Stop HTTP Server
        """
        self.server.stop_handling()

    def send_sensor_basic(self, device, type, current, units = None):
        """ Send sensor.basic xPL schema
            @param device : device
            @param type : type
            @param current : current
        """
        mess = "sensor.basic { device=%s, type=%s, current=%s}" % (device, type, current)
        print(mess)
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:demodata.py

示例9: Proxy

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class Proxy(XplPlugin):
    """ REST Proxy
        - create a HTTP server
        - process REST proxy requests
    """

    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()
        #self.log.info("Proxy initialisation done")

    def reload_config(self):
        '''
        Load configuration an start proxy server
        '''
        if self.server != None:
            self.stop_http()
            self.server = None
            self.server_process = None
        try:
            cfg_rest = Loader('rest')
            config_rest = cfg_rest.load()
            conf_rest = dict(config_rest[1])
            self.server_ip = conf_rest['rest_server_ip']
            self.server_port = conf_rest['rest_server_port']
        except KeyError:
            self.log.error("Can't retrieve REST configuration from domogik.cfg. Leave plugin.")
            self.force_leave()
        try:
            self.proxy_ip = self._config.query('proxy', 'proxy-ip')
            self.proxy_port = self._config.query('proxy', 'proxy-port')
        except:
            self.log.warning("Can't get proxy address configuration from XPL. Use default value.")
        finally:
            if self.proxy_ip == None:
                self.proxy_ip = self.server_ip
            try :
                self.proxy_port = int(self.proxy_port)
            except:
                self.proxy_port = str(int(self.server_port)+1)
        try:
            self.auth_method = self._config.query('proxy', 'auth-method')
        except:
            self.log.warning("Can't get authentification method from XPL. Use basic by default.")
        finally:
            if self.auth_method == None:
                self.auth_method = "basic"
        try:
            self.username = self._config.query('proxy', 'username')
            self.password = self._config.query('proxy', 'password')
        except:
            self.log.warning("Can't get username/password from XPL. Use defaults.")
        finally:
            if self.username == None or self.username == "None" :
                self.username = "admin"
            if self.password == None or self.password == "None" :
                self.password = "123"
        try:
            boo = self._config.query('proxy', 'use-ssl')
            #print boo
            self.use_ssl = True if boo == "True" else False
            if self.use_ssl:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.ssl_certificate = conf_rest['rest_ssl_certificate']
        except KeyError:
            self.log.warning("Can't get ssl configuration from XPL. Do not use it.")
            self.use_ssl = False
            self.ssl_certificate = None
        self.log.info("Proxy configuration  : ip:port = %s:%s" % (self.proxy_ip, self.proxy_port))
        if self.use_ssl == True:
            self.log.info("Proxy configuration : SSL support activated (certificate : %s)" % self.ssl_certificate)
        else:
            self.log.info("Proxy configuration : SSL support not activated")
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:proxy.py

示例10: OZwave

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class OZwave(XplHlpPlugin):
    """ Implement a listener for Zwave command messages
        and launch background  manager to listening zwave events by callback
    """
    def __init__(self):
        """ Create listener and background zwave manager
        """
        XplHlpPlugin.__init__(self, name = 'ozwave')
        
        # Récupère la config 
        # - device
        self._config = Query(self.myxpl, self.log)
        device = self._config.query('ozwave', 'device')
        ozwlogConf = self._config.query('ozwave', 'ozwlog')
        self._config = Query(self.myxpl, self.log)
        print ('Mode log openzwave :',  ozwlogConf)
        # Recupère l'emplacement des fichiers de configuration OZW
        pathUser = self.get_data_files_directory()  +'/'
        pathConfig = self._config.query('ozwave', 'configpath') + '/'
        # Initialise le manager Open zwave
        try:
            self.myzwave = OZWavemanager(self._config, self.send_xPL, self.sendxPL_trig, self.get_stop(), self.log, configPath = pathConfig,  userPath = pathUser,  ozwlog = ozwlogConf)
        except OZwaveException as e:
            self.log.error(e.value)
            print e.value
            self.force_leave()
            return
        self.log.debug("__init__ : Enable heplers")
        self.helpers =   \
           {
             "infostate" :
              {
                "cb" : self.myzwave.GetPluginInfo,
                "desc" : "Show Info status. Experimental.",
                "usage" : "memory",
              }
            }
        self.enable_helper()
        # Crée le listener pour les messages de commande xPL traités par les devices zwave
        Listener(self.ozwave_cmd_cb, self.myxpl,{'schema': 'ozwave.basic',
                                                                        'xpltype': 'xpl-cmnd'})
        # Validation avant l'ouverture du controleur, la découverte du réseaux zwave prends trop de temps -> RINOR Timeout
        self.add_stop_cb(self.myzwave.stop)
        self.enable_hbeat()
        # Ouverture du controleur principal
        self.myzwave.openDevice(device)
    
    def __sizeof__(self):
        return XplHlpPlugin.__sizeof__(self) + sum(sys.getsizeof(v) for v in self.__dict__.values())
    

    def ozwave_cmd_cb(self, message):
        """" Envoie la cmd xpl vers le OZWmanager"""
        print ("commande xpl recue")
        print message
        self.log.debug(message)
        if 'command' in message.data:
            if 'group'in message.data:
                # en provenance de l'UI spéciale
                self.ui_cmd_cb(message)
            else :
                cmd = message.data['command']
                device = message.data['device']
                if cmd == 'level' :
                    print ("appel envoi zwave command %s" %cmd)
                    lvl = message.data['level']
                    self.myzwave.sendNetworkZW(cmd, device, lvl)
                elif cmd == "on"  or cmd == "off" :
                    print ("appel envoi zwave command %s" %cmd)
                    self.myzwave.sendNetworkZW(cmd, device)
                else:
                    self.myzwave.sendNetworkZW(cmd, device)
                    
    def getdict2UIdata(self, UIdata):
        """ retourne un format dict en provenance de l'UI (passage outre le format xPL)"""
        retval = UIdata.replace('"', '"').replace('&squot;', "'").replace("&ouvr;", '{').replace("&ferm;", '}') ;
        try :
            return eval(retval)
        except OZwaveException as e:
            print retval
            self.log.debug ("Format data to UI : eval in getdict2UIdata error : " +   retval)
            return {'error': 'invalid format'}
            
    def getUIdata2dict(self, ddict):
        """Retourne le dict formatter pour UI (passage outre le format xPL)"""
        print "conversion pour transfertvers UI , " , str(ddict)
        for k in ddict :   # TODO: pour passer les 1452 chars dans RINOR, à supprimer quand MQ OK, 
            if isinstance(ddict[k], str) :
                ddict[k] = ddict[k].replace("'", "&squot;")  # remplace les caractères interdits pour rinor
                if len(str(ddict[k])) >800 : 
                    ddict[k] = ddict[k][:800]
                    print("value raccourccis : ", k, ddict[k])
                    self.log.debug ("Format data to UI : value to large, cut to 800, key : %s, value : %s" % (str(k), str(ddict[k])))
        return str(ddict).replace('{', '&ouvr;').replace('}', '&ferm;').replace('"','"').replace("'",'"').replace('False', 'false').replace('True', 'true').replace('None', '""')
        
    def ui_cmd_cb(self, message):
        """xpl en provenace de l'UI (config/special)"""
        response = True
        info = "essais"
        request = self.getdict2UIdata(message.data['value'])
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:ozwave.py

示例11: SmsManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class SmsManager(XplPlugin):
    """ Manage Sms
    """

    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()


    def sms_cb(self, message):
        """ Call sms lib
            @param message : xPL message detected by listener
        """
        # body contains the message
	self.log.debug("Function call back : entry")
        if 'body' in message.data:
            body = message.data['body']
        else:
            self._log.warning("Xpl message : missing 'body' attribute")
            return
        if 'to' in message.data:
            to = message.data['to']
        else:
            self._log.warning("Xpl message : missing 'to' attribute")
            return

        try:
	    self.log.debug("function call back : before send")
            self.my_sms.send(to,body)
	    self.log.debug("function call back : after send")
        except:
	       self.log.error("Error while sending sms : %s" % traceback.format_exc())
               mess = XplMessage()
               mess.set_type('xpl-trig')
               mess.set_schema('sendmsg.confirm')
               mess.add_data({'status' :  'Sms not send'})
               mess.add_data({'error' :  'function send'})
               self.myxpl.send(mess)
               return



        # Send xpl-trig to say plugin receive command
        mess = XplMessage()
        mess.set_type('xpl-trig')
        mess.set_schema('sendmsg.confirm')
	if self.my_sms.status_send == 0:
        	mess.add_data({'status' :  'Sms not send'})
		mess.add_data({'error' :  self.my_sms.status_error})
	else:
        	mess.add_data({'status' :  'Sms send'})
	
        self.myxpl.send(mess)
开发者ID:capof,项目名称:domogik,代码行数:81,代码来源:sms.py

示例12: RelayBoardUSBmanager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class RelayBoardUSBmanager(XplPlugin):
    """ Manage USB Relay Board
    """

    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 :)")

    def send_xpl(self, msg_device, msg_current, msg_type):
        """ Send xpl-trig to give status change
            @param msg_device : device
            @param msg_current : device's value
            @param msg_type : device's type
        """
        msg = XplMessage()
        msg.set_type("xpl-trig")
        msg.set_schema('sensor.basic')
        msg.add_data({'device' :  msg_device})
        msg.add_data({'type' :  msg_type})
        msg.add_data({'current' :  msg_current})
        self.myxpl.send(msg)

    def relayboard_cb(self, message):
        """ Call gceusbrb lib
            @param message : xPL message detected by listener
        """
        # device contains name of relayboard which will be used to get device
        if 'device' in message.data:
            msg_device = message.data['device']
        if 'type' in message.data:
            msg_type = message.data['type'].lower()
        if 'current' in message.data:
            msg_current = message.data['current'].upper()

        data = "device=%s, type=%s, current=%s" % (msg_device, msg_type, msg_current)
        data_name = msg_device.split("-")
        rb_name = data_name[0]
        elt = data_name[1][0:-1]
        num = int(data_name[1][-1])

        self.log.info("RelayBoard command received for '%s' on '%s'" % (rb_name, msg_device))

        if not rb_name in self.relayboards:
           self.log.warning("No Relay board called '%s' defined" % rb_name)
           return

        # check data
        if elt == 'led' and msg_current not in ['HIGH', 'LOW'] and msg_type != 'output':
            self.log.warning("Bad data : %s" % data)
            return
        
        # action in function of type
        self.relayboards[rb_name]['obj'].set_relay(num, msg_current)
开发者ID:capof,项目名称:domogik,代码行数:91,代码来源:gceusbrb.py

示例13: KarotzMain

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class KarotzMain(XplPlugin):
    '''Manage ZiBase
    '''    
    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 :)")
        
    def xpl_command(self, message):
        """ Call karotz lib function in function of given xpl message
            @param message : xpl message
        """
        cmd = None
        dev = None
        value = None
        
        if 'command' in message.data:
            cmd = message.data['command']
        if 'device' in message.data:
            device = message.data['device']
        if 'value' in message.data:
            value=message.data['value']
        if 'time' in message.data:
            tps=message.data['time']
        if 'right' in message.data:
            right=message.data['right']
            value=right
        if 'left' in message.data:
            left=message.data['left']

        self.log.debug(message.data)
        if value == None :
            self.log.warning("value not specified")
            return
        else:
            #self.log.debug("xpl %s received : device = %s value=%s " % (cmd, device, value))
            self.log.debug("xpl %s received " % (cmd) )    

            try:
                if cmd=='tts':
                    self.log.debug("xpl command=%s language=%s" % (cmd, self.lang))
                    self.karotz.tts(value,self.lang.upper())
                if cmd=='led':
                    self.log.debug("xpl command=%s color=%s time=%s" % (cmd, value,tps))
                    self.karotz.led(value,tps)
                if cmd=='ears':
                    self.log.debug("xpl command=%s right=%s left=%s" % (cmd, right, left))
                    self.karotz.ears(right,left)
            except:
                self.log.error("Error to send command=%s" % (traceback.format_exc()))
开发者ID:capof,项目名称:domogik,代码行数:79,代码来源:karotz.py

示例14: Telldus

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class Telldus(XplHlpPlugin):
    '''
    Manage chacon devices through the TellStick device
    '''
    def __init__(self):
        """
        Create the telldus class
        This class is used to connect devices (through telldus) to
        the xPL Network
        """
        XplHlpPlugin.__init__(self, name = 'telldus',
            reload_cb = self.telldus_reload_config_cb)
        self.log.debug("telldus.__init__ : Start ...")
        self._device = "/dev/tellstick"
        #Check if the device exists
        if not os.path.exists(self._device):
            self.log.warning(self._device +
                " is not present but Tellstick Duo don't use it.")
        else:
            self.log.debug("Device present as "+self._device)
        self._config = Query(self.myxpl, self.log)
        self.log.debug("telldus.__init__ : Try to load API")
        try:
            self._mytelldus = TelldusAPI(self, self.send_xpl, self.log,
                self._config,self.get_data_files_directory(), self.myxpl)
        except Exception:
            self.log.error("Something went wrong during telldus API init.")
            self.log.error("%s" % (traceback.format_exc()))
            self.force_leave()
            exit(1)
        self.add_stop_cb(self._mytelldus.unregister)
        self.log.debug("telldus.__init__ : Create listeners")
        Listener(self.telldus_cmnd_cb, self.myxpl,
                 {'schema': 'telldus.basic', 'xpltype': 'xpl-cmnd'})
        Listener(self.telldus_reload_config_cb, self.myxpl,
                 {'schema': 'domogik.system', 'xpltype': 'xpl-cmnd',
                  'command': 'reload', 'plugin': 'telldus'})
        self.enable_hbeat()
        try:
            boo = self._config.query('telldus', 'lightext')
            if boo == None:
                boo = "False"
            self.lightext = eval(boo)
        except:
            self.log.warning("Can't get delay configuration from XPL. Disable lighting extensions.")
            self.lightext = False
        if self.lightext == True:
            self.log.debug("telldus.__init__ : Try to load the lighting extension.")
            self.lighting = LightingExtension(self, self._name, \
                self._mytelldus.lighting_activate_device, \
                self._mytelldus.lighting_deactivate_device, \
                self._mytelldus.lighting_valid_device)
        self.helpers =   \
           { "list" :
              {
                "cb" : self._mytelldus.helper.helper_list,
                "desc" : "List devices in telldus daemon.",
                "usage" : "list [devicetype]",
                "param-list" : "devicetype",
                "min-args" : 0,
                "devicetype" : "the type of device to find",
              },
             "info" :
              {
                "cb" : self._mytelldus.helper.helper_info,
                "desc" : "Display device information.",
                "usage" : "info <device>",
                "param-list" : "device",
                "min-args" : 1,
                "device" : "device address",
              },
             "memory" :
              {
                "cb" : self._mytelldus.helper.helper_memory,
                "desc" : "Show memory usage of variables. Experimental.",
                "usage" : "memory",
                "param-list" : "",
                "min-args" : 0,
              },
            }
        if self.lightext == True:
            self.log.debug("telldus.__init__ : Try to enable the lighting extension.")
            self.lighting.enable_lighting()
        self.log.debug("telldus.__init__ : Try to load the helpers.")
        self.enable_helper()
        self.log.info("Telldus plugin correctly started")

    def telldus_cmnd_cb(self, message):
        """
        General callback for all command messages
        @param message : an XplMessage object
        """
        self.log.debug("telldus.telldus_cmnd_cb : Receive message.")
        commands = {
            'on': lambda hu, l, f: self._mytelldus.send_on(hu),
            'off': lambda hu, l, f: self._mytelldus.send_off(hu),
            'dim': lambda hu, l, f: self._mytelldus.send_dim(hu, l),
            'bright': lambda hu, l, f: self._mytelldus.send_bright(hu, l, f),
            'shine': lambda hu, l, f: self._mytelldus.send_shine(hu, l, f),
            'change': lambda hu, l, f: self._mytelldus.send_change(hu, l, f),
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:telldus.py

示例15: XplBridgeManager

# 需要导入模块: from domogik.xpl.common.queryconfig import Query [as 别名]
# 或者: from domogik.xpl.common.queryconfig.Query import query [as 别名]
class XplBridgeManager(XplPlugin):
    """ Send xpl message from hub to serial device
                    and vice versa
    """

    def __init__(self):
        """ Init plugin
        """
        XplPlugin.__init__(self, name='xpl2ser')

        # Configuration
        self._config = Query(self.myxpl, self.log)

        # Configuration : list of devices to check
        self.dev_list = {}
        num = 1
        loop = True
        while loop == True:
            dev = self._config.query('xpl2ser', 'device-%s' % str(num))
            if dev != None:
                self.log.info("Configuration : device=%s" % dev)
                # init object 
                baudrate = self._config.query('xpl2ser', 'baudrate-%s' % str(num))
                self.dev_list[dev] = { "baudrate" : baudrate }
                num += 1
            else:
                loop = False

        # no device configured
        if num == 1:
            msg = "No device configured. Exiting plugin"
            self.log.info(msg)
            print(msg)
            self.force_leave()
            return

        ### Start listening each device
        for dev in self.dev_list:
            try:
                self.dev_list[dev]["obj"] = XplBridge(self.log, self.send_xpl, self.get_stop())
                # Open serial device
                self.log.info("Open '%s'" % dev)
                try:
                    self.dev_list[dev]["obj"].open(dev, 
                                              self.dev_list[dev]["baudrate"])
                except XplBridgeException as e:
                    self.log.error(e.value)
                    print(e.value)
                    self.force_leave()
                    return
                self.log.info("Start listening for '%s'" % dev)
                dev_listen = threading.Thread(None,
                                              self.dev_list[dev]["obj"].listen,
                                              "listen_serial",
                                              (),
                                              {})
                dev_listen.start()
            except:
                self.log.error(traceback.format_exc())
                print(traceback.format_exc())
                # We don't quit plugin if an error occured
                # a device may have disappeared
                # Notice that it won't be read if device come back
                #self.force_leave()
                #return

        # Create listeners
        # Notice : this listener and callback function make this plugin send
        # on serial port each xpl message it reads on serial port
        # TODO : update this !
        #Listener(self.xplbridge_cb, self.myxpl)
 
        self.enable_hbeat()
        self.log.info("Plugin ready :)")

    def send_xpl(self, resp):
        """ Send xPL message on network
            @param resp : xpl message
        """
        print("Input xpl message : %s " % resp)
        try:
            msg = XplMessage(resp)
            self.myxpl.send(msg)
        except XplMessageError:
            error = "Bad data : %s" % traceback.format_exc()
            print(error)
            self.log.error(error)

    def xplbridge_cb(self, message):
        """ Call xplbridge lib for sending xpl message to serial
            @param message : xpl message to send
        """
        self.log.debug("Call xplbridge_cb")
        mesg = message.to_packet()
        # Write on serial device
        self.log.debug("Call write() ")
        self.br.write(mesg)
开发者ID:capof,项目名称:domogik,代码行数:99,代码来源:xpl2ser.py


注:本文中的domogik.xpl.common.queryconfig.Query.query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。