You can connect devices to IoT Platform over 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 a NB-IoT device to IoT Platform.CoAP
Procedure:
  1. Integrate an IoT Platform SDK into the NB-IoT module of a device. A supplier applies for the device certificate in the IoT Platform console and burns the device certificate to the device.
  2. Connects the NB-IoT device to IoT Platform over the mobile network of a carrier. Contact your local carrier to make sure that the NB-IoT network is available in the region where your device resides.
  3. After the devices are connected to IoT Platform, the machine-to-machine (M2M) platform of the carrier is used to manage the data traffic and fees incurred by the NB-IoT devices.
  4. Device can collect data in real time and report 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. IoT Platform provides data access APIs and message pushing services. These features allow you to forward data to the required application servers and enable quick integration with devices and applications.

Connect devices by using symmetric encryption

  1. Connect to the CoAP server.
    Endpoint:
    • The endpoint for public instances in the China (Shanghai) region is ${YourProductKey}.coap.cn-shanghai.link.aliyuncs.com:${port}.
      • ${YourProductKey}: Replace this variable with the ProductKey of the product to which the device belongs. You can obtain the ProductKey on the Device Details page of the IoT Platform console.
      • Replace the ${port} variable with your port number. Port 5682 is used for symmetric-key algorithms.
    • You can purchase instances in the China (Shanghai) region. To view the endpoint of the instance that you purchased, perform the following steps: Log on to the IoT Platform console. In the left-side navigation pane, click Instances. On the page that appears, click View in the Actions column of the instance. On the Instance Details page, you can view the endpoint.
  2. Authenticate the device.

    Sample authentication 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 of device authentication
    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 data that is received by the device. Valid values: application/json and application/cbor.
    Content-Format The MIME type of upstream data that the device reports 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. Parameters of device information
    Parameter Required Description
    productKey Yes The product key. In IoT Platform, each product key is unique. You can obtain the information from the Device Details page of the IoT Platform console.
    deviceName Yes The device name. You can use the device name that is generated by IoT Platform, or you can specify a new device name. You can obtain the information from the Device Details page of the IoT Platform console.
    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.

    Required parameters:

    • signmethod: the signature algorithm. The value must be the same as the value of the specified signmethod parameter.
    • DeviceSecret: the device secret. In the IoT Platform console, you can view the device secret on the Device Details page.
    • content: all parameters that are reported 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 device authentication request.

    Example:

    hmac_md5(mRPVdzSMu2nVBxzK77ERPIMxSYIv****, clientIda1NUjcV****&ff1a11e7c08d4b3db2b1500d8e0e55deviceNameff1a11e7c08d4b3db2b1500d8e0e55productKeya1NUjcV****seq10timestamp1524448722000)
    signmethod No The signature algorithm. Valid values: hmacmd5 and hmacsha1. Default value: hmacmd5.
    clientId Yes The client ID. 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.

    Sample response:

    {"random":"ad2b3a5eb51d6****","seqOffset":1,"token":"MZ8m37hp01w1SSqoDFzo001050****.ad2b"}
    Table 3. Response parameters
    Parameter Description
    random The key that is used to encrypt upstream and downstream data.
    seqOffset The offset.
    token The returned token in the case of successful authentication.
  3. Report data.

    Sample request of data reporting:

    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(token), 2089(seq)
    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 data is sent.
    Host Yes The endpoint.
    Port Yes The port number. Valid value: 5682.
    Accept Yes The MIME type of data that is received by the device. Valid values: application/json and application/cbor.
    Content-Format Yes The MIME type of upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    payload Yes The AES-encrypted upstream data.
    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 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 result to form a key. The sub-string starts in position 17.
      10c405821119959e5297516d185b71e3
    CustomOptions Yes Valid values:
    • 2088: the token. The value is the token that is returned after the device is authenticated.
      Note Each time the device reports data, the token is required. If the token expires, you must authenticate the device again and obtain another token.
    • 2089: the seq. The value must be greater than the value of the seqOffset parameter. The value is a random digit. The digit must be unique during the validity period for authentication.

    Sample response:

    number:2090 (IoT Platform message ID)

    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 setting of the CustomOptions parameter has a higher priority.

    After a message is reported, 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:
    • The endpoint for public instances in the China (Shanghai) region is ${YourProductKey}.coap.cn-shanghai.link.aliyuncs.com:${port}.
      • Replace the ${YourProductKey} variable with your product key. You can obtain the ProductKey on the Device Details page of the IoT Platform console.
      • Replace the ${port} variable with your port number. Default port number for DTLS is 5684.
    • You can purchase instances in the China (Shanghai) region. To view the endpoint of the instance that you purchased, perform the following steps: Log on to the IoT Platform console. In the left-side navigation pane, click Instances. On the page that appears, click View in the Actions column of the instance. On the Instance Details page, you can view the endpoint.
  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 product key.
    deviceName Yes The device name.
    DeviceSecret Yes The device secret.
    timestamp Yes The timestamp.
  3. Authenticate the device. You can use the authentication service to authenticate the device and obtain a token. Each time the device reports data to IoT Platform, the token information is required.

    Sample authentication 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
    Code Description Payload Description
    2.05 Content The returned token in the case of successful authentication The request is valid.
    4.00 Bad Request no payload The payload of the request is invalid.
    4.01 Unauthorized no payload The request is unauthorized.
    4.03 Forbidden no payload The request is denied.
    4.04 Not Found no payload The requested path does not exist.
    4.05 Method Not Allowed no payload The request method is invalid.
    4.06 Not Acceptable no payload The Accept parameter is invalid.
    4.15 Unsupported Content-Format no payload The Content parameter is invalid.
    5.00 Internal Server Error no payload The request failed because the timeout issue or an error occurs on the authentication server.
  4. Report data.

    The device reports data to the required 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.

    The device can report data only to a topic that allows the publish access, for example, /${YourProductKey}/${YourDeviceName}/pub. If the device name is device and product key is a1GFjLP****, the device reports data to the a1GFjLP****.coap.cn-shanghai.link.aliyuncs.com:5684/topic/a1GFjLP****/device/pub topic.

    Sample request for data reporting:

    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(token)
    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 data is sent.
    Host Yes The endpoint.
    Port Yes The port number. Valid value: 5684.
    Accept Yes The MIME type of data that is received by the device. Valid values: application/json and application/cbor.
    Content-Format Yes The MIME type of upstream data. IoT Platform does not verify the data. Valid values: application/json and application/cbor.
    CustomOptions Yes
    • number: 2088.
    • token: the token that is returned from the authentication service.
    Note Each time the device reports data, the token is required. If the token expires, you must re-authenticate the device and obtain another token.