这里有几个问题。
1。异常处理
你没有处理异常(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'
在那里干什么?
…
2。编码问题
基本上你的问题归结为一条线
def on_message(client, userdata, msg):
pass_to_func_and_pub(str(msg.payload))
通过呼叫
str
上
payload
其中
MqttMessage
,
哪个是
bytes
对象
在Python3中,您将得到这些字节的字符串化版本,例如。
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'))
希望能有帮助!