新人在这里。
我有一个简单的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.')