json AWS IoT核心pubsub.py示例如何将消息保存到变量

rqqzpn5f  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(129)

我对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的输出,我得到的是:A1
我还尝试更改函数,只使用color = json.loads(payload),但这样做时,输出为{'message': 'blue'}
是否有办法仍然将print(color)的输出作为blue,而不会收到错误消息:一米十一米?

ghhkc1vu

ghhkc1vu1#

我找到解决问题的办法了。

# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
global received_count
print("Received message from topic '{}': {}".format(topic, payload))
if topic.endswith('/pi'):
    rawData = (payload.decode())
    data = json.loads(rawData)
    Validate = rawData.split()
    check1 = (Validate[1])
    if check1 == check1:
        print(rawData)
        for person in data['message']:
            name = (person['name'])
            color = (person['color'])
            print(name)
            print(color)
received_count += 1
if received_count == cmdUtils.get_command("count"):
    received_all_event.set()

相关问题