我对python和AWS IoT都很陌生。我正在使用一个raspberry pi zero来发布和接收AWS IoT主题的消息。我可以很好地发送消息,也可以接收消息。现在我正在尝试找出一种方法来将这些消息保存为字符串。具体来说,我正在尝试保存我从主题发送的颜色。print(color)
预期输出:blue
我使用的函数是www.example.com文件中的"on_message_received"函数,该文件位于以下位置: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()
我改变了它,以保存我正在接收的消息到变量"颜色"。
# 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)
这是我从主题发送的消息的格式
{
"message": "blue"
}
这允许我保存接收到的消息到颜色,只是打印blue
然而,我也得到这个错误消息TypeError: string indices must be integers
,我知道这是因为应该有一个整数在括号中,而不是单词'message',但当我把一个0或1的输出,我得到的是:A
或1
我还尝试更改函数,只使用color = json.loads(payload)
,但这样做时,输出为{'message': 'blue'}
是否有办法仍然将print(color)
的输出作为blue
,而不会收到错误消息:一米十一米?
1条答案
按热度按时间ghhkc1vu1#
我找到解决问题的办法了。