I am very new to python as well as to AWS IoT. I am using a raspberry pi zero in conjunction to publish and receive messages from my AWS IoT topic. I can send messages just fine and I can also receive messages and now I'm trying to figure out a way to save these messages as a string. Specifically, I am trying to save the color I send from the topic.
print(color)
Expected output: blue
The function I am working with is the "on_message_received" function in the pubsub.py file found here: https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/pubsub.py
# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
print("Received message from topic '{}': {}".format(topic, payload))
global received_count
received_count += 1
if received_count == cmdUtils.get_command("count"):
received_all_event.set()
I changed it to save the message I am receiving to the variable "color".
# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
print("Received message from topic '{}': {}".format(topic, payload))
global received_count
received_count += 1
if received_count == cmdUtils.get_command("count"):
received_all_event.set()
color = json.loads(payload.decode())['message']
print(color)
This is the format of the message I am sending from the topic
{
"message": "blue"
}
This allows me to save the received message to color and just prints blue
However, I also get this error message TypeError: string indices must be integers
And I know this is because there is supposed to be an integer in the brackets instead of the word 'message'
but when I place either a 0 or a 1 the output, I get is either: A
or 1
I also tried changing the function and just having color = json.loads(payload)
But when I do this the output is {'message': 'blue'}
Is there a way to still get the output of print(color)
as blue
without getting the error message: TypeError: string indices must be integers
?
I figured out a way to fix my problem.