python - 在 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()
解决方案
您的代码在 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")
视为事件类型。
推荐阅读
- google-sheets - 在一个文件夹中插入信息,在其他 2 个文件夹中查看谷歌表格上的某些条件
- ruby-on-rails - 使用 Devise 在多租户应用程序上为不同帐户使用相同的电子邮件
- groovy - Objenesis 依赖导致实例化错误
- python - 查找列表的总平均列表python
- cakephp - 条件 AND 在同一字段 cakephp 2.5
- angular - node_modules/karma/config.tpl.ts:13:18 中的错误 - 错误 TS1109:预期表达式。更新了 Angular 9
- opencv - 有没有办法改变我的网络摄像头的输出缓冲区
- api - 邀请新成员加入工作区
- python - 如何使用 pytest 模拟 boto3 模块的功能
- java - 在 Linux 的后台运行和杀死 java 程序