【发布时间】:2020-09-17 18:38:10
【问题描述】:
我有一个设备通过网关将事件主题 (/devices/<dev_id>/events/motion) 发布到 PubSub。它正确登陆 PubSub,但 subFolder 只是一个空字符串。
在网关上,我使用下面的代码进行发布。 f"mb.{device_id}" 是 device_id(不是网关 ID,attribute 可以是任何东西 - 运动、温度等
def report(self, device_id, attribute, value):
topic = f"/devices/mb.{device_id}/events/{attribute}"
timestamp = datetime.utcnow().timestamp()
client.publish(topic, json.dumps({"v": value, "ts": timestamp}))
这就是监听 PubSub 队列的云函数。
def iot_to_bigtable(event, context):
payload = json.loads(base64.b64decode(event["data"]).decode("utf-8"))
timestamp = payload.get("ts")
value = payload.get("v")
if not timestamp or value is None:
raise BadDataException()
attributes = event.get("attributes", {})
device_id = attributes.get("deviceId")
registry_id = attributes.get("deviceRegistryId")
attribute = attributes.get("subFolder")
if not device_id or not registry_id or not attribute:
raise BadDataException()
Pub/Sub 中的事件示例:
{
@type: 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
attributes: {
deviceId: 'mb.26727bab-0f37-4453-82a4-75d93cb3f374',
deviceNumId: '2859313639674234',
deviceRegistryId: 'mb-staging',
deviceRegistryLocation: 'europe-west1',
gatewayId: 'mb.42e29cd5-08ad-40cf-9c1e-a1974144d39a',
projectId: 'mb-staging',
subFolder: ''
},
data: 'eyJ2IjogImxvdyIsICJ0cyI6IDE1OTA3NjgzNjcuMTMyNDQ4fQ=='
}
为什么subFolder 是空的?根据文档,我期望它是属性(即motion 或temperature)
【问题讨论】:
-
好的,奥卡姆剃刀...打印出 {attribute} 并确保您要发送一个子文件夹并且它不只是登陆一般的 Pub/Sub 主题?此外,是否在 IoT Core 本身中为该事件配置了子文件夹?仅向子文件夹发送内容不会执行任何操作,除非它在 IoT Core 中配置为将该子文件夹分流到与基本文件夹主题不同的主题。
-
感谢您这么快回复。我在
report函数中添加了一条打印语句,它打印出```将 {"v": 1, "ts": 1590818418.307897} 发送到 /devices/mb.26727bab-0f37-4453-82a4-75d93cb3f374/events/运动发送 {"v": 26, "ts": 1590818418.30808} 到 /devices/mb.26727bab-0f37-4453-82a4-75d93cb3f374/events/temperature 发送 {"v": "high", "ts": 1590818418.308173}到 /devices/mb.26727bab-0f37-4453-82a4-75d93cb3f374/events/level ``` 所以肯定将它发送到子文件夹 - 我认为? -
@GabeWeiss 关于您的第二个问题 - 我在文档中找到了这个:“发布到子文件夹的消息被转发到具有相同名称的 Cloud Pub/Sub 主题。相应的注册表必须配置为Cloud Pub/Sub 主题;否则,消息将转发到默认的 Cloud Pub/Sub 主题。”我的意思是,如果没有配置同名主题,我发布的任何子文件夹都应该放在默认的发布/订阅队列中?
-
对,但我认为它的工作方式是,除非为该子文件夹配置了主题,否则不会在 pub/sub 元数据中设置子文件夹。作为测试,如果可以,请尝试为注册表创建另一个主题,并将子文件夹配置为指向该主题,并查看子文件夹是否在该 pub/sub 消息上设置。
标签: google-cloud-platform google-cloud-functions google-cloud-pubsub google-cloud-iot