菜鸟在这里。
我有一个简单的python代码,该代码应该订阅一个主题,并使用MQTT协议将JSON有效内容发布到同一主题。但是由于某种原因,我无法将有效载荷作为JSON加载!
我在这里做什么错了?
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
mqtt_broker = '192.168.1.111'
mqtt_topic_one = 'mqtt_topic/tops_one'
mqtt_topic_two = 'mqtt_topic/tops_two'
json_data_1 = '''{
"this_json": "info",
"data": {
"multi_keyval": {
"1": "1",
"5": "5",
"15": "15"
},
"single_keyval": {
"single_key": "200"
}
}
}'''
def pass_to_func_and_pub(data_to_pub):
print(data_to_pub) # --------> This PRINTS
print(json.loads(data_to_pub)) # --------> This DOES NOT PRINT
# The following two lines don't work either.
unpacked_json = json.loads(data_to_pub)
client.publish(mqtt_topic_two, unpacked_json['this_json'])
def on_connect(client, userdata, flags, rc):
client.subscribe(mqtt_topic_one)
client.publish(mqtt_topic_one, json_data_1)
def on_message(client, userdata, msg):
pass_to_func_and_pub(str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqtt_broker)
try:
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
print('MQTT client disconnected, exiting now.')
答案 0 :(得分:4)
这里有两个问题。
您没有处理异常(我猜Paho实际上会在处理程序中忽略它们,以使客户端保持活动状态)。这意味着当在json.loads(data_to_pub)
中抛出异常 时,您永远不会看到此异常,但是由于没有本地except
块而退出了函数。
def pass_to_func_and_pub(data_to_pub):
print("Raw data: ", data_to_pub)
try:
unpacked_json = json.loads(data_to_pub)
except Exception as e:
print("Couldn't parse raw data: %s" % data_to_pub, e)
else:
print("JSON:", unpacked_json)
client.publish(mqtt_topic_two, unpacked_json['this_json'])
运行此改进版本,我们现在可以看到:
Couldn't parse raw data: b'{\n "this_json": "info",\n "data": {\n "multi_keyval": {\n "1": "1",\n "5": "5",\n "15": "15"\n },\n "single_keyval": {\n "single_key": "200"\n }\n }\n}' Expecting value: line 1 column 1 (char 0)
嗯,b'
在那做什么? ...
基本上,您的问题归结为一行
def on_message(client, userdata, msg):
pass_to_func_and_pub(str(msg.payload))
通过在str
的{{1}}(在Python 3中是payload
对象)的MqttMessage
上调用bytes
,您将获得这些字节的字符串化版本,例如b'foobar'
。
这个b
当然现在使它成为无效的JSON,因此Expecting value: line 1 column 1 (char 0)
...
请勿致电str
! Json.loads can handle bytes
too。所以:
def on_message(client, userdata, msg):
pass_to_func_and_pub(msg.payload)
或者,假设使用utf-8编码,我们可以更明确地做到这一点(我更喜欢在字符串中工作):
def on_message(client, userdata, msg):
pass_to_func_and_pub(msg.payload.decode('utf-8'))
希望有帮助!