
# 快速接入
#### 创建产品
为了方便体验，提供了一个烟感的产品模型，烟感会上报烟雾值、温度、湿度、烟雾报警、还支持响铃报警命令。以烟感为例，体验消息上报、属性上报等功能。
1. 访问[设备接入服务](https://www.huaweicloud.com/product/iothub.html)，单击"管理控制台"进入设备接入控制台，选择您的实例，单击实例卡片进入。
2. 单击左侧导航栏"产品"，单击页面左侧的"创建产品"。 
   图1产品-创建产品   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002358714305.png "点击放大")
   
   
3. 根据页面提示填写参数，然后单击"确定"完成产品的创建。 
   
   |                                                                     **基本信息**                                                                     ||
   |---|---|
   | 所属资源空间 | 平台自动将新创建的产品归属在默认资源空间下。如需归属在其他资源空间下，下拉选择所属的资源空间。如无对应的资源空间，请先创建[资源空间](https://support.huaweicloud.com/usermanual-iothub/iot_01_0006.html)。 |
   | 产品名称   | 自定义。支持字母、数字、下划线（_）、连字符（-）的字符组合。                                                                                                          |
   | 协议类型   | 选择"MQTT"。                                                                                                                                |
   | 数据格式   | 选择"JSON"。                                                                                                                                |
   | 设备类型选择 | 选择"自定义类型"                                                                                                                                |
   | 设备类型   | 填写"smokeDetector"                                                                                                                        |
   | **高级配置**                                                                                                                                         ||
   | 产品ID   | 不填写                                                                                                                                      |
   | 产品描述   | 请根据实际情况填写。                                                                                                                               |
      
   图2创建产品-MQTT   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981306829.png "点击放大")
   
   
 
#### 上传产品模型
1. 单击下载烟感产品模型[smokeDetector](https://iot-developer.obs.cn-north-4.myhuaweicloud.com:443/smokeDetector.zip)，获取产品模型文件。
2. 找到创建的产品，单击产品进入产品详情页。
3. 选择"基本信息"页签，单击"上传模型文件"，上传[1]获取的产品模型文件。
   
   图3产品-上传产品模型   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981312633.png "点击放大")
   
   
 
 #### 注册设备
1. 选择左侧导航栏"设备 \> 所有设备"，单击"注册设备"。
2. 根据页面提示信息填写参数，然后单击"确定"。 
   
   | 参数名称   | 说明                                |
   |:---|:---|
   | 所属资源空间 | 确保和创建的产品归属在同一个资源空间。               |
   | 所属产品   | 选择创建的产品。                          |
   | 设备标识码  | 即nodeID，设备唯一物理标识。可自定义，由英文字母和数字组成。 |
   | 设备名称   | 即device_name，可自定义。                |
   | 设备认证类型 | 选择"密钥"。                           |
   | 密钥     | 设备密钥，可自定义。若不填写密钥，物联网平台会自动生成密钥。    |
      
   设备注册成功后保存设备标识码、设备ID、密钥。
   
   
 
#### 设备初始化
1. 获取接入地址。可在控制台的"总览 \> 接入信息"中查看。
   图4接入信息-设备侧MQTT接入地址   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002379668860.png "点击放大") 
2. 输入设备对接信息。创建设备时，需要写入在[注册设备]时获取的设备ID、密钥，以及[1]中获取的设备对接信息，注意格式为***ssl://域名信息:端口号*** 或 ***ssl://IP地址:端口号***
   ```
   // 获取证书路径：加载iot平台的ca证书，进行服务端校验，使用sdk默认的ca.jks即可。
        URL resource = MessageSample.class.getClassLoader().getResource("ca.jks");
        File file = new File(resource.getPath());
        //例如在iot-device-demo文件 MessageSample.java中修改以下参数
        IoTDevice device = new IoTDevice("ssl://域名信息:8883",
                   "5e06bfee334dd4f33759f5b3_demo", "mysecret", file);
   ```
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/note_3.0-zh-cn.png)
   所有涉及设备ID和密码的文件均需要修改成对应的信息。
   
3. 建立连接。调用init接口，该接口是阻塞调用，如果建立连接成功会返回0。
   ```
   if (device.init() != 0) {
               return;
           }
   ```
   如果连接成功就会打印：
   ```
   2023-07-17 17:22:59  INFO MqttConnection:105 - Mqtt client connected. address :ssl://域名信息:8883
   ```
   
4. 创建设备并连接成功后，可以开始使用设备进行通信。调用IoT Device 的getClient接口获取设备客户端，客户端提供了消息、属性、命令等通讯接口。
![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
SDK默认提供断线重连功能，当调用device.init()后，当由于网络不稳定、网络不可达、平台主动断开连接等，导致连接失败，会在后台自动申请重连。若是客户不需要该机制，请见：[断线重连](https://github.com/huaweicloud/huaweicloud-iot-device-sdk-java#3.2)文档。
#### 消息上报
消息上报是指设备向平台上报消息。
1. 从device中获取客户端，调用IoTDevice的getClient接口即可获取到客户端。
2. 调用客户端的reportDeviceMessage接口来上报设备消息。在MessageSample这个例子中周期性上报消息：
   ```
   while (true) {
               device.getClient().reportDeviceMessage(new DeviceMessage("hello"), new ActionListener() {
                   @Override
                   public void onSuccess(Object context) {
                       log.info("reportDeviceMessage ok");
                   }
                   @Override
                   public void onFailure(Object context, Throwable var2) {
                       log.error("reportDeviceMessage fail: " + var2);
                   }
               });
               //上报自定义topic消息，注意需要先在平台配置自定义topic
               String topic = "$oc/devices/" + device.getDeviceId() + "/user/wpy";
               device.getClient().publishRawMessage(new RawMessage(topic, "hello raw message "),
                   new ActionListener() {
                       @Override
                       public void onSuccess(Object context) {
                           log.info("publishRawMessage ok: ");
                       }
                       @Override
                       public void onFailure(Object context, Throwable var2) {
                           log.error("publishRawMessage fail: " + var2);
                       }
                   });
               Thread.sleep(5000);
           }
   ```
   
3. 修改MessageSample类的main函数，替换自己的设备参数后运行MessageSample类，查看日志打印包含以下内容则表示消息上报成功。
   ```
   2024-04-16 16:43:11  INFO MessageSample:98 - reportDeviceMessage ok
   ```
   
4. 在设备接入控制台，选择"设备 \> 所有设备"-查看设备是否在线。
   图5设备列表-设备在线   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950367902.png "点击放大") 
5. 选择对应设备，单击"详情"，在设备详情页面启动设备消息跟踪。
   图6消息跟踪-启动消息跟踪   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950378340.png "点击放大") 
6. 查看消息跟踪，确认平台是否收到设备消息。
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
   消息跟踪会有一定的延时，如果没有看到数据，请等待后刷新。
   图7消息跟踪-查看device_sdk_java消息跟踪   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981497769.png "点击放大") 
 
#### 属性上报
1. 打开PropertySample类，这个例子中会定时的上报alarm、temperature、humidity、smokeConcentration这四个属性。
   ```
   //定时上报属性
           while (true) {
               Map<String ,Object> json = new HashMap<>();
               Random rand = new Random();
               //按照物模型设置属性
               json.put("alarm", 1);
               json.put("temperature", rand.nextFloat()*100.0f);
               json.put("humidity", rand.nextFloat()*100.0f);
               json.put("smokeConcentration", rand.nextFloat() * 100.0f);
               ServiceProperty serviceProperty = new ServiceProperty();
               serviceProperty.setProperties(json);
               serviceProperty.setServiceId("smokeDetector");//serviceId要和物模型一致
               
                  device.getClient().reportProperties(Arrays.asList(serviceProperty), new ActionListener() {
                   @Override
                   public void onSuccess(Object context) {
                       log.info("pubMessage success" );
                   }
                   @Override
                   public void onFailure(Object context, Throwable var2) {
                       log.error("reportProperties failed" + var2.toString());
                   }
               });
               Thread.sleep(10000);
           }
       }
   ```
   
2. 修改PropertySample的main函数后直接运行PropertySample类，查看日志打印包含以下内容则表示属性上报成功。
   ```
   2024-04-17 15:38:38  INFO PropertySample:144 - pubMessage success
   ```
   
3. 在平台设备详情页面可以看到最新上报的属性值。
   图8物模型-属性上报   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002039398625.png "点击放大") 
 
#### 属性读写
1. 调用客户端的setPropertyListener方法来设置属性回调接口。在PropertySample这个例子中，实现了属性读写接口。
   - 写属性处理：实现了alarm属性的写操作，其他属性不支持写操作。
   
   - 读属性处理：将本地属性值按照接口格式进行拼装。
   
   
   ```
   device.getClient().setPropertyListener(new PropertyListener() {
               //处理写属性
               @Override
               public void onPropertiesSet(String requestId, List<ServiceProperty> services) {
                   // 遍历service
                   for (ServiceProperty serviceProperty : services) {
                       log.info("OnPropertiesSet, serviceId is {}", serviceProperty.getServiceId());
                       // 遍历属性
                       for (String name : serviceProperty.getProperties().keySet()) {
                           log.info("property name is {}", name);
                           log.info("set property value is {}", serviceProperty.getProperties().get(name));
                       }
                   }
                   // 修改本地的属性值
                   device.getClient().respondPropsSet(requestId, IotResult.SUCCESS);
               }
               /**
                * 处理读属性。多数场景下，用户可以直接从平台读设备影子，此接口不用实现。
                * 但如果需要支持从设备实时读属性，则需要实现此接口。
                */
               @Override
               public void onPropertiesGet(String requestId, String serviceId) {
                   log.info("OnPropertiesGet, the serviceId is {}", serviceId);
                   Map<String, Object> json = new HashMap<>();
                   Random rand = new SecureRandom();
                   json.put("alarm", 1);
                   json.put("temperature", rand.nextFloat() * 100.0f);
                   json.put("humidity", rand.nextFloat() * 100.0f);
                   json.put("smokeConcentration", rand.nextFloat() * 100.0f);
                   ServiceProperty serviceProperty = new ServiceProperty();
                   serviceProperty.setProperties(json);
                   serviceProperty.setServiceId("smokeDetector");
                   device.getClient().respondPropsGet(requestId, Arrays.asList(serviceProperty));
               }
           });
   ```
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/note_3.0-zh-cn.png)
   1. 属性读写接口需要调用respondPropsGet和respondPropsSet接口来上报操作结果。
   
   2. 如果设备不支持平台主动到设备读，onPropertiesGet接口可以空实现
     
2. 运行PropertySample类，然后在平台上设备影子页面查看当前alarm属性值为1。
   图9设备影子-查看alarm属性   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981497737.png "点击放大") 
3. alarm属性修改为0。
   图10设备影子-属性配置alarm   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950378332.png "点击放大") 
4. 查看设备侧日志，看到设备收到属性设置，alarm被修改为0。
   图11查看属性设置   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002391165529.png "点击放大") 
 
#### 命令下发
设置命令监听器用来接收平台下发的命令，在回调接口里，需要对命令进行处理，并上报响应。
1. 在CommandSample例子中实现了命令的处理，收到命令后仅进行打印，然后调用respondCommand上报响应。
   ```
   device.getClient().setCommandListener(new CommandListener() {
               @Override
               public void onCommand(String requestId, String serviceId, String commandName, Map<String, Object> paras) {
                   log.info("onCommand, serviceId = {}", serviceId);
                   log.info("onCommand , name = {}", commandName);
                   log.info("onCommand, paras =  {}", paras.toString());
                   //处理命令
                   //发送命令响应
                   device.getClient().respondCommand(requestId, new CommandRsp(0));
               }
           });
   ```
   
2. 直接运行CommandSample类，然后在平台上下发命令，命令的serviceId填smokeDetector、命令名填ringAlarm、参数携带duration为整数20。
3. 查看日志，看到设备收到命令并上报了响应。
   图12查看日志   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002391205393.png "点击放大") 
 
