设备成功上报消息后,您可以尝试从云端下发指令到设备端。本文档讲解了如何通过云端应用调用SetDeviceProperty接口,设置设备属性值。同时,设备成功接收云端指令。

操作步骤

  1. 在Maven项目中加入依赖项,导入阿里云IoT 云端SDK。

    IoT Java SDK的Maven依赖坐标:

    <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-iot -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-iot</artifactId>
        <version>6.8.0</version>
    </dependency>

    阿里云公共包依赖坐标:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>3.5.1</version>
    </dependency>
  2. 初始化SDK。

    此处地域与产品地域保持一致,使用华东2。

    String accessKey = "<your accessKey>";
    String accessSecret = "<your accessSecret>";
    DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Iot", "iot.cn-shanghai.aliyuncs.com");
    IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
    DefaultAcsClient client = new DefaultAcsClient(profile); 
  3. 云端应用向设备下发属性设置指令,将开关属性设置为1。

    示例如下:

    SetDevicePropertyRequest request = new SetDevicePropertyRequest();
    request.setProductKey("a1zluR09W76");
    request.setDeviceName("device1");
    JSONObject itemJson = new JSONObject();
    itemJson.put("PowerSwitch", 1);
    request.setItems(itemJson.toString());
    
    try {
        SetDevicePropertyResponse response = client.getAcsResponse(request);
        System.out.println(response.getRequestId() + ", success: " + response.getSuccess());
    } catch (ClientException e) {
        e.printStackTrace();
    }
    说明 属性设置的具体调用方法,请参见SetDeviceProperty

执行结果

若设备成功接收到云端下发的信息,日志示例如下:
< {
<     "method": "thing.service.property.set",
<     "id": "432801169",
<     "params": {
<         "PowerSwitch": 1
<     },
<     "version": "1.0.0"
< }

user_report_reply_event_handler.94: Message Post Reply Received, Message ID: 646, Code: 200, Reply: {}
user_property_set_event_handler.114: Property Set Received, Request: {"PowerSwitch":1}

> {
>     "id": "647",
>     "version": "1.0",
>     "params": {
>         "PowerSwitch": 1
>     },
>     "method": "thing.event.property.post"
> }