Este tema describe cómo llamar a las operaciones API de Link SDK for C para enviar solicitudes de Message Queuing Telemetry Transport (MQTT) a IoT Platform, registrar dinámicamente un dispositivo y obtener la información de verificación necesaria para activarlo. En este ejemplo se utiliza un archivo de código de muestra llamado ./demos/dynregmq_basic_demo.c.
Contexto
Cuando personalice un SDK, establezca Device authentication scheme en Dynamic registration en la página SDK customization. Antes de usar el archivo de código de muestra de este tema, asegúrese de estar familiarizado con el contenido del tema Overview.
Paso 1: Inicializar el SDK
-
Agregue los archivos de encabezado.
#include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_dynregmq_api.h" -
Agregue la dependencia subyacente y configure la función de salida de registros.
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); aiot_state_set_logcb(demo_state_logcb); -
Llame a la operación aiot_dynregmq_init para crear una instancia de cliente llamada
dynregmqe inicializar los parámetros predeterminados.dynregmq_handle = aiot_dynregmq_init(); if (dynregmq_handle == NULL) { printf("aiot_dynregmq_init failed\n"); return -1; }
Paso 2: Configurar las funciones requeridas
Llame a la operación aiot_dynregmq_setopt para configurar los siguientes elementos:
Para más información, consulte MQTT-based dynamic registration.
-
Configure los parámetros de conexión.
-
Código de muestra:
char *product_key = "a18wP******"; char *product_secret = "CpIlPVCXI7******"; char *device_name = "LightSwitch"; char *mqtt_host = "iot-06******.mqtt.iothub.aliyuncs.com"; uint8_t skip_pre_regist =1; ... /* Specify the endpoint of the server. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_HOST, (void *)host); /* Specify the port of the server. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_PORT, (void *)&port); /* Specify the ProductKey of the device. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_PRODUCT_KEY, (void *)product_key); /* Specify the ProductSecret of the device. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_PRODUCT_SECRET, (void *)product_secret); /* Specify the DeviceName of the device. aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_DEVICE_NAME, (void *)device_name); /* Specify the security credential of the connection. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_NETWORK_CRED, (void *)&cred); /* Specify whether to use the preregistration-free verification method. */ aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_NO_WHITELIST, (void *)&skip_pre_regist); ... ... -
Parámetros:
Parámetro
Ejemplos
Descripción general
mqtt_host
iot-06.mqtt.iothub.aliyuncs.com
El endpoint al que desea conectar el dispositivo.
Formato:
${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com.skip_pre_regist
1
Especifica si se debe usar el método de verificación sin prerregistro.
0: no
1: sí
ImportantePara más información sobre los métodos de verificación con prerregistro y sin prerregistro de certificado único por producto, consulte Unique-certificate-per-product verification.
product_key
a18wP
La ProductKey y la ProductSecret que guardó cuando creó el producto en la consola de IoT Platform. Para más información, consulte Create a product.
product_secret
CpIlPVCXI7
device_name
LightSwitch
El DeviceName del dispositivo.
IoT Platform comprueba el DeviceName cuando un dispositivo inicia una solicitud de activación. Se recomienda usar un identificador que pueda obtenerse del dispositivo como DeviceName. El identificador puede ser la dirección MAC, el número de identidad internacional de equipo móvil (IMEI) o el número de serie (SN) del dispositivo.
-
-
Configure una devolución de llamada de mensajes.
-
Especifique una función de devolución de llamada de mensajes.
-
Código de muestra:
int main(int argc, char *argv[]) { ... Etc. aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_RECV_HANDLER, (void *)demo_dynregmq_recv_handler); aiot_dynregmq_setopt(dynregmq_handle, AIOT_DYNREGMQOPT_USERDATA, (void *)&demo_info); ... Etc. } -
Parámetros:
Parámetro
Ejemplo
Descripción
AIOT_DYNREGMQOPT_RECV_HANDLER
demo_dynregmq_recv_handler
Configura una devolución de llamada de mensajes. Cuando se recibe un mensaje, se llama a la devolución de llamada para realizar las operaciones necesarias.
AIOT_DYNREGMQOPT_USERDATA
&demo_info
El contexto. Cuando se llama a la operación
demo_dynregmq_recv_handler, se devuelve el valor obtenido de la operación.
-
-
Defina la función de devolución de llamada de mensajes.
void demo_dynregmq_recv_handler(void *handle, const aiot_dynregmq_recv_t *packet, void *userdata) { switch (packet->type) { /* TODO: You must save the space to which the packet parameter in the callback points. After the callback returns a result, the space is released. */ case AIOT_DYNREGMQRECV_DEVICEINFO_WL: { if (strlen(packet->data.deviceinfo_wl.device_secret) >= sizeof(demo_devinfo_wl.device_secret)) { break; } /* If you use the pre-registration verification method, make sure that the device_secret parameter is persisted. */ memset(&demo_devinfo_wl, 0, sizeof(demo_devinfo_wl_t)); memcpy(demo_devinfo_wl.device_secret, packet->data.deviceinfo_wl.device_secret, strlen(packet->data.deviceinfo_wl.device_secret)); } break; /* TODO: You must save the space to which the packet parameter in the callback points. After the callback returns a result, the space is released. */ case AIOT_DYNREGMQRECV_DEVICEINFO_NWL: { if (strlen(packet->data.deviceinfo_nwl.clientid) >= sizeof(demo_devinfo_nwl.conn_clientid) || strlen(packet->data.deviceinfo_nwl.username) >= sizeof(demo_devinfo_nwl.conn_username) || strlen(packet->data.deviceinfo_nwl.password) >= sizeof(demo_devinfo_nwl.conn_password)) { break; } /* If you use the preregistration-free verification method, make sure that the clientid, username, and password parameters are persisted. */ memset(&demo_devinfo_nwl, 0, sizeof(demo_devinfo_nwl_t)); memcpy(demo_devinfo_nwl.conn_clientid, packet->data.deviceinfo_nwl.clientid, strlen(packet->data.deviceinfo_nwl.clientid)); memcpy(demo_devinfo_nwl.conn_username, packet->data.deviceinfo_nwl.username, strlen(packet->data.deviceinfo_nwl.username)); memcpy(demo_devinfo_nwl.conn_password, packet->data.deviceinfo_nwl.password, strlen(packet->data.deviceinfo_nwl.password)); } break; default: { } break; } }
-
Paso 3: Enviar una solicitud
Llame a la operación aiot_dynregmq_send_request para enviar una solicitud de registro dinámico al servidor. Para obtener información sobre cómo configurar los parámetros, consulte Configure connection parameters.
res = aiot_dynregmq_send_request(dynregmq_handle);
if (res < STATE_SUCCESS) {
printf("aiot_dynregmq_send_request failed: -0x%04X\n", -res);
return -1;
}
Paso 4: Recibir una respuesta
Después de enviar la solicitud de registro , IoT Platform devuelve una respuesta. El dispositivo llama a la operación aiot_dynregmq_recv para recibir los datos de respuesta y procesarlos mediante la devolución de llamada de mensajes.
res = aiot_dynregmq_recv(dynregmq_handle);
if (res < STATE_SUCCESS) {
printf("aiot_dynregmq_recv failed: -0x%04X\n", -res);
return -1;
}
En este ejemplo, se imprimen los datos de respuesta. Debe especificar la lógica para guardar localmente la información de verificación del dispositivo devuelta. Esta información de verificación se utiliza cuando el dispositivo se conecta a IoT Platform.
if (skip_pre_regist == 0) {
printf("device secret: %s\n", demo_devinfo_wl.device_secret);
} else {
printf("clientid: %s\n", demo_devinfo_nwl.conn_clientid);
printf("username: %s\n", demo_devinfo_nwl.conn_username);
printf("password: %s\n", demo_devinfo_nwl.conn_password);
}
Paso 5: Salir del programa
Llame a la operación aiot_dynregmq_deinit para eliminar la instancia de cliente dynregmq y liberar los recursos relacionados.
res = aiot_dynregmq_deinit(&dynregmq_handle);
Siguientes pasos
-
Después de configurar el archivo de código de muestra, compile el archivo para generar un archivo ejecutable. En este ejemplo, se genera el archivo ejecutable
./output/dynregmq-basic-demo.Para más información, consulte Prepare a development environment.
Para más información sobre los resultados de ejecución, consulte View logs.
-
Si utiliza el método de verificación sin prerregistro de certificado único por producto para verificar el dispositivo, IoT Platform emite ClientId, UserName y Password en lugar de DeviceSecret al dispositivo después de verificarlo.
Puede especificar ClientId, UserName y Password para los parámetros
AIOT_MQTTOPT_USERNAME, AIOT_MQTTOPT_PASSWORD, y AIOT_MQTTOPT_CLIENTIDen el archivomqtt_basic_demo.cy llamar a la operaciónaiot_mqtt_connectpara conectar el dispositivo a IoT Platform. El siguiente código de muestra proporciona un ejemplo de cómo realizar las operaciones anteriores:char *user_name = "demo_user_name"; char *password = "demo_passwd"; char *client_id = "demo_client_id"; aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERNAME, user_name); aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PASSWORD, password); aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CLIENTID, client_id); res = aiot_mqtt_connect(mqtt_handle);