本文整理汇总了Python中domogikmq.reqrep.client.MQSyncReq类的典型用法代码示例。如果您正苦于以下问题:Python MQSyncReq类的具体用法?Python MQSyncReq怎么用?Python MQSyncReq使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MQSyncReq类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sendToMQ
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))
示例2: client_devices_new
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'
)
示例3: do_action
def do_action(self):
self.log.info(u"Command : Do an action...")
# live udate some values
self.log.debug(u"Command : Preprocessing on parameters...")
self.log.debug(u"Command : Parameters before processing : {0}".format(self._params))
params = {}
for key in self._params:
self._params[key] = ucode(self._params[key])
self.log.debug(u"Command : Preprocess for param : key={0}, typeofvalue={1}, value={2}".format(key, type(self._params[key]), self._params[key]))
params[key] = self._params[key]
if key == "color" and params[key].startswith("#"):
self.log.debug(u"- Processing : for a color, if the color starts with #, remove it")
params[key] = params[key][1:]
self.log.debug(u"Command : Parameters after processing : {0}".format(params))
self.log.debug(u"Command : Send action command over MQ...")
# do the command
cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('cmd.send')
msg.add_data('cmdid', self._cmdId)
msg.add_data('cmdparams', params)
self.log.debug(u"Command : Command id = '{0}', command params = '{1}'".format(self._cmdId, params))
# do the request
res = cli.request('xplgw', msg.get(), timeout=10)
if res:
data = res.get_data()
if not data['status']:
self.log.error(u"Command : Command sending to XPL gw failed: {0}".format(res))
else:
self.log.error(u"Command : XPL gw did not respond")
self.log.debug(u"Command : Action done")
示例4: _load_client_to_xpl_target
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")
示例5: clients
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
)
示例6: check_config
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))
示例7: send_to_butler
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()
示例8: delete_configuration
def delete_configuration(type, name, host):
cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action("config.delete")
msg.add_data("type", type)
msg.add_data("host", host)
msg.add_data("name", name)
result = cli.request("dbmgr", msg.get(), timeout=10)
if result:
data = result.get_data()
if "status" in data:
if not data["status"]:
print(result.get())
raise RuntimeError(
"DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}".format(
type, name, host, key, value
)
)
else:
return True
else:
print(result.get())
raise RuntimeError(
"DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}".format(
type, name, host, key, value
)
)
else:
raise RuntimeError("Timeout while deleting configuration for {0}-{1}.{2}".format(type, name, host))
示例9: on_message
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()))
示例10: test_XplCmd
def test_XplCmd(self, parameters = {}, statParams = None):
"""Send an Xpl cmd with statics parameters by request, if necessary start testcase listener for ack message and
check if insert in database is ok.
"""
if self.get_return_confirmation() :
schema, data, statResult = self.get_XplStat_fromAck(statParams)
th = threading.Thread(None, self.assert_Xpl_Stat_Ack_Wait, "th_test_0110_xpl-ack_from_{0}".format(self.command_name), (schema, data, statResult))
th.start()
time.sleep(1)
else :
print (u"No ack required for {0}".format(self.command_name))
if self._device and self.command_id :
cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('cmd.send')
msg.add_data('cmdid', self.command_id)
msg.add_data('cmdparams', parameters)
print (u"Send xpl_cmnd {0}".format(self.command_name))
cli.request('xplgw', msg.get(), timeout=10)
# if self.get_return_confirmation() :
# self.assert_get_last_command_in_db(statResult)
# else :
# print (u"No ack required for {0}".format(self.command_name))
return True
else : return False
示例11: delete
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
示例12: WSCommandSend
def WSCommandSend(self, data):
cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('cmd.send')
msg.add_data('cmdid', data['command_id'])
msg.add_data('cmdparams', data['parameters'])
return cli.request('xplgw', msg.get(), timeout=10).get()
示例13: __init__
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()
示例14: __init__
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)
示例15: client_devices_edit
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'
)