
# 快速接入
#### 创建产品
为了方便体验，提供了一个烟感的产品模型，烟感会上报烟雾值、温度、湿度、烟雾报警、还支持响铃报警命令。以烟感为例，体验消息上报、属性上报等功能。
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. 打开文件demos/device_demo/basic_test.c，将之前获取到的接入地址、设备ID以及设备密钥填入对应位置。 
   ```
   // 创建一个设备并初始化。在basic_test.c中修改连接参数：
   // You can get the access address from IoT Console "Overview" -> "Access Information"
   char *g_address = "域名"; 
   char *g_port = "8883";
   char *g_deviceId = "设备id"; 
   char *g_secret = "设备密钥";
   static void mqttDeviceSecretInit(char *address, char *port, char *deviceId, char *password) {
       IOTA_Init("."); // The certificate address is set to: ./conf/rootcert.pem
       IOTA_SetPrintLogCallback(MyPrintLog); // Set log printing method
       // MQTT protocol when the connection parameter is 1883; MQTTS protocol when the connection parameter is 8883
       IOTA_ConnectConfigSet(address, port, deviceId, password);
       int ret = IOTA_Connect();
       if (ret != 0) {
           PrintfLog(EN_LOG_LEVEL_ERROR, "basic_test: IOTA_Connect() error, Auth failed, result %d\n", ret);
           return -1;
       }
   }
   ```
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/caution_3.0-zh-cn.png)
   平台的证书可以从源码中[conf/rootcert.pem](https://github.com/huaweicloud/huaweicloud-iot-device-sdk-c/blob/master/conf/rootcert.pem)下载。
   
   
3. 编译及运行。在根目录运行以下命令，日志中打印"login success"表示设备鉴权成功。 
   ```
   export LD_LIBRARY_PATH=./lib/  #加载库文件
    make clean
    make device_demo
    ./basic_test
   ```
   图5连接成功   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002363788814.png "点击放大")
   
   
4. 查看设备运行情况。在控制台的设备详情页面查看设备已在线。 
   图6设备列表-设备在线   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950367902.png "点击放大")
   
   
 
![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
SDK默认提供断线重连功能，当调用设备初始化后，当由于网络不稳定、网络不可达、平台主动断开连接等，导致连接失败，会在后台自动申请重连。若是客户不需要该机制，请见：[断线重连](https://github.com/huaweicloud/huaweicloud-iot-device-sdk-c/blob/master/README_CN.md#6.6)文档。
#### 消息上报
消息上报是指设备向平台上报消息。API接口如下：
表1C语言消息上报接口 
| 功能           | 接口                                                                                                          |
|:---|:---|
| 自定义Topic消息上报 | HW_API_FUNC HW_INT IOTA_RawTopicMessageReport(HW_CHAR \*topic, HW_CHAR \*payload, int qos, void \*context); |
| 系统Topic消息上报  | HW_API_FUNC HW_VOID IOTA_SetUndefinedMessageCallback(PFN_MESSAGE_CALLBACK_HANDLER callbackHandler);         |
   
1. ./demos/device_demo/message_test.c是一个上报消息例子，可以通过IOTA_MessageDataReport函数将消息上报给平台。
   ```
   void basicMassage() 
   {
       // 订阅系统topic
       SubscribeAll(); 
       // 向连接设备上报一个id为123的消息，消息内容为"hello!"
       ST_IOTA_MESS_REP_INFO mass = {NULL, "name", "id", "hello!", "test"};
       int messageId = IOTA_MessageDataReport(mass, NULL);
       if (messageId != 0) {
           PrintfLog(EN_LOG_LEVEL_ERROR, "basicMassage() failed, messageId %d\n", messageId);
       }
       TimeSleep(3000);
   }
   ```
   
2. 在设备接入控制台，选择"设备 \> 所有设备"-查看设备是否在线。
   图7设备列表-设备在线   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950367902.png "点击放大") 
3. 选择对应设备，单击"详情"，在设备详情页面启动设备消息跟踪。
   图8消息跟踪-启动消息跟踪   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950378340.png "点击放大") 
4. 查看消息跟踪，确认平台是否收到设备消息。
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
   消息跟踪会有一定的延时，如果没有看到数据，请等待后刷新。
   图9消息跟踪-查看device_sdk_java消息跟踪   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981497769.png "点击放大") 
 
#### 属性上报
属性上报指的是设备将当前属性值上报给平台。属性设置指的是平台设置设备的属性值，API接口如下。
表2C语言属性上报接口 
| 功能       | 接口                                                                                                                               |
|:---|:---|
| 设备属性上报接口 | HW_INT IOTA_PropertiesReport(ST_IOTA_SERVICE_DATA_INFO pServiceData\[\], HW_INT serviceNum, HW_INT compressFlag, void \*context) |
   
1. 源代码中[demos/device_demo/properties_test.c](https://github.com/huaweicloud/huaweicloud-iot-device-sdk-c/blob/master/demos/device_demo/properties_test.c)是一个属性上报的例子，可以通过IOTA_PropertiesReport函数将属性上报给平台。
   ```
   void Test_propertiesReport() {
     int serviceNum = 1;//上报的service个数
     ST_IOTA_SERVICE_DATA_INFO services[serviceNum];
     //---------------the data of service-------------------------------
     char *service = "{\"temperature\": 28}";
     services[0].event_time = NULL;
     services[0].service_id = "smokeDetector";
     services[0].properties = service;
     int messageId = IOTA_PropertiesReport(services, serviceNum, 0, NULL);
     if(messageId != 0) {
   PrintfLog(EN_LOG_LEVEL_ERROR, "device_demo: Test_batchPropertiesReport() failed, messageId %d\n", messageId);
     }
   }
   ```
   
2. 在左侧导航栏中选择"设备 \> 所有设备"，选择对应设备单击"详情"，在"设备影子"处可以看到上报的属性值。
   图10设备影子-temperature   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002394220836.png "点击放大") 
![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
若是没有查看到属性上报值，确认是否已上传产品模型：[上传产品模型]。
#### 命令下发
设置命令监听器用来接收平台下发的命令，在回调接口里，将对命令进行处理，并上报响应。./demos/device_demo/command_test.c是一个处理平台命令下发的例子。下面代码的HandleCommandRequest函数作为命令监听器，即：
- 注册回调函数，设备接收命令下发（profile中定义的命令）。HW_API_FUNC HW_VOID IOTA_SetCmdCallback(PFN_CMD_CALLBACK_HANDLER callbackHandler) 通过该接口设置命令回调函数
  ```
  IOTA_SetCmdCallback(HandleCommandRequest);
  ```
  
- 当云端下发命令或端侧规则触发执行命令时，定义的函数会被调用。
  ```
  int beepState = 0; // 物模型，蜂鸣器状态
  // 响应命令下发
  static void Test_CommandResponse(char *requestId)
  {
    /* 请客户自行实现命令下发响应参数，以下为示例 */
    char pcCommandRespense[100] = {0}; // in service accumulator
    (void)sprintf_s(pcCommandRespense, sizeof(pcCommandRespense), "{\"Beep_State\": %d}", beepState); 
    int result_code = 0;
    char *response_name = "Smoke_Control_Beep";
    int messageId = IOTA_CommandResponse(requestId, result_code, response_name, pcCommandRespense, NULL);
    if (messageId != 0) {
        PrintfLog(EN_LOG_LEVEL_ERROR, "Test_CommandResponse() failed, messageId %d\n", messageId);
    }
  } 
  void HandleCommandRequest(EN_IOTA_COMMAND *command)
  {
      if (command == NULL) {
          return;
      }
      PrintfLog(EN_LOG_LEVEL_INFO, "command_test: HandleCommandRequest(), messageId %d, service_id %s, command_name %s, request_id %s\n", 
          command->mqtt_msg_info->messageId, command->service_id, command->command_name, command->request_id);
      PrintfLog(EN_LOG_LEVEL_INFO, "command_test: HandleCommandRequest(), request_id %s\n", command->request_id);
      /* 请客户自行实现命令下发处理逻辑 */
     
        Test_CommandResponse(command->request_id); //response command
  }
  ```
  
 
