
# 快速接入
本章将使用SmokeDetector样例指导您快速体验产品模型的创建、样例代码的配置与启动、以及SDK基本功能的使用。为了方便体验，提供了一个烟感的产品模型，烟感会上报烟雾值、温度、湿度、烟雾报警、还支持响铃报警命令。 以烟感为例，体验消息上报、属性上报、命令响应等功能。
#### 创建产品
为了方便体验，提供了一个烟感的产品模型，烟感会上报烟雾值、温度、湿度、烟雾报警、还支持响铃报警命令。以烟感为例，体验消息上报、属性上报等功能。
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. 在iot_device_demo/device/smoke_detector.py中将获取的接入地址、设备ID以及设备密钥填入对应位置。 
   ```
   server_uri = "access address"   # 需要改为用户保存的接入地址
    port = 8883
    device_id = "your device id"
    secret = "your device secret"
    # iot平台的CA证书，用于服务端校验
    iot_ca_cert_path = "./resources/root.pem"
    connect_auth_info = ConnectAuthInfo()
    connect_auth_info.server_uri = server_uri
    connect_auth_info.port = port
    connect_auth_info.id = device_id
    connect_auth_info.secret = secret
    connect_auth_info.iot_cert_path = iot_ca_cert_path
    client_conf = ClientConf(connect_auth_info)
    device = IotDevice(client_conf)
   ```
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/note_3.0-zh-cn.png)
   平台的证书可以从源码中[/iot_device_demo/resources/root.pem](https://github.com/huaweicloud/huaweicloud-iot-device-sdk-python/blob/main/iot_device_demo/resources/root.pem)下载。
   
   
3. 编译\&运行。执行样例，输出如下，如果包含connect result is : true则表示连接成功。 
   图5连接成功   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002361336776.png "点击放大")
   
   
4. 查看设备运行情况。在控制台的设备详情页面可以查看设备已在线以及设备上报的物模型数据。 
   图6设备列表-设备在线   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950367902.png "点击放大")
   图7查看上报数据-smokeDetector   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981329933.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-python/blob/main/README_CN.md#417-断链重连)。
#### 消息上报
消息上报是指设备向平台上报消息。
1. iot_device_demo/message/message_delivery_sample.py是一个上报消息例子，可以调用report_device_message方法将消息通过默认topic上报给平台，也可以调用publish_raw_message方法将消息通过自定义topic上报给平台。
   ```
   """ create device code here """
       default_publish_listener = DefaultPublishActionListener()
       device_message = DeviceMessage()
       device_message.content = "Hello Huawei"
       device_message2 = DeviceMessage()
       device_message2.content = "Custom topic Message"
       device_message3 = DeviceMessage()
       device_message3.content = "Custom Policy topic Message"
       # 定时上报消息
       while True:
           # 通过平台默认topic上报消息
           device.get_client().report_device_message(device_message,
                                                     default_publish_listener)
           time.sleep(1)
           payload = json.dumps(device_message2.to_dict())
           # 通过平台自定义topic上报消息
           device.get_client().publish_raw_message(RawMessage(custom_topic, payload, 1), default_publish_listener)
           time.sleep(1)
           payload = json.dumps(device_message3.to_dict())
           # 通过平台自定义策略中的topic上报消息
           device.get_client().publish_raw_message(RawMessage(custom_policy_topic, payload, 1), default_publish_listener)
           time.sleep(5)
   ```
   
2. 在设备接入控制台，选择"设备 \> 所有设备"-查看设备是否在线。
   图8设备列表-设备在线   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001950367902.png "点击放大") 
3. 选择对应设备，单击"详情"，在设备详情页面启动设备消息跟踪。
   图9消息跟踪-启动消息跟踪   
   ![](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)
   消息跟踪会有一定的延时，如果没有看到数据，请等待后刷新。
   图10消息跟踪-查看device_sdk_java消息跟踪   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000001981497769.png "点击放大") 
 
#### 属性上报
属性上报指的是设备将当前属性值上报给平台。
1. ./iot_device_demo/device/properties_sample.py是一个属性上报的例子，可以通过report_properties方法将属性上报给平台。
   ```
   def run():
       < create device code here ... >
       if device.connect() != 0:
           logger.error('init failed')
           return
       service_property = ServiceProperty()
       service_property.service_id = 'smokeDetector'
       service_property.properties = {'alarm': 10, 'smokeConcentration': 36, 'temperature': 64, 'humidity': 32}
       services = [service_property.to_dict()]
       while True:
           device.get_client().report_properties(services, DefaultPublishActionListener())
           time.sleep(5)
   ```
   
2. 例子中alarm、smokeConcentration、temperature、humidity这四个属性将周期性地上报给平台。在左侧导航栏中选择"设备 \> 所有设备"，设备列表中选择对应设备单击"详情"，可以查看设备上报的物模型数据。
   图11物模型-属性上报   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002039398625.png "点击放大")
   ![](https://support.huaweicloud.com/sdkreference-iothub/public_sys-resources/notice_3.0-zh-cn.png)
   若是没有查看到属性上报值，确认是否已上传产品模型：[上传产品模型](https://support.huaweicloud.com/sdkreference-iothub/iot_02_00902.html#ZH-CN_TOPIC_0000002340106441__section1054114275468)。
   
 
#### 命令下发
设置命令监听器用来接收平台下发的命令，在回调接口里，将对命令进行处理，并上报响应。
1. ./samples/command/platform_command.go是一个处理平台命令下发的例子。 代码中将CommandSampleListener的实例设置为命令监听器，CommandSampleListener类继承CommandListener类，实现了on_command方法。
   ```
   device.get_client().set_command_listener(CommandSampleListener(device))
   ```
   
2. device收到命令时将自动调用监听器中的on_command方法。
   ```
   class CommandSampleListener(CommandListener):
       def __init__(self, iot_device: IotDevice):
           """ 传入一个IotDevice实例 """
           self.device = iot_device
       def on_command(self, request_id, service_id, command_name, paras):
           logger.info('on_command requestId: ' + request_id)
           # 处理命令
           logger.info('begin to handle command')
           """ code here """
           logger.info(str(paras))
           # 命令响应
           command_rsp = CommandRsp()
           command_rsp.result_code = 0
           command_rsp.response_name = command_name
           command_rsp.paras = {"content": "Hello Huawei"}
           self.device.get_client().response_command(request_id, command_rsp)
   def run():
       < create device code here ... >
       # 设置监听器
       device.get_client().set_command_listener(CommandSampleListener(device))
       if device.connect() != 0:
           logger.error('init failed')
           return
       while True:
           time.sleep(5)
   ```
   
3. 执行代码后，在平台给设备下发命令，查看代码日志如下。
   图12Python语言命令下发   
   ![](https://support.huaweicloud.com/sdkreference-iothub/figure/zh-cn_image_0000002395053445.png "点击放大") 
 
