Devices can be connected over HTTPS to IoT Platform only in the China (Shanghai) region. The HTTPS communication method is available only for scenarios where devices report data to IoT Platform. Only the POST request method is supported. A device can report a maximum of 128 KB of data at a time.

Background information

This topic describes how to enable communication between a device and IoT Platform by using HTTPS and report data from the device to IoT Platform. It uses an environmental sensor as an example.

HTTPS

Create a product and add a device

In the IoT Platform console, create a product, add a device to the product, create a Thing Specification Language (TSL) model, and obtain certificate information about the device. The certificate information includes the ProductKey, DeviceName, and DeviceSecret parameters.

  1. Log on to the IoT Platform console.
  2. On the Overview page, find the instance and click the instance name to go to the Instance Details page.
    Notice Enterprise Edition instances are available only in the China (shanghai) and Japan (Tokyo) region. If your IoT Platform is not activated in the China (shanghai) or Japan (Tokyo) region, skip this step.
    Overview
  3. In the left-side navigation pane, choose Devices > Products. On the Products page, click Create Product to create a product.
    Parameter Description
    Product Name The name of the product.
    [DO NOT TRANSLATE] [DO NOT TRANSLATE]
    Node Type Select Directly Connected Device.
    Network Connection Method Select Wi-Fi.
    Data Type Select ICA Standard Data Format (Alink JSON).
    Authentication Mode Select Device Secret.
  4. After the product is created, click Create TSL.
  5. On the Define Feature tab of the Product Details page, choose Edit Draft > Add Self-defined Feature to add properties.
    The environmental sensor will report temperature data and humidity data. Therefore, you must add the following properties.
    Feature type Feature name Identifier Data type Value range Step Read/write type
    Property Temperature temperature int32 -10 to 50 1 Read-only
    Property Humidity humidity int32 1 to 100 1 Read-only
  6. After the TSL model is created, click Release Online to publish the TSL model.
  7. In the left-side navigation pane, click Devices and click Add Device to add a device to the product.
    After the device is added, obtain the values of ProductKey, DeviceName, and DeviceSecret parameters.

Send data from a device to a topic

Use HTTPS to enable communication between a device and IoT Platform and use POST requests to report temperature data and humidity data.

  1. Obtain a device token.

    When a device attempts to communicate with IoT Platform, IoT will authenticate the device. After the authentication is complete, a device token is returned. The token is required when the device reports data to IoT Platform.

    The following table lists the parameters that you must specify to obtain a device token.

    Parameter Description
    method The request method. You must specify POST for the parameter.
    uri Specify https://iot-as-http.cn-shanghai.aliyuncs.com/auth.
    productKey The product key. You can obtain the information from the Device Details page of the IoT Platform console.
    deviceName The name of the device. You can obtain the information from the Device Details page of the IoT platform console.
    clientId The client ID. The ID can be a maximum of 64 characters in length. The ID can be the MAC address or SN of the device. The following sample code uses the random() function to generate a random ID.
    timestamp The timestamp. The following sample code uses the now() function to obtain a timestamp.
    signmethod The type of the algorithm. Valid values: hmacmd5 and hmacsha1.
    sign The signature. Use the following function to generate a signature.
    password = signHmacSha1(params, deviceConfig.deviceSecret)

    Use the following code to obtain a device token.

    var rp = require('request-promise');
    const crypto = require('crypto');
    
    const deviceConfig = {
        productKey: "<yourProductKey>",
        deviceName: "<yourDeviceName>",
        deviceSecret: "<yourDeviceSecret>"
    }
    
    //Obtain a token.
    rp(getAuthOptions(deviceConfig))
        .then(function(parsedBody) {
            console.log('Auth Info :',parsedBody)
        })
        }).catch(function (err) {
            console.log('Auth err :'+JSON.stringify(err))
        });
    
    //Specify the required parameters for authentication.
    function getAuthOptions(deviceConfig) {
    
        const params = {
            productKey: deviceConfig.productKey,
            deviceName: deviceConfig.deviceName,
            timestamp: Date.now(),
            clientId: Math.random().toString(36).substr(2),
        }
    
        //Specify the required parameters.
        var password = signHmacSha1(params, deviceConfig.deviceSecret);
    
        var options = {
            method: 'POST',
            uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/auth',
            "body": {
                "version": "default",
                "clientId": params.clientId,
                "signmethod": "hmacSha1",
                "sign": password,
                "productKey": deviceConfig.productKey,
                "deviceName": deviceConfig.deviceName,
                "timestamp": params.timestamp
            },
            json: true
        };
    
        return options;
    }
    
    //HmacSha1 sign
    function signHmacSha1(params, deviceSecret) {
    
        let keys = Object.keys(params).sort();
        // Sort parameters in the alphabetical order.
        keys = keys.sort();
        const list = [];
        keys.map((key) => {
            list.push(`${key}${params[key]}`);
        });
        const contentStr = list.join('');
        return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
    }
    After you specify the required parameters in the code, run the code to initiate device authentication. If the authentication is successful, a device token is returned.token
    Note A device token will expire after seven days. Make sure that you have solutions to token expiration issues.
  2. Report data from the device.

    After a device is authenticated, a token is returned. You can specify the token for the password parameter that is required for data reporting.

    The following table lists the parameters that you must specify to report data.

    Parameter Description
    method The request method. You must specify POST.
    uri The syntax is https://iot-as-http.cn-shanghai.aliyuncs.com/topic + topic. The URL consists of the HTTP endpoint of IoT Platform and the name of a topic.
    The second topic specifies the name of a topic of the following syntax:
    /sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post
    body The data to report.
    password The device token.
    Content-Type The content type of the data. Set the value to application/octet-stream.

    The following code shows how to report data.

    const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
    //Report data.
    pubData(topic, token, getPostData())
    
    function pubData(topic, token, data) {
    
        const options = {
            method: 'POST',
            uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/topic' + topic,
            body: data,
            headers: {
                password: token,
                'Content-Type': 'application/octet-stream'
            }
        }
    
        rp(options)
            .then(function(parsedBody) {
                console.log('publish success :' + parsedBody)
            })
            .catch(function(err) {
                console.log('publish err ' + JSON.stringify(err))
            });
    
    }
    // Create test data that conforms to the TSL model.
    function getPostData() {
        var payloadJson = {
            id: Date.now(),
            params: {
                humidity: Math.floor((Math.random() * 20) + 60),
                temperature: Math.floor((Math.random() * 20) + 10)
            },
            method: "thing.event.property.post"
        }
    
        console.log("===postData\n topic=" + topic)
        console.log(payloadJson)
    
        return JSON.stringify(payloadJson);
    }
    After you specify the required parameters in the code, run the code to report data. Then, view the results in local logs.log

    To find the temperature data and humidity data that are reported from the device, follow these steps: Log on to the IoT Platform console. Go to the Device Details page. View the data on the Status tab. If data is displayed as expected, it indicates that the device is connected to IoT Platform and the data is reported.

For more information about HTTPS communication, see Establish connections over HTTPS.