All Products
Search
Document Center

IoT Platform:Example

Last Updated:Jul 07, 2023

This article describes how to call the API operations of Link SDK for C toconnect HTTPS-baseddevices with IoT Platform and receive messages. In this example, the ./demos/http_basic_demosample code file is used.

Background information

For more information about HTTPS connections, see Overview.

Step 1: Initialize a client

Add the underlying dependency and configure the log output feature, the aiot_http_init operation to create a client instance and initialize the default parameters.

 /* Add the underlying dependencies to the SDK. */
    aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
    /* Configure the log output feature for the SDK. */
    aiot_state_set_logcb(demo_state_logcb);
    ...
    ...

    /* Create an HTTPS client instance and set the default parameters. */
    http_handle = aiot_http_init();

Step 2: Configure required features

Call the aiot_http_setopt operation to configure the following items:

  1. Set connection parameters.

  2. Configure event callbacks.

For more information about the parameters of the operation, see aiot_http_option_t.

  1. Set connection parameters.

    • Sample code

          char       *http_host = "iot-as-http.cn-shanghai.aliyuncs.com";
          ...
          aiot_sysdep_network_cred_t cred;
          char *product_key       = "a18wP******";
          char *device_name       = "LightSwitch";
          char *device_secret     = "uwMTmVAMnGGHaAkqmeDY6cHxxB******";
          ...
          ...
      
          /* Set the domain name of the HTTPS server.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_HOST, (void *)host);
          /* Set the server port.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_PORT, (void *)&port);
          /* Set the security credential of the device.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_NETWORK_CRED, &cred);
          /* Set the ProductKey of the device.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_PRODUCT_KEY, product_key);
          /* Set the DeviceName of the device.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_DEVICE_NAME, device_name);
          /* Set the DeviceSecret of the device.  */
          aiot_http_setopt(http_handle, AIOT_HTTPOPT_DEVICE_SECRET, device_secret);
                                      
    • Parameters:

      Parameter

      Example

      Description

      http_host

      iot-06z00ax1o******.http.iothub.aliyuncs.com

      The endpoint.

      • If you use an Enterprise Edition instance, or a public instance that is activated on July 30, 2021 or later, view the endpoint on the Instance Details page. Click View Development Configurations in the upper-right corner. On the Development Configurations panel, the endpoint is displayed.

      • If you use a public instance that is activated before July 30, 2021, the endpoint is https://iot-as-http.${YourRegionId}.aliyuncs.com.

      product_key

      a18wP******

      The device authentication information. For more information, see Obtain device authentication information.

      In this example, the unique-certificate-per-device authentication method is used.

      device_name

      LightSwitch

      device_secret

      uwMTmVAMnGGHaAkqmeDY6cHxxB******

  2. Configure status monitoring.

    1. Specify the callbacks to monitor status.

      • Sample code

            int main(int argc, char *argv[])
        {
            ...
            ...
        
            /* Specify the callback that is called when data arrives. */
            aiot_http_setopt(http_handle, AIOT_HTTPOPT_RECV_HANDLER, demo_http_recv_handler);
            /* Specify the callback that is called when the internal status changes. */
            aiot_http_setopt(http_handle, AIOT_HTTPOPT_EVENT_HANDLER, demo_http_event_handler);
        
        }
      • Parameters:

        Parameter

        Example

        Description

        AIOT_HTTPOPT_RECV_HANDLER

        demo_http_recv_handler

        When the device receives a response message, the callback is called to perform the required operations.

        AIOT_HTTPOPT_EVENT_HANDLER

        demo_http_event_handler

        When the token changes, the callback is called to ensure the validity of the token.

    2. Define the callback to monitor status.

      • When the token changes, the callback is called to perform the required operations.

        void demo_http_event_handler(void *handle, const aiot_http_event_t *event, void *user_data)
        {
            int32_t res;
        
            /* Handle expired tokens. */
            if (event->type == AIOT_HTTPEVT_TOKEN_INVALID) {
                printf("token invalid, invoke iot_http_auth to get new token\n");
                res = aiot_http_auth(handle);
                printf("aiot_http_auth in callback, res = -0x%04x\r\n", -res);
            }
        }
      • When a network message is read, the callback is called to perform the required operations. In this example, the message is printed. When you specify the processing logic, take note of the following items.

        • For more information about the parameters of a response message, see Establish connections over HTTPS.

        • A received message contains the following sections: AIOT_HTTPRECV_STATUS_CODE, AIOT_HTTPRECV_HEADER, and AIOT_HTTPRECV_BODY. These sections indicate the status code, message type, and message body, respectively.

        • Process status codes based on your business needs. For more information about status codes, see List of HTTP status codes.

        void demo_http_recv_handler(void *handle, const aiot_http_recv_t *packet, void *userdata)
        {
            switch (packet->type) {
                case AIOT_HTTPRECV_STATUS_CODE: {
                    /* TODO: If the following code is not annotated, the SDK receives a message and prints the HTTPS status code by using this callback, such as 404, 200, and 302.  */
                    /* printf("status code: %d\n", packet->data.status_code.code); */
                }
                break;
        
                case AIOT_HTTPRECV_HEADER: {
                    /* TODO: If the following code is not annotated, the SDK receives a message and prints the HTTPS header by using this callback, such as Content-Length.  */
                    /* printf("key: %s, value: %s\n", packet->data.header.key, packet->data.header.value); */
                }
                break;
        
                /* TODO: If you need to process HTTPS response messages from IoT Platform, specify the logic. In this example, response messages are printed.  */
                case AIOT_HTTPRECV_BODY: {
                    printf("%.*s\r\n", packet->data.body.len, packet->data.body.buffer);
                }
                break;
        
                default: {
                }
                break;
        
            }
        }

Step 3: Establish a connection

Call the aiot_http_auth operation to send an authentication request to the IoT Platform and obtain a token. For information about how to specify the parameters, see Set connection parameters.

/* Initiate an authentication request and obtain a token. */
    res = aiot_http_auth(http_handle);
    if (res == 0) {
        printf("aiot_http_auth succeed\r\n");
    } else {
        /* If the authentication fails, release resources of the instance and exit the program. */
        printf("aiot_http_auth failed, res = -0x%04x\r\n", -res);
        aiot_http_deinit(&http_handle);
        return -1;
    }

Step 4: Send a message

Call the aiot_http_send operation in the demo_http_post_lightswitch function to send a message to a specified topic.

Note
  • In this example, sent messages are printed. You can customize the demo_http_post_lightswitch function based on your business needs.

  • You must delete annotation symbols on both sides of the sample code to send messages to IoT Platform.

  • Sample code

    int32_t demo_http_post_lightswitch(void *handle)
    {
        char data[] = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}";
        int32_t res;
    
        res = aiot_http_send(handle,
                             "/a1wAf******/LightSwitch/user/update",
                             (uint8_t *)data,
                             strlen(data));
        if (res < 0) {
            printf("aiot_http_send res = -0x%04X\r\n", -res);
            return res;
        }
        ...
        ...
    }
  • Parameters:

    Parameter

    Example

    Description

    data[]

    {\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}

    The message that is sent to IoT Platform.

    In this example, a custom topic is used. Therefore, you can customize the message format.

    For more information about message formats, see Data formats.

    topic

    /a1wAf******/LightSwitch/user/update

    The topic that has the Publish permission.

    • a18wP******indicates the ProductKey of the device.

    • LightSwitchindicates the DeviceName of the device.

    The device can send messages to IoT Platform by using this topic.

    For more information about topics, see Topics.

Step 5: Receive a response

After the message is sent, IoT Platform returns a response message. The device calls the aiot_http_recv operation to receive the HTTPS response data and process the data by using the event callback.

    res = aiot_http_recv(handle);
    if (res >= 0) {
        /* If a response from the server is received and the response code is 0, device data is submitted. */
        return 0;
    } else {
        printf("aiot_http_recv res = -0x%04X\r\n", -res);
        return -1;
    }

Step 6: Exit the program

Call aiot_http_deinit operation to destroy the HTTPS client instance and release resources.

    aiot_http_deinit(&http_handle);
    printf("program exit as normal return\r\n");
    printf("\r\n");

    return 0;

What to do next

  • After you configure the sample code file, compile the file to generate an executable file. In this example, the ./output/http-basic-demo executable file is generated.

    For more information, see Compilation and running.

  • For more information about running results, see View logs.