예제 #1
0
    def delete(self, did):
        """
        @api {del} /device/id Delete a device
        @apiName delDevice
        @apiGroup Device

        @apiParam {Number} id The id of the device to be deleted

        @apiSuccess {String} none No data is returned

        @apiSuccessExample Success-Response:
            HTTTP/1.1 200 OK

        @apiErrorExample Error-Response:
            HTTTP/1.1 500 INTERNAL SERVER ERROR
        """
        cli = MQSyncReq(urlHandler.zmq_context)
        msg = MQMessage()
        msg.set_action('device.delete')
        msg.set_data({'did': did})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                return 201, None
            else:
                return 500, data["reason"]
        else:
            return 500, "DbMgr did not respond on the device.create, check the logs"
        return 201, None
예제 #2
0
파일: admin.py 프로젝트: Nico0084/domogik
 def on_message(self, msg, content=None):
     #print(ws_list.list())
     """ This function is quite tricky
         It is called by both WebSocketHandler and MQASyncSub...
     """
     try:
         ### websocket message (from the web)
         # there are the mesages send by the administration javascript part thanks to the ws.send(...) function
         if not content:
             jsons = json.loads(msg)
             # req/rep
             if 'mq_request' in jsons and 'data' in jsons:
                 cli = MQSyncReq(zmq.Context())
                 msg = MQMessage()
                 msg.set_action(str(jsons['mq_request']))
                 msg.set_data(jsons['data'])
                 if 'dst' in jsons:
                     cli.request(str(jsons['dst']), msg.get(), timeout=10).get()
                 else:
                     cli.request('manager', msg.get(), timeout=10).get()
             # pub
             elif 'mq_publish' in jsons and 'data' in jsons:
                 print("Publish : {0}".format(jsons['data']))
                 self.pub.send_event(jsons['mq_publish'],
                                     jsons['data'])
         ### MQ message (from domogik)
         # these are the published messages which are received here
         else:
             try:
                 self.write_message({"msgid": msg, "content": content})
             except WebSocketClosedError:
                 self.close()
     except:
         print("Error : {0}".format(traceback.format_exc()))
예제 #3
0
파일: admin.py 프로젝트: domogik/domogik
 def sendToMQ(self, message):
     try:
         ctx = zmq.Context()
         jsons = json.loads(message)
         # req/rep
         if 'mq_request' in jsons and 'data' in jsons:
             cli = MQSyncReq(ctx)
             msg = MQMessage()
             msg.set_action(str(jsons['mq_request']))
             msg.set_data(jsons['data'])
             print(u"REQ : {0}".format(msg.get()))
             if 'dst' in jsons:
                 dst = str(jsons['dst'])
             else:
                 dst = 'manager'
             res = cli.request(dst, msg.get(), timeout=10)
             if res:
                 print(res.get())
             cli.shutdown()
             del cli
         # pub
         elif 'mq_publish' in jsons and 'data' in jsons:
             self.pub.send_event(jsons['mq_publish'],
                             jsons['data'])
     except Exception as e:
         print(u"Error sending mq message: {0}".format(e))
예제 #4
0
 def sendToMQ(self, message):
     try:
         ctx = zmq.Context()
         jsons = json.loads(message)
         # req/rep
         if 'mq_request' in jsons and 'data' in jsons:
             cli = MQSyncReq(ctx)
             msg = MQMessage()
             msg.set_action(str(jsons['mq_request']))
             msg.set_data(jsons['data'])
             print(u"REQ : {0}".format(msg.get()))
             if 'dst' in jsons:
                 dst = str(jsons['dst'])
             else:
                 dst = 'manager'
             res = cli.request(dst, msg.get(), timeout=10)
             if res:
                 print(res.get())
             cli.shutdown()
             del cli
         # pub
         elif 'mq_publish' in jsons and 'data' in jsons:
             self.pub.send_event(jsons['mq_publish'], jsons['data'])
     except Exception as e:
         print(u"Error sending mq message: {0}".format(e))
예제 #5
0
def client_devices_delete(client_id, did):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.delete')
    msg.set_data({'did': did})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        data = res.get_data()
        if data["status"]:
            flash(gettext("Device deleted succesfully"), 'success')
        else:
            flash(gettext("Device deleted failed"), 'warning')
            flash(data["reason"], 'danger')
    else:
        flash(gettext("DbMgr did not respond on the device.delete, check the logs"), 'danger')
    return redirect("/client/{0}/dmg_devices/known".format(client_id))
예제 #6
0
파일: admin.py 프로젝트: altenide/domogik
 def on_message(self, msg, content=None):
     if not content:
         # this is a websocket message
         jsons = json.loads(msg)
         if 'action' in jsons and 'data' in jsons:
             cli = MQSyncReq(zmq.Context())
             msg = MQMessage()
             msg.set_action(str(jsons['action']))
             msg.set_data(jsons['data'])
             if 'dst' in jsons:
                 print cli.request(str(jsons['dst']), msg.get(), timeout=10).get()
             else:
                 print cli.request('manager', msg.get(), timeout=10).get()
     else:
         # this is a mq message
         for cli in AdminWebSocket.clients:
             cli.write_message({"msgid": msg, "content": content})
예제 #7
0
 def on_message(self, msg, content=None):
     if not content:
         # this is a websocket message
         jsons = json.loads(msg)
         if 'action' in jsons and 'data' in jsons:
             cli = MQSyncReq(zmq.Context())
             msg = MQMessage()
             msg.set_action(str(jsons['action']))
             msg.set_data(jsons['data'])
             if 'dst' in jsons:
                 print cli.request(str(jsons['dst']), msg.get(),
                                   timeout=10).get()
             else:
                 print cli.request('manager', msg.get(), timeout=10).get()
     else:
         # this is a mq message
         for cli in AdminWebSocket.clients:
             cli.write_message({"msgid": msg, "content": content})
예제 #8
0
파일: clients.py 프로젝트: refaqtor/domogik
def client_devices_delete(client_id, did):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.delete')
    msg.set_data({'did': did})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        data = res.get_data()
        if data["status"]:
            flash(gettext("Device deleted succesfully"), 'success')
        else:
            flash(gettext("Device deleted failed"), 'warning')
            flash(data["reason"], 'danger')
    else:
        flash(
            gettext(
                "DbMgr did not respond on the device.delete, check the logs"),
            'danger')
    return redirect("/client/{0}/dmg_devices/known".format(client_id))
예제 #9
0
    def create_device(self, name, nodeidchildid, devicetype):
        """ Create a new device for this plugin
        """
        client_id = "plugin-mysensors.{0}".format(get_sanitized_hostname())
        # name = "Node xx" or SensorName/Node_id.Child_id
        # nodeidchildid = Node_id.Child_id
        # devicetype = "mysensors.node" or "mysensors.s_temp" ...
        devicedata = {
            'data': {
                u'name':
                name,
                u'description':
                "",
                u'reference':
                "",
                u'global': [{
                    u'key': u'nodesensor',
                    u'value': nodeidchildid,
                    u'type': u'string',
                    u'description': u'nodeid.sensorid'
                }],
                u'client_id':
                client_id,
                u'device_type':
                devicetype,
                u'xpl': [],
                u'xpl_commands': {},
                u'xpl_stats': {}
            }
        }

        cli = MQSyncReq(zmq.Context())
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data(devicedata)
        response = cli.request('dbmgr', msg.get(), timeout=10).get()
        create_result = json.loads(response[1])  # response[1] is a string !
        self.log.debug(u"==> Create device result: '%s'" % response)
        if not create_result["status"]:
            self.log.error("### Failed to create device '%s' (%s) !" %
                           (nodeidchildid))
        '''
예제 #10
0
    def _mdp_reply_butler_discuss(self, message):
        """ Discuss over req/rep
            this should NOT be called with a 10 seconds timeout...
        """
        # TODO : merge with the on_message function !!!

        content = message.get_data()
        self.log.info(u"Received message : {0}".format(content))

        self.add_to_history(u"interface.input", content)
        reply = self.process(content['text'])

        # fill empty data
        for elt in [
                'identity', 'media', 'location', 'sex', 'mood', 'reply_to'
        ]:
            if elt not in content:
                content[elt] = None

        # publish over MQ
        data = {
            "media": content['media'],
            "location": content['location'],
            "sex": self.butler_sex,
            "mood": self.butler_mood,
            "is_reply": True,
            "reply_to": content['source'],
            "identity": self.butler_name,
            "lang": self.lang,
            "text": reply
        }
        self.log.info(u"Send response over MQ : {0}".format(data))

        msg = MQMessage()
        msg.set_action('butler.discuss.result')
        msg.set_data(data)
        self.reply(msg.get())

        self.add_to_history(u"interface.output", data)
예제 #11
0
파일: admin.py 프로젝트: ewintec/domogik
 def publishToMQ(self):
     ctx = zmq.Context()
     cli = MQSyncReq(ctx)
     pub = MQPub(ctx, 'admin')
     while True:
         message = yield self.MQmessages.get()
         jsons = json.loads(message)
         # req/rep
         if 'mq_request' in jsons and 'data' in jsons:
             msg = MQMessage()
             msg.set_action(str(jsons['mq_request']))
             msg.set_data(jsons['data'])
             print("REQ : {0}".format(msg.get()))
             if 'dst' in jsons:
                 print cli.request(str(jsons['dst']), msg.get(), timeout=10).get()
             else:
                 print cli.request('manager', msg.get(), timeout=10).get()
         # pub
         elif 'mq_publish' in jsons and 'data' in jsons:
             print("Publish : {0}".format(jsons['data']))
             pub.send_event(jsons['mq_publish'],
                                 jsons['data'])
예제 #12
0
 def publishToMQ(self):
     ctx = zmq.Context()
     cli = MQSyncReq(ctx)
     pub = MQPub(ctx, 'admin')
     while True:
         message = yield self.MQmessages.get()
         jsons = json.loads(message)
         # req/rep
         if 'mq_request' in jsons and 'data' in jsons:
             msg = MQMessage()
             msg.set_action(str(jsons['mq_request']))
             msg.set_data(jsons['data'])
             print("REQ : {0}".format(msg.get()))
             if 'dst' in jsons:
                 print cli.request(str(jsons['dst']), msg.get(),
                                   timeout=10).get()
             else:
                 print cli.request('manager', msg.get(), timeout=10).get()
         # pub
         elif 'mq_publish' in jsons and 'data' in jsons:
             print("Publish : {0}".format(jsons['data']))
             pub.send_event(jsons['mq_publish'], jsons['data'])
예제 #13
0
파일: butler.py 프로젝트: domogik/domogik
    def _mdp_reply_butler_discuss(self, message):
        """ Discuss over req/rep
            this should NOT be called with a 10 seconds timeout...
        """
        # TODO : merge with the on_message function !!!

        content = message.get_data()
        self.log.info(u"Received message : {0}".format(content))

        self.add_to_history(u"interface.input", content)
        reply = self.process(content['text'])

        # fill empty data
        for elt in ['identity', 'media', 'location', 'sex', 'mood', 'reply_to']:
            if elt not in content:
                content[elt] = None

        # publish over MQ
        data =              {"media" : content['media'],
                             "location" : content['location'],
                             "sex" : self.butler_sex,
                             "mood" : self.butler_mood,
                             "is_reply" : True,
                             "reply_to" : content['source'],
                             "identity" : self.butler_name,
                             "lang" : self.lang,
                             "text" : reply}
        self.log.info(u"Send response over MQ : {0}".format(data))


        msg = MQMessage()
        msg.set_action('butler.discuss.result')
        msg.set_data(data)
        self.reply(msg.get())

        self.add_to_history(u"interface.output", data)
예제 #14
0
        td.del_devices_by_client(client_id)
    except:
        print(
            u"Error while deleting all the test device for the client id '{0}' : {1}"
            .format(client_id, traceback.format_exc()))
#        sys.exit(1)

# create a test device
    try:
        #        params = td.get_params(client_id, "ozwave.primary_controller")
        # TODO: To replace by td.get_params when domogik testcase will use MQ
        cli = MQSyncReq(zmq.Context())
        msg = MQMessage()
        msg.set_action('device.params')
        msg.set_data({
            'device_type': 'ozwave.primary_controller',
            'client_id': client_id
        })
        response = cli.request('admin', msg.get(), timeout=15)
        if response is not None:
            response = response.get_data()
            if 'result' in response:
                print(u"{0} : The params are: {1}".format(
                    datetime.now(), response['result']))
                params = response['result']
            else:
                print("Error when getting devices param for {0} : {1}".format(
                    client_id, response))
        else:
            print("Error when getting devices param for {0}".format(client_id))

        # fill in the params
예제 #15
0
def client_devices_new_wiz(client_id, device_type_id, product):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.set_data({'device_type': device_type_id})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        params = detaila['result']
    else:
        flash(gettext("Device creation failed"), "warning")
        flash(gettext("DbMGR is not answering with device_type parameters"), "danger")
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    # dynamically generate the wtfform
    class F(Form):
        name = TextField("Device", [Required()], description=gettext("the display name for this device"))
        description = TextField("Description", description=gettext("A description for this device"))
        reference = TextField("Reference", description=gettext("A reference for this device"))
        pass
    # add the global params
    for item in params["global"]:
        # build the field
        name = "Parameter - {0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()], description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()], description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()], description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()], description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()], description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()], description=item["description"], choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()], description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()], description=item["description"])
        setattr(F, "glob|{0}".format(item["key"]), field)
    # add the xpl params
    for item in params["xpl"]:
        # build the field
        name = "xPL Parameter - '{0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()], description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()], description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()], description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()], description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()], description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()], description=item["description"], choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()], description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()], description=item["description"])
        setattr(F, "xpl|{0}".format(item["key"]), field)
    for cmd in params["xpl_commands"]:
        for item in params["xpl_commands"][cmd]:
            # build the fiel
            name = "Xpl-Command '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()], description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()], description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()], description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()], description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()], description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()], description=item["description"], choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()], description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()], description=item["description"])
            setattr(F, "cmd|{0}|{1}".format(cmd,item["key"]), field)
    for cmd in params["xpl_stats"]:
        for item in params["xpl_stats"][cmd]:
            # build the fiel
            name = "Xpl-Stat '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()], description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()], description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()], description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()], description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()], description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()], description=item["description"], choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()], description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()], description=item["description"])
            setattr(F, "stat|{0}|{1}".format(cmd,item["key"]), field)
    form = F()

    if request.method == 'POST' and form.validate():
        # aprams hold the stucture,
        # append a vlaue key everywhere with the value submitted
        # or fill in the key
        params['client_id'] = client_id
        for item in request.form:
            if item in ["name", "reference", "description"]:
                # handle the global things
                params[item] = request.form.get(item)
            elif item.startswith('xpl') or item.startswith('glob'):
                # handle the global params
                if item.startswith('xpl'):
                    key = 'xpl'
                else:
                    key = 'global'
                par = item.split('|')[1]
                i = 0
                while i < len(params[key]):
                    param = params[key][i]
                    if par == param['key']:
                        params[key][i]['value'] = request.form.get(item)
                    i = i + 1
            elif item.startswith('stat') or item.startswith('cmd'):
                if item.startswith('stat'):
                    key = "xpl_stats"
                else:
                    key = "xpl_commands"
                name = item.split('|')[1]
                par = item.split('|')[2]
                i = 0
                while i < len(params[key][name]):
                    param = params[key][name][i]
                    if par == param['key']:
                        params[key][name][i]['value'] = request.form.get(item)
                    i = i + 1
        # we now have the json to return
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': params})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                # reload stats
                req = MQSyncReq(app.zmq_context)
                msg = MQMessage()
                msg.set_action( 'reload' )
                resp = req.request('xplgw', msg.get(), 100)
                flash(gettext("Device cerated succesfully"), 'success')
            else:
                flash(gettext("Device creation failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(gettext("DbMgr did not respond on the device.create, check the logs"), 'danger')
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    return render_template('client_device_new_wiz.html',
            form = form,
            params = params,
            dtype = device_type_id,
            clientid = client_id,
            mactive="clients",
            active = 'devices'
            )
예제 #16
0
파일: clients.py 프로젝트: refaqtor/domogik
def client_devices_new_wiz(client_id, device_type_id, product):
    detail = get_client_detail(client_id)
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.set_data({'device_type': device_type_id})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        params = detaila['result']
    else:
        flash(gettext("Device creation failed"), "warning")
        flash(gettext("DbMGR is not answering with device_type parameters"),
              "danger")
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    # dynamically generate the wtfform
    class F(Form):
        name = TextField(
            "Device name", [Required()],
            description=gettext("The display name for this device"))
        try:
            default = request.args.get('Description')
        except:
            default = None
        description = TextField(
            "Description",
            description=gettext("A description for this device"),
            default=default)
        try:
            default = request.args.get('Reference')
        except:
            default = None
        reference = TextField(
            "Reference",
            description=gettext("A reference for this device"),
            default=default)
        pass

    # Form for the Global part
    class F_global(Form):
        pass

    # Form for the xpl part
    class F_xpl(Form):
        pass

    # Form for the xpl command part
    class F_xpl_command(Form):
        pass

    # Form for the xpl stat part
    class F_xpl_stat(Form):
        pass

    # add the global params
    for item in params["global"]:
        # build the field
        name = "{0}".format(item["key"])
        try:
            default = request.args.get(name)
        except:
            if item["type"] == "boolean":
                default = False
            else:
                default = None
        if 'default' in item:
            default = item['default']
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                #default = True
                default = 'y'
            else:
                #default = False
                default = 'n'
            #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
            #field = BooleanField(name, [], description=item["description"], default=default)
            field = RadioField(name, [validators.Required()],
                               description=item["description"],
                               choices=[('y', 'Yes'), ('n', 'No')],
                               default=default)
        elif item["type"] == "integer":
            field = IntegerField(name, [InputRequired()],
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "date":
            field = DateField(name, [InputRequired()],
                              description=item["description"],
                              default=default)
        elif item["type"] == "datetime":
            field = DateTimeField(name, [InputRequired()],
                                  description=item["description"],
                                  default=default)
        elif item["type"] == "float":
            field = FloatField(name, [InputRequired()],
                               description=item["description"],
                               default=default)
        elif item["type"] == "choice":
            choices = []
            if type(item["choices"]) == list:
                for key in sorted(item["choices"]):
                    choices.append((key, key))
            else:
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices,
                                default=default)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"],
                                  default=default)
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"],
                              default=default)
        setattr(F, "glob|{0}".format(item["key"]), field)
        setattr(F_global, "glob|{0}".format(item["key"]), field)
    # add the xpl params
    for item in params["xpl"]:
        # build the field
        name = "{0}".format(item["key"])
        try:
            default = request.args.get(name)
        except:
            default = None
        if 'default' in item:
            default = item['default']
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                #default = True
                default = 'y'
            else:
                #default = False
                default = 'n'
            #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
            #field = BooleanField(name, [], description=item["description"], default=default)
            field = RadioField(name, [validators.Required()],
                               description=item["description"],
                               choices=[('y', 'Yes'), ('n', 'No')],
                               default=default)
        elif item["type"] == "integer":
            field = IntegerField(name, [InputRequired()],
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "date":
            field = DateField(name, [Required()],
                              description=item["description"],
                              default=default)
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()],
                                  description=item["description"],
                                  default=default)
        elif item["type"] == "float":
            field = FloatField(name, [InputRequired()],
                               description=item["description"],
                               default=default)
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices,
                                default=default)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"],
                                  default=default)
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"],
                              default=default)
        setattr(F, "xpl|{0}".format(item["key"]), field)
        setattr(F_xpl, "xpl|{0}".format(item["key"]), field)
    for cmd in params["xpl_commands"]:
        for item in params["xpl_commands"][cmd]:
            # build the field
            name = "{0} - {1}".format(cmd, item["key"])
            try:
                default = request.args.get(name)
            except:
                default = None
            if 'default' in item:
                default = item['default']
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    #default = True
                    default = 'y'
                else:
                    #default = False
                    default = 'n'
                #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
                #field = BooleanField(name, [], description=item["description"], default=default)
                field = RadioField(name, [validators.Required()],
                                   description=item["description"],
                                   choices=[('y', 'Yes'), ('n', 'No')],
                                   default=default)
            elif item["type"] == "integer":
                field = IntegerField(name, [InputRequired()],
                                     description=item["description"],
                                     default=default)
            elif item["type"] == "date":
                field = DateField(name, [Required()],
                                  description=item["description"],
                                  default=default)
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()],
                                      description=item["description"],
                                      default=default)
            elif item["type"] == "float":
                field = FloatField(name, [InputRequired()],
                                   description=item["description"],
                                   default=default)
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()], description=item["description"], choices=choices, \
                        default=default)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()],
                                      description=item["description"],
                                      default=default)
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()],
                                  description=item["description"],
                                  default=default)
            setattr(F, "cmd|{0}|{1}".format(cmd, item["key"]), field)
            setattr(F_xpl_command, "cmd|{0}|{1}".format(cmd, item["key"]),
                    field)
    for cmd in params["xpl_stats"]:
        for item in params["xpl_stats"][cmd]:
            # build the field
            name = "{0} - {1}".format(cmd, item["key"])
            try:
                default = request.args.get(name)
            except:
                default = None
            if 'default' in item:
                default = item['default']
            desc = item["description"]
            if 'multiple' in item and len(item['multiple']) == 1:
                desc = "{0}. Multiple values allowed, seperate with '{1}'".format(
                    desc, item['multiple'])
                # ugly fix, override field type
                item['type'] = "string"
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    #default = True
                    default = 'y'
                else:
                    #default = False
                    default = 'n'
                #field = BooleanField(name, [validators.InputRequired(gettext("This value is required"))], \
                #        description=desc, default=default)
                #field = BooleanField(name, [], \
                #        description=desc, default=default)
                field = RadioField(name, [validators.Required()],
                                   description=item["description"],
                                   choices=[('y', 'Yes'), ('n', 'No')],
                                   default=default)
            elif item["type"] == "integer":
                field = IntegerField(name, [validators.InputRequired(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "date":
                field = DateField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "datetime":
                field = DateTimeField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "float":
                field = FloatField(name, [validators.InputRequired(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, choices=choices, default=default)
            elif item["type"] == "password":
                field = PasswordField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            setattr(F, "stat|{0}|{1}".format(cmd, item["key"]), field)
            setattr(F_xpl_stat, "stat|{0}|{1}".format(cmd, item["key"]), field)
    # create the forms
    form = F()
    form_global = F_global()
    form_xpl = F_xpl()
    form_xpl_command = F_xpl_command()
    form_xpl_stat = F_xpl_stat()

    if request.method == 'POST' and form.validate():
        # aprams hold the stucture,
        # append a vlaue key everywhere with the value submitted
        # or fill in the key
        params['client_id'] = client_id
        for item in request.form:
            if item in ["name", "reference", "description"]:
                # handle the global things
                params[item] = request.form.get(item)
            elif item.startswith('xpl') or item.startswith('glob'):
                # handle the global params
                if item.startswith('xpl'):
                    key = 'xpl'
                else:
                    key = 'global'
                par = item.split('|')[1]
                i = 0
                while i < len(params[key]):
                    param = params[key][i]
                    if par == param['key']:
                        params[key][i]['value'] = request.form.get(item)
                    i = i + 1
            elif item.startswith('stat') or item.startswith('cmd'):
                if item.startswith('stat'):
                    key = "xpl_stats"
                else:
                    key = "xpl_commands"
                name = item.split('|')[1]
                par = item.split('|')[2]
                i = 0
                while i < len(params[key][name]):
                    param = params[key][name][i]
                    if par == param['key']:
                        params[key][name][i]['value'] = request.form.get(item)
                    i = i + 1
        # we now have the json to return
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': params})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                flash(gettext("Device created succesfully"), 'success')
            else:
                flash(gettext("Device creation failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(
                gettext(
                    "DbMgr did not respond on the device.create, check the logs"
                ), 'danger')
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    return render_template('client_device_new_wiz.html',
                           form=form,
                           form_global=form_global,
                           form_xpl=form_xpl,
                           form_xpl_command=form_xpl_command,
                           form_xpl_stat=form_xpl_stat,
                           params=params,
                           dtype=device_type_id,
                           clientid=client_id,
                           mactive="clients",
                           active='devices',
                           client_detail=detail)
예제 #17
0
                }
            ],
            "xpl_commands": {
                
            },
            "global": [
                {
                    "type": "integer",
                    "description": "The time in minutes between each check.",
                    "key": "interval"
                }
            ],
            "device_type": "diskfree.disk_usage",
            "description": ""
        }
    }'
]
"""

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.params')
msg.set_data({'device_type': 'velbus.dimmer'})
print(cli.request('dbmgr', msg.get(), timeout=10).get())

예제 #18
0
파일: butler.py 프로젝트: refaqtor/domogik
def api_butler_discuss_post():
    """
    @api {post} /butler/discuss Discuss with the butler
    @apiName postButlerDiscuss
    @apiGroup Butler
    @apiVersion 0.5.0


    @apiExample Example usage with wget
        If authentication is activated, you will need to also use these options : --auth-no-challenge --http-user=admin --http-password=123 
        $ wget -qO- http://192.168.1.10:40406/rest/butler/discuss --post-data='{"text" : "hello", "source" : "a_script"}' --header="Content-type: application/json"
        {
            "identity": "Aria", 
            "location": null, 
            "media": null, 
            "mood": null, 
            "reply_to": "a_script", 
            "sex": "female", 
            "text": "hi"
        }

    @apiSuccessExample Success-Response:
        HTTTP/1.1 200 
        {
            "identity": "Aria", 
            "location": null, 
            "media": null, 
            "mood": null, 
            "reply_to": "a_script", 
            "sex": "female", 
            "text": "hi"
        }

    @apiErrorExample Butler does not respond in time
        HTTTP/1.1 400 Bad Request
        {
            msg: "butler does not respond"
        }
    
    @apiErrorExample Other error
        HTTTP/1.1 400 Bad Request
        {
            msg: "error while parsing butler response : ...'
        }
    """
    try:
        json_data = json.loads(request.data)
    except:
        return 400, {'msg': u"Error while decoding received json data. Error is : {0}".format(traceback.format_exc())}

    cli = MQSyncReq(app.zmq_context)

    msg = MQMessage()
    msg.set_action('butler.discuss.do')
    msg.set_data(json_data)

    # do the request
    # we allow a long timeout because the butler can take some time to respond...
    # some functions are quite long (requests to external webservices, ...)
    resp = cli.request('butler', msg.get(), timeout=60)
    if resp:
        try:
            response = resp.get_data()
            return 200, response
        except:
            return 400, {'msg': u"error while parsing butler response : {0}".format(resp) }
    else:
        return 400, {'msg': "butler does not respond"}
예제 #19
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())

예제 #20
0
파일: clients.py 프로젝트: domogik/domogik
def client_devices_new_wiz(client_id, device_type_id, product):
    detail = get_client_detail(client_id)
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.set_data({'device_type': device_type_id})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        params = detaila['result']
    else:
        flash(gettext("Device creation failed"), "warning")
        flash(gettext("DbMGR is not answering with device_type parameters"), "danger")
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    # dynamically generate the wtfform
    class F(Form):
        name = TextField("Device name", [Required()], description=gettext("The display name for this device"))
        try: default = request.args.get('Description')
        except: default = None
        description = TextField("Description", description=gettext("A description for this device"), default=default)
        try: default = request.args.get('Reference')
        except: default = None
        reference = TextField("Reference", description=gettext("A reference for this device"), default=default)
        pass
    # Form for the Global part
    class F_global(Form):
        pass
    # Form for the xpl part
    class F_xpl(Form):
        pass
    # Form for the xpl command part
    class F_xpl_command(Form):
        pass
    # Form for the xpl stat part
    class F_xpl_stat(Form):
        pass

    # add the global params
    for item in params["global"]:
        # build the field
        name = "{0}".format(item["key"])
        try: 
            default = request.args.get(name)
        except: 
            if item["type"] == "boolean":
                default = False
            else:
                default = None
        if 'default' in item:
            default = item['default']
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                #default = True
                default = 'y'
            else:
                #default = False
                default = 'n'
            #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
            #field = BooleanField(name, [], description=item["description"], default=default)
            field = RadioField( name, 
                                [validators.Required()], description=item["description"],
                                choices=[('y', 'Yes'), ('n', 'No')], default=default
                              )
        elif item["type"] == "integer":
            field = IntegerField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "date":
            field = DateField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "datetime":
            field = DateTimeField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "float":
            field = FloatField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "choice":
            choices = []
            if type(item["choices"]) == list:
                for key in sorted(item["choices"]):
                    choices.append((key, key))
            else:
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()], description=item["description"], choices=choices, default=default)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()], description=item["description"], default=default)
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()], description=item["description"], default=default)
        setattr(F, "glob|{0}".format(item["key"]), field)
        setattr(F_global, "glob|{0}".format(item["key"]), field)
    # add the xpl params
    for item in params["xpl"]:
        # build the field
        name = "{0}".format(item["key"])
        try: default = request.args.get(name)
        except: default = None
        if 'default' in item:
            default = item['default']
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                #default = True
                default = 'y'
            else:
                #default = False
                default = 'n'
            #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
            #field = BooleanField(name, [], description=item["description"], default=default)
            field = RadioField( name,
                                [validators.Required()], description=item["description"],
                                choices=[('y', 'Yes'), ('n', 'No')], default=default
                              )
        elif item["type"] == "integer":
            field = IntegerField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "date":
            field = DateField(name, [Required()], description=item["description"], default=default)
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()], description=item["description"], default=default)
        elif item["type"] == "float":
            field = FloatField(name, [InputRequired()], description=item["description"], default=default)
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()], description=item["description"], choices=choices, default=default)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()], description=item["description"], default=default)
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()], description=item["description"], default=default)
        setattr(F, "xpl|{0}".format(item["key"]), field)
        setattr(F_xpl, "xpl|{0}".format(item["key"]), field)
    for cmd in params["xpl_commands"]:
        for item in params["xpl_commands"][cmd]:
            # build the field
            name = "{0} - {1}".format(cmd, item["key"])
            try: default = request.args.get(name)
            except: default = None
            if 'default' in item:
                default = item['default']
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    #default = True
                    default = 'y'
                else:
                    #default = False
                    default = 'n'
                #field = BooleanField(name, [InputRequired()], description=item["description"], default=default)
                #field = BooleanField(name, [], description=item["description"], default=default)
                field = RadioField( name,
                                    [validators.Required()], description=item["description"],
                                    choices=[('y', 'Yes'), ('n', 'No')], default=default
                                  )
            elif item["type"] == "integer":
                field = IntegerField(name, [InputRequired()], description=item["description"], default=default)
            elif item["type"] == "date":
                field = DateField(name, [Required()], description=item["description"], default=default)
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()], description=item["description"], default=default)
            elif item["type"] == "float":
                field = FloatField(name, [InputRequired()], description=item["description"], default=default)
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()], description=item["description"], choices=choices, \
                        default=default)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()], description=item["description"], default=default)
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()], description=item["description"], default=default)
            setattr(F, "cmd|{0}|{1}".format(cmd, item["key"]), field)
            setattr(F_xpl_command, "cmd|{0}|{1}".format(cmd, item["key"]), field)
    for cmd in params["xpl_stats"]:
        for item in params["xpl_stats"][cmd]:
            # build the field
            name = "{0} - {1}".format(cmd, item["key"])
            try: default = request.args.get(name)
            except: default = None
            if 'default' in item:
                default = item['default']
            desc = item["description"]
            if 'multiple' in item and len(item['multiple']) == 1:
                desc = "{0}. Multiple values allowed, seperate with '{1}'".format(desc, item['multiple'])
                # ugly fix, override field type
                item['type'] = "string"
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    #default = True
                    default = 'y'
                else:
                    #default = False
                    default = 'n'
                #field = BooleanField(name, [validators.InputRequired(gettext("This value is required"))], \
                #        description=desc, default=default)
                #field = BooleanField(name, [], \
                #        description=desc, default=default)
                field = RadioField( name,
                                    [validators.Required()], description=item["description"],
                                    choices=[('y', 'Yes'), ('n', 'No')], default=default
                                  )
            elif item["type"] == "integer":
                field = IntegerField(name, [validators.InputRequired(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "date":
                field = DateField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "datetime":
                field = DateTimeField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "float":
                field = FloatField(name, [validators.InputRequired(gettext("This value is required"))], \
                        description=desc, default=default)
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, choices=choices, default=default)
            elif item["type"] == "password":
                field = PasswordField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [validators.Required(gettext("This value is required"))], \
                        description=desc, default=default)
            setattr(F, "stat|{0}|{1}".format(cmd, item["key"]), field)
            setattr(F_xpl_stat, "stat|{0}|{1}".format(cmd, item["key"]), field)
    # create the forms
    form = F()
    form_global = F_global()
    form_xpl = F_xpl()
    form_xpl_command = F_xpl_command()
    form_xpl_stat = F_xpl_stat()

    if request.method == 'POST' and form.validate():
        # aprams hold the stucture,
        # append a vlaue key everywhere with the value submitted
        # or fill in the key
        params['client_id'] = client_id
        for item in request.form:
            if item in ["name", "reference", "description"]:
                # handle the global things
                params[item] = request.form.get(item)
            elif item.startswith('xpl') or item.startswith('glob'):
                # handle the global params
                if item.startswith('xpl'):
                    key = 'xpl'
                else:
                    key = 'global'
                par = item.split('|')[1]
                i = 0
                while i < len(params[key]):
                    param = params[key][i]
                    if par == param['key']:
                        params[key][i]['value'] = request.form.get(item)
                    i = i + 1
            elif item.startswith('stat') or item.startswith('cmd'):
                if item.startswith('stat'):
                    key = "xpl_stats"
                else:
                    key = "xpl_commands"
                name = item.split('|')[1]
                par = item.split('|')[2]
                i = 0
                while i < len(params[key][name]):
                    param = params[key][name][i]
                    if par == param['key']:
                        params[key][name][i]['value'] = request.form.get(item)
                    i = i + 1
        # we now have the json to return
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': params})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                flash(gettext("Device created succesfully"), 'success')
            else:
                flash(gettext("Device creation failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(gettext("DbMgr did not respond on the device.create, check the logs"), 'danger')
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    return render_template('client_device_new_wiz.html',
            form = form,
            form_global = form_global,
            form_xpl = form_xpl,
            form_xpl_command = form_xpl_command,
            form_xpl_stat = form_xpl_stat,
            params = params,
            dtype = device_type_id,
            clientid = client_id,
            mactive="clients",
            active = 'devices',
            client_detail = detail
            )
예제 #21
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"]:
                urlHandler.reload_stats()        
                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
예제 #22
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())
예제 #23
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())
예제 #24
0
            "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())



예제 #25
0
def api_butler_discuss_get():
    """
    @api {get} /butler/discuss Discuss with the butler
    @apiName postButlerDiscuss
    @apiGroup Butler
    @apiVersion 0.5.0

    @apiParam data The json data for the butler
    @apiParam callback The callback name (automatically added by jquery)

    @apiExample Example usage with wget
        $ wget -qO- 'http://192.168.1.10:40406/rest/butler/discuss?callback=foo&data={"text" : "hello", "source" : "a_script"}' --header="Content-type: application/json"
        foo({
            "identity": "Aria", 
            "location": null, 
            "media": null, 
            "mood": null, 
            "reply_to": "a_script", 
            "sex": "female", 
            "text": "hi"
        })

    @apiSuccessExample Success-Response:
        HTTTP/1.1 200 
        foo({
            "identity": "Aria", 
            "location": null, 
            "media": null, 
            "mood": null, 
            "reply_to": "a_script", 
            "sex": "female", 
            "text": "hi"
        })

    @apiErrorExample Butler does not respond in time
        HTTTP/1.1 400 Bad Request
        foo({
            msg: "butler does not respond"
        })
    
    @apiErrorExample Other error
        HTTTP/1.1 400 Bad Request
        foo({
            msg: "error while parsing butler response : ...'
        })
    """
    try:
        json_data = json.loads(request.args['data'])
        if 'callback' in request.args:
            callback = request.args['callback']
        else:
            callback = "callback_not_defined"
    except:
        return 400, {
            'msg':
            u"Error while decoding received json data. Error is : {0}".format(
                traceback.format_exc())
        }, "None"

    cli = MQSyncReq(app.zmq_context)

    msg = MQMessage()
    msg.set_action('butler.discuss.do')
    msg.set_data(json_data)

    # do the request
    # we allow a long timeout because the butler can take some time to respond...
    # some functions are quite long (requests to external webservices, ...)
    resp = cli.request('butler', msg.get(), timeout=60)
    if resp:
        try:
            response = resp.get_data()
            return 200, response, callback
        except:
            return 400, {
                'msg':
                u"error while parsing butler response : {0}".format(resp)
            }, callback
    else:
        return 400, {'msg': "butler does not respond"}, callback
예제 #26
0
def client_devices_new_wiz(client_id, device_type_id, product):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.set_data({'device_type': device_type_id})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        params = detaila['result']
    else:
        flash(gettext("Device creation failed"), "warning")
        flash(gettext("DbMGR is not answering with device_type parameters"),
              "danger")
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    # dynamically generate the wtfform
    class F(Form):
        name = TextField(
            "Device", [Required()],
            description=gettext("the display name for this device"))
        description = TextField(
            "Description",
            description=gettext("A description for this device"))
        reference = TextField(
            "Reference", description=gettext("A reference for this device"))
        pass

    # add the global params
    for item in params["global"]:
        # build the field
        name = "Parameter - {0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()],
                              description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"])
        setattr(F, "glob|{0}".format(item["key"]), field)
    # add the xpl params
    for item in params["xpl"]:
        # build the field
        name = "xPL Parameter - '{0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()],
                              description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"])
        setattr(F, "xpl|{0}".format(item["key"]), field)
    for cmd in params["xpl_commands"]:
        for item in params["xpl_commands"][cmd]:
            # build the fiel
            name = "Xpl-Command '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()],
                                  description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()],
                                    description=item["description"],
                                    choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()],
                                      description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()],
                                  description=item["description"])
            setattr(F, "cmd|{0}|{1}".format(cmd, item["key"]), field)
    for cmd in params["xpl_stats"]:
        for item in params["xpl_stats"][cmd]:
            # build the fiel
            name = "Xpl-Stat '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()],
                                  description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()],
                                    description=item["description"],
                                    choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()],
                                      description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()],
                                  description=item["description"])
            setattr(F, "stat|{0}|{1}".format(cmd, item["key"]), field)
    form = F()

    if request.method == 'POST' and form.validate():
        # aprams hold the stucture,
        # append a vlaue key everywhere with the value submitted
        # or fill in the key
        params['client_id'] = client_id
        for item in request.form:
            if item in ["name", "reference", "description"]:
                # handle the global things
                params[item] = request.form.get(item)
            elif item.startswith('xpl') or item.startswith('glob'):
                # handle the global params
                if item.startswith('xpl'):
                    key = 'xpl'
                else:
                    key = 'global'
                par = item.split('|')[1]
                i = 0
                while i < len(params[key]):
                    param = params[key][i]
                    if par == param['key']:
                        params[key][i]['value'] = request.form.get(item)
                    i = i + 1
            elif item.startswith('stat') or item.startswith('cmd'):
                if item.startswith('stat'):
                    key = "xpl_stats"
                else:
                    key = "xpl_commands"
                name = item.split('|')[1]
                par = item.split('|')[2]
                i = 0
                while i < len(params[key][name]):
                    param = params[key][name][i]
                    if par == param['key']:
                        params[key][name][i]['value'] = request.form.get(item)
                    i = i + 1
        # we now have the json to return
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': params})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                # reload stats
                req = MQSyncReq(app.zmq_context)
                msg = MQMessage()
                msg.set_action('reload')
                resp = req.request('xplgw', msg.get(), 100)
                flash(gettext("Device cerated succesfully"), 'success')
            else:
                flash(gettext("Device creation failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(
                gettext(
                    "DbMgr did not respond on the device.create, check the logs"
                ), 'danger')
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    return render_template('client_device_new_wiz.html',
                           form=form,
                           params=params,
                           dtype=device_type_id,
                           clientid=client_id,
                           mactive="clients",
                           active='devices')