You can connect devices to IoT Platform over the Constrained Application Protocol (CoAP). CoAP is used for low-power and resource-constrained devices, such as NB-IoT devices. This article describes how to connect a device to IoT Platform over CoAP. It also describes how to authenticate 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
Serial number Description
1 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.
2 Connect the NB-IoT device to IoT Platform over the mobile network of a carrier. You must contact your local carrier to make sure that the NB-IoT network is available in the region where your device resides.
3 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.
4 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 transmit data to multiple Alibaba Cloud services for further processing. These services include big data services, database services, and Tablestore.
5 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.
    Endpoint: ${YourProductKey}.coap.${region}.link.aliyuncs.com:${port}.
    • Replace the ${YourProductKey} variable with the ProductKey of the product to which your device belongs. You can log on to the IoT Platform console and view the ProductKey on the Device Details page.
    • Replace the ${region} variable with your region ID. For more information about region IDs, see Regions and zones.
    • Replace the ${port} variable with your port number. Port 5682 is used for symmetric encryption.
  2. Authenticate the device.

    Sample request:

    POST /auth
    Host: ${YourEndpoint}
    Port: 5682
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: null
    Table 1. Parameters
    Parameter Description
    Method The request method. Valid value: POST.
    URL The URL. Valid value: /auth.
    Host The endpoint.
    Port The port number. Valid value: 5682.
    Accept The MIME type of the data that is received by the device. Valid values: application/json and application/cbor.
    Content-Format The MIME type of the data that the device submits to IoT Platform. Valid values: application/json and application/cbor.
    payload The JSON-formatted device information for authentication. For more information, see the following table.
    Table 2. Fields in the payload parameter
    Field Required Description
    productKey Yes The 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.
    deviceName Yes The 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.
    ackMode  No The 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.

    sign Yes 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 methods are supported.

    Required parameters:

    • signmethod: the signature algorithm. The value must be the same as the value of the specified 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 these parameters. No splicing symbol is used to separate these 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 authentication.

    Example:

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

    Sample response:

    null
    Table 3. Response parameters
    Parameter Description
    random The key that is used to encrypt upstream and downstream data.
    seqOffset The initial offset of the seq parameter.
    token The token returned if the device is authenticated.
  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
    Parameter Required Description
    Method Yes The request method. Valid value: POST.
    URL Yes The URL of the topic. Format: /topic/${topic}. Replace the ${topic} variable with the topic to which the data is sent.
    Host Yes The endpoint.
    Port Yes The port number. Valid value: 5682.
    Accept Yes The MIME type of the data that is received. Valid values: application/json and application/cbor.
    Content-Format Yes The MIME type of the upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    payload Yes The upstream data that is encrypted by using the Advanced Encryption Standard (AES).
    Note If you use 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 by using 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
    CustomOptions Yes The custom option. Valid values:
    • 2088: the token parameter. Use the value of the token parameter that is returned after the device is authenticated.
      Note Each time the device submits data, the token parameter is required. If the token expires, you must re-authenticate 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 authentication. We recommend that you use a value that is incremented based on the seq parameter in each request packet and perform AES encryption on 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 or URL parameter, for 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.
    Endpoint: ${YourProductKey}.coap.${region}.link.aliyuncs.com:${port}.
    • Replace the ${YourProductKey} variable with the ProductKey of the product to which your device belongs. You can log on to the IoT Platform console and view the ProductKey on the Device Details page.
    • Replace the ${region} variable with your region ID. For more information about region IDs, see Regions and zones.
    • Replace the ${port} variable with your port number. The default port number for DTLS is 5684.
  2. If you use an official device SDK, DTLS uses the PSK algorithm to secure channels by default.
    If you use a third-party device SDK, you must 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
    Parameter Required Description
    authType Yes The authentication type. Valid value: devicename.
    signMethod Yes The signature algorithm. Valid values: hmacmd5, hmacsha1, and hmacsha256.
    productKey Yes The ProductKey of the product to which the device belongs.
    deviceName Yes The DeviceName of the device.
    DeviceSecret Yes The DeviceSecret of the device.
    timestamp Yes The timestamp.
  3. Authenticate the device. You can use the auth operation to authenticate the device and obtain a token. Each time the device submits data to IoT Platform, the token parameter is required.

    Sample request:

    POST /auth
    Host: ${YourEndpoint}
    Port: 5684
    Accept: application/json or application/cbor
    Content-Format: application/json or application/cbor
    payload: null

    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
    Code Message Payload Description
    2.05 Content Token if the device passes the authentication. The request is valid.
    4.00 Bad Request no payload The payload in the request is invalid.
    4.01 Unauthorized no payload The request is unauthorized.
    4.03 Forbidden no payload The request is forbidden.
    4.04 Not Found no payload The requested URL does not exist.
    4.05 Method Not Allowed no payload The request method is not allowed.
    4.06 Not Acceptable no payload The Accept parameter is invalid.
    4.15 Unsupported Content-Format no payload The requested content is invalid.
    5.00 Internal Server Error no payload The request failed because a timeout issue or an error occurs on the authentication 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 for data submission.

    For example, the topic format is /${YourProductKey}/${YourDeviceName}/pub. 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
    Parameter Required Description
    Method Yes The request method. Valid value: POST.
    URL Yes /topic/${topic}. Replace the ${topic} variable with the topic to which the data is sent.
    Host Yes The endpoint.
    Port Yes The port number. Valid value: 5684.
    Accept Yes The MIME type of the data that is received. Valid values: application/json and application/cbor.
    Content-Format Yes The MIME type of the upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    CustomOptions Yes
    • number: Set the value to 2088.
    • token: the token that is returned from the authentication service.
    Note Each time the device submits data, the token parameter is required. If the token expires, you must re-authenticate the device and obtain another token.

Example

For information about the example of connecting devices to IoT Platform over CoAP, see Access IoT Platform by using CoAP.