當前位置: 首頁>>代碼示例>>Python>>正文


Python DbHelper.get_device方法代碼示例

本文整理匯總了Python中domogik.common.database.DbHelper.get_device方法的典型用法代碼示例。如果您正苦於以下問題:Python DbHelper.get_device方法的具體用法?Python DbHelper.get_device怎麽用?Python DbHelper.get_device使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在domogik.common.database.DbHelper的用法示例。


在下文中一共展示了DbHelper.get_device方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _SensorThread

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [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_device [as 別名]

#.........這裏部分代碼省略.........

    def _parse_conversions(self, data):
        """ Translate the mq data into a dict
        """
        tmp = {}
        for cli in data:
            tmp[cli] = data[cli]
        self.client_conversion_map = tmp

    def _send_xpl_command(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
                Needed info in data:
                - cmdid         => command id to send
                - cmdparams     => key/value pair of all params needed for this command
        """
        with self._db.session_scope():
            self.log.info(u"Received new cmd request: {0}".format(data))
            failed = False
            request = data.get_data()
            if 'cmdid' not in request:
                failed = "cmdid not in message data"
            if 'cmdparams' not in request:
                failed = "cmdparams not in message data"
            if not failed:
                # get the command
                cmd = self._db.get_command(request['cmdid'])
                if cmd is not None:
                    if cmd.xpl_command is not None:
                        xplcmd = cmd.xpl_command
                        xplstat = self._db.get_xpl_stat(xplcmd.stat_id)
                        if xplstat is not None:
                            # get the device from the db
                            dev = self._db.get_device(int(cmd.device_id))
                            msg = XplMessage()
                            if not dev['client_id'] in self.client_xpl_map.keys():
                                self._load_client_to_xpl_target()
                            if not dev['client_id'] in self.client_xpl_map.keys():
                                failed = "Can not fincd xpl source for {0} client_id".format(dev['client_id'])
                            else:
                                msg.set_target(self.client_xpl_map[dev['client_id']])
                            msg.set_source(self.myxpl.get_source())
                            msg.set_type("xpl-cmnd")
                            msg.set_schema(xplcmd.schema)
                            # static paramsw
                            for par in xplcmd.params:
                                msg.add_data({par.key : par.value})
                            # dynamic params
                            for par in cmd.params:
                                if par.key in request['cmdparams']:
                                    value = request['cmdparams'][par.key]
                                    # chieck if we need a conversion
                                    if par.conversion is not None and par.conversion != '':
                                        if dev['client_id'] in self.client_conversion_map:
                                            if par.conversion in self.client_conversion_map[dev['client_id']]:
                                                exec(self.client_conversion_map[dev['client_id']][par.conversion])
                                                value = locals()[par.conversion](value)
                                    msg.add_data({par.key : value})
                                else:
                                    failed = "Parameter ({0}) for device command msg is not provided in the mq message".format(par.key)
                            if not failed:
                                # send out the msg
                                self.log.debug(u"Sending xplmessage: {0}".format(msg))
                                self.myxpl.send(msg)
                                xplstat = self._db.detach(xplstat)
                                # generate an uuid for the matching answer published messages
開發者ID:ewintec,項目名稱:domogik,代碼行數:70,代碼來源:xplgw.py

示例3: XplManager

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [as 別名]

#.........這裏部分代碼省略.........
        else:
            self.log.error(u"Updating client conversion list was not successfull, no response from manager")

    def _parse_conversions(self, data):
        tmp = {}
        for cli in data:
            tmp[cli] = data[cli]
        self.client_conversion_map = tmp

    def _send_xpl_command(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
                Needed info in data:
                - cmdid         => command id to send
                - cmdparams     => key/value pair of all params needed for this command
        """
        with self._db.session_scope():
            self.log.info(u"Received new cmd request: {0}".format(data))
            failed = False
            request = data.get_data()
            if 'cmdid' not in request:
                failed = "cmdid not in message data"
            if 'cmdparams' not in request:
                failed = "cmdparams not in message data"
            if not failed:
                # get the command
                cmd = self._db.get_command(request['cmdid'])
                if cmd is not None:
                    if cmd.xpl_command is not None:
                        xplcmd = cmd.xpl_command
                        xplstat = self._db.get_xpl_stat(xplcmd.stat_id)
                        if xplstat is not None:
                            # get the device from the db
                            dev = self._db.get_device(int(cmd.device_id))
                            msg = XplMessage()
                            if not dev['client_id'] in self.client_xpl_map.keys():
                                self._load_client_to_xpl_target()
                            if not dev['client_id'] in self.client_xpl_map.keys():
                                failed = "Can not fincd xpl source for {0} client_id".format(dev['client_id'])
                            else:
                                msg.set_target(self.client_xpl_map[dev['client_id']])
                            msg.set_source(self.myxpl.get_source())
                            msg.set_type("xpl-cmnd")
                            msg.set_schema( xplcmd.schema)
                            # static params
                            for p in xplcmd.params:
                                msg.add_data({p.key : p.value})
                            # dynamic params
                            for p in cmd.params:
                                if p.key in request['cmdparams']:
                                    value = request['cmdparams'][p.key]
                                    # chieck if we need a conversion
                                    if p.conversion is not None and p.conversion != '':
                                        if dev['client_id'] in self.client_conversion_map:
                                            if p.conversion in self.client_conversion_map[dev['client_id']]:
                                                exec(self.client_conversion_map[dev['client_id']][p.conversion])
                                                value = locals()[p.conversion](value)
                                    msg.add_data({p.key : value})
                                else:
                                    failed = "Parameter ({0}) for device command msg is not provided in the mq message".format(p.key)
                            if not failed:
                                # send out the msg
                                self.log.debug(u"sending xplmessage: {0}".format(msg))
                                self.myxpl.send(msg)
                                ### Wait for answer
                                stat_received = 0
開發者ID:anuraagkapoor,項目名稱:domogik,代碼行數:70,代碼來源:xplgw.py

示例4: _callback

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [as 別名]
 def _callback(self, message):
     """ Callback for the xpl message
     @param message : the Xpl message received
     """
     self._log_stats.debug( "_callback started for: {0}".format(message) )
     db = DbHelper()
     current_date = calendar.timegm(time.gmtime())
     stored_value = None
     try:
         # find what parameter to store
         for param in self._stat.params:
             # self._log_stats.debug("Checking param {0}".format(param))
             if param.sensor_id is not None and param.static is False:
                 if param.key in message.data:
                     with db.session_scope():
                         value = message.data[param.key]
                         # self._log_stats.debug( \
                         #        "Key found {0} with value {1}." \
                         #        .format(param.key, value))
                         store = True
                         if param.ignore_values:
                             if value in eval(param.ignore_values):
                                 self._log_stats.debug( \
                                         "Value {0} is in the ignore list {0}, so not storing." \
                                         .format(value, param.ignore_values))
                                 store = False
                         if store:
                             # get the sensor and dev
                             sen = db.get_sensor(param.sensor_id)
                             dev = 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:
                                     if sen.conversion in self._conv[dev['client_id']]:
                                         self._log_stats.debug( \
                                             "Calling conversion {0}".format(sen.conversion))
                                         exec(self._conv[dev['client_id']][sen.conversion])
                                         value = locals()[sen.conversion](value)
                             self._log_stats.info( \
                                     "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, param.key, value))
                             # do the store
                             stored_value = value
                             try:
                                 db.add_sensor_history(\
                                         param.sensor_id, \
                                         value, \
                                         current_date)
                             except:
                                 self._log_stats.error("Error when adding sensor history : {0}".format(traceback.format_exc()))
                         else:
                             self._log_stats.debug("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" : stored_value})
                 #else:
                 #    self._log_stats.debug("Key not found in message data")
             #else:
             #    self._log_stats.debug("No sensor attached")
     except:
         self._log_stats.error(traceback.format_exc())
開發者ID:anuraagkapoor,項目名稱:domogik,代碼行數:66,代碼來源:xplgw.py

示例5: DBConnector

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [as 別名]

#.........這裏部分代碼省略.........
                     history_store=hstore, \
                     history_max=hmax, \
                     history_expire=hexpire, \
                     timeout=timeout, \
                     formula=formula, \
                     data_type=data_type)
                if not res:
                    status = False
                else:
                    status = True 
            else:
                status = False
                reason = "There is no such sensor"
                self.log.debug(reason)
            # delete done
        except DbHelperException as d:
            status = False
            reason = "Error while updating sensor: {0}".format(d.value)
            self.log.error(reason)
        except:
            status = False
            reason = "Error while updating sensor: {0}".format(traceback.format_exc())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('sensor.update.result')
        msg.add_data('status', status)
        if reason:
            msg.add_data('reason', reason)
        self.log.debug(msg.get())
        self.reply(msg.get())
        # send the pub message
        if status and res:
            dev = self._db.get_device(res.device_id)
            self._pub.send_event('device.update',
                     {"device_id" : res.device_id,
                      "client_id" : dev['client_id']})

    def _mdp_reply_deviceparam_update_result(self, data):
        status = True
        reason = False

        self.log.debug(u"Updating device param : {0}".format(data))
        try:
            data = data.get_data()
            if 'dpid' in data:
                dpid = data['dpid']
                val = data['value']
                # do the update
                res = self._db.udpate_device_param(dpid, value=val)
                if not res:
                    status = False
                else:
                    status = True 
            else:
                status = False
                reason = "There is no such device param"
                self.log.debug(reason)
            # delete done
        except DbHelperException as d:
            status = False
            reason = "Error while updating device param: {0}".format(d.value)
            self.log.error(reason)
        except:
            status = False
            reason = "Error while updating device param: {0}".format(traceback.format_exc())
開發者ID:domogik,項目名稱:domogik,代碼行數:70,代碼來源:dbmgr.py

示例6: __init__

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [as 別名]
class StatsManager:
    """
    Listen on the xPL network and keep stats of device and system state
    """
    def __init__(self, handler_params, xpl):
        """ 
        @param handler_params : The server params 
        @param xpl : A xPL Manager instance 
        """

        try:
            self.myxpl = xpl

            # logging initialization
            log = logger.Logger('rest-stat')
            self._log_stats = log.get_logger('rest-stat')
            self._log_stats.info("Rest Stat Manager initialisation...")
    
            # create the dbHelper 
            self._db = DbHelper()

            ### Rest data
            self.handler_params = handler_params
            self.handler_params.append(self._log_stats)
            self.handler_params.append(self._db)
    
            self._event_requests = self.handler_params[0]._event_requests
            self.get_exception = self.handler_params[0].get_exception

            self.stats = None
        except :
            self._log_stats.error("%s" % traceback.format_exc())
    
    def load(self):
        """ (re)load all xml files to (re)create _Stats objects
        """
        self._log_stats.info("Rest Stat Manager loading.... ")
        try:
            # not the first load : clean
            if self.stats != None:
                for x in self.stats:
                    self.myxpl.del_listener(x.get_listener())

            ### Load stats
            # key1, key2 = device_type_id, schema
            self.stats = []
            for sen in self._db.get_all_sensor():
                self._log_stats.debug(sen)
                statparam = self._db.get_xpl_stat_param_by_sensor(sen.id)
                if statparam is None:
                    self._log_stats.error('Corresponding xpl-stat param can not be found for sensor %s' % (sen))
                    continue
                stat = self._db.get_xpl_stat(statparam.xplstat_id)
                if stat is None:
                    self._log_stats.error('Corresponding xpl-stat can not be found for xplstatparam %s' % (statparam))
                    continue
                dev = self._db.get_device(stat.device_id)
                if dev is None:
                    self._log_stats.error('Corresponding device can not be found for xpl-stat %s' % (stat))
                    continue
                # xpl-trig
                self.stats.append(self._Stat(self.myxpl, dev, stat, sen, \
                                  "xpl-trig", self._log_stats, \
                                  self._log_stats, self._db, \
                                  self._event_requests))
                # xpl-stat
                self.stats.append(self._Stat(self.myxpl, dev, stat, sen, \
                                  "xpl-stat", self._log_stats, \
                                  self._log_stats, self._db, \
                                  self._event_requests))
        except:
            self._log_stats.error("%s" % traceback.format_exc())
  
    class _Stat:
        """ This class define a statistic parser and logger instance
        Each instance create a Listener and the associated callbacks
        """

        def __init__(self, xpl, dev, stat, sensor, xpl_type, log_stats, log_stats_unknown, db, event_requests):
            """ 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._event_requests = event_requests
            self._db = db
            self._log_stats = log_stats
            #self._log_stats_unknown = log_stats_unknown
            self._dev = dev
            self._stat = stat
            self._sen = sensor
            
            ### build the filter
            params = {'schema': stat.schema, 'xpltype': xpl_type}
            for p in stat.params:
                if p.static:
                    params[p.key] = p.value
#.........這裏部分代碼省略.........
開發者ID:capof,項目名稱:domogik,代碼行數:103,代碼來源:stat.py

示例7: _SensorThread

# 需要導入模塊: from domogik.common.database import DbHelper [as 別名]
# 或者: from domogik.common.database.DbHelper import get_device [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_device方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。