Todos los productos
Search
Centro de documentos

IoT Platform:Ejemplo

Última actualización: Sep 07, 2026

Este artículo describe cómo llamar a las operaciones de API de Link SDK for C para conectar dispositivos basados en HTTPS con IoT Platform y recibir mensajes. En este ejemplo se utiliza el archivo de código de muestra ./demos/http_basic_demo.

Contexto

Para obtener más información sobre las conexiones HTTPS, consulte Overview.

Paso 1: Inicializar un cliente

Agregue la dependencia subyacente y configure la función de salida de registros. Después, utilice la operación aiot_http_init para crear una instancia de cliente e inicializar los parámetros predeterminados.

 /* 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();

Paso 2: Configurar las funciones obligatorias

Llame a la operación aiot_http_setopt para configurar los siguientes elementos:

  1. Set connection parameters.

  2. Configure event callbacks.

Para obtener más información sobre los parámetros de la operación, consulte aiot_http_option_t.

  1. Establezca los parámetros de conexión.

    • Código de muestra

          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);
                                      
    • Parámetros:

      Parámetro

      Ejemplo

      Descripción

      http_host

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

      El endpoint.

      • Si utiliza una instancia de Enterprise Edition o una instancia pública activada el 30 de julio de 2021 o después, consulte el endpoint en la página Instance Details. Haga clic en View Development Configurations en la esquina superior derecha. El endpoint se muestra en el panel Development Configurations.

      • Si utiliza una instancia pública activada antes del 30 de julio de 2021, el endpoint es https://iot-as-http.${YourRegionId}.aliyuncs.com.

      product_key

      a18wP

      La información de autenticación del dispositivo. Para obtener más información, consulte Obtain device verification information.

      En este ejemplo se utiliza el método de autenticación de certificado único por dispositivo.

      device_name

      LightSwitch

      device_secret

      uwMTmVAMnGGHaAkqmeDY6cHxxB

  2. Configure el monitoreo de estado.

    1. Especifique las devoluciones de llamada para monitorear el estado.

      • Código de muestra

            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);
        
        }
      • Parámetros:

        Parámetro

        Ejemplo

        Descripción

        AIOT_HTTPOPT_RECV_HANDLER

        demo_http_recv_handler

        Cuando el dispositivo recibe un mensaje de respuesta, se llama a esta devolución de llamada para ejecutar las operaciones necesarias.

        AIOT_HTTPOPT_EVENT_HANDLER

        demo_http_event_handler

        Cuando el token cambia, se llama a esta devolución de llamada para garantizar la validez del token.

    2. Defina la devolución de llamada para monitorear el estado.

      • Cuando el token cambia, se llama a esta devolución de llamada para ejecutar las operaciones necesarias.

        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);
            }
        }
      • Cuando se lee un mensaje de red, se llama a esta devolución de llamada para ejecutar las operaciones necesarias. En este ejemplo, el mensaje se imprime. Al definir la lógica de procesamiento, tenga en cuenta los siguientes puntos.

        • Para obtener más información sobre los parámetros de un mensaje de respuesta, consulte Connect and communicate over HTTPS.

        • Un mensaje recibido contiene las siguientes secciones: AIOT_HTTPRECV_STATUS_CODE, AIOT_HTTPRECV_HEADER y AIOT_HTTPRECV_BODY. Estas secciones indican el código de estado, el tipo de mensaje y el cuerpo del mensaje, respectivamente.

        • Procese los códigos de estado según sus necesidades de negocio. Para obtener más información sobre los códigos de estado, consulte la lista de códigos de estado HTTP.

        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;
        
            }
        }

Paso 3: Establecer una conexión

Llame a la operación aiot_http_auth para enviar una solicitud de autenticación a IoT Platform y obtener un token. Para obtener información sobre cómo especificar los parámetros, consulte 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;
    }

Paso 4: Enviar un mensaje

Llame a la operación aiot_http_send dentro de la función demo_http_post_lightswitch para enviar un mensaje a un tema específico.

Nota
  • En este ejemplo, los mensajes enviados se imprimen. Puede personalizar la función demo_http_post_lightswitch según sus necesidades de negocio.

  • Debe eliminar los símbolos de comentario a ambos lados del código de muestra para enviar mensajes a IoT Platform.

  • Código de muestra

    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;
        }
        ...
        ...
    }
  • Parámetros:

    Parámetro

    Ejemplo

    Descripción

    data[]

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

    El mensaje que se envía a IoT Platform.

    En este ejemplo se utiliza un tema personalizado. Por lo tanto, puede personalizar el formato del mensaje.

    Para obtener más información sobre los formatos de mensaje, consulte Data formats.

    topic

    /a1wAf/LightSwitch/user/update

    El tema que tiene el permiso Publish.

    • a18wP indica el ProductKey del dispositivo.

    • LightSwitch indica el DeviceName del dispositivo.

    El dispositivo puede enviar mensajes a IoT Platform mediante este tema.

    Para obtener más información sobre los temas, consulte What is a topic.

Paso 5: Recibir una respuesta

Después de enviar el mensaje, IoT Platform devuelve un mensaje de respuesta. El dispositivo llama a la operación aiot_http_recv para recibir los datos de respuesta HTTPS y procesarlos mediante la devolución de llamada de eventos.

    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;
    }

Paso 6: Salir del programa

Llame a la operación aiot_http_deinit para destruir la instancia de cliente HTTPS y liberar recursos.

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

    return 0;

Qué hacer a continuación

  • Una vez configurado el archivo de código de muestra, compílelo para generar un archivo ejecutable. En este ejemplo se genera el archivo ejecutable ./output/http-basic-demo.

    Para obtener más información, consulte Compilation and running.

  • Para obtener más información sobre los resultados de ejecución, consulte Operation logs.