La demostración ./demos/cota_basic_demo.c muestra cómo implementar la configuración remota de un dispositivo.
Contexto
Para obtener más información sobre la función de configuración remota, consulte Overview.
La función de configuración remota requiere una conexión MQTT. Para obtener más información sobre las conexiones MQTT, consulte MQTT connection.
no heading
Paso 1: Inicialización
-
Agregue el archivo de encabezado.
…… …… #include "aiot_ota_api.h" …… -
Configure las dependencias subyacentes y la salida de registros.
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); aiot_state_set_logcb(demo_state_logcb); -
Llame a aiot_ota_init para crear una instancia OTA.
ota_handle = aiot_ota_init(); if (NULL == ota_handle) { printf("aiot_ota_init failed\r\n"); aiot_mqtt_deinit(&mqtt_handle); return -2; }
Paso 2: Configure las funciones
Llame a aiot_ota_setopt para configurar a continuación las siguientes opciones.
-
Asocie el handle de la conexión MQTT.
ImportanteAntes de establecer los parámetros de configuración remota,
asegúrese de que los parámetros como las credenciales del dispositivo estén configurados. Para obtener más información, consulte
Configure MQTT connection parameters
.
-
aiot_ota_setopt(ota_handle, AIOT_OTAOPT_MQTT_HANDLE, mqtt_handle); -
Elemento de configuración
Ejemplo
Descripción
AIOT_OTAOPT_MQTT_HANDLE
mqtt_handle
Las solicitudes de configuración remota usan una conexión MQTT. Este elemento asocia el handle de dicha conexión.
-
-
Establezca la devolución de llamada para los mensajes de instrucción de configuración remota.
-
aiot_ota_setopt(ota_handle, AIOT_OTAOPT_RECV_HANDLER, demo_ota_recv_handler); -
Elemento de configuración
Ejemplo
Descripción
AIOT_OTAOPT_MQTT_HANDLE
demo_ota_recv_handler
Se invoca cuando el dispositivo recibe una instrucción de configuración remota de IoT Platform.
-
Paso 3: Un dispositivo solicita activamente mensajes de configuración
Si un dispositivo está desconectado cuando IoT Platform envía una instrucción de configuración remota, puede solicitarla después de conectarse.
Si no se creó ninguna tarea de dispositivo en IoT Platform, la llamada a la API devuelve
receive task get detail reply, task_id:[$next],status:[9]
.
-
Llame a aiot_mqtt_pub para enviar una solicitud a IoT Platform y obtener la información de configuración remota.
-
{ char *topic_string = "/sys/a18wP******/LightSwitch/thing/config/get"; char *payload_string = "{\"id\":\"123\",\"params\":{\"configScope\":\"product\",\"getType\":\"file\"}}"; res = aiot_mqtt_pub(mqtt_handle, topic_string, (uint8_t *)payload_string, strlen(payload_string), 0); if (res < STATE_SUCCESS) { printf("aiot_mqtt_pub failed: -0x%04X\r\n", -res); /* If the connection fails, destroy the MQTT instance and release resources. */ goto exit; } } -
Parámetro Valor de ejemplo Descripción topic_string /sys/a18wP******5/LightSwitch/thing/config/get El tema que se usa para solicitar la información de configuración remota. Para obtener más información sobre los temas, consulte What is a topic?.
En el código de ejemplo:
a18wPes el ProductKey del dispositivo.LightSwitches el DeviceName del dispositivo.
Para obtener más información, consulte Obtain device credentials.
payload_string {\"id\":\"123\",\"params\":{\"configScope\":\"product\",\"getType\":\"file\"}} El contenido del mensaje de solicitud. El mensaje de solicitud tiene formato JSON. Corresponde al valor de params en los datos con formato Alink. Para obtener más información, consulte A device actively requests configuration information.
-
-
Cuando IoT Platform recibe la solicitud, devuelve la información de configuración al dispositivo.
NotaEl tamaño máximo del contenido de configuración remota es de 64 KB.
Habilite la configuración remota y edítela en la
. Para obtener más información, consulte
.
-
Llame a aiot_mqtt_recv para recibir el mensaje de instrucción de configuración remota.
Si el puntero
g_dl_handlees nulo, el sistema solo sondea los mensajes MQTT de la red.Si el puntero
g_dl_handleno es nulo, se llama a la funciónaiot_download_recv.
while (1) { aiot_mqtt_process(mqtt_handle); res = aiot_mqtt_recv(mqtt_handle); if (res == STATE_SYS_DEPEND_NWK_CLOSED) { sleep(1); } if (NULL != g_dl_handle) { /* Before the remote configuration is received, change the MQTT message receiving timeout period to 100 ms to reduce the interval between two remote configuration downloads. */ int32_t ret = aiot_download_recv(g_dl_handle); timeout_ms = 100; if (STATE_DOWNLOAD_FINISHED == ret) { aiot_download_deinit(&g_dl_handle); /* After the remote configuration is received, change the MQTT message receiving timeout period back to the default value of 5000 ms. */ timeout_ms = 5000; } aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms); } } -
Después de que el dispositivo recibe el mensaje de instrucción de configuración, se activa la función de devolución de llamada
demo_ota_recv_handler.Use la siguiente información para escribir la lógica de procesamiento de la función de devolución de llamada:
IoT Platform envía instrucciones de configuración remota al dispositivo mediante el tema
/sys/${ProductKey}/${DeviceName}/thing/config/push.Link SDK analiza sintácticamente las instrucciones de IoT Platform en una estructura de datos aiot_ota_recv_t y procesa automáticamente los mensajes de configuración.
El tipo de mensaje para la configuración remota es AIOT_OTARECV_COTA.
Dentro de la función de devolución de llamada, inicie una solicitud HTTPS para descargar el archivo de configuración remota. Para obtener información sobre cómo escribir esta función, consulte Step 5: Download the remote configuration file.
Paso 4: Un dispositivo recibe la información de configuración remota enviada por IoT Platform
Si el dispositivo está conectado, recibe de inmediato la instrucción de configuración remota de IoT Platform y activa la función de devolución de llamada.
Para obtener más información, consulte Write the processing logic for the callback function.
Paso 5: Descargue el archivo de configuración remota
El dispositivo no descarga automáticamente el archivo de configuración después de recibir la instrucción correspondiente. Llame a la API de Link SDK para iniciar la descarga.
-
Inicialice el descargador.
Llame a
para crear una
descarga
uint32_t res = 0; uint16_t port = 443; uint32_t max_buffer_len = 2048; aiot_sysdep_network_cred_t cred; void *dl_handle = aiot_download_init(); if (NULL == dl_handle || NULL == ota_msg->task_desc) { return; } printf("configId: %s, configSize: %u Bytes\r\n", ota_msg->task_desc->version, ota_msg->task_desc->size_total); memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; cred.max_tls_fragment = 16384; cred.x509_server_cert = ali_ca_cert; cred.x509_server_cert_len = strlen(ali_ca_cert); -
Configure los parámetros de descarga.
Llame a
para configurar los parámetros de la tarea de descarga.
/* Set the download method to TLS download. */ if ((STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_CRED, (void *)(&cred))) || /* Set the server port for the download. */ (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_PORT, (void *)(&port))) || /* Set the information about the download task. This information is obtained from the task_desc member of the ota_msg input parameter. It includes the download URL, and the size and version number of the remote configuration. */ (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_TASK_DESC, (void *)(ota_msg->task_desc))) || /* Set the callback function that the SDK calls when the downloaded content arrives. */ (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_RECV_HANDLER, (void *)(demo_download_recv_handler))) || /* Set the maximum buffer length for a single download. The user is notified each time the buffer is full. */ (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_BODY_BUFFER_MAX_LEN, (void *)(&max_buffer_len))) || /* Send an HTTP GET request to the HTTP server. */ (STATE_SUCCESS != aiot_download_send_request(dl_handle))) { if (res != STATE_SUCCESS) { aiot_download_deinit(&dl_handle); break; } } -
Una vez enviada la solicitud de descarga, el dispositivo recibe un mensaje de confirmación que activa la función de devolución de llamada
demo_download_recv_handlerpara procesar la descarga.Use la siguiente información para escribir la lógica de procesamiento de la función de devolución de llamada:
La estructura de datos del mensaje de descarga es aiot_download_recv_t. Este es un parámetro de entrada de la función de devolución de llamada.
El campo
packet->typedel mensaje de descarga es AIOT_DLRECV_HTTPBODY.El código de ejemplo solo imprime los datos. Descargue el archivo de configuración en una ubicación específica.
void demo_download_recv_handler(void *handle, const aiot_download_recv_t *packet, void *userdata) { /* Currently, only the case where packet->type is AIOT_DLRECV_HTTPBODY is supported. */ if (!packet || AIOT_DLRECV_HTTPBODY != packet->type) { return; } int32_t percent = packet->data.percent; uint8_t *src_buffer = packet->data.buffer; uint32_t src_buffer_len = packet->data.len; /* If percent is a negative number, a packet reception exception or a digest verification error occurred. */ if (percent < 0) { /* A packet reception exception or a digest verification error occurred. */ printf("exception happend, percent is %d\r\n", percent); return; } …… …… } -
Llame a aiot_download_report_progress para reportar el progreso de la descarga.
void demo_download_recv_handler(void *handle, const aiot_download_recv_t *packet, void *userdata) { /* Currently, only the case where packet->type is AIOT_DLRECV_HTTPBODY is supported. */ if (!packet || AIOT_DLRECV_HTTPBODY != packet->type) { return; …… …… aiot_download_report_progress(handle, percent); printf("config len is %d, config content is %.*s\r\n", src_buffer_len, src_buffer_len, (char *)src_buffer); } -
Cuando finalice la descarga, llame a aiot_download_deinit para establecer el handle
g_dl_handlecomo nulo.while (1) { aiot_mqtt_process(mqtt_handle); res = aiot_mqtt_recv(mqtt_handle); if (res == STATE_SYS_DEPEND_NWK_CLOSED) { sleep(1); } if (NULL != g_dl_handle) { /* Before the remote configuration is received, change the MQTT message receiving timeout period to 100 ms to reduce the interval between two remote configuration downloads. */ int32_t ret = aiot_download_recv(g_dl_handle); timeout_ms = 100; if (STATE_DOWNLOAD_FINISHED == ret) { aiot_download_deinit(&g_dl_handle); /* After the remote configuration is received, change the MQTT message receiving timeout period back to the default value of 5000 ms. */ timeout_ms = 5000; } aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms); } }
Paso 6: Salir del programa
Llame a aiot_ota_deinit para destruir la instancia OTA.
aiot_ota_deinit(&ota_handle);
Pasos siguientes
-
./output/cota-basic-demo.
Para obtener más información, consulte Compile and run.