I have 2 python scripts, one on RPI and the other on my pc. I am trying to send metrics from RPI to pc in json format via MQTT using mosquitto. After executing the subscriber script, the connection is successfully established, but I get a "JSONDecodeError: Expecting value: line 1 column 1 (char 0)". I assume it's because it's trying to decode the json, but there's nothing in msg.payload because the publisher hasn't sent anything yet. My question is how to make sure that decoding only happens if the publisher sends a "message".
Subscriber script:
import paho.mqtt.client as mqtt
import json
# callback function when client connects to MQTT broker
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# subscribe to topic
client.subscribe("test")
# callback function when message is received from MQTT broker
def on_message(client, userdata, msg):
# decode JSON message
json_data = json.loads(msg.payload.decode("utf-8"))
# print individual values
print("Variable 1:", json_data[0])
print("Variable 2:", json_data[1])
print("Variable 3:", json_data[2])
print("Variable 4:", json_data[3])
print("Variable 5:", json_data[4])
print("Variable 6:", json_data[5])
print("Variable 7:", json_data[6])
# create MQTT client instance
client = mqtt.Client()
# set callback functions
client.on_connect = on_connect
client.on_message = on_message
# connect to MQTT broker
client.connect("test.mosquitto.org", 1883, 60)
# start MQTT client loop
client.loop_forever()
Publisher script:
import json
import paho.mqtt.publish as publish
x = 1
y = 2
z = 3
a = "hello"
b = True
c = [4, 5, 6]
d = {"name": "John", "age": 30}
data = {
"x": x,
"y": y,
"z": z,
"a": a,
"b": b,
"c": c,
"d": d
}
json_data = json.dumps(data)
publish.single("test", json_data, hostname="test.mosquitto.org")```
the result should be json format which I will save later.
I suggest re-writing on_message() as follows:
def on_message(client, userdata, msg):
try:
if _msg := msg.payload.decode("utf-8"):
for i, jd in enumerate(json.loads(_msg), 1):
# print individual values
print(f"Variable {i}:", jd)
except Exception as e:
print(e)
Note:
Requires Python 3.8+