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


Python DbHelper.get_all_xpl_stat方法代码示例

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


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

示例1: _SensorThread

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_all_xpl_stat [as 别名]
    class _SensorThread(threading.Thread):
        """ SensorThread class
        Class that will handle the sensor storage in a seperated thread
        This will get messages from the SensorQueue
        """
        def __init__(self, log, queue, conv, pub):
            threading.Thread.__init__(self)
            self._db = DbHelper()
            self._log = log
            self._queue = queue
            self._conv = conv
            self._pub = pub

        def _find_storeparam(self, item):
            #print("ITEM = {0}".format(item['msg']))
            found = False
            tostore = []
            for xplstat in self._db.get_all_xpl_stat():
                sensors = 0
                matching = 0
                statics = 0
                if xplstat.schema == item["msg"].schema:
                    #print("  XPLSTAT = {0}".format(xplstat))
                    # we found a possible xplstat
                    # try to match all params and try to find a sensorid and a vlaue to store
                    for param in xplstat.params:
                        #print("    PARAM = {0}".format(param))
                        ### Caution !
                        # in case you, who are reading this, have to debug something like that :
                        # 2015-08-16 22:04:26,190 domogik-xplgw INFO Storing stat for device 'Garage' (6) and sensor 'Humidity' (69): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,306 domogik-xplgw INFO Storing stat for device 'Salon' (10) and sensor 'Humidity' (76): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,420 domogik-xplgw INFO Storing stat for device 'Chambre d'Ewan' (11) and sensor 'Humidity' (80): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,533 domogik-xplgw INFO Storing stat for device 'Chambre des parents' (12) and sensor 'Humidity' (84): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,651 domogik-xplgw INFO Storing stat for device 'Chambre de Laly' (13) and sensor 'Humidity' (88): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,770 domogik-xplgw INFO Storing stat for device 'Entrée' (17) and sensor 'Humidity' (133): key 'current' with value '53' after conversion.
                        #
                        # which means that for a single xPL message, the value is stored in several sensors (WTF!!! ?)
                        # It can be related to the fact that the device address key is no more corresponding between the plugin (info.json and xpl sent by python) and the way the device was create in the databse
                        # this should not happen, but in case... well, we may try to find a fix...

                        if param.key in item["msg"].data and param.static:
                            statics = statics + 1
                            if param.multiple is not None and len(param.multiple) == 1 and item["msg"].data[param.key] in param.value.split(param.multiple):
                                matching = matching + 1
                            elif item["msg"].data[param.key] == param.value:
                                matching = matching + 1
                    # now we have a matching xplstat, go and find all sensors
                    if matching == statics:
                        #print("  MATHING !!!!!")
                        for param in xplstat.params:
                            if param.key in item["msg"].data and not param.static:     
                                #print("    ===> TOSTORE !!!!!!!!! : {0}".format({'param': param, 'value': item["msg"].data[param.key]}))
                                tostore.append( {'param': param, 'value': item["msg"].data[param.key]} )
                    if len(tostore) > 0:
                        found = True
            if found:
                return (found, tostore)
            else:
                return False

        def run(self):
            while True:
                try:
                    item = self._queue.get()
                    self._log.debug(u"Getting item from the sensorQueue, current length = {0}".format(self._queue.qsize()))
                    # if clientid is none, we don't know this sender so ignore
                    # TODO check temp disabled until external members are working
                    #if item["clientId"] is not None:
                    if True:
                        with self._db.session_scope():
                            fdata = self._find_storeparam(item)
                            if fdata:
                                #// ICI !!!
                                self._log.debug(u"Found a matching sensor, so starting the storage procedure. Sensor : {0}".format(fdata))
                                for data in fdata[1]:
                                    value = data['value']
                                    storeparam = data['param']
                                    current_date = calendar.timegm(time.gmtime())
                                    store = True
                                    if storeparam.ignore_values:
                                        if value in eval(storeparam.ignore_values):
                                            self._log.debug(u"Value {0} is in the ignore list {0}, so not storing.".format(value, storeparam.ignore_values))
                                            store = False
                                    if store:
                                        # get the sensor and dev
                                        sen = self._db.get_sensor(storeparam.sensor_id)
                                        dev = self._db.get_device(sen.device_id)
                                        # check if we need a conversion
                                        if sen.conversion is not None and sen.conversion != '':
                                            if dev['client_id'] in self._conv and sen.conversion in self._conv[dev['client_id']]:
                                                self._log.debug( \
                                                    u"Calling conversion {0}".format(sen.conversion))
                                                exec(self._conv[dev['client_id']][sen.conversion])
                                                value = locals()[sen.conversion](value)
                                        self._log.info( \
                                                u"Storing stat for device '{0}' ({1}) and sensor '{2}' ({3}): key '{4}' with value '{5}' after conversion." \
                                                .format(dev['name'], dev['id'], sen.name, sen.id, storeparam.key, value))
                                        # do the store
                                        try:
                                            self._db.add_sensor_history(\
#.........这里部分代码省略.........
开发者ID:ewintec,项目名称:domogik,代码行数:103,代码来源:xplgw.py

示例2: XplManager

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_all_xpl_stat [as 别名]

#.........这里部分代码省略.........
                                        reply = json.loads(stat['content'])
                                        reply_msg = MQMessage()
                                        reply_msg.set_action('cmd.send.result')
                                        reply_msg.add_data('stat', reply)
                                        reply_msg.add_data('status', True)
                                        reply_msg.add_data('reason', None)
                                        self.log.debug(u"mq reply".format(reply_msg.get()))
                                        self.reply(reply_msg.get())
        if failed:
            self.log.error(failed)
            reply_msg = MQMessage()
            reply_msg.set_action('cmd.send.result')
            reply_msg.add_data('status', False)
            reply_msg.add_data('reason', failed)
            self.log.debug(u"mq reply".format(reply_msg.get()))
            self.reply(reply_msg.get())

    def load(self):
        """ (re)load all xml files to (re)create _Stats objects
        """
        self.log.info(u"Rest Stat Manager loading.... ")
        self._db.open_session()
        try:
            # not the first load : clean
            if self.stats != None:
                self.log.info(u"reloading")
                for stat in self.stats:
                    self.myxpl.del_listener(stat.get_listener())

            ### Load stats
            # key1, key2 = device_type_id, schema
            self.stats = []
            created_stats = []
            for stat in self._db.get_all_xpl_stat():
                # xpl-trig
                self.stats.append(self._Stat(self.myxpl, stat, "xpl-trig", \
                                self.log, self.pub, self.client_conversion_map))
                # xpl-stat
                self.stats.append(self._Stat(self.myxpl, stat, "xpl-stat", \
                                self.log, self.pub, self.client_conversion_map))
        except:
            self.log.error(u"%s" % traceback.format_exc())
        self._db.close_session()
        self.log.info(u"Loading finished")

    class _Stat:
        """ This class define a statistic parser and logger instance
        Each instance create a Listener and the associated callbacks
        """

        def __init__(self, xpl, stat, xpl_type, log, pub, conversions):
            """ Initialize a stat instance
            @param xpl : A xpl manager instance
            @param stat : A XplStat reference
            @param xpl-type: what xpl-type to listen for
            """
            ### Rest data
            self._log_stats = log
            self._stat = stat
            self._pub = pub
            self._conv = conversions

            ### build the filter
            params = {'schema': stat.schema, 'xpltype': xpl_type}
            for param in stat.params:
                if param.static:
开发者ID:anuraagkapoor,项目名称:domogik,代码行数:70,代码来源:xplgw.py

示例3: XplManager

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_all_xpl_stat [as 别名]

#.........这里部分代码省略.........

                #print(cmd.xpl_command)
                #<XplCommand: name='Switch', stat_id='82', cmd_id='6', json_id='switch_lighting2', device_id='21', id='6', schema='ac.basic'>
                if cmd.xpl_command != None:
                    xpl_command = {
                                    'name' : cmd.xpl_command.name,
                                    'stat_id' : cmd.xpl_command.stat_id,
                                    'cmd_id' : cmd.xpl_command.cmd_id,
                                    'json_id' : cmd.xpl_command.json_id,
                                    'device_id' : cmd.xpl_command.device_id,
                                    'id' : cmd.xpl_command.id,
                                    'schema' : cmd.xpl_command.schema,
                                    'params' : []
                                  }
                    
                    for param in cmd.xpl_command.params:
                        #print(param)
                        #<XplCommandParam: value='0x0038abfc', key='address', xplcmd_id='6'>
                        xpl_command['params'].append({'value' : param.value,
                                                      'key' : param.key,
                                                      'xplcmd_id' : param.xplcmd_id})

                    self.all_commands[str(cmd.id)]['xpl_command'] = xpl_command
                    
        #print(self.all_commands)
        self.log.info("Event : one device changed. Reloading data for commands -- finished")

    def _reload_xpl_stats(self):
        """ Reload the commands
        """
        self.log.info("Event : one device changed. Reloading data for xpl stats")
        self.all_xpl_stats = {}
        with self._db.session_scope():
            for xplstat in self._db.get_all_xpl_stat():
                #print(xplstat)
                #print(xplstat.params)
                # <XplStat: name='Open/Close sensor', json_id='open_close', device_id='95', id='185', schema='ac.basic'>
                # <XplStatParam: xplstat_id='188', multiple='None', value='None', ignore_values='', sensor_id='411', static='False', key='current', type='None'>
                a_xplstat = {'name' : xplstat.name,
                             'json_id' : xplstat.json_id,
                             'device_id' : xplstat.device_id,
                             'id' : xplstat.id,
                             'schema' : xplstat.schema,
                             'params' : []
                            }
                for a_xplstat_param in xplstat.params:
                    a_xplstat['params'].append({
                                                 'xplstat_id' : a_xplstat_param.xplstat_id,
                                                 'multiple' : a_xplstat_param.multiple,
                                                 'value' : a_xplstat_param.value,
                                                 'ignore_values' : a_xplstat_param.ignore_values,
                                                 'sensor_id' : a_xplstat_param.sensor_id,
                                                 'static' : a_xplstat_param.static,
                                                 'key' : a_xplstat_param.key,
                                                 'type' : a_xplstat_param.type
                                               })

                self.all_xpl_stats[str(xplstat.id)] = a_xplstat
            #print(self.all_xpl_stats)

        self.log.info("Event : one device changed. Reloading data for xpl stats -- finished")


    def _handle_mq_sensor(self, content):
        """ Handles an mq sensor message and push it into the queue
        the sensorStorage thread will do all conversion
开发者ID:domogik,项目名称:domogik,代码行数:70,代码来源:xplgw.py

示例4: _XplSensorThread

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_all_xpl_stat [as 别名]
    class _XplSensorThread(threading.Thread):
        """ XplSensorThread class
        Thread that will handle the received xplStat(s) and xplTrigger(s)
        It will try to find the matching sensor and then store it into the sensor Store Queue
        This is done in a thread as it can be time consuming to do the DB lookups
        """
        def __init__(self, log, queue, storeQueue):
            threading.Thread.__init__(self)
            self._db = DbHelper()
            self._log = log
            self._queue = queue
            self._queue_store = storeQueue
            # on startup, load the device parameters
            self.on_device_changed()

        def on_device_changed(self):
            """ Function called when a device have been changed to reload the devices parameters
            """
            self._log.info("Event : one device changed. Reloading data for _XplSensorThread")
            self.all_xpl_stat = []
            with self._db.session_scope():
                for xplstat in self._db.get_all_xpl_stat():
                    #print(xplstat)
                    #print(xplstat.params)
                    # <XplStat: name='Open/Close sensor', json_id='open_close', device_id='95', id='185', schema='ac.basic'>
                    # <XplStatParam: xplstat_id='188', multiple='None', value='None', ignore_values='', sensor_id='411', static='False', key='current', type='None'>
                    a_xplstat = {'name' : xplstat.name,
                                 'json_id' : xplstat.json_id,
                                 'device_id' : xplstat.device_id,
                                 'id' : xplstat.id,
                                 'schema' : xplstat.schema,
                                 'params' : []
                                }
                    for a_xplstat_param in xplstat.params:
                        a_xplstat['params'].append({
                                                     'xplstat_id' : a_xplstat_param.xplstat_id,
                                                     'multiple' : a_xplstat_param.multiple,
                                                     'value' : a_xplstat_param.value,
                                                     'ignore_values' : a_xplstat_param.ignore_values,
                                                     'sensor_id' : a_xplstat_param.sensor_id,
                                                     'static' : a_xplstat_param.static,
                                                     'key' : a_xplstat_param.key,
                                                     'type' : a_xplstat_param.type
                                                   })

                    self.all_xpl_stat.append(a_xplstat)
                #print(self.all_xpl_stat)

            self._log.info("Event : one device changed. Reloading data for _XplSensorThread -- finished")

        def _find_storeparam(self, item):
            #print("ITEM = {0}".format(item['msg']))
            found = False
            tostore = []
            #for xplstat in self._db.get_all_xpl_stat():
            for xplstat in self.all_xpl_stat:
                sensors = 0
                matching = 0
                statics = 0
                if xplstat['schema'] == item["msg"].schema:
                    #print("  XPLSTAT = {0}".format(xplstat))
                    # we found a possible xplstat
                    # try to match all params and try to find a sensorid and a vlaue to store
                    for param in xplstat['params']:
                        #print("    PARAM = {0}".format(param))
                        ### Caution !
                        # in case you, who are reading this, have to debug something like that :
                        # 2015-08-16 22:04:26,190 domogik-xplgw INFO Storing stat for device 'Garage' (6) and sensor 'Humidity' (69): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,306 domogik-xplgw INFO Storing stat for device 'Salon' (10) and sensor 'Humidity' (76): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,420 domogik-xplgw INFO Storing stat for device 'Chambre d'Ewan' (11) and sensor 'Humidity' (80): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,533 domogik-xplgw INFO Storing stat for device 'Chambre des parents' (12) and sensor 'Humidity' (84): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,651 domogik-xplgw INFO Storing stat for device 'Chambre de Laly' (13) and sensor 'Humidity' (88): key 'current' with value '53' after conversion.
                        # 2015-08-16 22:04:26,770 domogik-xplgw INFO Storing stat for device 'Entrée' (17) and sensor 'Humidity' (133): key 'current' with value '53' after conversion.
                        #
                        # which means that for a single xPL message, the value is stored in several sensors (WTF!!! ?)
                        # It can be related to the fact that the device address key is no more corresponding between the plugin (info.json and xpl sent by python) and the way the device was create in the databse
                        # this should not happen, but in case... well, we may try to find a fix...

                        if param['key'] in item["msg"].data and param['static']:
                            statics = statics + 1
                            if param['multiple'] is not None and len(param['multiple']) == 1 and item["msg"].data[param['key']] in param['value'].split(param['multiple']):
                                matching = matching + 1
                            elif item["msg"].data[param['key']] == param['value']:
                                matching = matching + 1
                    # now we have a matching xplstat, go and find all sensors
                    if matching == statics:
                        #print("  MATHING !!!!!")
                        for param in xplstat['params']:
                            if param['key'] in item["msg"].data and not param['static']:     
                                #print("    ===> TOSTORE !!!!!!!!! : {0}".format({'param': param, 'value': item["msg"].data[param['key']]}))
                                tostore.append( {'param': param, 'value': item["msg"].data[param['key']]} )
                    if len(tostore) > 0:
                        found = True
            if found:
                return (found, tostore)
            else:
                return False

        def run(self):
            while True:
#.........这里部分代码省略.........
开发者ID:domogik,项目名称:domogik,代码行数:103,代码来源:xplgw.py

示例5: _SensorThread

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_all_xpl_stat [as 别名]
    class _SensorThread(threading.Thread):
        """ SensorThread class
        Class that will handle the sensor storage in a seperated thread
        This will get messages from the SensorQueue
        """
        def __init__(self, log, queue, conv, pub):
            threading.Thread.__init__(self)
            self._db = DbHelper()
            self._log = log
            self._queue = queue
            self._conv = conv
            self._pub = pub

        def _find_storeparam(self, item):
            found = False
            tostore = []
            for xplstat in self._db.get_all_xpl_stat():
                sensors = 0
                matching = 0
                statics = 0
                if xplstat.schema == item["msg"].schema:
                    # we found a possible xplstat
                    # try to match all params and try to find a sensorid and a vlaue to store
                    for param in xplstat.params:
                        if param.key in item["msg"].data and param.static:
                            statics = statics + 1
                            if param.multiple is not None and len(param.multiple) == 1 and item["msg"].data[param.key] in param.value.split(param.multiple):
                                matching = matching + 1
                            elif item["msg"].data[param.key] == param.value:
                                matching = matching + 1
                    # now we have a matching xplstat, go and find all sensors
                    if matching == statics:
                        for param in xplstat.params:
                            if param.key in item["msg"].data and not param.static:
                                tostore.append( {'param': param, 'value': item["msg"].data[param.key]} )
                    if len(tostore) > 0:
                        found = True
            if found:
                return (found, tostore)
            else:
                return False

        def run(self):
            while True:
                try:
                    item = self._queue.get()
                    self._log.debug(u"Getting item from the sensorQueue, current length = {0}".format(self._queue.qsize()))
                    # if clientid is none, we don't know this sender so ignore
                    # TODO check temp disabled until external members are working
                    #if item["clientId"] is not None:
                    if True:
                        with self._db.session_scope():
                            fdata = self._find_storeparam(item)
                            if fdata:
                                self._log.debug(u"Found a matching sensor, so starting the storage procedure")
                                for data in fdata[1]:
                                    value = data['value']
                                    storeparam = data['param']
                                    current_date = calendar.timegm(time.gmtime())
                                    store = True
                                    if storeparam.ignore_values:
                                        if value in eval(storeparam.ignore_values):
                                            self._log.debug(u"Value {0} is in the ignore list {0}, so not storing.".format(value, storeparam.ignore_values))
                                            store = False
                                    if store:
                                        # get the sensor and dev
                                        sen = self._db.get_sensor(storeparam.sensor_id)
                                        dev = self._db.get_device(sen.device_id)
                                        # check if we need a conversion
                                        if sen.conversion is not None and sen.conversion != '':
                                            if dev['client_id'] in self._conv and sen.conversion in self._conv[dev['client_id']]:
                                                self._log.debug( \
                                                    u"Calling conversion {0}".format(sen.conversion))
                                                exec(self._conv[dev['client_id']][sen.conversion])
                                                value = locals()[sen.conversion](value)
                                        self._log.info( \
                                                u"Storing stat for device '{0}' ({1}) and sensor '{2}' ({3}): key '{4}' with value '{5}' after conversion." \
                                                .format(dev['name'], dev['id'], sen.name, sen.id, storeparam.key, value))
                                        # do the store
                                        try:
                                            self._db.add_sensor_history(\
                                                    storeparam.sensor_id, \
                                                    value, \
                                                    current_date)
                                        except Exception as exp:
                                            self._log.error(u"Error when adding sensor history : {0}".format(traceback.format_exc()))
                                    else:
                                        self._log.debug(u"Don't need to store this value")
                                    # publish the result
                                    self._pub.send_event('device-stats', \
                                              {"timestamp" : current_date, \
                                              "device_id" : dev['id'], \
                                              "sensor_id" : sen.id, \
                                              "stored_value" : value})

                except Queue.Empty:
                    # nothing in the queue, sleep for 1 second
                    time.sleep(1)
                except Exception as exp:
                    self._log.error(traceback.format_exc())
开发者ID:Ecirbaf36,项目名称:domogik,代码行数:102,代码来源:xplgw.py


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