Beispiel #1
0
def client_devices_new(client_id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.detail.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        data = detaila[client_id]['data']
    else:
        data = {}
    if type(data["device_types"]) is not dict:
        dtypes = {}
    else:
        dtypes = list(data["device_types"].keys())
    products = {}
    if "products" in data:
        for prod in data["products"]:
            products[prod["name"]] = prod["type"]
 
    return render_template('client_device_new.html',
            device_types = dtypes,
            products = products,
            clientid = client_id,
            mactive="clients",
            active = 'devices'
            )
    def send_to_butler(self, command_line, widget_proxy, live):
        you = u"You > {0}".format(command_line)
        self.parent.value.set_values(self.parent.value.get() + [you])
        self.parent.wMain.values = self.parent.value.get()
        self.parent.wMain.display()

        # handle special commands
        if command_line.lower() == "quit":
            IOLoop.instance().stop()
            sys.exit(0)  # why is this needed ?

        elif command_line.lower() == "reload":
            try:
                cli = MQSyncReq(zmq.Context())
                msg = MQMessage()
                msg.set_action('butler.reload.do')
                result = cli.request('butler', msg.get(), timeout=10).get()
                if result:
                    msg = "*** action reload : {0}".format(result)
                    self.parent.value.set_values(self.parent.value.get() + [msg])
            except:
                msg = u"*** action reload : error (is butler component ok ?)"
                self.parent.value.set_values(self.parent.value.get() + [msg])

        # handle butler
        else:
            self.parent.butler_cb(command_line, identity = "cli user", media = "chat", location = None, mood = None)

        self.parent.wMain.values = self.parent.value.get()
        self.parent.wMain.display()
Beispiel #3
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()
Beispiel #4
0
def configure(type, name, host, key, value):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action("config.set")
    msg.add_data("type", type)
    msg.add_data("host", host)
    msg.add_data("name", name)
    msg.add_data("data", {key: value})
    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(
            "Error while setting configuration for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value)
        )
Beispiel #5
0
def clients():
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.list.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        client_list = res.get_data()
    else:
        client_list = {}

    client_list_per_host_per_type = OrderedDict()
    for client in client_list:
        cli_type = client_list[client]['type']
        cli_host = client_list[client]['host']

        if not client_list_per_host_per_type.has_key(cli_host):
            client_list_per_host_per_type[cli_host] = {}

        if not client_list_per_host_per_type[cli_host].has_key(cli_type):
            client_list_per_host_per_type[cli_host][cli_type] = {}

        client_list_per_host_per_type[cli_host][cli_type][client] = client_list[client]

    return render_template('clients.html',
        mactive="clients",
        overview_state="collapse",
        clients=client_list,
        client_list_per_host_per_type=client_list_per_host_per_type
        )
Beispiel #6
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))
Beispiel #7
0
def client_devices_known(client_id):
    detail = get_client_detail(client_id)

    if app.datatypes == {}:
        cli = MQSyncReq(app.zmq_context)
        msg = MQMessage()
        msg.set_action('datatype.get')
        res = cli.request('manager', msg.get(), timeout=10)
        if res is not None:
            app.datatypes = res.get_data()['datatypes']
        else:
            app.datatypes = {}

    # todo : grab from MQ ?
    with app.db.session_scope():
        devices = app.db.list_devices_by_plugin(client_id)

    # sort clients per device type
    devices_by_device_type_id = {}
    for dev in devices:
        if devices_by_device_type_id.has_key(dev['device_type_id']):
            devices_by_device_type_id[dev['device_type_id']].append(dev)
        else:
            devices_by_device_type_id[dev['device_type_id']] = [dev]

    return render_template('client_devices.html',
            datatypes = app.datatypes,
            devices = devices,
            devices_by_device_type_id = devices_by_device_type_id,
            clientid = client_id,
            mactive="clients",
            active = 'devices',
            rest_url = get_rest_url(),
            client_detail = detail
            )
Beispiel #8
0
 def _load_client_to_xpl_target(self):
     """ Request the client conversion info
         This is an mq req to manager
         If this function does not call self._parse_xpl_target(), all xpl sensors will not be procesed!
     """
     nb_try = 0
     max_try = 5
     ok = False
     while nb_try <= max_try and ok == False:
         nb_try += 1
         cli = MQSyncReq(self.zmq)
         msg = MQMessage()
         msg.set_action('client.list.get')
         response = cli.request('manager', msg.get(), timeout=10)
         if response:
             self._parse_xpl_target(response.get_data())
             ok = True
         else:
             self.log.error(\
                 u"Updating client list failed, no response from manager (try number {0}/{1})".format(nb_try, max_try))
             # We fail to load the client list, so we wait to get something
             time.sleep(5)
     if ok == True:
         self.log.info(u"Updating client list success") 
     else:
         self.log.error(u"Updating client list failed too much time! The xpl sensors will not be processed by this component")
Beispiel #9
0
    def __init__(self, log, dbid, name, json, disabled):
        """ Create the instance
        @param log : A logger instance
        @param dbid : The id of this scenario in the db
        @param json : The json describing the scenario
        """
        self._log = log
        self._name = name
        self._json = json
        self._disabled = disabled

        self.zmq = zmq.Context()
        # datatypes
        self.datatypes = {}
        cli = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('datatype.get')
        res = cli.request('manager', msg.get(), timeout=10)
        if res is not None:
            res = res.get_data()
            if 'datatypes' in res:
                self.datatypes = res['datatypes']

        self._parsed_condition = None
        self._mapping = { 'test': {}, 'action': {} }
        if not self._disabled:
            self._instanciate()
Beispiel #10
0
    def __init__(self, log = None, trigger = None):
        AbstractParameter.__init__(self, log, trigger)
        self.log = log

        #self.set_type("string")
        #self.add_expected_entry("sensor_id", "integer", "The sensor id to check")

        # first, let's get the devices list
        try:
            cli = MQSyncReq(zmq.Context())
            msg = MQMessage()
            msg.set_action('device.get')
            json_devices = cli.request('dbmgr', msg.get(), timeout=10).get()[1]
            devices = json.loads(json_devices)['devices']
            print(devices)
            sensors_list = []
            for dev in devices:
                name = dev['name']
                for sen_idx in dev['sensors']:
                    sen_name = dev['sensors'][sen_idx]['name']
                    sen_id = dev['sensors'][sen_idx]['id']
                    sensors_list.append(['{0} : {1}'.format(name, sen_name), 
                                         '{0}'.format(sen_id)])
            print(sensors_list)
        except:
            self.log.error("Error while getting devices list : {0}".format(traceback.format_exc()))



        # then, et's configure our sensor id selector :)
        self.set_type("list")
        self.add_expected_entry("sensor_id", "list", "The sensor id to check")
        #list_sensors = [['sensor1', 'sensor2'], ['a', 'A']]
        self.set_list_of_values("sensor_id", sensors_list)
Beispiel #11
0
def client_devices_edit(client_id, did):
    with app.db.session_scope():
        device = app.db.get_device_sql(did)
        MyForm = model_form(Device, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['params', 'commands', 'sensors', 'address', 'xpl_commands', 'xpl_stats', 'device_type_id', 'client_id', 'client_version'])
        form = MyForm(request.form, device)

        if request.method == 'POST' and form.validate():
            # save it
            app.db.update_device(did, \
                    d_name=request.form['name'], \
                    d_description=request.form['description'], \
                    d_reference=request.form['reference'])
            # message the suer
            flash(gettext("Device saved"), 'success')
            # reload stats
            req = MQSyncReq(app.zmq_context)
            msg = MQMessage()
            msg.set_action( 'reload' )
            resp = req.request('xplgw', msg.get(), 100)
            # redirect
            return redirect("/client/{0}/dmg_devices/known".format(client_id))
        else:
            return render_template('client_device_edit.html',
                form = form,
                clientid = client_id,
                mactive="clients",
                active = 'devices'
                )
Beispiel #12
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        Plugin.__init__(self, name = 'admin')
        # logging initialization
        self.log.info(u"Admin Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

	try:
            try:
                # admin config
                cfg_admin = Loader('admin')
                config_admin = cfg_admin.load()
                conf_admin = dict(config_admin[1])
                self.interfaces = conf_admin['interfaces']
                self.port = conf_admin['port']
                # if use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_admin['use_ssl']
                self.key_file = conf_admin['ssl_certificate']
                self.cert_file = conf_admin['ssl_key']

            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
		self.use_ssl = False
		self.key_file = ""
		self.cert_file = ""
                self.clean_json = False
                self.log.error("Error while reading configuration for section [admin] : using default values instead")
            self.log.info(u"Configuration : interfaces:port = %s:%s" % (self.interfaces, self.port))
	    
	    # get all datatypes
            cli = MQSyncReq(self.zmq)
            msg = MQMessage()
            msg.set_action('datatype.get')
            res = cli.request('manager', msg.get(), timeout=10)
            if res is not None:
                self.datatypes = res.get_data()['datatypes']
            else:
                self.datatypes = {}

 	    # Launch server, stats
            self.log.info(u"Admin Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
	    self.start_http()
            # calls the tornado.ioloop.instance().start()
            
            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except :
            self.log.error(u"%s" % self.get_exception())
Beispiel #13
0
 def reload_stats(self):
     self.log.debug(u"=============== reload stats")                                                                                                                              
     req = MQSyncReq(self.zmq)
     msg = MQMessage()
     msg.set_action( 'reload' )
     resp = req.request('xplgw', msg.get(), 100)
     self.log.debug(u"Reply from xplgw: {0}".format(resp))
     self.log.debug(u"=============== reload stats END")
Beispiel #14
0
 def _load_client_to_xpl_target(self):
     cli = MQSyncReq(self.zmq)
     msg = MQMessage()
     msg.set_action('client.list.get')
     response = cli.request('manager', msg.get(), timeout=10)
     if response:
         self._parse_xpl_target(response.get_data())
     else:
         self.log.error(u"Updating client list was not successfull, no response from manager")
Beispiel #15
0
def get_butler_history():
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('butler.history.get')
    res = cli.request('butler', msg.get(), timeout=10)
    if res is not None:
        history = res.get_data()['history']
    else:
        history = []
    return history
Beispiel #16
0
def get_clients_list():
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.list.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        client_list = res.get_data()
    else:
        client_list = {}
    return client_list
Beispiel #17
0
def orphans_delete(did):
    with app.db.session_scope():
        app.db.del_device(did)
    # reload stats
    req = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action( 'reload' )
    resp = req.request('xplgw', msg.get(), 100)
    flash(gettext("Device deleted"), "success")
    return redirect("/orphans")
Beispiel #18
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())
Beispiel #19
0
def client_devices_known(client_id):
    detail = get_client_detail(client_id)

    if app.datatypes == {}:
        cli = MQSyncReq(app.zmq_context)
        msg = MQMessage()
        msg.set_action('datatype.get')
        res = cli.request('manager', msg.get(), timeout=10)
        if res is not None:
            app.datatypes = res.get_data()['datatypes']
        else:
            app.datatypes = {}

    # todo : grab from MQ ?
    with app.db.session_scope():
        try:
            devices = app.db.list_devices_by_plugin(client_id)
            error = None
        except:
            error = "Error while retrieving the devices list. Error is : {0}".format(traceback.format_exc())
            devices = []

    # first sort by device name
    devices = sorted(devices, key=itemgetter("name"))
    #    device_types_list[key] = data["device_types"][key]

    # group clients per device type
    devices_by_device_type_id = {}
    for dev in devices:
        try:
            device_type_name = detail['data']['device_types'][dev['device_type_id']]['name']
        except KeyError:
            print(u"Warning : the device type '{0}' does not exist anymore in the installed package release. Device type name set as the existing id in database".format(dev['device_type_id']))
            device_type_name = dev['device_type_id']
        if device_type_name in devices_by_device_type_id:
            devices_by_device_type_id[device_type_name].append(dev)
        else:
            devices_by_device_type_id[device_type_name] = [dev]

    # sorting
    # disabled as this breaks because of storing other objects then normal strings
    devices_by_device_type_id = json.dumps(devices_by_device_type_id, sort_keys=True)
    devices_by_device_type_id = json.loads(devices_by_device_type_id, object_pairs_hook=OrderedDict)

    return render_template('client_devices.html',
            datatypes = app.datatypes,
            devices = devices,
            devices_by_device_type_id = devices_by_device_type_id,
            clientid = client_id,
            mactive="clients",
            active = 'devices',
            #rest_url = get_rest_url(),
            rest_url = request.url_root + "rest",
            client_detail = detail,
            error = error)
Beispiel #20
0
def scenario_blocks_actions():
    """
        Blockly.Blocks['dom_action_log'] = {
          init: function() {
            this.setColour(160);
            this.appendDummyInput()
            .appendField('Log Message')
                .appendField(new Blockly.FieldTextInput("<message to log>"), "message");
            this.setPreviousStatement(true, "null");
            this.setNextStatement(true, "null");
            this.setTooltip('');
            this.setInputsInline(false);
            this.contextMenu = false;
          }
        };
    """
    js = ""
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('action.list')
    res = cli.request('scenario', msg.get(), timeout=10)
    if res is not None:
        res = res.get_data()
        if 'result' in res:
            res = res['result']
            for act, params in res.iteritems():
                p = []
                jso = ""
                for par, parv in params['parameters'].iteritems():
                    papp = "this.appendDummyInput().appendField('{0}')".format(parv['description'])
                    if parv['type'] == 'string':
                        jso = '{0}, "{1}": "\'+ block.getFieldValue(\'{1}\') + \'" '.format(jso, par)
                        papp = "{0}.appendField(new Blockly.FieldTextInput('{1}'), '{2}');".format(papp, parv['default'],par)
                    elif parv['type'] == 'integer':
                        jso = '{0}, "{1}": \'+ block.getFieldValue(\'{1}\') + \' '.format(jso, par)
                        papp = "{0}.appendField(new Blockly.FieldTextInput('{1}'), '{2}');".format(papp, parv['default'],par)
                    else:
                        papp = "{0};".format(papp)
                    p.append(papp)
                add = """Blockly.Blocks['{0}'] = {{
                        init: function() {{
                            this.setHelpUrl('');
                            this.setColour(160);
                            this.appendDummyInput().appendField("{0}");
                            {1}
                            this.setPreviousStatement(true, "null");
                            this.setNextStatement(true, "null");
                            this.setTooltip('{2}');
                            this.setInputsInline(false);
                        }}
                    }};
                    """.format(act, '\n'.join(p), params['description'], jso)
                js = '{0}\n\r{1}'.format(js, add)
    return Response(js, content_type='text/javascript; charset=utf-8')
Beispiel #21
0
 def reload_stats(self):
     try:
         self.log.debug(u"=============== reload stats")                                                                                                                              
         req = MQSyncReq(self.zmq)
         msg = MQMessage()
         msg.set_action( 'reload' )
         resp = req.request('xplgw', msg.get(), 100)
         self.log.debug(u"Reply from xplgw: {0}".format(resp))
         self.log.debug(u"=============== reload stats END")
     except:
         self.log.error(u"Error while reloading stats : {0}".format(traceback.format_exc()))
Beispiel #22
0
def get_client_detail(client_id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.detail.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        detail = detaila[client_id]
    else:
        detail = {}
    return detail
Beispiel #23
0
def get_brain_content(client_id):
    # get data over MQ
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('butler.scripts.get')
    res = cli.request('butler', msg.get(), timeout=10)
    if res is not None:
        data = res.get_data()
        detail = {}
        try:
            detail[client_id] = data[client_id]
        except KeyError:
            # this can happen if you install a package and don't do a butler reload!
            detail[client_id] = None
    else:
        detail = {}

    # sorting
    detail = json.dumps(detail, sort_keys=True)
    detail = json.loads(detail, object_pairs_hook=OrderedDict)

    # do a post processing on content to add html inside
    for client_id in detail:
        # we skip the learn file
        if client_id in ["learn", "not_understood"]:
            continue
        if detail[client_id]:
            for lang in detail[client_id]:
                idx = 0
                for file in detail[client_id][lang]:
                    content = html_escape(detail[client_id][lang][file])

                    # python objects
                    idx += 1
                    reg = re.compile(r"&gt; object", re.IGNORECASE)
                    content = reg.sub("<button class='btn btn-info' onclick=\"$('#python_object_{0}').toggle();\"><span class='glyphicon glyphicon-paperclip' aria-hidden='true'></span> python object</button><div class='python' id='python_object_{0}' style='display: none'>&gt; object".format(idx), content)

                    reg = re.compile(r"&lt; object", re.IGNORECASE)
                    content = reg.sub("&lt; object</div>", content)

                    # trigger
                    reg = re.compile(r"\+(?P<trigger>.*)", re.IGNORECASE)
                    content = reg.sub("<strong>+\g<trigger></strong>", content)

                    # comments
                    reg = re.compile(r"//(?P<comment>.*)", re.IGNORECASE)
                    content = reg.sub("<em>//\g<comment></em>", content)


                    detail[client_id][lang][file] = content
        else:
            detail[client_id] = ""
    return detail
Beispiel #24
0
    def get_device_list(self, quit_if_no_device = False):
        """ Request the dbmgr component over MQ to get the devices list for this client
            @param quit_if_no_device: if True, exit the plugin if there is no devices
        """
        self.log.info(u"Retrieve the devices list for this client...")
        mq_client = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('device.get')
        msg.add_data('type', 'plugin')
        msg.add_data('name', self._name)
        msg.add_data('host', self.get_sanitized_hostname())
        result = mq_client.request('dbmgr', msg.get(), timeout=10)
        if not result:
            self.log.error(u"Unable to retrieve the device list")
            self.force_leave()
            return []
        else:
            device_list = result.get_data()['devices']
            if device_list == []:
                self.log.warn(u"There is no device created for this client")
                if quit_if_no_device:
                    self.log.warn(u"The developper requested to stop the client if there is no device created")
                    self.force_leave()
                    return []
            for a_device in device_list:
                self.log.info(u"- id : {0}  /  name : {1}  /  device type id : {2}".format(a_device['id'], \
                                                                                    a_device['name'], \
                                                                                    a_device['device_type_id']))
                # log some informations about the device
                # notice that even if we are not in the XplPlugin class we will display xpl related informations :
                # for some no xpl plugins, there will just be nothing to display.

                # first : the stats
                self.log.info(u"  xpl_stats features :")
                for a_xpl_stat in a_device['xpl_stats']:
                    self.log.info(u"  - {0}".format(a_xpl_stat))
                    self.log.info(u"    Static Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat]['parameters']['static']:
                        self.log.info(u"    - {0} = {1}".format(a_feature['key'], a_feature['value']))
                    self.log.info(u"    Dynamic Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat]['parameters']['dynamic']:
                        self.log.info(u"    - {0}".format(a_feature['key']))

                # then, the commands
                self.log.info(u"  xpl_commands features :")
                for a_xpl_cmd in a_device['xpl_commands']:
                    self.log.info(u" - {0}".format(a_xpl_cmd))
                    self.log.info(u" + Parameters :")
                    for a_feature in a_device['xpl_commands'][a_xpl_cmd]['parameters']:
                        self.log.info(u" - {0} = {1}".format(a_feature['key'], a_feature['value']))

            self.devices = device_list
            return device_list
Beispiel #25
0
 def _load_conversions(self):
     """ Request the client conversion info
     This is an mq req to manager
     """
     cli = MQSyncReq(self.zmq)
     msg = MQMessage()
     msg.set_action('client.conversion.get')
     response = cli.request('manager', msg.get(), timeout=10)
     if response:
         self._parse_conversions(response.get_data())
     else:
         self.log.error(\
             u"Updating conversion list failed, no response from manager")
Beispiel #26
0
def scenario():
    scenarios = []
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action("scenario.list")
    res = cli.request("scenario", msg.get(), timeout=10)
    if res is not None:
        res = res.get_data()
        if "result" in res:
            res = res["result"]
            for scen in res:
                scenarios.append(scen)
    return render_template("scenario.html", scenarios=scenarios, mactive=u"scenario")
Beispiel #27
0
    def _mdp_reply_butler_scripts(self, message):
        """ Send the raw content for the brain parts over the MQ
        """

        # TODO : handle choice of the client in the req message

        # load not understood queries data
        self.read_not_understood_file()

        msg = MQMessage()
        msg.set_action('butler.scripts.result')
        msg.add_data(u"learn", self.learn_content)
        msg.add_data(u"not_understood", self.not_understood_content)
        for client_id in self.brain_content:
            msg.add_data(client_id, self.brain_content[client_id])
        self.reply(msg.get())
Beispiel #28
0
    def post(self):
        """
        @api {post} /device Create a device
        @apiName postDevice
        @apiGroup Device

        @apiParamTitle (data) Post parameters
        @apiParam (data) {Json} params The populated device params json string

        @apiSuccess {json} result The json representation of the created device

        @apiSuccessExample Success-Response:
            HTTTP/1.1 201 Created
            {
                "xpl_stats": {
                    "get_temp": {
                        "json_id": "get_temp",
                        "schema": "sensor.basic",
                        "id": 4,
                        "parameters": {
                            "dynamic": [
                                {
                                    "ignore_values": "",
                                    "sensor_name": "temp",
                                    "key": "current"
                                }
                            ],
                            "static": [
                                {
                                    "type": "integer",
                                    "value": "2",
                                    "key": "device"
                                },
                                {
                                    "type": null,
                                    "value": "temp",
                                    "key": "type"
                                },
                                {
                                    "type": null,
                                    "value": "c",
                                    "key": "units"
                                }
                            ]
                        },
                        "name": "get_temp"
                    },
                    ...
                },
                "commands": {
                    ...
                },
                "description": "Test Temp",
                "reference": "VMB1TS",
                "xpl_commands": {
                    ...
                },
                "client_id": "plugin-velbus.igor",
                "device_type_id": "velbus.temp",
                "sensors": {
                    "temp": {
                        "value_min": 21.875,
                        "data_type": "DT_Temp",
                        "incremental": false,
                        "id": 4,
                        "reference": "temp",
                        "conversion": "",
                        "name": "temp_sensor",
                        "last_received": 1410857216,
                        "timeout": 0,
                        "formula": null,
                        "last_value": "29.1875",
                        "value_max": 37.4375
                    }
                },
                "parameters": {
                    ...
                },
                "id": 3,
                "name": "Temp elentrik"
            }

        @apiErrorExample Error-Response:
            HTTTP/1.1 500 Internal Server Error
        """
        cli = MQSyncReq(urlHandler.zmq_context)
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': json.loads(request.form.get('params'))})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                return 201, data["result"]
            else:
                return 500, data["reason"]
        else:
            return 500, "DbMgr did not respond on the device.create, check the logs"
        return 201, None
Beispiel #29
0
    def query(self, type, name, key=None):
        '''
        Ask the config system for the value. Calling this function will make
        your program wait until it got an answer

        @param type : the client type
        @param name : the client name of the item requesting the value, must exists in the config database
        @param key : the key to fetch corresponding value
        @return : the value if key != None
                  a dictionnary will all keys/values if key = None
        '''
        msg = MQMessage()
        msg.set_action('config.get')
        msg.add_data('type', type)
        msg.add_data('name', name)
        msg.add_data('host', get_sanitized_hostname())
        if key != None:
            msg.add_data('key', key)
        else:
            key = "*"
        self._log.info("Request query config for client {0} : key {1}".format(
            name, key))
        ret = self.cli.request('dbmgr', msg.get(), timeout=QUERY_CONFIG_WAIT)

        ### no response from dbmgr
        if ret is None:
            self._log.error(
                "Query config for client {0} on host {1}, key {2} : no response from dbmgr"
                .format(name, get_sanitized_hostname(), key))
            return None

        ### response from dbmgr
        else:
            dat = ret.get_data()
            if dat['status']:
                self._log.debug(
                    "Query config : successfull response : {0}".format(ret))
                if key == "*":
                    return dat['data']
                else:
                    val = dat['value']
                    # do some cast
                    if val == "None":
                        val = None
                    return val
            else:
                self._log.error(
                    "Query config : error returned. Reason : {0}".format(
                        dat['reason']))
                return None
Beispiel #30
0
@apiGroup Devices
@apiDescription This request is used to ask Domogik's dbmgr to delete a Domogik device in database. 
* Source client : Domogik admin, any other interface which can create some devices
* Target client : always 'dbmgr'

@apiExample {python} Example usage:
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('device.delete')
    msg.add_data('did', <id>)
    print(cli.request('dbmgr', msg.get(), timeout=10).get())
        
    Here is a json example:
    {
        u'status': True,
        u'reason': None
    }
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device.delete')
msg.add_data('did', 1)
print(cli.request('dbmgr', msg.get(), timeout=10).get())

@apiGroup Butler
@apiDescription This request is used to ask Domogik's Butler to reload the brain parts
* Source client : Domogik admin, any other interface which can manage the clients
* Target client : always 'butler' 

@apiExample {python} Example usage:
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('butler.reload.do')
    print(cli.request('butler', msg.get(), timeout=10).get())

@apiSuccessExample {json} Success-Response:
['butler.reload.result', '{"status": true, "reason": ""}']

@apiErrorExample {json} Error-Response:
['butler.reload.result', '{"status": false, "reason": "some error message"}']
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('butler.reload.do')
print(cli.request('butler', msg.get(), timeout=10).get())



Beispiel #32
0
    def _mdp_reply_sensor_update_result(self, data):
        status = True
        reason = False

        self.log.debug(u"Updating sensor : {0}".format(data))
        try:
            data = data.get_data()
            if 'sid' in data:
                sid = data['sid']
                if 'history_round' not in data:
                    hround = None
                else:
                    hround = data['history_round']
                if 'history_store' not in data:
                    hstore = None
                else:
                    hstore = data['history_store']
                if 'history_max' not in data:
                    hmax = None
                else:
                    hmax = data['history_max']
                if 'history_expire' not in data:
                    hexpire = None
                else:
                    hexpire = data['history_expire']
                if 'timeout' not in data:
                    timeout = None
                else:
                    timeout = data['timeout']
                if 'formula' not in data:
                    formula = None
                else:
                    formula = data['formula']
                if 'data_type' not in data:
                    data_type = None
                else:
                    data_type = data['data_type']
                # do the update
                res = self._db.update_sensor(sid, \
                     history_round=hround, \
                     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']
            })
Beispiel #33
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']
            })
Beispiel #34
0
            "host": "darkstar",
            "type": "plugin",
            "last_seen": 1412278856.468068
        },
        "plugin-teleinfo.darkstar": {
            "status": "unknown",
            "name": "teleinfo",
            "xpl_source": "domogik-teleinfo.darkstar",
            "configured": false,
            "pid": 0,
            "package_id": "plugin-teleinfo",
            "host": "darkstar",
            "type": "plugin",
            "last_seen": 1412278856.43876
        }
    }'
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('client.list.get')
print(cli.request('manager', msg.get(), timeout=10).get())


Beispiel #35
0
 def _mdp_reply(self, action, payload):
     msg = MQMessage()
     msg.set_action(action)
     msg.add_data('result', payload)
     self.reply(msg.get())
@apiVersion 0.4.1
@apiName butler.history.get
@apiGroup Butler
@apiDescription This request is used to ask Domogik's Butler all the N last exchanges
* Source client : Domogik admin, any other interface which can manage the clients
* Target client : always 'butler' 

@apiExample {python} Example usage:
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('butler.history.get')
    print(cli.request('butler', msg.get(), timeout=10).get())

@apiSuccessExample {json} Success-Response:
[
    TODO
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('butler.history.get')
print(cli.request('butler', msg.get(), timeout=10).get())


Beispiel #37
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 = ""

        ### process parameters
        msg_data = data.get_data()
        if 'sensor_id' in msg_data:
            sensor_id = msg_data['sensor_id']
        else:
            reason = "ERROR when getting sensor history. No sensor_id declared in the message"
            self.log.error(reason)
            status = False
            sensor_id = None
        if 'mode' in msg_data:
            if msg_data['mode'] == "last":
                mode = "last"
            elif msg_data['mode'] == "period":
                mode = "period"
            else:
                reason = "ERROR when getting sensor history. No valid type (last, from) declared in the message"
                self.log.error(reason)
                status = False
                mode = None
        else:
            reason = "ERROR when getting sensor history. No type (last, from) declared in the message"
            self.log.error(reason)
            status = False
            sensor_id = None

        values = None

        ### last N values
        if mode == "last":
            if 'number' in msg_data:
                number = msg_data['number']
            else:
                number = 1

            try:
                history = self._db.list_sensor_history(sensor_id, number)
                if len(history) == 0:
                    values = None
                else:
                    values = self._db.list_sensor_history(sensor_id, number)
            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

        ### period
        elif mode == "period":
            if 'from' in msg_data:
                frm = msg_data['from']
            else:
                reason = "ERROR when getting sensor history. No key 'from' defined for mode = 'period'!"
                self.log.error(reason)
                status = False
                frm = None

            if 'to' in msg_data:
                to = msg_data['to']
            else:
                to = None

            if frm != None and to == None:
                values = self._db.list_sensor_history_between(sensor_id, frm)
                print(values)

            else:
                # TODO
                values = "TODO"

        msg.add_data('status', status)
        msg.add_data('reason', reason)
        msg.add_data('sensor_id', sensor_id)
        msg.add_data('mode', mode)
        msg.add_data('values', values)

        self.reply(msg.get())
Beispiel #38
0
            "source" : "a_client",
            "identity" : "someone",
            "text" : "hello"}
    msg.set_data(data)
    print(cli.request('butler', msg.get(), timeout=30).get())

@apiSuccessExample {json} Success-Response:
['butler.discuss.result', '{"mood": null, "media": "audio", "sex": "female", "location": null, "text": "Salut", "reply_to": "a_client", "identity": "Aria"}']

"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('butler.discuss.do')
data = {
    "media": "audio",
    "location": None,
    "sex": None,
    "mood": None,
    "source": "a_client",
    "identity": "someone",
    "text": "hello"
}
msg.set_data(data)
print(cli.request('butler', msg.get(), timeout=30).get())
#!/usr/bin/python
# -*- coding: utf-8 -*-

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.pubsub.subscriber import MQAsyncSub
from domogikmq.message import MQMessage
from domogik.common.plugin import STATUS_ALIVE, STATUS_STOPPED
import json

name = 'vigilightning'
host = 'vmserver16'

print(u"Request plugin startup to the manager for '{0}' on '{1}'".format(name, host))
cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('plugin.start.do')
msg.add_data('type', "plugin")
msg.add_data('name', name)
msg.add_data('host', host)
result = cli.request('manager', msg.get(), 10)
print(u"Result start: {0}".format(result))
Beispiel #40
0
    def _mdp_reply_config_set(self, data):
        """ Reply to config.set MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config set : missing 'type' field : {0}".format(data)

        if msg_data['type'] not in ["plugin", "brain", "interface"]:
            status = False
            reason = "You are not able to configure items for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config set : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config set : missing 'host' field : {0}".format(data)

        if 'data' not in msg_data:
            status = False
            reason = "Config set : missing 'data' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            data = msg_data['data']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try:
                # we add a configured key set to true to tell the UIs and plugins that there are some configuration elements
                self._db.set_plugin_config(type, name, host, "configured",
                                           True)
                for key in msg_data['data']:
                    self._db.set_plugin_config(type, name, host, key,
                                               data[key])
                self.publish_config_updated(type, name, host)
            except:
                reason = "Error while setting configuration for '{0} {1} on {2}' : {3}".format(
                    type, name, host, traceback.format_exc())
                status = False
                self.log.error(reason)

        msg.add_data('status', status)
        msg.add_data('reason', reason)

        self.log.debug(msg.get())
        self.reply(msg.get())
Beispiel #41
0
    def _mdp_reply_devices_params_result(self, data):
        """
            Reply to device.params mq req
            @param data : MQ req message
                => should contain
                    - device_type
        """
        status = True

        try:
            # check we have all the needed info
            msg_data = data.get_data()
            if 'device_type' not in msg_data:
                status = False
                reason = "Device params request : missing 'cevice_type' field : {0}".format(
                    data)
            else:
                dev_type_id = msg_data['device_type']

            # check the received info
            if status:
                cli = MQSyncReq(self.zmq)
                msg = MQMessage()
                msg.set_action('device_types.get')
                msg.add_data('device_type', dev_type_id)
                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"
            if status:
                pjson = res.get_data()
                if pjson is None:
                    status = False
                    reason = "No data for {0} found by manager".format(
                        msg_data['device_type'])
            if status:
                pjson = pjson[dev_type_id]
                if pjson is None:
                    status = False
                    reason = "The json for {0} found by manager is empty".format(
                        msg_data['device_type'])
                self.log.debug(
                    "Device Params result : json received by the manager is : {0}"
                    .format(pjson))
            if not status:
                # we don't have all info so exit
                msg = MQMessage()
                msg.set_action('device.params.result')
                msg.add_data('result', 'Failed')
                msg.add_data('reason', reason)
                self.log.debug(msg.get())
                self.reply(msg.get())
                return

            # we have the json now, build the params
            msg = MQMessage()
            msg.set_action('device.params.result')
            stats = []
            result = {}
            result['device_type'] = dev_type_id
            result['name'] = ""
            result['reference'] = ""
            result['description'] = ""
            # append the global xpl and on-xpl params
            result['xpl'] = []
            result['global'] = []
            for param in pjson['device_types'][dev_type_id]['parameters']:
                if param['xpl']:
                    del param['xpl']
                    result['xpl'].append(param)
                else:
                    del param['xpl']
                    result['global'].append(param)
            # find the xplCommands
            result['xpl_commands'] = {}
            for cmdn in pjson['device_types'][dev_type_id]['commands']:
                cmd = pjson['commands'][cmdn]
                if 'xpl_command' in cmd:
                    xcmdn = cmd['xpl_command']
                    xcmd = pjson['xpl_commands'][xcmdn]
                    result['xpl_commands'][xcmdn] = []
                    stats.append(xcmd['xplstat_name'])
                    for param in xcmd['parameters']['device']:
                        result['xpl_commands'][xcmdn].append(param)
            # find the xplStats
            sensors = pjson['device_types'][dev_type_id]['sensors']
            #print("SENSORS = {0}".format(sensors))
            for xstatn in pjson['xpl_stats']:
                #print("XSTATN = {0}".format(xstatn))
                xstat = pjson['xpl_stats'][xstatn]
                for sparam in xstat['parameters']['dynamic']:
                    #print("XSTATN = {0}, SPARAM = {1}".format(xstatn, sparam))
                    #if 'sensor' in sparam and xstatn in sensors:
                    # => This condition was used to fix a bug which occurs while creating complexe devices for rfxcom
                    #    But is introduced a bug for the geoloc plugin...
                    #    In fact we had to fix the rfxcom info.json file (open_close uses now rssi_open_close instead of
                    #    rssi_lighting2
                    #    So, this one is NOT the good one.
                    if 'sensor' in sparam:
                        # => this condition was the original one restored to make the geoloc pluin ok for tests
                        #    Strangely, there is no issue while using the admin (which uses only mq)
                        #    but is sucks with test library which uses rest...
                        #    This one is the good one
                        if sparam['sensor'] in sensors:
                            #print("ADD")
                            stats.append(xstatn)
            result['xpl_stats'] = {}
            #print("STATS = {0}".format(stats))
            for xstatn in stats:
                xstat = pjson['xpl_stats'][xstatn]
                result['xpl_stats'][xstatn] = []
                for param in xstat['parameters']['device']:
                    result['xpl_stats'][xstatn].append(param)
            # return the data
            msg.add_data('result', result)
            self.log.debug(msg.get())
            self.reply(msg.get())
        except:
            self.log.error(
                "Error when replying to device.params for data={0}. Error: {1}"
                .format(data, traceback.format_exc()))
Beispiel #42
0
                    "interval": {
                        "key": "interval",
                        "type": "integer",
                        "id": 8,
                        "value": "1"
                    }
                },
                "id": 8,
                "name": "test_device_diskfree"
            }
        ],
        "host": "darkstar",
        "type": "plugin"
    }'
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device.get')
#msg.add_data('type', 'plugin')
#msg.add_data('name', 'diskfree')
#msg.add_data('host', 'darkstar')
print(cli.request('dbmgr', msg.get(), timeout=10).get())

Beispiel #43
0
#!/usr/bin/python
"""
@apiIgnore TODO : This method is not yet documented
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('parameter.list')
print(cli.request('scenario', msg.get(), timeout=10).get())


Beispiel #44
0
            },
            {
                'value': 60,
                u'type': u'integer',
                u'description': u'Thetimeinsecondsbetweeneachcheck.',
                u'key': u'interval'
            }
        ],
        u'client_id': u'plugin-teleinfo.darkstar',
        u'device_type': 'teleinfo.electric_meter',
        u'name': 'test_device_teleinfo'
    }

@apiParam {String} data The json data which represents the Domogik device to create. 


@apiSuccessExample {json} Success-Response:
[]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device.create')
msg.set_data({'data': {'some': 'json content'}})
print(cli.request('dbmgr', msg.get(), timeout=10).get())
Beispiel #45
0
    def _mdp_reply_config_delete(self, data):
        """ Reply to config.delete MQ req
            Delete all the config items for the given type, name and host
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] not in ["plugin", "brain", "interface"]:
            status = False
            reason = "Configuration deletion not available for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try:
                self._db.del_plugin_config(type, name, host)
                self.log.info(u"Delete config for {0} {1}".format(type, name))
                self.publish_config_updated(type, name, host)
            except:
                status = False
                reason = "Error while deleting configuration for '{0} {1} on {2} : {3}".format(
                    type, name, host, traceback.format_exc())
                self.log.error(reason)

        msg.add_data('reason', reason)
        msg.add_data('status', status)

        self.log.debug(msg.get())
        self.reply(msg.get())
Beispiel #46
0
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('device.update')
    msg.add_data('did', <id>)
    msg.add_data('name', <name>)
    msg.add_data('description', <description>)
    msg.add_data('reference', <reference>)
    print(cli.request('dbmgr', msg.get(), timeout=10).get())
        
    Here is a json example:
    {
        u'status': True,
        u'reason': None
    }
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device.update')
msg.add_data('did', 1)
msg.add_data('name', "new name")
msg.add_data('description', "new description")
msg.add_data('reference', "new reference")
print(cli.request('dbmgr', msg.get(), timeout=10).get())

Beispiel #47
0
    def _mdp_reply_config_get(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] not in ["plugin", "brain", "interface"]:
            status = False
            reason = "Configuration request not available for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if 'key' not in msg_data:
            get_all_keys = True
            key = "*"
        else:
            get_all_keys = False
            key = msg_data['key']

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            msg.add_data(
                'key', key
            )  # we let this here to display key or * depending on the case
            try:
                if get_all_keys == True:
                    config = self._db.list_plugin_config(type, name, host)
                    self.log.info(
                        u"Get config for {0} {1} with key '{2}' : value = {3}".
                        format(type, name, key, config))
                    json_config = {}
                    for elt in config:
                        json_config[elt.key] = self.convert(elt.value)
                    msg.add_data('data', json_config)
                else:
                    value = self._fetch_techno_config(name, type, host, key)
                    # temporary fix : should be done in a better way (on db side)
                    value = self.convert(value)
                    self.log.info(
                        u"Get config for {0} {1} with key '{2}' : value = {3}".
                        format(type, name, key, value))
                    msg.add_data('value', value)
            except:
                status = False
                reason = "Error while getting configuration for '{0} {1} on {2}, key {3}' : {4}".format(
                    type, name, host, key, traceback.format_exc())
                self.log.error(reason)

        msg.add_data('reason', reason)
        msg.add_data('status', status)

        self.log.debug(msg.get())
        self.reply(msg.get())
Beispiel #48
0
        "values": [
            "1027.3"
        ]
    }'
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())

# example 1 : get the latest value
msg = MQMessage()
msg.set_action('sensor_history.get')
msg.add_data('sensor_id', 3)
msg.add_data('mode', 'last')
msg.add_data('number', 1)
print(cli.request('dbmgr', msg.get(), timeout=10).get())

# example 2 : get the last N values
msg = MQMessage()
msg.set_action('sensor_history.get')
msg.add_data('sensor_id', 3)
msg.add_data('mode', 'last')
msg.add_data('number', 3)
print(cli.request('dbmgr', msg.get(), timeout=10).get())

# example 3 : get the values since a timestamp
Beispiel #49
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: {0}".format(msg))
        action = msg.get_action().split(".")
        if action[0] == "client" and action[1] == "cmd" :
            # action on dmg device
            data = msg.get_data()
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            idsClient = self.managerClients.getIdsClient(data)
            find = False
            if idsClient != [] :
                for id in idsClient :
                    client = self.managerClients.getClient(id)
                    if client :
                        self.log.debug(u"Handle requested action for Notify client {0} : {1}".format(id, data))
                        commands = client.getDmgCommands()
                        for cmd in commands :
                            if commands[cmd]['id'] == data['command_id'] :
                                find = True
                                client.handle_cmd(data)
                                reply_msg.add_data('status', True)
                                reply_msg.add_data('reason', None)
                                break

            if not find :
                self.log.warning(u"Requested action received for unknown Notify client : {0}".format(data))
                reply_msg.add_data('status', False)
                reply_msg.add_data('reason', u"Requested action received for unknown Notify client : {0}".format(data))
            self.log.debug(u"Reply to MQ: {0}".format(reply_msg.get()))
            self.reply(reply_msg.get())
Beispiel #50
0
    def _mdp_reply_devices_result(self, data):
        """ Reply to device.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('device.result')
        status = True

        msg_data = data.get_data()

        # request for all devices
        if 'type' not in msg_data and \
           'name' not in msg_data and \
           'host' not in msg_data and \
           'timestamp' not in msg_data:
            reason = ""
            status = True
            dev_list = self._db.list_devices()
            dev_json = dev_list
            msg.add_data('status', status)
            msg.add_data('reason', reason)
            msg.add_data('devices', dev_json)
        elif 'timestamp' in msg_data:
            # request for all devices that changed after timestamp
            reason = ""
            status = True
            dev_list = self._db.list_devices_by_timestamp(
                msg_data['timestamp'])
            dev_json = dev_list
            msg.add_data('status', status)
            msg.add_data('reason', reason)
            msg.add_data('devices', dev_json)
        else:
            # request for all devices of one client
            if 'type' not in msg_data:
                status = False
                reason = "Devices request : missing 'type' field : {0}".format(
                    data)

            if 'name' not in msg_data:
                status = False
                reason = "Devices request : missing 'name' field : {0}".format(
                    data)

            if 'host' not in msg_data:
                status = False
                reason = "Devices request : missing 'host' field : {0}".format(
                    data)

            if status == False:
                self.log.error(reason)
            else:
                reason = ""
                type = msg_data['type']
                name = msg_data['name']
                host = msg_data['host']
                dev_list = self._db.list_devices_by_plugin(
                    "{0}-{1}.{2}".format(type, name, host))

            #dev_json = json.dumps(dev_list, cls=domogik_encoder(), check_circular=False),
            dev_json = dev_list
            msg.add_data('status', status)
            msg.add_data('reason', reason)
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            msg.add_data('devices', dev_json)

        self.reply(msg.get())
Beispiel #51
0
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('plugin.start.do')
    msg.add_data('name', 'diskfree')
    msg.add_data('host', 'darkstar')
    print(cli.request('manager', msg.get(), timeout=10).get())

@apiParam {String} name The plugin name to start
@apiParam {String} host The host on which is hosted the plugin

@apiSuccessExample {json} Success-Response:
['plugin.start.result', '{"status": true, "host": "darkstar", "reason": "", "name": "diskfree"}']

@apiErrorExample {json} Error-Response:
['plugin.start.result', '{"status": false, "host": "darkstar", "reason": "Plugin \'xxx\' does not exist on this host", "name": "xxx"}']
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('plugin.start.do')
msg.add_data('name', 'diskfree')
msg.add_data('host', 'darkstar')
print(cli.request('manager', msg.get(), timeout=10).get())


Beispiel #52
0
def device_params(client_id, dev_type_id):
    """
    @api {get} /device/params/<clientId>/<device_type> Retrieve the needed parameter for creating a device
    @apiName getDeviceParams
    @apiGroup Device

    @apiParam {String} clientId The clientId to request the parameter from
    @apiParam {String} device_type The device type to request the parameters for

    @apiSuccess {json} result The json representing the device type
    
    @apiSampleRequest /device/params/plugin-velbus.igor/velbus.relay

    @apiSuccessExample Success-Response:
        HTTTP/1.1 200 OK
        {
            "xpl_stats": {
                "get_level_bin": []
            },
            "name": "",
            "reference": "",
            "xpl": [
                {
                    "max_value": 4,
                    "min_value": 1,
                    "type": "integer",
                    "description": "The channel number",
                    "key": "channel"
                },
                {
                    "max_value": 255,
                    "min_value": 0,
                    "type": "integer",
                    "description": "The decimal address",
                    "key": "device"
                }
            ],
            "xpl_commands": {
                "set_level_bin": []
            },
            "global": [],
            "client_id": "plugin-velbus.igor",
            "device_type": "velbus.relay",
            "description": ""
        }

    @apiErrorExample Error-Response:
        HTTTP/1.1 404 Not Found
    """
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.add_data('device_type', dev_type_id)
    res = cli.request('dbmgr', msg.get(), timeout=10)
    result = {}
    if res:
        res = res.get_data()
        print(type(res['result']))
        # test if dbmgr returns a str ("Failed")
        # and process this case...
        if isinstance(res['result'], str) or isinstance(
                res['result'], unicode):
            return 500, "DbMgr did not respond as expected, check the logs. Response is : {0}. {1}".format(
                res['result'], res['reason'])
        result = res['result']
        result["client_id"] = client_id
    # return the info
    return 200, result
Beispiel #53
0
    msg.add_data('command_id', 6)
    msg.add_data('device_id', 6)
    msg.add_data('param1', 1)
    msg.add_data('param2', 2)
    return cli.request('igor.velbus', msg.get(), timeout=10).get()


@apiSuccessExample {json} Success-Response:
[
    'client.command.response',
    '{
        "status" : true,
        "reason" : null,
    }'
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('client.cmd')
msg.add_data('command_id', 6)
msg.add_data('device_id', 6)
msg.add_data('param1', 1)
msg.add_data('param2', 2)
print cli.request('igor.velbus', msg.get(), timeout=10).get()
Beispiel #54
0
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('cmd.send')
    msg.add_data('cmdid', 6)
    msg.add_data('cmdparams', {"command" : 1})
    return cli.request('xplgw', msg.get(), timeout=10).get()


@apiSuccessExample {json} Success-Response:
[
    'cmd.send.result',
    '{
        "status" : true,
        "reason" : null,
        "uuid" : "8a09462a-4d02-40fd-bf67-4c19240bfbdd"
    }'
]
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('cmd.send')
msg.add_data('cmdid', 6)
msg.add_data('cmdparams', {"command": 1})
print cli.request('xplgw', msg.get(), timeout=10).get()
Beispiel #55
0
#!/usr/bin/python
"""
@apiIgnore TODO : This method is not yet documented
"""

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogikmq.reqrep.client import MQSyncReq
from domogikmq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('helper.help.get')
msg.add_data('command', 'scan')
print(cli.request('velbus', msg.get(), timeout=10).get())

Beispiel #56
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import zmq
import json
from time import sleep

from domogikmq.message import MQMessage
from domogikmq.reqrep.client import MQSyncReq

z = zmq.Context()
m = MQMessage('test.list', {})
m2 = MQMessage('parameter.list', {})
m3 = MQMessage('scenario.list', {})
m4 = MQMessage('action.list', {})
c = MQSyncReq(z)

print "==== List of tests ===="
tests = c.request('scenario', m.get())
print tests
print "==== List of parameters ===="
print c.request('scenario', m2.get())
print "==== List of conditions ===="
print c.request('scenario', m3.get())
print "==== List actions ===="
print c.request('scenario', m4.get())
print "==== Get one test ===="
print tests._data['result']
print type(tests._data['result'])
#tests_data = json.loads(tests._data['result'])
tests_data = tests._data['result']