设备影子 Topic
设备影子充当中介,支持设备和用户应用程序查看设备状态和更新设备配置。设备、用户应用程序、设备影子三者之间通过两个特殊的 Topic 来实现通信:
$shadow/operation/${productId}/${deviceName}
:用于发布(上行)消息,可实现对设备影子数据的 get/update 操作。$shadow/operation/result/${productId}/${deviceName}
:用于订阅(下行)消息,影子服务端通过此 Topic 发送应答和推送消息。说明:
以上主题均为设备创建时由系统默认创建,设备 SDK 内部会自动订阅上述主题。


设备获取影子
如果设备想要获取设备影子最近的数据时,需要向
$shadow/operation/${productId}/${deviceName}
主题发布 get 消息,报文格式如下:{"type": "get","clientToken": 8480}
说明:
clientToken 是用于唯一标识会话业务的 TOKEN ,由设备端生成,物联网通信平台原样传回。
物联网通信平台接收请求后,通过向
$shadow/operation/result/${productId}/${deviceName}
主题发布消息进行响应,格式如下:{"clientToken": "8480","payload": {"state": {"delta": {"alarmvalue": "50"},"desired": {"alarmvalue": "50"},"reported": {"temperature": 32}},"timestamp": 1678783950012,"version": 14},"result": 0,"timestamp": 1678783991,"type": "get"}
如果设备影子文档中有 desired 部分,则物联网通信平台会自动生成相应的 delta 部分。如果没有 desired 部分,则没有 desired 和 delta 部分的内容。
设备更新影子
说明:
消息中的 version 需与平台上保持一致,如果不确定,version 可传0进行不校验 version 更新。
设备通过向
$shadow/operation/${productId}/${deviceName}
主题发送 update 消息,更新设备影子数据,格式如下:{"type": "update","state": {"reported": {"temperature": 35}},"version": 0,"clientToken": 5551}
当物联网通信平台收到此消息时,首先判断消息中的 version 是否与设备影子服务端中的 version 一致。如果一致,则设备影子服务端执行更新设备影子流程。
物联网通信平台接收请求后,通过向
$shadow/operation/result/${productId}/${deviceName}
主题发布消息进行响应,此时 payload 中的内容字段仅包含对此次更新字段的相关内容,格式如下:{"clientToken": "5551","payload": {"state": {"reported": {"temperature": 35}},"timestamp": 1678785359634,"version": 15},"result": 0,"timestamp": 1678785359634,"type": "update"}
如果消息中的 version 与设备影子服务端的 version 不一致,则物联网通信平台向
$shadow/operation/result/ABC1234567/AirConditioner
发送以下消息进行回应,此时 payload 中的内容将返回完整的设备影子文档内容。{"clientToken": "8734","payload": {"state": {"desired": {"alarmvalue": "50"},"reported": {"temperature": 35}},"timestamp": 1678785359634,"version": 15},"result": 5005,"timestamp": 1678785670967,"type": "update"}
如果设备想删除设备影子服务端 reported 中某些字段,可在 update 时,把这些字段内容置为 null,格式如下:
{"type": "update","state": {"reported": {"temperature": null}},"version": 0,"clientToken": 6584}
应用程序更新影子
说明:
消息中的 version 需与平台上保持一致,如果不确定,version 可传0进行不校验 version 更新。
当物联网通信平台收到此云API请求后,首先判断请求中 version 是否与设备影子服务端中的 version 一致。如果一致,则执行更新设备影子流程,并响应此云API请求。
应用程序成功修改设备影子 desired 字段后,如果设备此时处于在线状态,物联网通信平台会通过
$shadow/operation/result/ABC1234567/AirConditioner
向设备发送 delta 消息,设备收到设备影子更新的内容;如果设备此时处于离线状态,上线后,可通过 设备获取影子 获取 desired 字段内容。{"payload": {"state": {"alarmvalue": "50"},"timestamp": 1678786529510,"version": 17},"timestamp": 1678786529510,"type": "delta"}
当设备收到 delta 消息后,设备通过上报 desired 字段为null的消息,清空设备影子服务端 desired 字段内容,方式是通过向
$shadow/operation/${productId}/${deviceName}
主题发送消息,格式如下:{"type": "update","state": {"desired": null},"version": 0,"clientToken": 5686}
错误码
错误码 | 描述 |
5000 | 参数不完整 |
5001 | 影子不存在 |
5004 | 非法请求参数 |
5005 | 版本不匹配 |
5007 | DB 错误 |
5008 | 版本冲突 |
5009 | 非法 Topic |
5010 | 影子更新失败 |
5011 | 文档大小超过限制 |
5100 | 内部错误 |