Exemplo n.º 1
0
 def test_XplCmd(self, parameters={}, statParams=None):
     """Send an Xpl cmd with statics parameters by request, if necessary start testcase listener for ack message and 
          check if insert in database is ok.
     """
     if self.get_return_confirmation():
         schema, data, statResult = self.get_XplStat_fromAck(statParams)
         th = threading.Thread(
             None, self.assert_Xpl_Stat_Ack_Wait,
             "th_test_0110_xpl-ack_from_{0}".format(self.command_name),
             (schema, data, statResult))
         th.start()
         time.sleep(1)
     else:
         print(u"No ack required for {0}".format(self.command_name))
     if self._device and self.command_id:
         cli = MQSyncReq(zmq.Context())
         msg = MQMessage()
         msg.set_action('cmd.send')
         msg.add_data('cmdid', self.command_id)
         msg.add_data('cmdparams', parameters)
         print(u"Send xpl_cmnd {0}".format(self.command_name))
         cli.request('xplgw', msg.get(), timeout=10)
         #            if self.get_return_confirmation() :
         #                self.assert_get_last_command_in_db(statResult)
         #            else :
         #                print (u"No ack required for {0}".format(self.command_name))
         return True
     else:
         return False
Exemplo n.º 2
0
    def do_action(self):
        self.log.info(u"Command : Do an action...")

        # live udate some values
        self.log.debug(u"Command : Preprocessing on parameters...")
        self.log.debug(u"Command : Parameters before processing : {0}".format(self._params))
        params = {}
        for key in self._params:
            self._params[key] = ucode(self._params[key])
            self.log.debug(u"Command : Preprocess for param : key={0}, typeofvalue={1}, value={2}".format(key, type(self._params[key]), self._params[key]))
            params[key] = self._params[key]
            if key == "color" and params[key].startswith("#"):
                self.log.debug(u"- Processing : for a color, if the color starts with #, remove it")
                params[key] = params[key][1:]

        self.log.debug(u"Command : Parameters after processing : {0}".format(params))
        self.log.debug(u"Command : Send action command over MQ...")

        # do the command
        cli = MQSyncReq(zmq.Context())
        msg = MQMessage()
        msg.set_action('cmd.send')
        msg.add_data('cmdid', self._cmdId)
        msg.add_data('cmdparams', params)

        self.log.debug(u"Command : Command id = '{0}', command params = '{1}'".format(self._cmdId, params)) 
        # do the request
        res = cli.request('xplgw', msg.get(), timeout=10)
        if res:
            data = res.get_data()
            if not data['status']:
                self.log.error(u"Command : Command sending to XPL gw failed: {0}".format(res))
        else:
            self.log.error(u"Command : XPL gw did not respond")
        self.log.debug(u"Command : Action done")
Exemplo n.º 3
0
 def WSCommandSend(self, data):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', data['command_id'])
     msg.add_data('cmdparams', data['parameters'])
     return cli.request('xplgw', msg.get(), timeout=10).get()
Exemplo n.º 4
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        XplPlugin.on_mdp_request(self, msg)
        if msg.get_action() == "client.cmd":
            print(msg)
            reason = None
            status = True
            data = msg.get_data()
            if 'blacklist' in data:
                bl = data['blacklist']
            else:
                reason = u"Invalid command : no blacklist key in message"
                status = False

            if status == True:
                try:
                    with open(self.blacklist_file, 'ab') as fp_blacklist:
                        fp_blacklist.write("\n{0};{1}".format("manual blacklisting", bl))
                except:
                    reason = u"Error while completing blacklist file : {0}. Error is : {1}".format(self.blacklist_file, traceback.format_exc())
                    self.log.error(reason)
                    status = False
                self.load_blacklist()


            self.log.info("Reply to command")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())

            if status == True:
                thread.start_new_thread(self.open_modems, ())
Exemplo n.º 5
0
 def request_startup(self):
     """ Request the plugin to start over the manager
     """
     print(
         u"Request plugin startup to the manager for '{0}' on '{1}'".format(
             self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.start.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request('manager', msg.get(), timeout=10)
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response from the manager : {0}".format(content))
         if content['status']:
             print(u"Plugin started")
             return True
         else:
             print(u"Error : plugin not started")
             return False
     else:
         raise RuntimeError(
             "MQ Timeout when requesting manager to start the plugin")
Exemplo n.º 6
0
def delete_configuration(type, name, host):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.delete')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
        data = result.get_data()
        if 'status' in data:
            if not data['status']:
                print(result.get())
                raise RuntimeError(
                    "DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}"
                    .format(type, name, host, key, value))
            else:
                return True
        else:
            print(result.get())
            raise RuntimeError(
                "DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}"
                .format(type, name, host, key, value))
    else:
        raise RuntimeError(
            "Timeout while deleting configuration for {0}-{1}.{2}".format(
                type, name, host))
Exemplo n.º 7
0
 def request_stop(self):
     """ Request the plugin to stop
     """
     print(u"Request plugin to stop : '{0}' on '{1}'".format(
         self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.stop.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request("plugin-{0}.{1}".format(self.name, self.host),
                          msg.get(),
                          timeout=30)
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response : {0}".format(content))
         if content['status']:
             print(u"Plugin stopped")
             return True
         else:
             print(u"Error : plugin not stopped")
             return False
     else:
         raise RuntimeError(
             "MQ Timeout when requesting to stop the plugin (the plugin didn't stop itself)"
         )
Exemplo n.º 8
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            # search for related device
            for a_device in self.devices:
                for a_cmd in a_device['commands']:
                    if data['command_id'] == a_device['commands'][a_cmd]['id']:
                        # As we will just execute a shell script, we can't really known if the command will be ok and how long it will take...
                        # so we respond first on MQ to say we got the request

                        self.log.info("Reply to command 0MQ")
                        reply_msg = MQMessage()
                        reply_msg.set_action('client.cmd.result')
                        reply_msg.add_data('status', True)
                        reply_msg.add_data('reason', '')
                        self.reply(reply_msg.get())

                        # Now, launch the speak action !
                        ip = self.get_parameter(a_device, "ip")
                        lang = 'fr-FR'
                        thr_speak = threading.Thread(None,
                                                     self.yi.speak,
                                                     "speak",
                                                     (ip, lang, data['text'], self.get_data_files_directory),
                                                     {})
                        thr_speak.start()
        self.register_thread(thr_speak)
Exemplo n.º 9
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        #self.log.debug(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.debug(u"==> Received 0MQ messages data: %s" %
                           format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            sensor_id = self.get_related_sensor_id(data['device_id'],
                                                   data['command_id'])
            self.log.debug(u"Storing data for sensor_id = {0} : '{1}'".format(
                sensor_id, data["value"]))
            status, reason = self.send_data(sensor_id, data["value"])

            self.log.info("Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 10
0
 def _mdp_reply_butler_features(self, message):
     """ Butler features
     """
     msg = MQMessage()
     msg.set_action('butler.features.result')
     msg.add_data(u"features", self.butler_features)
     self.reply(msg.get())
Exemplo n.º 11
0
 def WSCommandSend(self, data):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', data['command_id'])
     msg.add_data('cmdparams', data['parameters'])
     return cli.request('xplgw', msg.get(), timeout=10).get()
Exemplo n.º 12
0
 def _mdp_reply_butler_features(self, message):
     """ Butler features
     """
     msg = MQMessage()
     msg.set_action('butler.features.result')
     msg.add_data("features", self.butler_features)
     self.reply(msg.get())
Exemplo n.º 13
0
 def _mdp_reply_butler_history(self, message):
     """ Butler history
     """
     msg = MQMessage()
     msg.set_action('butler.history.result')
     msg.add_data("history", self.history)
     self.reply(msg.get())
Exemplo n.º 14
0
    def _mdp_reply_sensor_history(self, data):
        """ Reply to sensor_history.get MQ req
            @param data : MQ req message

            If no other param than the sensor id, return the last value
        """
        msg = MQMessage()
        msg.set_action('sensor_history.result')
        status = True
        reason = ""

        msg_data = data.get_data()

        try:
            sensor_id = msg_data['sensor_id']
            history = self._db.list_sensor_history(sensor_id, 1)
            if len(history) == 0:
                last_value = None
            else: 
                last_value = self._db.list_sensor_history(sensor_id, 1)[0].value_str
        except:
            self.log.error("ERROR when getting sensor history for id = {0} : {1}".format(sensor_id, traceback.format_exc()))
            reason = "ERROR : {0}".format(traceback.format_exc())
            status = False

        msg.add_data('status', status)
        msg.add_data('reason', reason)
        msg.add_data('sensor_id', sensor_id)
        msg.add_data('values', [last_value])

        self.reply(msg.get())
Exemplo n.º 15
0
 def _mdp_reply_butler_history(self, message):
     """ Butler history
     """
     msg = MQMessage()
     msg.set_action('butler.history.result')
     msg.add_data(u"history", self.history)
     self.reply(msg.get())
Exemplo n.º 16
0
    def _mdp_reply_devices_delete_result(self, data):
        status = True
        reason = False

        try:
            did = data.get_data()['did']
            if did:
                res = self._db.del_device(did)
                if not res:
                    status = False
                else:
                    status = True 
            else:
                status = False
                reason = "Device delete failed"
            # delete done
            self.reload_stats()
        except DbHelperException as d:
            status = False
            reason = "Error while deleting device: {0}".format(d.value)
        except:
            status = False
            reason = "Error while deleting device: {0}".format(traceback.format_exc())
        # send the result
        msg = MQMessage()
        msg.set_action('device.delete.result')
        msg.add_data('status', status)
        if reason:
            msg.add_data('reason', reason)
        self.log.debug(msg.get())
        self.reply(msg.get())
Exemplo n.º 17
0
    def test_XplCmd(self, parameters = {}, statParams = None):
        """Send an Xpl cmd with statics parameters by request, if necessary start testcase listener for ack message and 
             check if insert in database is ok.
        """
        if self.get_return_confirmation() :
            schema,  data,  statResult = self.get_XplStat_fromAck(statParams)
            th = threading.Thread(None, self.assert_Xpl_Stat_Ack_Wait, "th_test_0110_xpl-ack_from_{0}".format(self.command_name), (schema,  data, statResult))
            th.start()
            time.sleep(1)
        else : 
            print (u"No ack required for {0}".format(self.command_name))
        if self._device and self.command_id :
            cli = MQSyncReq(zmq.Context())
            msg = MQMessage()
            msg.set_action('cmd.send')
            msg.add_data('cmdid', self.command_id)
            msg.add_data('cmdparams', parameters)
            print (u"Send xpl_cmnd {0}".format(self.command_name))
            cli.request('xplgw', msg.get(), timeout=10)
#            if self.get_return_confirmation() :
#                self.assert_get_last_command_in_db(statResult)
#            else : 
#                print (u"No ack required for {0}".format(self.command_name))
            return True
        else : return False
Exemplo n.º 18
0
def delete_configuration(type, name, host):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action("config.delete")
    msg.add_data("type", type)
    msg.add_data("host", host)
    msg.add_data("name", name)
    result = cli.request("dbmgr", msg.get(), timeout=10)
    if result:
        data = result.get_data()
        if "status" in data:
            if not data["status"]:
                print(result.get())
                raise RuntimeError(
                    "DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}".format(
                        type, name, host, key, value
                    )
                )
            else:
                return True
        else:
            print(result.get())
            raise RuntimeError(
                "DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}".format(
                    type, name, host, key, value
                )
            )
    else:
        raise RuntimeError("Timeout while deleting configuration for {0}-{1}.{2}".format(type, name, host))
Exemplo n.º 19
0
 def _mdp_reply_helper_help(self, data):
     content = data.get_data()
     if 'command' in contens.keys():
         if content['command'] in self.helpers.keys():
             msg = MQMessage()
             msg.set_action('helper.help.result')
             msg.add_data('help', self.helpers[content['command']]['help'])
             self.reply(msg.get())
Exemplo n.º 20
0
 def _mdp_reply_helper_help(self, data):
     content = data.get_data()
     if 'command' in contens.keys():
         if content['command'] in self.helpers.keys():
             msg = MQMessage()
             msg.set_action('helper.help.result')
             msg.add_data('help', self.helpers[content['command']]['help'])
             self.reply(msg.get())
Exemplo n.º 21
0
    def _mdp_reply_devices_update_result(self, data):
        status = True
        reason = False

        self.log.debug(u"Updating device : {0}".format(data))
        try:
            data = data.get_data()
            if 'did' in data:
                did = data['did']
                if 'name' not in data:
                    name = None
                else:
                    name = data['name']
                if 'reference' not in data:
                    ref = None
                else:
                    ref = data['reference']
                if 'description' not in data:
                    desc = None
                else:
                    desc = data['description']
                # do the update
                res = self._db.update_device(did, \
                    d_name=name, \
                    d_description=desc, \
                    d_reference=ref)
                if not res:
                    status = False
                else:
                    status = True
            else:
                status = False
                reason = "There is no such device"
                self.log.debug(reason)
            # delete done
        except DbHelperException as d:
            status = False
            reason = "Error while updating device: {0}".format(d.value)
            self.log.error(reason)
        except:
            status = False
            reason = "Error while updating device: {0}".format(
                traceback.format_exc())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('device.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:
            self._pub.send_event('device.update', {
                "device_id": res.id,
                "client_id": res.client_id
            })
Exemplo n.º 22
0
    def send_rep_ack(self, status, reason, cmd_id):
        """ Send ACQ to a command via MQ
		"""
        #self.log.info(u"==> Reply ACK to command id '%s' for device '%s'" % (cmd_id, dev_name))
        reply_msg = MQMessage()
        reply_msg.set_action('client.cmd.result')
        reply_msg.add_data('status', status)
        reply_msg.add_data('reason', reason)
        self.reply(reply_msg.get())
Exemplo n.º 23
0
 def _mdp_reply_device_new_get(self, data):
     """ Return a list of new devices detected
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('device.new.result')
     msg.add_data('devices', self.new_devices)
     self.reply(msg.get())
Exemplo n.º 24
0
 def _mdp_reply_helper_list(self, data):
     """ Return a list of supported helpers
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('helper.list.result')
     msg.add_data('actions', self.helpers.keys())
     self.reply(msg.get())
Exemplo n.º 25
0
def scenario_disable(id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('scenario.disable')
    msg.add_data('cid', id)
    res = cli.request('scenario', msg.get(), timeout=10)
    flash(gettext(u"Scenario disabled"), u"success")
    return redirect(u"/scenario")
    pass
Exemplo n.º 26
0
 def _mdp_reply_device_new_get(self, data):
     """ Return a list of new devices detected
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('device.new.result')
     msg.add_data('devices', self.new_devices)
     self.reply(msg.get())
 def send_rep_ack(self, status, reason, cmd_id, dev_name):
     """ Send MQ REP (acq) to command
     """
     self.log.info(u"==> Reply MQ REP (acq) to REQ command id '%s' for device '%s'" % (cmd_id, dev_name))
     reply_msg = MQMessage()
     reply_msg.set_action('client.cmd.result')
     reply_msg.add_data('status', status)
     reply_msg.add_data('reason', reason)
     self.reply(reply_msg.get())
Exemplo n.º 28
0
 def _mdp_reply_helper_list(self, data):
     """ Return a list of supported helpers
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('helper.list.result')
     msg.add_data('actions', self.helpers.keys())
     self.reply(msg.get())
Exemplo n.º 29
0
def scenario_del(id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action("scenario.delete")
    msg.add_data("cid", id)
    res = cli.request("scenario", msg.get(), timeout=10)
    flash(gettext(u"Scenario deleted"), u"success")
    return redirect(u"/scenario")
    pass
Exemplo n.º 30
0
    def _mdp_reply_devices_update_result(self, data):
        status = True
        reason = False

        self.log.debug(u"Updating device : {0}".format(data))
        try:
            data = data.get_data()
            if 'did' in data:
                did = data['did']
                if 'name' not in data:
                    name = None
                else:
                    name = data['name']
                if 'reference' not in data:
                    ref = None
                else:
                    ref = data['reference']
                if 'description' not in data:
                    desc = None
                else:
                    desc = data['description']
                # do the update
                res = self._db.update_device(did, \
                    d_name=name, \
                    d_description=desc, \
                    d_reference=ref)
                if not res:
                    status = False
                else:
                    status = True 
            else:
                status = False
                reason = "There is no such device"
                self.log.debug(reason)
            # delete done
        except DbHelperException as d:
            status = False
            reason = "Error while updating device: {0}".format(d.value)
            self.log.error(reason)
        except:
            status = False
            reason = "Error while updating device: {0}".format(traceback.format_exc())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('device.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:
            self._pub.send_event('device.update',
                     {"device_id" : res.id,
                      "client_id" : res.client_id})
Exemplo n.º 31
0
 def request_stop(self):
     """ Request the plugin to stop
     """
     print(u"Request plugin to stop : '{0}' on '{1}'".format(self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.stop.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request("plugin-{0}.{1}".format(self.name, self.host), msg.get(), timeout=10) 
     return True
 def send_rep_ack(self, status, reason, cmd_id, dev_name):
     """ Send MQ REP (acq) to command
     """
     self.log.info(
         u"==> Reply MQ REP (acq) to REQ command id '%s' for device '%s'" %
         (cmd_id, dev_name))
     reply_msg = MQMessage()
     reply_msg.set_action('client.cmd.result')
     reply_msg.add_data('status', status)
     reply_msg.add_data('reason', reason)
     self.reply(reply_msg.get())
Exemplo n.º 33
0
def get_controller_nodes(NetworkID, abort = False):
    data = { u'nodes': [],
                u'error': u''}
    if not abort :
        cli = MQSyncReq(app.zmq_context)
        msg = MQMessage()
        msg.set_action('ozwave.ctrl.nodes')
        msg.add_data('NetworkID', NetworkID)
        res = cli.request('plugin-ozwave.{0}'.format(get_sanitized_hostname()), msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
        else : data['error'] =  u'Plugin timeout response.'
    return data
Exemplo n.º 34
0
def get_request(client_id, action, data, abort = False):
    resData = {u'error': u'', u'data': {}}
    if not abort :
        cli = MQSyncReq(app.zmq_context)
        msg = MQMessage()
        msg.set_action(action)
        for key in data:
            msg.add_data(key, data[key])
        res = cli.request(client_id, msg.get(), timeout=10)
        if res is not None:
            resData = res.get_data()
            action = res.get_action()
        else : resData['error'] =  u'Plugin timeout response on request : {0}.'.format(action)
    return action, resData
Exemplo n.º 35
0
 def do_action(self, condition, tests):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action("cmd.send")
     msg.add_data("cmdid", self._params["cmdid"])
     msg.add_data("cmdparams", self._params["cmdparams"])
     # do the request
     res = cli.request("xplgw", msg.get(), timeout=10)
     if res:
         data = res.get_data()
         if not data["status"]:
             self._log.error("Command sending to XPL gw failed: {0}".format(res))
     else:
         self._log.error("XPL gw did not respond")
Exemplo n.º 36
0
 def do_action(self):
     print self._params
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', self._cmdId)
     msg.add_data('cmdparams', self._params)
     # do the request
     res = cli.request('xplgw', msg.get(), timeout=10)
     if res:
         data = res.get_data()
         if not data['status']:
             self.log.error("Command sending to XPL gw failed: {0}".format(res))
     else:
         self.log.error("XPL gw did not respond")
Exemplo n.º 37
0
 def request_stop(self):
     """ Request the plugin to stop
     """
     print(u"Request plugin to stop : '{0}' on '{1}'".format(
         self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.stop.do')
     msg.add_data('type', "plugin")
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request("plugin-{0}.{1}".format(self.name, self.host),
                          msg.get(),
                          timeout=10)
     return True
Exemplo n.º 38
0
def get_controller_state(NetworkID, abort = False):
    data = {u'NetworkID': u'unknown', u'Node': 1, u'Init_state': u'unknown', u'Node count': 0, u'Protocol': u'unknown',
                u'Node sleeping': 0, u'ListNodeId': [], u'Library': u'undefined', u'state': u'dead', u'Version': u'undefined',
                u'HomeID': u'undefined', u'Primary controller': u'undefined', u'Model': u'undefined', u'Poll interval': 0,
                u'error': u''}
    if not abort :
        cli = MQSyncReq(app.zmq_context)
        msg = MQMessage()
        msg.set_action('ozwave.ctrl.get')
        msg.add_data('NetworkID', NetworkID)
        res = cli.request('plugin-ozwave.{0}'.format(get_sanitized_hostname()), msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
        else : data['error'] =  u'Plugin timeout response.'
    return data
def get_StrikePoints(device_id):
    data = {u'status': u'fail', u'strikes': [], u'error': u''}
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('vigilightning.manager.getstrikes')
    msg.add_data('device_id', device_id)
    res = cli.request('plugin-vigilightning.{0}'.format(
        get_sanitized_hostname()),
                      msg.get(),
                      timeout=10)
    if res is not None:
        data = res.get_data()
    else:
        data['error'] = u'Plugin timeout response.'
    print(u"********* get_StrikePoints : {0}".format(data))
    return data
Exemplo n.º 40
0
    def loadDevices(cls, develop):
        logger.info(u"MQ: Loading Devices info")
        Device.clean()
        msg = MQMessage()
        msg.set_action('client.list.get')
        res = cli.request('manager', msg.get(), timeout=10)
        if res is not None:
            _datac = res.get_data()
        else:
            _datac = {}
        session = Session()
        for client in _datac.itervalues(): 
            # for each plugin client, we request the list of devices
            if client["type"] == "plugin":
                msg = MQMessage()
                msg.set_action('device.get')
                msg.add_data('type', 'plugin')
                msg.add_data('name', client["name"])
                msg.add_data('host', client["host"])
                logger.info(u"MQ: Get devices list for client {0}-{1}.{2}".format("plugin", client["name"], client["host"]))
                res = cli.request('dbmgr', msg.get(), timeout=10)
                if res is not None:
                    _datad = res.get_data()
                else:
                    _datad = {}
                if 'devices' in _datad:
                    for device in _datad["devices"]:
                        logger.info(u"- {0}".format(device["name"]))
                        d = Device(id=device["id"], name=device["name"], type=device["device_type_id"], reference=device["reference"])
                        session.add(d)
                        if "commands" in device:
                            for ref, command  in device["commands"].iteritems():
                                c = Command(id=command["id"], name=command["name"], device_id=device["id"], reference=ref, return_confirmation=command["return_confirmation"])
                                session.add(c)
                                c.datatypes = ""
                                for param in command["parameters"]:
                                    p = CommandParam(command_id=c.id, key=param["key"], datatype_id=param["data_type"])
                                    session.add(p)
                                    c.datatypes += param["data_type"]
                                session.add(c)
                        if "sensors" in device:
                            for ref, sensor in device["sensors"].iteritems():
                                s = Sensor(id=sensor["id"], name=sensor["name"], device_id=device["id"], reference=ref, datatype_id=sensor["data_type"], last_value=sensor["last_value"], last_received=sensor["last_received"], timeout=sensor["timeout"])
                                session.add(s)

        session.commit()
        session.flush()
Exemplo n.º 41
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))

            self.log.info(u"Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 42
0
 def _send_command(self, data):
     """
     Send a command, first find out if its an xpl or mq command
     TODO move convertion to here
     """
     # TODO : clean the 2 linew below
     #with self._db.session_scope():
     if 1 == 1:
         self.log.info(u"Received new cmd request: {0}".format(data))
         failed = False
         status = False
         uuid = None
         request = data.get_data()
         if 'cmdid' not in request:
             failed = "cmdid not in message data"
             status = False
         if 'cmdparams' not in request:
             failed = "cmdparams not in message data"
             status = False
         if not failed:
             # get the command
             #cmd = self._db.get_command(request['cmdid'])
             cmd = self.all_commands[str(request['cmdid'])]
             if cmd is not None:
                 if cmd['xpl_command'] is not None:
                     status, uuid, failed = self._send_xpl_command(
                         cmd, request)
                 else:
                     status, uuid, failed = self._send_mq_command(
                         cmd, request)
                     pass
             else:
                 failed = "Can not find the command"
                 status = False
         else:
             status = False
         self.log.debug("   => status: {0}, uuid: {1}, msg: {2}".format(
             status, uuid, failed))
         # reply
         reply_msg = MQMessage()
         reply_msg.set_action('cmd.send.result')
         reply_msg.add_data('uuid', str(uuid))
         reply_msg.add_data('status', status)
         reply_msg.add_data('reason', failed)
         self.log.debug(u"   => mq reply to requestor")
         self.reply(reply_msg.get())
Exemplo n.º 43
0
    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())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('deviceparam.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']
            })
Exemplo n.º 44
0
    def do_action(self):
        self.log.info(u"Command : Do an action...")

        # live udate some values
        self.log.debug(u"Command : Preprocessing on parameters...")
        self.log.debug(u"Command : Parameters before processing : {0}".format(
            self._params))
        params = {}
        for key in self._params:
            self._params[key] = ucode(self._params[key])
            self.log.debug(
                u"Command : Preprocess for param : key={0}, typeofvalue={1}, value={2}"
                .format(key, type(self._params[key]), self._params[key]))
            params[key] = self._params[key]
            if key == "color" and params[key].startswith("#"):
                self.log.debug(
                    u"- Processing : for a color, if the color starts with #, remove it"
                )
                params[key] = params[key][1:]

        self.log.debug(
            u"Command : Parameters after processing : {0}".format(params))
        self.log.debug(u"Command : Send action command over MQ...")

        # do the command
        cli = MQSyncReq(zmq.Context())
        msg = MQMessage()
        msg.set_action('cmd.send')
        msg.add_data('cmdid', self._cmdId)
        msg.add_data('cmdparams', params)

        self.log.debug(
            u"Command : Command id = '{0}', command params = '{1}'".format(
                self._cmdId, params))
        # do the request
        res = cli.request('xplgw', msg.get(), timeout=10)
        if res:
            data = res.get_data()
            if not data['status']:
                self.log.error(
                    u"Command : Command sending to XPL gw failed: {0}".format(
                        res))
        else:
            self.log.error(u"Command : XPL gw did not respond")
        self.log.debug(u"Command : Action done")
Exemplo n.º 45
0
def api_ncommand(cid):
    """
    @api {get} /rest/cmd/id/<int:cid> Trigger a command
    @apiName getCommand
    @apiGroup Command
    @apiVersion 0.4.1

    @apiParam {Number} id The commandId to generate
    @apiParam Key A key value pair for each command param

    @apiSuccessExample Success-Response:
        HTTTP/1.1 204 No Content 

    @apiErrorExample Gateway Timeout
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'XPL gateway does not respond'
        }
    
    @apiErrorExample Other error
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'Bad command Id'
        }
    """
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('cmd.send')
    msg.add_data('cmdid', cid)
    # build the commandparams
    cmdparams = {}
    for param in request.args:
        cmdparams[param] = request.args.get(param)
    msg.add_data('cmdparams', cmdparams)
    # do the request
    resp = cli.request('xplgw', msg.get(), timeout=10)
    if resp:
        response = resp.get_data()
        if response['status']:
            return 204, None
        else:
            return 400, {'msg': response['reason']}
    else:
        return 400, {'msg': "XPL gateway does not respond"}
Exemplo n.º 46
0
def api_ncommand(cid):
    """
    @api {get} /rest/cmd/id/<int:cid> Trigger a command
    @apiName getCommand
    @apiGroup Command
    @apiVersion 0.4.1

    @apiParam {Number} id The commandId to generate
    @apiParam Key A key value pair for each command param

    @apiSuccessExample Success-Response:
        HTTTP/1.1 204 No Content 

    @apiErrorExample Gateway Timeout
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'XPL gateway does not respond'
        }
    
    @apiErrorExample Other error
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'Bad command Id'
        }
    """
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('cmd.send')
    msg.add_data('cmdid', cid)
    # build the commandparams
    cmdparams = {}
    for param in request.args:
        cmdparams[param] = request.args.get(param)
    msg.add_data('cmdparams', cmdparams)
    # do the request
    resp = cli.request('xplgw', msg.get(), timeout=10)
    if resp:
        response = resp.get_data()
        if response['status']:
            return 204, None
        else:
            return 400, {'msg': response['reason']}
    else:
        return 400, {'msg': "XPL gateway does not respond"}
Exemplo n.º 47
0
def api_ncommand(cid):
    """
    @api {get} /cmd/id/<int:cid>?Key Trigger a command
    @apiName getCommand
    @apiGroup Command

    @apiParam {Number} id The commandId to generate
    @apiParam Key A key value pair for each command param separate by & key1=value1&key2=value2

    @apiSuccessExample Success-Response:
        HTTTP/1.1 204 No Content 

    @apiErrorExample Gateway Timeout
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'XPL gateway does not respond'
        }
    
    @apiErrorExample Other error
        HTTTP/1.1 400 No Bad Request
        {
            msg: 'Bad command Id'
        }
    """
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action("cmd.send")
    msg.add_data("cmdid", cid)
    # build the commandparams
    cmdparams = {}
    for param in request.args:
        cmdparams[param] = request.args.get(param)
    msg.add_data("cmdparams", cmdparams)
    # do the request
    resp = cli.request("xplgw", msg.get(), timeout=10)
    if resp:
        response = resp.get_data()
        if response["status"]:
            return 204, None
        else:
            return 400, {"msg": response["reason"]}
    else:
        return 400, {"msg": "XPL gateway does not respond"}
Exemplo n.º 48
0
 def _send_command(self, data):
     """
     Send a command, first find out if its an xpl or mq command
     TODO move convertion to here
     """
     # TODO : clean the 2 linew below
     #with self._db.session_scope():
     if 1 == 1:
         self.log.info(u"Received new cmd request: {0}".format(data))
         failed = False
         status = False
         uuid = None
         request = data.get_data()
         if 'cmdid' not in request:
             failed = "cmdid not in message data"
             status = False
         if 'cmdparams' not in request:
             failed = "cmdparams not in message data"
             status = False
         if not failed:
             # get the command
             #cmd = self._db.get_command(request['cmdid'])
             cmd = self.all_commands[str(request['cmdid'])]
             if cmd is not None:
                 if cmd['xpl_command'] is not None:
                     status, uuid, failed = self._send_xpl_command(cmd, request)
                 else:
                     status, uuid, failed = self._send_mq_command(cmd, request)
                     pass
             else:
                 failed = "Can not find the command"
                 status = False
         else:
             status = False
         self.log.debug("   => status: {0}, uuid: {1}, msg: {2}".format(status, uuid, failed))
         # reply
         reply_msg = MQMessage()
         reply_msg.set_action('cmd.send.result')
         reply_msg.add_data('uuid', str(uuid))
         reply_msg.add_data('status', status)
         reply_msg.add_data('reason', failed)
         self.log.debug(u"   => mq reply to requestor")
         self.reply(reply_msg.get())
Exemplo n.º 49
0
    def _mdp_reply_devices_create_result(self, data):
        status = True
        reason = False
        result = False
        # get the filled package json
        params = data.get_data()['data']
        # get the json
        cli = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('device_types.get')
        msg.add_data('device_type', params['device_type'])
        res = cli.request('manager', msg.get(), timeout=10)
        del cli
        if res is None:
            status = False
            reason = "Manager is not replying to the mq request"
        pjson = res.get_data()
        if pjson is None:
            status = False
            reason = "No data for {0} found by manager".format(
                params['device_type'])
        pjson = pjson[params['device_type']]
        if pjson is None:
            status = False
            reason = "The json for {0} found by manager is empty".format(
                params['device_type'])

        if status:
            # call the add device function
            res = self._db.add_full_device(params, pjson)
            if not res:
                status = False
                reason = "An error occured while adding the device in database. Please check the file dbmgr.log for more informations"
            else:
                status = True
                reason = False
                result = res

        msg = MQMessage()
        msg.set_action('device.create.result')
        if reason:
            msg.add_data('reason', reason)
        if result:
            msg.add_data('result', result)
        msg.add_data('status', status)
        self.log.debug(msg.get())
        self.reply(msg.get())
        # send the pub message
        if status and res:
            self._pub.send_event('device.update', {
                "device_id": res['id'],
                "client_id": res['client_id']
            })
Exemplo n.º 50
0
    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())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('deviceparam.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']})
Exemplo n.º 51
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            status, reason = self.send_data(data["device_id"], data["value"])

            self.log.info("Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 52
0
 def _mdp_reply_butler_reload(self, message):
     """ Reload the brain 
     """
     msg = MQMessage()
     msg.set_action('butler.reload.result')
     try:
         self.reload()
         msg.add_data(u"status", True)
         msg.add_data(u"reason", "")
     except:
         msg.add_data(u"status", False)
         msg.add_data(u"reason", "Error while reloading brain parts : {0}".format(traceback.format_exc()))
     self.reply(msg.get())
Exemplo n.º 53
0
    def _mdp_reply_devices_delete_result(self, data):
        status = True
        reason = False

        self.log.debug(u"Deleting device : {0}".format(data))
        try:
            did = data.get_data()['did']
            if did:
                res = self._db.del_device(did)
                if not res:
                    status = False
                else:
                    status = True
            else:
                status = False
                reason = "There is no such device"
                self.log.debug(reason)
            # delete done
        except DbHelperException as d:
            status = False
            reason = "Error while deleting device: {0}".format(d.value)
            self.log.error(reason)
        except:
            status = False
            reason = "Error while deleting device: {0}".format(
                traceback.format_exc())
            self.log.error(reason)
        # send the result
        msg = MQMessage()
        msg.set_action('device.delete.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:
            self._pub.send_event('device.update', {
                "device_id": did,
                "client_id": res.client_id
            })
Exemplo n.º 54
0
    def _mdp_reply_plugin_stop(self, data):
        """ Stop the plugin
            @param data : MQ req message

            First, send the MQ Rep to 'ack' the request
            Then, change the plugin status to STATUS_STOP_REQUEST
            Then, quit the plugin by calling force_leave(). This should make the plugin send a STATUS_STOPPED if all is ok

            Notice that no check is done on the MQ req content : we need nothing in it as it is directly addressed to a plugin
        """
        # check if the message is for us
        content = data.get_data()
        if content['name'] != self._name or content['host'] != self.get_sanitized_hostname():
            return

        ### Send the ack over MQ Rep
        msg = MQMessage()
        msg.set_action('plugin.stop.result')
        status = True
        reason = ""
        msg.add_data('status', status)
        msg.add_data('reason', reason)
        msg.add_data('name', self._name)
        msg.add_data('host', self.get_sanitized_hostname())
        self.log.info("Send reply for the stop request : {0}".format(msg))
        self.reply(msg.get())

        ### Change the plugin status
        self._set_status(STATUS_STOP_REQUEST)

        ### Try to stop the plugin
        # if it fails, the manager should try to kill the plugin
        self.force_leave()
Exemplo n.º 55
0
def check_config(type, name, host, key, exp_value):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.get')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    msg.add_data('key', key)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
	data = result.get_data()
	if 'status' in data:
	    if not data['status']:
                print(result.get())
	        raise RuntimeError("DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
            else:
                if 'value' in data:
                    if data['value'] != exp_value:
       			print(result.get())
                        raise RuntimeError("The returned value is not the expected value for {0}-{1}.{2} : {3} = {4} but received {5}".format(type, name, host, key, exp_value, data['value']))
		    else:
                        return True
                else:
                    print(result.get())
	            raise RuntimeError("DbMgr did not return a value on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
        else:
	    print(result.get())
	    raise RuntimeError("DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
    else:
        raise RuntimeError("Error while setting configuration for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))