首页 > 解决方案 > 在 python 中使用应用程序时无法从 watson iot 获取最后缓存的设备事件

问题描述

我正在尝试使用 python 获取最后一个设备事件,但出现此错误:

wiotp.sdk.application.client.ApplicationClient  INFO    Connected successfully: 
a:orgid:5d633cbe-14c0-4d05-b4d6-86bf97a068d9
Traceback (most recent call last):
  File "fetch_event_data_fromWatson_iot.py", line 23, in <module>
    print("Event from device: %s:%s" % (event.typeId, event.deviceId))
AttributeError: 'str' object has no attribute 'typeId'.

我的代码如下:

import wiotp.sdk.application
from wiotp.sdk.messages import Message, MessageCodec, JsonCodec, RawCodec, Utf8Codec

import json
import base64
myConfig = { 
    "auth": 
{        "key": "-----",
        "token": "-----"
        }
        }
client = wiotp.sdk.application.ApplicationClient(config=myConfig)


client.connect()


device = {"typeId": "ESP8266", "deviceId": "ecg", "eventId": "status"}
lastEvents = client.lec.get(device,"status")

for event in lastEvents:
    print("Event from device: %s:%s" % (event.typeI`enter code here`d, event.deviceId))
    print("- Event ID: %s " % (event.eventId))
    print("- Format: %s" % (event.format))
    print("- Cached at: %s" % (event.timestamp.isoformat()))

    # The payload is always returned base64 encoded by the API
    print("- Payload (base64 encoded): %s" % (event.payload))

    # Depending on the content of the message this may not be a good idea (e.g. if it was originally binary data)
    print("- Payload (decoded): %s" % (base64.b64decode(event.payload).decode('utf-8')))
#

client.disconnect()

标签: pythonwatson-iot

解决方案


您的代码在 lec 上调用 get 而不是 getAll:

lastEvents = client.lec.get(device,"status")

所以不是返回列表而是返回事件字典。您需要更改代码以调用 getAll ( https://ibm-watson-iot.github.io/iot-python/application/api/lec/#get-all-last-cached-events ):

lastEvents = client.lec.getAll(device)

或者只是删除您的for event in lastEvents:循环并将返回的对象client.lec.get(device,"status")视为事件类型。


推荐阅读