コード例 #1
0
ファイル: xplgw.py プロジェクト: Basilic/domogik
 def _callback(self, message):
     """ Callback for the xpl message
     @param message : the Xpl message received
     """
     self._log_stats.debug("Stat received for device {0}." \
             .format(self._dev['name']))
     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:
                     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:
                         # check if we need a conversion
                         if self._sen.conversion is not None and self._sen.conversion != '':
                             value = call_package_conversion(\
                                         self._log_stats, \
                                         self._dev['client_id'], \
                                         self._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(self._dev['name'], self._dev['id'], self._sen.name, self._sen.id, param.key, value))
                         # do the store
                         stored_value = value
                         my_db = DbHelper()
                         with my_db.session_scope():
                             my_db.add_sensor_history(\
                                     param.sensor_id, \
                                     value, \
                                     current_date)
                         del(my_db)
                     else:
                         self._log_stats.debug("Don't need to store this 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())
     # publish the result
     self._pub.send_event('device-stats', \
                   {"timestamp" : current_date, \
                   "device_id" : self._dev['id'], \
                   "sensor_id" : self._sen.id, \
                   "stored_value" : stored_value})
コード例 #2
0
ファイル: stat.py プロジェクト: capof/domogik
 def _callback(self, message):
     """ Callback for the xpl message
     @param message : the Xpl message received 
     """
     my_db = DbHelper()
     self._log_stats.debug("Stat received for device %s." \
             % (self._dev.name))
     current_date = calendar.timegm(time.gmtime())
     device_data = []
     try:
         # find what parameter to store
         for p in self._stat.params:
             if p.sensor_id is not None:
                 if p.key in message.data:
                     value = message.data[p.key]
                     self._log_stats.debug("Key found %s with value %s." \
                         % (p.key, value))
                     store = True
                     if p.ignore_values:
                         if value in eval(p.ignore_values):
                             self._log_stats.debug("Value %s is in the ignore list %s, so not storing." \
                                  % (value, p.ignore_values))
                             store = False
                     if store:
                         # check if we need a conversion
                         if self._sen.conversion is not None and self._sen.conversion != '':
                             value = call_package_conversion(\
                                         self._log_stats, self._dev.device_type.plugin_id, \
                                         self._sen.conversion, value)
                             self._log_stats.debug("Key found %s with value %s after conversion." \
                                 % (p.key, value))
                         # do the store
                         device_data.append({"value" : value, "sensor": p.sensor_id})
                         my_db.add_sensor_history(p.sensor_id, value, current_date)
     except:
         error = "Error when processing stat : %s" % traceback.format_exc()
         print("==== Error in Stats ====")
         print(error)
         print("========================")
         self._log_stats.error(error)
     # put data in the event queue
     self._event_requests.add_in_queues(self._dev.id, 
             {"timestamp" : current_date, "device_id" : self._dev.id, "data" : device_data})
     del(my_db)
コード例 #3
0
ファイル: xplgw.py プロジェクト: Basilic/domogik
    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()
                            # update the client list
                            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 != '':
				        value = call_package_conversion(\
						self.log, dev['client_id'], \
						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
			        if xplstat != None:
				    # get xpl message from queue
				    self.log.debug(u"Command : wait for answer...")
				    sub = MQSyncSub( self.zmq, 'rest-command', ['device-stats'] )
				    stat = sub.wait_for_event()
				    if stat is not None:
				        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())
			else:
			    failed = "xplStat {0} does not exists".format(xplcmd.stat_id)
		    else:
                        failed = "Command {0} has no associated xplcommand".format(cmd.id)
		else:
		    failed = "Command {0} does not exists".format(request['cmdid'])

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