更新时间:2024-02-28 GMT+08:00
分享

创建设备

功能介绍

应用服务器可调用此接口在物联网平台创建一个设备,仅在创建后设备才可以接入物联网平台。

  • 该接口支持使用gateway_id参数指定在父设备下创建一个子设备,并且支持多级子设备,当前最大支持二级子设备。

  • 该接口同时还支持对设备进行初始配置,接口会读取创建设备请求参数product_id对应的产品详情,如果产品的属性有定义默认值,则会将该属性默认值写入该设备的设备影子中。

  • 用户还可以使用创建设备请求参数shadow字段为设备指定初始配置,指定后将会根据service_id和desired设置的属性值与产品中对应属性的默认值比对,如果不同,则将以shadow字段中设置的属性值为准写入到设备影子中。

  • 该接口仅支持创建单个设备,如需批量注册设备,请参见 创建批量任务

调用方法

请参见如何调用API

URI

POST /v5/iot/{project_id}/devices

表1 路径参数

参数

是否必选

参数类型

描述

project_id

String

参数说明:项目ID。获取方法请参见 获取项目ID

请求参数

表2 请求Header参数

参数

是否必选

参数类型

描述

X-Auth-Token

String

参数说明:用户Token。通过调用IAM服务 获取IAM用户Token接口获取,接口返回的响应消息头中“X-Subject-Token”就是需要获取的用户Token。简要的获取方法样例请参见 Token认证

Instance-Id

String

参数说明:实例ID。物理多租下各实例的唯一标识,建议携带该参数,在使用专业版时必须携带该参数。您可以在IoTDA管理控制台界面,选择左侧导航栏“总览”页签查看当前实例的ID,具体获取方式请参考查看实例详情

表3 请求Body参数

参数

是否必选

参数类型

描述

device_id

String

参数说明:设备ID,全局唯一,用于唯一标识一个设备。如果携带该参数,平台将设备ID设置为该参数值;如果不携带该参数,设备ID由物联网平台分配获得,生成规则为product_id + _ + node_id拼接而成。 取值范围:长度不超过128,只允许字母、数字、下划线(_)、连接符(-)的组合,建议不少于4个字符。

node_id

String

参数说明:设备标识码,通常使用IMEI、MAC地址或Serial No作为node_id。 设备标识码长度为1到64个字符,包含英文字母、数字、连接号-和下划线_。 注意:NB设备由于模组烧录信息后无法配置,所以NB设备会校验node_id全局唯一。 取值范围:长度不超过64,只允许字母、数字、下划线(_)、连接符(-)的组合,建议不少于4个字符。

device_name

String

参数说明:设备名称,资源空间下唯一,用于资源空间下唯一标识一个设备。 取值范围:长度不超过256,只允许中文、字母、数字、以及_?'#().,&%@!-等字符的组合,建议不少于4个字符。

最小长度:1

最大长度:256

product_id

String

参数说明:设备关联的产品ID,用于唯一标识一个产品模型,创建产品后获得。方法请参见 创建产品取值范围:长度不超过36,只允许字母、数字、下划线(_)、连接符(-)的组合。

auth_info

AuthInfo object

参数说明:设备的接入认证信息。

description

String

参数说明:设备的描述信息。 取值范围:长度不超过2048,只允许中文、字母、数字、以及_?'#().,&%@!-等字符的组合

最大长度:2048

gateway_id

String

参数说明:网关ID,用于标识设备所属的父设备,即父设备的设备ID。携带该参数时,表示在该父设备下创建一个子设备,这个子设备不与平台直连,此时必须保证这个父设备在平台已存在,创建成功后子设备的gateway_id等于该参数值;不携带该参数时,表示创建一个和平台直连的设备,创建成功后设备的device_id和gateway_id一致。注意:当前平台最多支持二级子设备。 取值范围:长度不超过128,只允许字母、数字、下划线(_)、连接符(-)的组合。

app_id

String

参数说明:资源空间ID。此参数为非必选参数,存在多资源空间的用户需要使用该接口时,建议携带该参数指定创建的设备归属到哪个资源空间下,否则创建的设备将会归属到默认资源空间下。 取值范围:长度不超过36,只允许字母、数字、下划线(_)、连接符(-)的组合。

extension_info

Object

参数说明:设备扩展信息。用户可以自定义任何想要的扩展信息,如果在创建设备时为子设备指定该字段,将会通过MQTT接口“平台通知网关子设备新增“将该信息通知给网关。字段值大小上限为1K。

shadow

Array of InitialDesired objects

参数说明:设备初始配置。用户使用该字段可以为设备指定初始配置,指定后将会根据service_id和desired设置的属性值与产品中对应属性的默认值比对,如果不同,则将以shadow字段中设置的属性值为准写入到设备影子中。service_id的值和desired内的属性必须是profile中定义的。

表4 AuthInfo

参数

是否必选

参数类型

描述

auth_type

String

参数说明:鉴权类型。注意:不填写auth_type默认为密钥认证接入方式(SECRET)。 取值范围

  • SECRET:使用密钥认证接入方式。

  • CERTIFICATES:使用证书认证接入方式。

secret

String

参数说明:设备密钥,认证类型使用密钥认证接入(SECRET)可填写该字段。注意:NB设备密钥由于协议特殊性,只支持十六进制密钥接入;查询设备列表接口不返回该参数。 取值范围:长度不低于8不超过32,只允许字母、数字、下划线(_)、连接符(-)的组合。

最小长度:8

最大长度:32

fingerprint

String

参数说明:证书指纹,认证类型使用证书认证接入(CERTIFICATES)可填写该字段,注册设备时不填写该字段则取第一次设备接入时的证书指纹。 取值范围:长度为40的十六进制字符串或者长度为64的十六进制字符串。

secure_access

Boolean

参数说明:指设备是否通过安全协议方式接入。 取值范围

  • true:通过安全协议方式接入。

  • false:通过非安全协议方式接入。非安全接入的设备存在被仿冒等安全风险,请谨慎使用。

缺省值:true

timeout

Integer

参数说明:设备接入的有效时间,单位:秒,默认值:0 若设备在有效时间内未接入物联网平台并激活,则平台会删除该设备的注册信息。若设置为“0”,则表示平台不会删除该设备的注册信息(建议填写为“0”)。 注意:该参数只对直连设备生效。

最小值:0

最大值:2147483647

缺省值:0

表5 InitialDesired

参数

是否必选

参数类型

描述

service_id

String

参数说明:设备的服务ID,在设备关联的产品模型中定义。 取值范围:长度不超过32,只允许中文、字母、数字、以及_?'#().,&%@!-等字符的组合。

desired

Object

参数说明:设备初始配置属性数据,Json格式,里面是一个个键值对,每个键都是产品模型中属性的参数名(property_name),目前如样例所示只支持一层结构;这里设置的属性值与产品中对应属性的默认值比对,如果不同,则将以该字段中设置的属性值为准写入到设备影子中;如果想要删除整个desired可以填写空object(例如"desired":{}),如果想要删除某一个属性期望值可以将属性置位null(例如{"temperature":null})

响应参数

状态码: 201

表6 响应Body参数

参数

参数类型

描述

app_id

String

资源空间ID。

最大长度:36

app_name

String

资源空间名称。

device_id

String

设备ID,用于唯一标识一个设备。在注册设备时直接指定,或者由物联网平台分配获得。由物联网平台分配时,生成规则为"product_id" + "_" + "node_id"拼接而成。

最大长度:256

node_id

String

设备标识码,通常使用IMEI、MAC地址或Serial No作为node_id。

最大长度:64

gateway_id

String

网关ID,用于标识设备所属的父设备,即父设备的设备ID。当设备是直连设备时,gateway_id与设备的device_id一致。当设备是非直连设备时,gateway_id为设备所关联的父设备的device_id。

最大长度:256

device_name

String

设备名称。

最大长度:256

node_type

String

设备节点类型。

  • ENDPOINT:非直连设备。

  • GATEWAY:直连设备或网关。

  • UNKNOWN:未知。

description

String

设备的描述信息。

最大长度:2048

fw_version

String

设备的固件版本。

最大长度:256

sw_version

String

设备的软件版本。

最大长度:256

device_sdk_version

String

设备的sdk信息。

最大长度:256

auth_info

AuthInfoRes object

设备的接入认证信息。

product_id

String

设备关联的产品ID,用于唯一标识一个产品模型。

product_name

String

设备关联的产品名称。

status

String

设备的状态。

  • ONLINE:设备在线。

  • OFFLINE:设备离线。

  • ABNORMAL:设备异常。

  • INACTIVE:设备未激活。

  • FROZEN:设备冻结。

create_time

String

在物联网平台注册设备的时间。格式:yyyyMMdd'T'HHmmss'Z',如20151212T121212Z。

connection_status_update_time

String

设备最近一次连接状态(ONLINE:在线,OFFLINE:离线,ABNORMAL:异常)变化时间。格式:yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ,如2015-12-12T12:12:122Z。

active_time

String

设备激活时间。格式:yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ,如2015-12-12T12:12:122Z。

tags

Array of TagV5DTO objects

设备的标签列表。

extension_info

Object

设备扩展信息。用户可以自定义任何想要的扩展信息,如果在创建设备时为子设备指定该字段,将会通过MQTT接口“平台通知网关子设备新增“将该信息通知给网关。

表7 AuthInfoRes

参数

参数类型

描述

auth_type

String

参数说明:鉴权类型。注意:不填写auth_type默认为密钥认证接入方式(SECRET)。 取值范围

  • SECRET:使用密钥认证接入方式。

  • CERTIFICATES:使用证书认证接入方式。

secret

String

参数说明:设备密钥,认证类型使用密钥认证接入(SECRET)可填写该字段。注意:NB设备密钥由于协议特殊性,只支持十六进制密钥接入;查询设备列表接口不返回该参数。 取值范围:长度不低于8不超过32,只允许字母、数字、下划线(_)、连接符(-)的组合。

最小长度:8

最大长度:32

secondary_secret

String

参数说明:设备备用密钥,认证类型使用密钥认证接入(SECRET)该字段有效,当主密钥校验不通过时,会启用辅密钥校验,辅密钥与主密钥有相同的效力;辅密钥对coap协议接入的设备不生效。注意:NB设备密钥由于协议特殊性,只支持十六进制密钥接入;查询设备列表接口不返回该参数。 取值范围:长度不低于8不超过32,只允许字母、数字、下划线(_)、连接符(-)的组合。

最小长度:8

最大长度:32

fingerprint

String

参数说明:证书指纹,认证类型使用证书认证接入(CERTIFICATES)该字段有效,注册设备时不填写该字段则取第一次设备接入时的证书指纹。 取值范围:长度为40的十六进制字符串或者长度为64的十六进制字符串。

secondary_fingerprint

String

参数说明:证书备用指纹,认证类型使用证书认证接入(CERTIFICATES)该字段有效,当主指纹校验不通过时,会启用辅指纹校验,辅指纹与主指纹有相同的效力。 取值范围:长度为40的十六进制字符串或者长度为64的十六进制字符串。

secure_access

Boolean

参数说明:指设备是否通过安全协议方式接入。 取值范围

  • true:通过安全协议方式接入。

  • false:通过非安全协议方式接入。非安全接入的设备存在被仿冒等安全风险,请谨慎使用。

缺省值:true

timeout

Integer

参数说明:设备接入的有效时间,单位:秒,默认值:0 若设备在有效时间内未接入物联网平台并激活,则平台会删除该设备的注册信息。若设置为“0”,则表示平台不会删除该设备的注册信息(建议填写为“0”)。 注意:该参数只对直连设备生效。

最小值:0

最大值:2147483647

缺省值:0

表8 TagV5DTO

参数

参数类型

描述

tag_key

String

参数说明:标签键,在同一资源下标签键唯一。绑定资源时,如果设置的键已存在,则将覆盖之前的标签值。如果设置的键值不存在,则新增标签。 取值范围:长度不超过64,只允许中文、字母、数字、以及_.-等字符的组合。

tag_value

String

参数说明:标签值。 取值范围:长度不超过128,只允许中文、字母、数字、以及_.-等字符的组合。

请求示例

  • 创建设备,认证类型为秘钥认证。

    POST https://{endpoint}/v5/iot/{project_id}/devices
    
    {
      "device_id" : "d4922d8a-6c8e-4396-852c-164aefa6638f",
      "node_id" : "ABC123456789",
      "device_name" : "dianadevice",
      "product_id" : "b640f4c203b7910fc3cbd446ed437cbd",
      "auth_info" : {
        "auth_type" : "SECRET",
        "secret" : "3b935a250c50dc2c6d481d048cefdc3c",
        "secure_access" : true
      },
      "description" : "watermeter device",
      "app_id" : "jeQDJQZltU8iKgFFoW060F5SGZka",
      "extension_info" : {
        "aaa" : "xxx",
        "bbb" : 0
      },
      "shadow" : [ {
        "service_id" : "WaterMeter",
        "desired" : {
          "temperature" : "60"
        }
      } ]
    }
  • 创建设备,认证类型为证书认证。

    POST https://{endpoint}/v5/iot/{project_id}/devices
    
    {
      "device_id" : "d4922d8a-6c8e-4396-852c-164aefa6638f",
      "node_id" : "ABC123456789",
      "device_name" : "dianadevice",
      "product_id" : "b640f4c203b7910fc3cbd446ed437cbd",
      "auth_info" : {
        "auth_type" : "CERTIFICATES",
        "fingerprint" : "dc0f1016f495157344ac5f1296335cff725ef22f",
        "secure_access" : true
      },
      "description" : "watermeter device",
      "app_id" : "jeQDJQZltU8iKgFFoW060F5SGZka",
      "extension_info" : {
        "aaa" : "xxx",
        "bbb" : 0
      },
      "shadow" : [ {
        "service_id" : "WaterMeter",
        "desired" : {
          "temperature" : "60"
        }
      } ]
    }
  • 创建设备,设备类型非直连设备。

    POST https://{endpoint}/v5/iot/{project_id}/devices
    
    {
      "device_id" : "d4922d8a-6c8e-4396-852c-164aefa6638f",
      "node_id" : "ABC123456789",
      "device_name" : "dianadevice",
      "product_id" : "b640f4c203b7910fc3cbd446ed437cbd",
      "description" : "watermeter device",
      "app_id" : "jeQDJQZltU8iKgFFoW060F5SGZka",
      "gateway_id" : "5a332c1a-d14f-489c-a8e7-4753b1bb0872",
      "extension_info" : {
        "aaa" : "xxx",
        "bbb" : 0
      },
      "shadow" : [ {
        "service_id" : "WaterMeter",
        "desired" : {
          "temperature" : "60"
        }
      } ]
    }

响应示例

状态码: 201

Created

{
  "app_id" : "jeQDJQZltU8iKgFFoW060F5SGZka",
  "app_name" : "testAPP01",
  "device_id" : "d4922d8a-6c8e-4396-852c-164aefa6638f",
  "node_id" : "ABC123456789",
  "gateway_id" : "d4922d8a-6c8e-4396-852c-164aefa6638f",
  "device_name" : "dianadevice",
  "node_type" : "ENDPOINT",
  "description" : "watermeter device",
  "fw_version" : "1.1.0",
  "sw_version" : "1.1.0",
  "auth_info" : {
    "auth_type" : "SECRET",
    "secret" : "3b93****fdc3c",
    "fingerprint" : "dc0f****f22f",
    "secure_access" : true,
    "timeout" : 0
  },
  "product_id" : "b640f4c203b7910fc3cbd446ed437cbd",
  "product_name" : "Thermometer",
  "status" : "INACTIVE",
  "create_time" : "20190303T081011Z",
  "connection_status_update_time" : null,
  "active_time" : null,
  "tags" : [ {
    "tag_key" : "testTagName",
    "tag_value" : "testTagValue"
  } ],
  "extension_info" : {
    "aaa" : "xxx",
    "bbb" : 0
  }
}

SDK代码示例

SDK代码示例如下。

Java

  • 创建设备,认证类型为秘钥认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.AbstractCredentials;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion;
    import com.huaweicloud.sdk.iotda.v5.*;
    import com.huaweicloud.sdk.iotda.v5.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class AddDeviceSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                    .withAk(ak)
                    .withSk(sk);
    
            IoTDAClient client = IoTDAClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(IoTDARegion.valueOf("<YOUR REGION>"))
                    .build();
            AddDeviceRequest request = new AddDeviceRequest();
            AddDevice body = new AddDevice();
            List<InitialDesired> listbodyShadow = new ArrayList<>();
            listbodyShadow.add(
                new InitialDesired()
                    .withServiceId("WaterMeter")
                    .withDesired("{\"temperature\":\"60\"}")
            );
            AuthInfo authInfobody = new AuthInfo();
            authInfobody.withAuthType("SECRET")
                .withSecret("3b935a250c50dc2c6d481d048cefdc3c")
                .withSecureAccess(true);
            body.withShadow(listbodyShadow);
            body.withExtensionInfo("{\"aaa\":\"xxx\",\"bbb\":0}");
            body.withAppId("jeQDJQZltU8iKgFFoW060F5SGZka");
            body.withDescription("watermeter device");
            body.withAuthInfo(authInfobody);
            body.withProductId("b640f4c203b7910fc3cbd446ed437cbd");
            body.withDeviceName("dianadevice");
            body.withNodeId("ABC123456789");
            body.withDeviceId("d4922d8a-6c8e-4396-852c-164aefa6638f");
            request.withBody(body);
            try {
                AddDeviceResponse response = client.addDevice(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • 创建设备,认证类型为证书认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.AbstractCredentials;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion;
    import com.huaweicloud.sdk.iotda.v5.*;
    import com.huaweicloud.sdk.iotda.v5.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class AddDeviceSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                    .withAk(ak)
                    .withSk(sk);
    
            IoTDAClient client = IoTDAClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(IoTDARegion.valueOf("<YOUR REGION>"))
                    .build();
            AddDeviceRequest request = new AddDeviceRequest();
            AddDevice body = new AddDevice();
            List<InitialDesired> listbodyShadow = new ArrayList<>();
            listbodyShadow.add(
                new InitialDesired()
                    .withServiceId("WaterMeter")
                    .withDesired("{\"temperature\":\"60\"}")
            );
            AuthInfo authInfobody = new AuthInfo();
            authInfobody.withAuthType("CERTIFICATES")
                .withFingerprint("dc0f1016f495157344ac5f1296335cff725ef22f")
                .withSecureAccess(true);
            body.withShadow(listbodyShadow);
            body.withExtensionInfo("{\"aaa\":\"xxx\",\"bbb\":0}");
            body.withAppId("jeQDJQZltU8iKgFFoW060F5SGZka");
            body.withDescription("watermeter device");
            body.withAuthInfo(authInfobody);
            body.withProductId("b640f4c203b7910fc3cbd446ed437cbd");
            body.withDeviceName("dianadevice");
            body.withNodeId("ABC123456789");
            body.withDeviceId("d4922d8a-6c8e-4396-852c-164aefa6638f");
            request.withBody(body);
            try {
                AddDeviceResponse response = client.addDevice(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • 创建设备,设备类型非直连设备。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.AbstractCredentials;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion;
    import com.huaweicloud.sdk.iotda.v5.*;
    import com.huaweicloud.sdk.iotda.v5.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class AddDeviceSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                    .withAk(ak)
                    .withSk(sk);
    
            IoTDAClient client = IoTDAClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(IoTDARegion.valueOf("<YOUR REGION>"))
                    .build();
            AddDeviceRequest request = new AddDeviceRequest();
            AddDevice body = new AddDevice();
            List<InitialDesired> listbodyShadow = new ArrayList<>();
            listbodyShadow.add(
                new InitialDesired()
                    .withServiceId("WaterMeter")
                    .withDesired("{\"temperature\":\"60\"}")
            );
            body.withShadow(listbodyShadow);
            body.withExtensionInfo("{\"aaa\":\"xxx\",\"bbb\":0}");
            body.withAppId("jeQDJQZltU8iKgFFoW060F5SGZka");
            body.withGatewayId("5a332c1a-d14f-489c-a8e7-4753b1bb0872");
            body.withDescription("watermeter device");
            body.withProductId("b640f4c203b7910fc3cbd446ed437cbd");
            body.withDeviceName("dianadevice");
            body.withNodeId("ABC123456789");
            body.withDeviceId("d4922d8a-6c8e-4396-852c-164aefa6638f");
            request.withBody(body);
            try {
                AddDeviceResponse response = client.addDevice(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    

Python

  • 创建设备,认证类型为秘钥认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.auth.credentials import DerivedCredentials
    from huaweicloudsdkiotda.v5.region.iotda_region import IoTDARegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkiotda.v5 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = __import__('os').getenv("CLOUD_SDK_AK")
        sk = __import__('os').getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
                .with_derived_predicate(DerivedCredentials.get_default_derived_predicate()) \
    
        client = IoTDAClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(IoTDARegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = AddDeviceRequest()
            listShadowbody = [
                InitialDesired(
                    service_id="WaterMeter",
                    desired="{\"temperature\":\"60\"}"
                )
            ]
            authInfobody = AuthInfo(
                auth_type="SECRET",
                secret="3b935a250c50dc2c6d481d048cefdc3c",
                secure_access=True
            )
            request.body = AddDevice(
                shadow=listShadowbody,
                extension_info="{\"aaa\":\"xxx\",\"bbb\":0}",
                app_id="jeQDJQZltU8iKgFFoW060F5SGZka",
                description="watermeter device",
                auth_info=authInfobody,
                product_id="b640f4c203b7910fc3cbd446ed437cbd",
                device_name="dianadevice",
                node_id="ABC123456789",
                device_id="d4922d8a-6c8e-4396-852c-164aefa6638f"
            )
            response = client.add_device(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 创建设备,认证类型为证书认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.auth.credentials import DerivedCredentials
    from huaweicloudsdkiotda.v5.region.iotda_region import IoTDARegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkiotda.v5 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = __import__('os').getenv("CLOUD_SDK_AK")
        sk = __import__('os').getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
                .with_derived_predicate(DerivedCredentials.get_default_derived_predicate()) \
    
        client = IoTDAClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(IoTDARegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = AddDeviceRequest()
            listShadowbody = [
                InitialDesired(
                    service_id="WaterMeter",
                    desired="{\"temperature\":\"60\"}"
                )
            ]
            authInfobody = AuthInfo(
                auth_type="CERTIFICATES",
                fingerprint="dc0f1016f495157344ac5f1296335cff725ef22f",
                secure_access=True
            )
            request.body = AddDevice(
                shadow=listShadowbody,
                extension_info="{\"aaa\":\"xxx\",\"bbb\":0}",
                app_id="jeQDJQZltU8iKgFFoW060F5SGZka",
                description="watermeter device",
                auth_info=authInfobody,
                product_id="b640f4c203b7910fc3cbd446ed437cbd",
                device_name="dianadevice",
                node_id="ABC123456789",
                device_id="d4922d8a-6c8e-4396-852c-164aefa6638f"
            )
            response = client.add_device(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 创建设备,设备类型非直连设备。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.auth.credentials import DerivedCredentials
    from huaweicloudsdkiotda.v5.region.iotda_region import IoTDARegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkiotda.v5 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = __import__('os').getenv("CLOUD_SDK_AK")
        sk = __import__('os').getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
                .with_derived_predicate(DerivedCredentials.get_default_derived_predicate()) \
    
        client = IoTDAClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(IoTDARegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = AddDeviceRequest()
            listShadowbody = [
                InitialDesired(
                    service_id="WaterMeter",
                    desired="{\"temperature\":\"60\"}"
                )
            ]
            request.body = AddDevice(
                shadow=listShadowbody,
                extension_info="{\"aaa\":\"xxx\",\"bbb\":0}",
                app_id="jeQDJQZltU8iKgFFoW060F5SGZka",
                gateway_id="5a332c1a-d14f-489c-a8e7-4753b1bb0872",
                description="watermeter device",
                product_id="b640f4c203b7910fc3cbd446ed437cbd",
                device_name="dianadevice",
                node_id="ABC123456789",
                device_id="d4922d8a-6c8e-4396-852c-164aefa6638f"
            )
            response = client.add_device(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    

Go

  • 创建设备,认证类型为秘钥认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        iotda "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/region"
        core_auth "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithDerivedPredicate(core_auth.GetDefaultDerivedPredicate()). // Used in derivative ak/sk authentication scenarios
            Build()
    
        client := iotda.NewIoTDAClient(
            iotda.IoTDAClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.AddDeviceRequest{}
    	desiredShadow:= "{\"temperature\":\"60\"}"
    	var desiredShadowInterface interface{} = desiredShadow
    	var listShadowbody = []model.InitialDesired{
            {
                ServiceId: "WaterMeter",
                Desired: &desiredShadowInterface,
            },
        }
    	authTypeAuthInfo:= "SECRET"
    	secretAuthInfo:= "3b935a250c50dc2c6d481d048cefdc3c"
    	secureAccessAuthInfo:= true
    	authInfobody := &model.AuthInfo{
    		AuthType: &authTypeAuthInfo,
    		Secret: &secretAuthInfo,
    		SecureAccess: &secureAccessAuthInfo,
    	}
    	var extensionInfoAddDevice interface{} = "{\"aaa\":\"xxx\",\"bbb\":0}"
    	appIdAddDevice:= "jeQDJQZltU8iKgFFoW060F5SGZka"
    	descriptionAddDevice:= "watermeter device"
    	deviceNameAddDevice:= "dianadevice"
    	deviceIdAddDevice:= "d4922d8a-6c8e-4396-852c-164aefa6638f"
    	request.Body = &model.AddDevice{
    		Shadow: &listShadowbody,
    		ExtensionInfo: &extensionInfoAddDevice,
    		AppId: &appIdAddDevice,
    		Description: &descriptionAddDevice,
    		AuthInfo: authInfobody,
    		ProductId: "b640f4c203b7910fc3cbd446ed437cbd",
    		DeviceName: &deviceNameAddDevice,
    		NodeId: "ABC123456789",
    		DeviceId: &deviceIdAddDevice,
    	}
    	response, err := client.AddDevice(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • 创建设备,认证类型为证书认证。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        iotda "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/region"
        core_auth "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithDerivedPredicate(core_auth.GetDefaultDerivedPredicate()). // Used in derivative ak/sk authentication scenarios
            Build()
    
        client := iotda.NewIoTDAClient(
            iotda.IoTDAClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.AddDeviceRequest{}
    	desiredShadow:= "{\"temperature\":\"60\"}"
    	var desiredShadowInterface interface{} = desiredShadow
    	var listShadowbody = []model.InitialDesired{
            {
                ServiceId: "WaterMeter",
                Desired: &desiredShadowInterface,
            },
        }
    	authTypeAuthInfo:= "CERTIFICATES"
    	fingerprintAuthInfo:= "dc0f1016f495157344ac5f1296335cff725ef22f"
    	secureAccessAuthInfo:= true
    	authInfobody := &model.AuthInfo{
    		AuthType: &authTypeAuthInfo,
    		Fingerprint: &fingerprintAuthInfo,
    		SecureAccess: &secureAccessAuthInfo,
    	}
    	var extensionInfoAddDevice interface{} = "{\"aaa\":\"xxx\",\"bbb\":0}"
    	appIdAddDevice:= "jeQDJQZltU8iKgFFoW060F5SGZka"
    	descriptionAddDevice:= "watermeter device"
    	deviceNameAddDevice:= "dianadevice"
    	deviceIdAddDevice:= "d4922d8a-6c8e-4396-852c-164aefa6638f"
    	request.Body = &model.AddDevice{
    		Shadow: &listShadowbody,
    		ExtensionInfo: &extensionInfoAddDevice,
    		AppId: &appIdAddDevice,
    		Description: &descriptionAddDevice,
    		AuthInfo: authInfobody,
    		ProductId: "b640f4c203b7910fc3cbd446ed437cbd",
    		DeviceName: &deviceNameAddDevice,
    		NodeId: "ABC123456789",
    		DeviceId: &deviceIdAddDevice,
    	}
    	response, err := client.AddDevice(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • 创建设备,设备类型非直连设备。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        iotda "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/region"
        core_auth "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithDerivedPredicate(core_auth.GetDefaultDerivedPredicate()). // Used in derivative ak/sk authentication scenarios
            Build()
    
        client := iotda.NewIoTDAClient(
            iotda.IoTDAClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.AddDeviceRequest{}
    	desiredShadow:= "{\"temperature\":\"60\"}"
    	var desiredShadowInterface interface{} = desiredShadow
    	var listShadowbody = []model.InitialDesired{
            {
                ServiceId: "WaterMeter",
                Desired: &desiredShadowInterface,
            },
        }
    	var extensionInfoAddDevice interface{} = "{\"aaa\":\"xxx\",\"bbb\":0}"
    	appIdAddDevice:= "jeQDJQZltU8iKgFFoW060F5SGZka"
    	gatewayIdAddDevice:= "5a332c1a-d14f-489c-a8e7-4753b1bb0872"
    	descriptionAddDevice:= "watermeter device"
    	deviceNameAddDevice:= "dianadevice"
    	deviceIdAddDevice:= "d4922d8a-6c8e-4396-852c-164aefa6638f"
    	request.Body = &model.AddDevice{
    		Shadow: &listShadowbody,
    		ExtensionInfo: &extensionInfoAddDevice,
    		AppId: &appIdAddDevice,
    		GatewayId: &gatewayIdAddDevice,
    		Description: &descriptionAddDevice,
    		ProductId: "b640f4c203b7910fc3cbd446ed437cbd",
    		DeviceName: &deviceNameAddDevice,
    		NodeId: "ABC123456789",
    		DeviceId: &deviceIdAddDevice,
    	}
    	response, err := client.AddDevice(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    

更多

更多编程语言的SDK代码示例,请参见API Explorer的代码示例页签,可生成自动对应的SDK代码示例。

状态码

状态码

描述

201

Created

400

Bad Request

401

Unauthorized

403

Forbidden

404

Not Found

500

Internal Server Error

错误码

请参见错误码

分享:

    相关文档

    相关产品