You can connect devices to IoT Platform over Constrained Application Protocol (CoAP). CoAP is suitable for low-power and resource-constrained devices, such as NB-IoT devices. This topic describes how to connect a device to IoT Platform over CoAP. This topic also describes how to verify the device by using Datagram Transport Layer Security (DTLS) or symmetric encryption.

Procedure

The following figure shows how to connect an NB-IoT device to IoT Platform. coap
No.Description
Integrate an IoT Platform SDK into the NB-IoT module of a device. A device provider applies for the device certificate in the IoT Platform console and burns the device certificate to the device.
Connect the NB-IoT device to IoT Platform over the mobile network of a carrier. Contact your local carrier to ensure that the NB-IoT network is available in the region where your device resides.
Use the machine-to-machine (M2M) platform of the carrier to manage data traffic and fees. The M2M platform capabilities are provided by the carrier.
Collect data in real time and submit the data to IoT Platform over CoAP or UDP. IoT Platform allows you to establish secure connections with hundreds of millions of devices and manage a large amount of device data. IoT Platform also allows you to forward data to multiple Alibaba Cloud services for further processing. The services include big data services, database services, and Tablestore.
Use the data access-related API operations and message pushing services that are provided by IoT Platform to forward data to business servers and integrate devices and applications.

Connect devices by using symmetric encryption

  1. Connect to the CoAP server.
    Endpoints: For information about how to connect a device to the endpoint of a public instance or Enterprise Edition instance over CoAP, see View the endpoint of an instance.
  2. Verify the device.

    Sample request:

    POST /auth
    Host: ${YourEndpoint}
    Port: 5682
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: {"productKey":"a1NUjcV****","deviceName":"ff1a11e7c08d4b3db2b1500d8e0e55","clientId":"a1NUjcV****&ff1a11e7c08d4b3db2b1500d8e0e55","sign":"F9FD53EE0CD010FCA40D14A9FE******", "seq":"10"}
    Table 1. Parameters
    ParameterDescription
    MethodThe request method. Valid value: POST.
    URLThe URL. Valid value: /auth.
    HostThe endpoint.
    PortThe port number. Valid value: 5682.
    AcceptThe Multipurpose Internet Mail Extensions (MIME) type of the data that is received by the device. Valid values: application/json and application/cbor.
    Content-FormatThe MIME type of the data that the device submits to IoT Platform. Valid values: application/json and application/cbor.
    payloadThe JSON-formatted device information for verification. For more information, see the following table.
    Table 2. Fields in the payload parameter
    FieldRequiredDescription
    productKeyYesThe ProductKey in the device certificate. The ProductKey is a globally unique identifier (GUID) that is issued by IoT Platform to the product. You can log on to the IoT Platform console and view the ProductKey on the Device Details page.
    deviceNameYesThe DeviceName in the device certificate. The DeviceName is the system-defined or custom device name when you register the device. You can log on to the IoT Platform console and view the DeviceName on the Device Details page.
    ackModeNoThe communication mode. Valid values:
    • 0: IoT Platform returns response data and an ACK message at the same time.
    • 1: IoT Platform returns an ACK message and then returns response data.

    Default value: 0.

    signYesCalculate the signature.

    You can use the signmethod(DeviceSecret,content) function to calculate a signature. Then, you can specify the signature for the sign parameter. The hmacmd5 and hmacsha1 signature algorithms are supported.

    Required parameters:

    • signmethod: the signature algorithm. The value must be the same as the value that you specified for the signmethod parameter.
    • DeviceSecret: the DeviceSecret of the device. You can log on to the IoT Platform console and view the DeviceSecret on the Device Details page.
    • content: all parameters that are submitted to IoT Platform, except for the version, sign, resources, and signmethod parameters. The values are spliced in sequence based on the alphabetical order of the parameters. No splicing symbol is used to separate the values.
      Note The parameter values that are used to calculate the signature must be the same as the parameter values that you specify in the request of device verification.

    Example:

    hmac_md5(mRPVdzSMu2nVBxzK77ERPIMxSYIv****, clientIda1NUjcV****&ff1a11e7c08d4b3db2b1500d8e0e55deviceNameff1a11e7c08d4b3db2b1500d8e0e55productKeya1NUjcV****seq10timestamp1524448722000)
    signmethodNoThe signature algorithm. Valid values: hmacmd5 and hmacsha1. Default value: hmacmd5.
    clientIdYesThe ID of the client. The client ID must be 1 to 64 characters in length. We recommend that you specify the MAC address or SN of the device as the value of the clientId parameter.
    timestampNoThe Timestamp. IoT Platform does not verify the timestamp.
    seqYesThe serial number that is contained in the verification request. The value is a random number that is generated by the device.

    Sample response:

    {"random":"ad2b3a5eb51d6****","seqOffset":1,"token":"MZ8m37hp01w1SSqoDFzo001050****.ad2b"}
    Table 3. Response parameters
    ParameterDescription
    randomThe key that is used to encrypt upstream and downstream data.
    seqOffsetThe initial offset of the seq parameter.
    tokenThe token returned if the device is verified.
  3. Submit data.

    Sample request:

    POST /topic/${topic}
    Host: ${YourEndpoint}
    Port: 5682
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: ${your_data}
    CustomOptions: number:2088, 2089
    Table 4. Parameters
    ParameterRequiredDescription
    MethodYesThe request method. Valid value: POST.
    URLYesThe URL of the topic. Format: /topic/${topic}. Replace the ${topic} variable with the topic to which the data is sent.
    HostYesThe endpoint.
    PortYesThe port number. Valid value: 5682.
    AcceptYesThe MIME type of the data that is received by the device. Valid values: application/json and application/cbor.
    Content-FormatYesThe MIME type of the upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    payloadYesThe upstream data that is encrypted by using the Advanced Encryption Standard (AES).
    Note If you use the AES to encrypt data, set the Transform parameter to AES/CBC/PKCS5Padding and the IV parameter to 543yhjy97ae7fyfg. A key is generated by using the SHA-256 algorithm.

    Example:

    If the request is deviceSecret=zPwChiLh0EaifR809D5Rc6LDIC6A****, the response is random=8fe3c8d50e10****.
    1. Combine the values of the deviceSecret and random parameters to form a string in the ${deviceSecret},${random} format.
      zPwChiLh0EaifR809D5Rc6LDIC6A****,8fe3c8d50e10****
    2. IoT Platform encodes the preceding string in the UTF-8 format, encrypts the encoded string by using the SHA-256 algorithm, and then converts the string into a hexadecimal string.
      59ea5ac1cb092e5910c405821119959e5297516d185b71e344735cf3f268****
    3. IoT Platform uses the subString(16,48) function to extract a sub-string of 32 characters from the preceding string to form a key. The extraction starts from the 17th character of the string.
      10c405821119959e5297516d185b71e3
    CustomOptionsYesThe custom option. Valid values:
    • 2088: the token parameter. Use the value of the token parameter that is returned after the device is verified.
      Note The token parameter is required when the device submits data. If the token has expired, you must re-verify the device and obtain another token.
    • 2089: the seq parameter. The value must be greater than the value of the seqOffset parameter. The value must be a random number that is unique during the validity period of the verification. We recommend that you use a value that is incremented based on the seq parameter in each request and use the AES to encrypt the value.

    Sample response:

    number:2090

    2090: the ID of the message in IoT Platform.

    You can specify the token and seq parameters in the CustomOptions parameter. You can also specify the token and seq parameters in the URL parameter. Example: /topic/${topic}?token=xxxx&seq=xxxxx. If you specify the token and seq parameters for the CustomOptions and URL parameters at the same time, the CustomOptions parameter is used.

    After a message is sent to IoT Platform, a status code that indicates a successful request and a message ID that is generated by IoT Platform are returned.

Connect devices to IoT Platform over DTLS

  1. Connect to the CoAP server.
    Endpoints: For information about how to connect a device to the endpoint of a public instance or Enterprise Edition instance over CoAP, see View the endpoint of an instance.
  2. Download the root certificate for DTLS secure channels. Then, you can use the DTLS libraries to connect the device to IoT Platform.
    psk_id: "${authType}" + "|" + "${signMethod}" + "|" + "${productKey}" + "&" + "${deviceName}" + "timestamp"
    psk: signMethod(DeviceSecret, "${productKey}" + "&" + "${deviceName}" + "${timestamp}")
    Table 5. Parameters
    ParameterRequiredDescription
    authTypeYesThe verification type. Valid value: devicename.
    signMethodYesThe signature algorithm. Valid values: hmacmd5, hmacsha1, and hmacsha256.
    productKeyYesThe ProductKey of the product to which the device belongs.
    deviceNameYesThe DeviceName of the device.
    DeviceSecretYesThe DeviceSecret of the device.
    timestampYesThe timestamp.
  3. Verify the device. You can use the auth operation to verify the device and obtain a token. The token parameter is required when the device submits data.

    Sample request:

    POST /auth
    Host: ${YourEndpoint}
    Port: 5684
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: {"productKey":"ZG1EvTE****","deviceName":"NlwaSPXsCpTQuh8FxBGH","clientId":"mylight1000002","sign":"bccb3d2618afe74b3eab12b94042****"}

    For more information about the required parameters and payload parameters except for the Port parameter, see Connect devices by using symmetric encryption.

    Sample response:

    response: {"token":"f13102810756432e85dfd351eeb4****"}
    Table 6. Response codes
    CodeMessagePayloadDescription
    2.05ContentA token if the device passes the verification.The request is valid.
    4.00Bad Requestno payloadThe payload in the request is invalid.
    4.01Unauthorizedno payloadThe request is unauthorized.
    4.03Forbiddenno payloadThe request is forbidden.
    4.04Not Foundno payloadThe requested URL does not exist.
    4.05Method Not Allowedno payloadThe request method is not allowed.
    4.06Not Acceptableno payloadThe Accept parameter is invalid.
    4.15Unsupported Content-Formatno payloadThe requested content is invalid.
    5.00Internal Server Errorno payloadThe request failed because a timeout issue or an error occurs on the verification server.
  4. Submit data.
    The device submits data to IoT Platform by using a custom topic.

    You can create a custom topic in the IoT Platform console. Go to the Product Details page of the product to which the device belongs, and click the Topic Categories tab. Only topics that have the Publish permission can be used to submit data.

    For example, a topic is in the /${YourProductKey}/${YourDeviceName}/pub format. If the DeviceName is device and the ProductKey is a1GFjLP ****, you can use the a1GFjLP****.coap.cn-shanghai.link.aliyuncs.com:5684/topic/a1GFjLP****/device/pub topic to submit data.

    Sample request:

    POST /topic/${topic}
    Host: ${YourEndpoint}
    Port: 5684
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: ${your_data}
    CustomOptions: number:2088
    Table 7. Parameters
    ParameterRequiredDescription
    MethodYesThe request method. Valid value: POST.
    URLYes/topic/${topic}. Replace the ${topic} variable with the topic to which the data is sent.
    HostYesThe endpoint.
    PortYesThe port number. Valid value: 5684.
    AcceptYesThe MIME type of the data that is received by the device. Valid values: application/json and application/cbor.
    Content-FormatYesThe MIME type of the upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    CustomOptionsYes
    • number: Set the value to 2088.
    • token: the token that is returned by the verification service.
    Note The token parameter is required when the device submits data. If the token has expired, you must re-verify the device and obtain another token.

Example

For information about the example on how to connect devices to IoT Platform over CoAP, see Connect a device to IoT Platform by using CoAP.