### Example: Linux Platform HAL Implementation Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This section provides a concrete example of how to implement the HAL interfaces on a Linux platform, demonstrating the usage of standard C library functions and POSIX threads. ```APIDOC ## Example: Linux Platform HAL Implementation ### Description This example demonstrates the implementation of several HAL interfaces for the Linux platform using standard C library functions and POSIX threads. ### Memory Management - **HAL_Malloc** - Uses `malloc` for memory allocation. - **HAL_Free** - Uses `free` to deallocate memory. ### System Functions - **HAL_Printf** - Implemented using `vprintf` for formatted output. - **HAL_Snprintf** - Implemented using `vsnprintf` for safe string formatting. - **HAL_SleepMs** - Uses `usleep` to pause execution in milliseconds. - **HAL_UptimeMs** - Uses `gettimeofday` to calculate system uptime in milliseconds. ### Mutex - **HAL_MutexCreate** - Creates a POSIX mutex (`pthread_mutex_t`) and returns a pointer to it. - **HAL_MutexDestroy** - Destroys a POSIX mutex and frees the associated memory. - **HAL_MutexLock** - Locks a POSIX mutex. - **HAL_MutexUnlock** - Unlocks a POSIX mutex. ### Code Example (C) ```c #include #include #include #include #include #include void *HAL_Malloc(uint32_t size) { return malloc(size); } void HAL_Free(void *ptr) { free(ptr); } void HAL_Printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int HAL_Snprintf(char *str, const int len, const char *fmt, ...) { va_list args; int rc; va_start(args, fmt); rc = vsnprintf(str, len, fmt, args); va_end(args); return rc; } void HAL_SleepMs(uint32_t ms) { usleep(ms * 1000); } uint64_t HAL_UptimeMs(void) { struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)(tv.tv_sec * 1000 + tv.tv_usec / 1000); } void *HAL_MutexCreate(void) { pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); if (mutex) { pthread_mutex_init(mutex, NULL); } return mutex; } void HAL_MutexDestroy(void *mutex) { if (mutex) { pthread_mutex_destroy((pthread_mutex_t *)mutex); free(mutex); } } void HAL_MutexLock(void *mutex) { if (mutex) { pthread_mutex_lock((pthread_mutex_t *)mutex); } } void HAL_MutexUnlock(void *mutex) { if (mutex) { pthread_mutex_unlock((pthread_mutex_t *)mutex); } } ``` ``` -------------------------------- ### Linux Platform HAL Implementation Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Example implementation of core HAL functions using standard Linux system libraries. ```c #include #include #include #include #include #include void *HAL_Malloc(uint32_t size) { return malloc(size); } void HAL_Free(void *ptr) { free(ptr); } void HAL_Printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int HAL_Snprintf(char *str, const int len, const char *fmt, ...) { va_list args; int rc; va_start(args, fmt); rc = vsnprintf(str, len, fmt, args); va_end(args); return rc; } void HAL_SleepMs(uint32_t ms) { usleep(ms * 1000); } uint64_t HAL_UptimeMs(void) { struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)(tv.tv_sec * 1000 + tv.tv_usec / 1000); } void *HAL_MutexCreate(void) { pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); if (mutex) { pthread_mutex_init(mutex, NULL); } return mutex; } void HAL_MutexDestroy(void *mutex) { if (mutex) { pthread_mutex_destroy((pthread_mutex_t *)mutex); free(mutex); } } void HAL_MutexLock(void *mutex) { if (mutex) { pthread_mutex_lock((pthread_mutex_t *)mutex); } } void HAL_MutexUnlock(void *mutex) { if (mutex) { pthread_mutex_unlock((pthread_mutex_t *)mutex); } } ``` -------------------------------- ### Get Device Information Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This C function retrieves device information, including product key, device name, and device secret, using HAL functions. It also constructs a device ID string. ```c /* 获取设备信息 */ int iotx_get_devinfo(iotx_deviceinfo_t *p_devinfo) { if (NULL == p_devinfo) { return IOTX_ERR_INVALID_PARAM; } memset(p_devinfo, 0x00, sizeof(iotx_deviceinfo_t)); HAL_GetProductKey(p_devinfo->product_key); HAL_GetDeviceName(p_devinfo->device_name); HAL_GetDeviceSecret(p_devinfo->device_secret); HAL_Snprintf(p_devinfo->device_id, IOTX_PRODUCT_KEY_LEN + IOTX_DEVICE_NAME_LEN + 2, "%s.%s", p_devinfo->product_key, p_devinfo->device_name); return IOTX_SUCCESS; } ``` -------------------------------- ### Initialize and Use MQTT Client in C Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Demonstrates the full lifecycle of an MQTT client including initialization, event handling, subscription, and periodic message publishing. Requires hardware abstraction layer (HAL) functions to retrieve device credentials. ```c #include "dev_sign_api.h" #include "mqtt_api.h" char DEMO_PRODUCT_KEY[IOTX_PRODUCT_KEY_LEN + 1] = {0}; char DEMO_DEVICE_NAME[IOTX_DEVICE_NAME_LEN + 1] = {0}; char DEMO_DEVICE_SECRET[IOTX_DEVICE_SECRET_LEN + 1] = {0}; /* MQTT事件回调 - 处理消息到达事件 */ void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt)msg->msg; switch (msg->event_type) { case IOTX_MQTT_EVENT_PUBLISH_RECEIVED: printf("收到消息:\n"); printf(" Topic : %.*s\n", topic_info->topic_len, topic_info->ptopic); printf(" Payload: %.*s\n", topic_info->payload_len, topic_info->payload); break; case IOTX_MQTT_EVENT_DISCONNECT: printf("MQTT断开连接\n"); break; case IOTX_MQTT_EVENT_RECONNECT: printf("MQTT重新连接\n"); break; default: break; } } /* MQTT全局事件处理 */ void example_event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { printf("MQTT事件类型: %d\n", msg->event_type); } int main(int argc, char *argv[]) { void *pclient = NULL; int res = 0; iotx_mqtt_param_t mqtt_params; /* 获取设备三元组信息 */ HAL_GetProductKey(DEMO_PRODUCT_KEY); HAL_GetDeviceName(DEMO_DEVICE_NAME); HAL_GetDeviceSecret(DEMO_DEVICE_SECRET); /* 初始化MQTT参数 */ memset(&mqtt_params, 0x0, sizeof(mqtt_params)); /* 可选参数配置 */ /* mqtt_params.host = "xxx.iot-as-mqtt.cn-shanghai.aliyuncs.com"; */ /* mqtt_params.port = 1883; */ /* mqtt_params.request_timeout_ms = 2000; */ /* mqtt_params.clean_session = 0; */ /* mqtt_params.keepalive_interval_ms = 60000; */ /* mqtt_params.write_buf_size = 1024; */ /* mqtt_params.read_buf_size = 1024; */ mqtt_params.handle_event.h_fp = example_event_handle; /* 构建MQTT客户端并连接 */ pclient = IOT_MQTT_Construct(&mqtt_params); if (NULL == pclient) { printf("MQTT连接失败\n"); return -1; } /* 订阅主题 */ char topic[128] = {0}; snprintf(topic, sizeof(topic), "/%s/%s/user/get", DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME); res = IOT_MQTT_Subscribe(pclient, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL); if (res < 0) { printf("订阅失败\n"); IOT_MQTT_Destroy(&pclient); return -1; } /* 发布消息 */ char *payload = "{\"message\":\"hello world!\"}"; res = IOT_MQTT_Publish_Simple(pclient, topic, IOTX_MQTT_QOS0, payload, strlen(payload)); if (res < 0) { printf("发布失败\n"); } /* 主循环 - 处理MQTT消息 */ int loop_cnt = 0; while (loop_cnt++ < 100) { IOT_MQTT_Yield(pclient, 200); /* 200ms超时 */ if (loop_cnt % 20 == 0) { /* 周期性发布消息 */ IOT_MQTT_Publish_Simple(pclient, topic, IOTX_MQTT_QOS0, payload, strlen(payload)); } } /* 取消订阅 */ IOT_MQTT_Unsubscribe(pclient, topic); /* 销毁MQTT客户端 */ IOT_MQTT_Destroy(&pclient); return 0; } ``` -------------------------------- ### Initialize and Connect Linkkit Device Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This snippet shows how to initialize Linkkit, set domain and reply configurations, open the master device, and connect to the Aliyun server. It includes a loop for retrying connection if it fails. ```c IOT_Ioctl(IOTX_IOCTL_SET_DOMAIN, (void *)&domain_type); /* 设置是否接收云端回复 */ IOT_Ioctl(IOTX_IOCTL_RECV_EVENT_REPLY, (void *)&post_reply_need); /* 创建主设备资源 */ g_user_example_ctx.master_devid = IOT_Linkkit_Open( IOTX_LINKKIT_DEV_TYPE_MASTER, &master_meta_info); if (g_user_example_ctx.master_devid < 0) { printf("IOT_Linkkit_Open 失败\n"); return -1; } /* 连接阿里云服务器 */ do { res = IOT_Linkkit_Connect(g_user_example_ctx.master_devid); if (res < 0) { printf("IOT_Linkkit_Connect 失败, 5秒后重试...\n"); HAL_SleepMs(5000); } } while (res < 0); ``` -------------------------------- ### Initialize Linkkit and Register Callbacks Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Initializes the Linkkit SDK with device metadata, sets the log level, and registers essential event callbacks for connection, disconnection, property setting, service requests, report replies, and initialization completion. Ensure device credentials are correctly obtained before this step. ```c #include "infra_types.h" #include "infra_defs.h" #include "infra_compat.h" #include "dev_model_api.h" char PRODUCT_KEY[IOTX_PRODUCT_KEY_LEN + 1] = {0}; char PRODUCT_SECRET[IOTX_PRODUCT_SECRET_LEN + 1] = {0}; char DEVICE_NAME[IOTX_DEVICE_NAME_LEN + 1] = {0}; char DEVICE_SECRET[IOTX_DEVICE_SECRET_LEN + 1] = {0}; #define EXAMPLE_MASTER_DEVID (0) typedef struct { int master_devid; int cloud_connected; int master_initialized; } user_example_ctx_t; static user_example_ctx_t g_user_example_ctx; /* 云端连接成功回调 */ static int user_connected_event_handler(void) { printf("云端连接成功\n"); g_user_example_ctx.cloud_connected = 1; return 0; } /* 云端断开连接回调 */ static int user_disconnected_event_handler(void) { printf("云端连接断开\n"); g_user_example_ctx.cloud_connected = 0; return 0; } /* 设备初始化完成回调 */ static int user_initialized(const int devid) { printf("设备初始化完成, devid=%d\n", devid); g_user_example_ctx.master_initialized = 1; return 0; } /* 属性上报响应回调 */ static int user_report_reply_event_handler(const int devid, const int msgid, const int code, const char *reply, const int reply_len) { printf("属性上报响应: msgid=%d, code=%d, reply=%.*s\n", msgid, code, reply_len, reply ? reply : "NULL"); return 0; } /* 云端属性设置回调 */ static int user_property_set_event_handler(const int devid, const char *request, const int request_len) { printf("收到属性设置: %s\n", request); /* 回复属性设置(将收到的属性值上报) */ IOT_Linkkit_Report(EXAMPLE_MASTER_DEVID, ITM_MSG_POST_PROPERTY, (unsigned char *)request, request_len); return 0; } /* 云端服务调用回调 */ static int user_service_request_event_handler(const int devid, const char *serviceid, const int serviceid_len, const char *request, const int request_len, char **response, int *response_len) { printf("收到服务调用: serviceid=%.*s, request=%s\n", serviceid_len, serviceid, request); /* 构造响应 */ const char *response_fmt = "{\"Result\": %d}"; *response_len = strlen(response_fmt) + 10; *response = (char *)HAL_Malloc(*response_len); if (*response) { HAL_Snprintf(*response, *response_len, response_fmt, 100); *response_len = strlen(*response); } return 0; } /* 上报设备属性 */ void user_post_property(void) { static int counter = 0; char property_payload[64] = {0}; HAL_Snprintf(property_payload, sizeof(property_payload), "{\"Counter\": %d}", counter++); int res = IOT_Linkkit_Report(EXAMPLE_MASTER_DEVID, ITM_MSG_POST_PROPERTY, (unsigned char *)property_payload, strlen(property_payload)); printf("属性上报, msgid=%d\n", res); } /* 触发设备事件 */ void user_post_event(void) { char *event_id = "HardwareError"; char *event_payload = "{\"ErrorCode\": 0}"; int res = IOT_Linkkit_TriggerEvent(EXAMPLE_MASTER_DEVID, event_id, strlen(event_id), event_payload, strlen(event_payload)); printf("事件上报, msgid=%d\n", res); } int main(int argc, char **argv) { int res = 0; iotx_linkkit_dev_meta_info_t master_meta_info; int domain_type = IOTX_CLOUD_REGION_SHANGHAI; int post_reply_need = 1; memset(&g_user_example_ctx, 0, sizeof(user_example_ctx_t)); /* 获取设备信息 */ HAL_GetProductKey(PRODUCT_KEY); HAL_GetProductSecret(PRODUCT_SECRET); HAL_GetDeviceName(DEVICE_NAME); HAL_GetDeviceSecret(DEVICE_SECRET); /* 设置设备元数据 */ memset(&master_meta_info, 0, sizeof(iotx_linkkit_dev_meta_info_t)); memcpy(master_meta_info.product_key, PRODUCT_KEY, strlen(PRODUCT_KEY)); memcpy(master_meta_info.product_secret, PRODUCT_SECRET, strlen(PRODUCT_SECRET)); memcpy(master_meta_info.device_name, DEVICE_NAME, strlen(DEVICE_NAME)); memcpy(master_meta_info.device_secret, DEVICE_SECRET, strlen(DEVICE_SECRET)); /* 设置日志级别 */ IOT_SetLogLevel(IOT_LOG_DEBUG); /* 注册事件回调 */ IOT_RegisterCallback(ITE_CONNECT_SUCC, user_connected_event_handler); IOT_RegisterCallback(ITE_DISCONNECTED, user_disconnected_event_handler); IOT_RegisterCallback(ITE_SERVICE_REQUEST, user_service_request_event_handler); IOT_RegisterCallback(ITE_PROPERTY_SET, user_property_set_event_handler); IOT_RegisterCallback(ITE_REPORT_REPLY, user_report_reply_event_handler); IOT_RegisterCallback(ITE_INITIALIZE_COMPLETED, user_initialized); /* 设置云端区域 */ ``` -------------------------------- ### Initialize and Authenticate HTTP Client Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Initializes the HTTP client with device information and performs device authentication. Ensure device details are correctly set before initialization. ```c #include "infra_types.h" #include "infra_defs.h" #include "http_api.h" #define IOTX_PRODUCT_KEY "a1KqSriAwh0" #define IOTX_DEVICE_NAME "basic_test_01" #define IOTX_DEVICE_SECRET "5gme06iFl3W1g8non2ksVs5e8Qlus4Hw" #define IOTX_DEVICE_ID "a1KqSriAwh0.basic_test_01" #define MAX_BUF_LEN 256 #define DEFAULT_TIMEOUT 5000 static char request_buf[MAX_BUF_LEN]; static char response_buf[MAX_BUF_LEN]; int main(int argc, char **argv) { iotx_device_info_t device_info; iotx_http_param_t http_param; void *handle = NULL; memset(&http_param, 0, sizeof(http_param)); /* 设置设备信息 */ HAL_SetProductKey((char *)IOTX_PRODUCT_KEY); HAL_SetDeviceName((char *)IOTX_DEVICE_NAME); HAL_SetDeviceSecret((char *)IOTX_DEVICE_SECRET); strncpy(device_info.product_key, IOTX_PRODUCT_KEY, IOTX_PRODUCT_KEY_LEN); strncpy(device_info.device_secret, IOTX_DEVICE_SECRET, IOTX_DEVICE_SECRET_LEN); strncpy(device_info.device_name, IOTX_DEVICE_NAME, IOTX_DEVICE_NAME_LEN); strncpy(device_info.device_id, IOTX_DEVICE_ID, IOTX_DEVICE_ID_LEN); http_param.device_info = &device_info; http_param.timeout_ms = DEFAULT_TIMEOUT; /* 初始化HTTP客户端 */ handle = IOT_HTTP_Init(&http_param); if (NULL == handle) { printf("HTTP初始化失败\n"); return -1; } /* 设备认证 */ if (0 != IOT_HTTP_DeviceNameAuth(handle)) { printf("HTTP认证失败\n"); IOT_HTTP_DeInit(&handle); return -1; } printf("HTTP认证成功\n"); /* 发送测试 */ http_send_test(handle); /* 断开连接并释放资源 */ IOT_HTTP_Disconnect(handle); IOT_HTTP_DeInit(&handle); return 0; } ``` -------------------------------- ### Configure System Settings and Logging Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Sets global parameters such as log levels, cloud regions, and event callbacks using the IOT_Ioctl interface. ```c #include "infra_compat.h" #include "infra_defs.h" int main(int argc, char *argv[]) { int domain_type; int dynamic_register; int post_reply_need; /* 设置日志级别 */ IOT_SetLogLevel(IOT_LOG_DEBUG); /* 调试级别 */ /* IOT_SetLogLevel(IOT_LOG_INFO); */ /* 信息级别 */ /* IOT_SetLogLevel(IOT_LOG_WARNING); */ /* 警告级别 */ /* IOT_SetLogLevel(IOT_LOG_ERROR); */ /* 错误级别 */ /* IOT_SetLogLevel(IOT_LOG_NONE); */ /* 关闭日志 */ /* 设置云端区域 */ domain_type = IOTX_CLOUD_REGION_SHANGHAI; /* 上海 */ /* domain_type = IOTX_CLOUD_REGION_SINGAPORE; */ /* 新加坡 */ /* domain_type = IOTX_CLOUD_REGION_JAPAN; */ /* 日本 */ /* domain_type = IOTX_CLOUD_REGION_USA_WEST; */ /* 美国西部 */ /* domain_type = IOTX_CLOUD_REGION_GERMANY; */ /* 德国 */ IOT_Ioctl(IOTX_IOCTL_SET_DOMAIN, (void *)&domain_type); /* 获取当前区域设置 */ IOT_Ioctl(IOTX_IOCTL_GET_DOMAIN, (void *)&domain_type); printf("当前云端区域: %d\n", domain_type); /* 设置动态注册开关 */ dynamic_register = 0; /* 0-禁用, 1-启用 */ IOT_Ioctl(IOTX_IOCTL_SET_DYNAMIC_REGISTER, (void *)&dynamic_register); /* 设置是否接收属性/事件上报的云端回复 */ post_reply_need = 1; /* 0-不需要, 1-需要 */ IOT_Ioctl(IOTX_IOCTL_RECV_EVENT_REPLY, (void *)&post_reply_need); IOT_Ioctl(IOTX_IOCTL_RECV_PROP_REPLY, (void *)&post_reply_need); /* 设置自定义MQTT域名 */ /* const char *custom_domain = "custom.iot.example.com"; */ /* IOT_Ioctl(IOTX_IOCTL_SET_MQTT_DOMAIN, (void *)custom_domain); */ /* 注册系统事件监听 */ iotx_event_regist_cb(event_monitor_callback); /* 打印内存统计 */ IOT_DumpMemoryStats(IOT_LOG_DEBUG); return 0; } /* 系统事件监听回调 */ void event_monitor_callback(int event) { switch (event) { case IOTX_AWSS_START: printf("AWSS启动\n"); break; case IOTX_AWSS_GOT_SSID_PASSWD: printf("获取到WiFi信息\n"); break; case IOTX_CONN_CLOUD: printf("正在连接云端\n"); break; case IOTX_CONN_CLOUD_SUC: printf("云端连接成功\n"); break; case IOTX_CONN_CLOUD_FAIL: printf("云端连接失败\n"); break; case IOTX_RESET: printf("设备重置\n"); break; default: printf("未知事件: %d\n", event); break; } } ``` -------------------------------- ### Perform Dynamic Device Registration Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Uses ProductKey, ProductSecret, and DeviceName to request a DeviceSecret from the cloud, simplifying the manufacturing process. ```c #include #include #include "infra_types.h" #include "infra_defs.h" #include "dynreg_api.h" void HAL_Printf(const char *fmt, ...); int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN]); int HAL_GetProductSecret(char *product_secret); int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN]); int main(int argc, char *argv[]) { int32_t res = 0; iotx_dev_meta_info_t meta; iotx_http_region_types_t region = IOTX_HTTP_REGION_SHANGHAI; printf("动态注册示例\n"); /* 初始化设备元数据 */ memset(&meta, 0, sizeof(iotx_dev_meta_info_t)); /* 获取ProductKey、ProductSecret和DeviceName */ HAL_GetProductKey(meta.product_key); HAL_GetProductSecret(meta.product_secret); HAL_GetDeviceName(meta.device_name); printf("ProductKey: %s\n", meta.product_key); printf("DeviceName: %s\n", meta.device_name); /* 执行动态注册,获取DeviceSecret */ res = IOT_Dynamic_Register(region, &meta); if (res < 0) { printf("动态注册失败, 错误码: %d\n", res); return -1; } /* 成功获取DeviceSecret */ printf("\n动态注册成功!\n"); printf("DeviceSecret: %s\n", meta.device_secret); /* 后续可将DeviceSecret保存到持久存储 */ /* HAL_SetDeviceSecret(meta.device_secret); */ return 0; } ``` -------------------------------- ### Initialize and Run CoAP Client Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This C function initializes a CoAP client, performs device authentication, and enters a main loop for sending data and processing CoAP messages. It uses PSK security mode and retries sending data periodically. ```c int main(int argc, char **argv) { iotx_coap_config_t config; iotx_deviceinfo_t deviceinfo; iotx_coap_context_t *p_ctx = NULL; int count = 0; /* 获取设备信息 */ HAL_GetProductKey(IOTX_PRODUCT_KEY); HAL_GetDeviceName(IOTX_DEVICE_NAME); HAL_GetDeviceSecret(IOTX_DEVICE_SECRET); IOT_SetLogLevel(IOT_LOG_DEBUG); /* 配置CoAP参数 */ memset(&config, 0x00, sizeof(iotx_coap_config_t)); /* 使用PSK安全模式的在线URL */ char url[256] = {0}; snprintf(url, sizeof(url), "coap-psk://%s.coap.cn-shanghai.link.aliyuncs.com:5682", IOTX_PRODUCT_KEY); config.p_url = url; iotx_get_devinfo(&deviceinfo); config.p_devinfo = (iotx_device_info_t *)&deviceinfo; config.wait_time_ms = 3000; /* 初始化CoAP客户端 */ p_ctx = IOT_CoAP_Init(&config); if (NULL == p_ctx) { printf("CoAP初始化失败\n"); return -1; } /* 设备认证 */ if (IOTX_SUCCESS != IOT_CoAP_DeviceNameAuth(p_ctx)) { printf("设备认证失败\n"); IOT_CoAP_Deinit(&p_ctx); return -1; } /* 主循环 */ do { if (count == 0 || count % 10 == 0) { iotx_post_data_to_server(p_ctx); } count++; /* 处理CoAP消息 */ IOT_CoAP_Yield(p_ctx); } while (count < 100); /* 释放资源 */ IOT_CoAP_Deinit(&p_ctx); printf("CoAP客户端退出\n"); return 0; } ``` -------------------------------- ### Main Loop for Linkkit Device Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This snippet demonstrates the main loop for a Linkkit-connected device. It includes periodic yielding for network operations, reporting properties, and triggering events. A fixed number of iterations (100) is used before closing the connection. ```c /* 主循环 */ int cnt = 0; while (cnt++ < 100) { IOT_Linkkit_Yield(200); /* 200ms超时 */ /* 每2秒上报属性 */ if ((cnt % 2) == 0) { user_post_property(); } /* 每10秒触发事件 */ if ((cnt % 10) == 0) { user_post_event(); } HAL_SleepMs(1000); } /* 关闭Linkkit */ IOT_Linkkit_Close(g_user_example_ctx.master_devid); return 0; } ``` -------------------------------- ### HAL Interface Declarations Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Required function signatures for platform-specific implementation. ```c /* HAL接口声明 - 用户需实现 */ /* 内存管理 */ void *HAL_Malloc(uint32_t size); void HAL_Free(void *ptr); /* 设备信息 */ int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN + 1]); int HAL_GetProductSecret(char product_secret[IOTX_PRODUCT_SECRET_LEN + 1]); int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN + 1]); int HAL_GetDeviceSecret(char device_secret[IOTX_DEVICE_SECRET_LEN + 1]); int HAL_SetProductKey(char *product_key); int HAL_SetDeviceName(char *device_name); int HAL_SetDeviceSecret(char *device_secret); /* 系统功能 */ void HAL_Printf(const char *fmt, ...); int HAL_Snprintf(char *str, const int len, const char *fmt, ...); void HAL_SleepMs(uint32_t ms); uint64_t HAL_UptimeMs(void); /* 网络接口 (TCP) */ uintptr_t HAL_TCP_Establish(const char *host, uint16_t port); int HAL_TCP_Destroy(uintptr_t fd); int32_t HAL_TCP_Write(uintptr_t fd, const char *buf, uint32_t len, uint32_t timeout_ms); int32_t HAL_TCP_Read(uintptr_t fd, char *buf, uint32_t len, uint32_t timeout_ms); /* SSL/TLS接口 */ uintptr_t HAL_SSL_Establish(const char *host, uint16_t port, const char *ca_crt, uint32_t ca_crt_len); int32_t HAL_SSL_Destroy(uintptr_t handle); int32_t HAL_SSL_Write(uintptr_t handle, const char *buf, int len, int timeout_ms); int32_t HAL_SSL_Read(uintptr_t handle, char *buf, int len, int timeout_ms); /* 互斥锁 */ void *HAL_MutexCreate(void); void HAL_MutexDestroy(void *mutex); void HAL_MutexLock(void *mutex); void HAL_MutexUnlock(void *mutex); /* 信号量 */ void *HAL_SemaphoreCreate(void); void HAL_SemaphoreDestroy(void *sem); void HAL_SemaphorePost(void *sem); int HAL_SemaphoreWait(void *sem, uint32_t timeout_ms); ``` -------------------------------- ### Linkkit Device Lifecycle Management Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Endpoints and functions for managing the lifecycle of an IoT device, including initialization, connection, and resource cleanup. ```APIDOC ## IOT_Linkkit_Open ### Description Creates a master device resource and initializes the Linkkit context. ### Method Function Call ### Parameters - **dev_type** (int) - Required - Device type (e.g., IOTX_LINKKIT_DEV_TYPE_MASTER) - **meta_info** (pointer) - Required - Device metadata information ### Response - **devid** (int) - Returns the device ID on success, or a negative value on failure. ``` ```APIDOC ## IOT_Linkkit_Connect ### Description Establishes a connection to the Aliyun IoT server for the specified device. ### Method Function Call ### Parameters - **devid** (int) - Required - The device ID returned by IOT_Linkkit_Open ### Response - **result** (int) - Returns 0 on success, or a negative value on failure. ``` ```APIDOC ## IOT_Linkkit_Close ### Description Closes the Linkkit connection and releases associated resources. ### Method Function Call ### Parameters - **devid** (int) - Required - The device ID to close ``` -------------------------------- ### HAL Interface Declarations Source: https://context7.com/aliyun/iotkit-embedded/llms.txt These are the core HAL interface declarations that users must implement for their target platform. This ensures the SDK can operate across different hardware and operating systems. ```APIDOC ## HAL Interface Declarations ### Description These are the HAL interface declarations that users need to implement to make the SDK platform-independent. ### Memory Management - **HAL_Malloc** (void *(*)(uint32_t size)) - Allocates a block of memory. - **HAL_Free** (void (*)(void *ptr)) - Frees a previously allocated block of memory. ### Device Information - **HAL_GetProductKey** (int (*)(char product_key[IOTX_PRODUCT_KEY_LEN + 1])) - Retrieves the Product Key of the device. - **HAL_GetProductSecret** (int (*)(char product_secret[IOTX_PRODUCT_SECRET_LEN + 1])) - Retrieves the Product Secret of the device. - **HAL_GetDeviceName** (int (*)(char device_name[IOTX_DEVICE_NAME_LEN + 1])) - Retrieves the Device Name. - **HAL_GetDeviceSecret** (int (*)(char device_secret[IOTX_DEVICE_SECRET_LEN + 1])) - Retrieves the Device Secret. - **HAL_SetProductKey** (int (*)(char *product_key)) - Sets the Product Key. - **HAL_SetDeviceName** (int (*)(char *device_name)) - Sets the Device Name. - **HAL_SetDeviceSecret** (int (*)(char *device_secret)) - Sets the Device Secret. ### System Functions - **HAL_Printf** (void (*)(const char *fmt, ...)) - Prints formatted output to the console or a designated output. - **HAL_Snprintf** (int (*)(char *str, const int len, const char *fmt, ...)) - Formats data into a string with a specified length limit. - **HAL_SleepMs** (void (*)(uint32_t ms)) - Pauses the execution of the current thread for a specified number of milliseconds. - **HAL_UptimeMs** (uint64_t (*)(void)) - Returns the number of milliseconds since the system was powered on or reset. ### Network Interface (TCP) - **HAL_TCP_Establish** (uintptr_t (*)(const char *host, uint16_t port)) - Establishes a TCP connection to a specified host and port. - **HAL_TCP_Destroy** (int (*)(uintptr_t fd)) - Destroys an established TCP connection. - **HAL_TCP_Write** (int32_t (*)(uintptr_t fd, const char *buf, uint32_t len, uint32_t timeout_ms)) - Writes data to a TCP connection. - **HAL_TCP_Read** (int32_t (*)(uintptr_t fd, char *buf, uint32_t len, uint32_t timeout_ms)) - Reads data from a TCP connection. ### SSL/TLS Interface - **HAL_SSL_Establish** (uintptr_t (*)(const char *host, uint16_t port, const char *ca_crt, uint32_t ca_crt_len)) - Establishes a secure SSL/TLS connection. - **HAL_SSL_Destroy** (int32_t (*)(uintptr_t handle)) - Destroys an established SSL/TLS connection. - **HAL_SSL_Write** (int32_t (*)(uintptr_t handle, const char *buf, int len, int timeout_ms)) - Writes data over an SSL/TLS connection. - **HAL_SSL_Read** (int32_t (*)(uintptr_t handle, char *buf, int len, int timeout_ms)) - Reads data from an SSL/TLS connection. ### Mutex - **HAL_MutexCreate** (void *(*)(void)) - Creates a mutex. - **HAL_MutexDestroy** (void (*)(void *mutex)) - Destroys a mutex. - **HAL_MutexLock** (void (*)(void *mutex)) - Locks a mutex. - **HAL_MutexUnlock** (void (*)(void *mutex)) - Unlocks a mutex. ### Semaphore - **HAL_SemaphoreCreate** (void *(*)(void)) - Creates a semaphore. - **HAL_SemaphoreDestroy** (void (*)(void *sem)) - Destroys a semaphore. - **HAL_SemaphorePost** (void (*)(void *sem)) - Posts (signals) a semaphore. - **HAL_SemaphoreWait** (int (*)(void *sem, uint32_t timeout_ms)) - Waits for a semaphore to be posted. ``` -------------------------------- ### OTA固件升级示例代码 Source: https://context7.com/aliyun/iotkit-embedded/llms.txt 展示了通过MQTT通道初始化OTA、下载固件、上报进度以及校验固件完整性的完整流程。需要确保设备已正确配置ProductKey、DeviceName和DeviceSecret。 ```c #include "infra_compat.h" #include "mqtt_api.h" #include "ota_api.h" char g_product_key[IOTX_PRODUCT_KEY_LEN + 1]; char g_device_name[IOTX_DEVICE_NAME_LEN + 1]; char g_device_secret[IOTX_DEVICE_SECRET_LEN + 1]; #define OTA_BUF_LEN (5000) /* MQTT事件处理 */ void event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { switch (msg->event_type) { case IOTX_MQTT_EVENT_DISCONNECT: printf("MQTT断开连接\n"); break; case IOTX_MQTT_EVENT_RECONNECT: printf("MQTT重新连接\n"); break; default: break; } } int ota_mqtt_example(void) { void *pclient = NULL; void *h_ota = NULL; iotx_conn_info_pt pconn_info; iotx_mqtt_param_t mqtt_params; FILE *fp = NULL; char buf_ota[OTA_BUF_LEN]; int ota_over = 0; /* 打开文件保存固件 */ fp = fopen("ota.bin", "wb+"); if (NULL == fp) { printf("打开文件失败\n"); return -1; } /* 获取设备信息 */ HAL_GetProductKey(g_product_key); HAL_GetDeviceName(g_device_name); HAL_GetDeviceSecret(g_device_secret); /* 设置连接信息 */ if (0 != IOT_SetupConnInfo(g_product_key, g_device_name, g_device_secret, (void **)&pconn_info)) { printf("认证请求失败\n"); fclose(fp); return -1; } /* 初始化MQTT参数 */ memset(&mqtt_params, 0x0, sizeof(mqtt_params)); mqtt_params.port = pconn_info->port; mqtt_params.host = pconn_info->host_name; mqtt_params.client_id = pconn_info->client_id; mqtt_params.username = pconn_info->username; mqtt_params.password = pconn_info->password; mqtt_params.pub_key = pconn_info->pub_key; mqtt_params.request_timeout_ms = 2000; mqtt_params.clean_session = 0; mqtt_params.keepalive_interval_ms = 60000; mqtt_params.read_buf_size = 2048; mqtt_params.write_buf_size = 2048; mqtt_params.handle_event.h_fp = event_handle; /* 构建MQTT连接 */ pclient = IOT_MQTT_Construct(&mqtt_params); if (NULL == pclient) { printf("MQTT连接失败\n"); fclose(fp); return -1; } /* 初始化OTA */ h_ota = IOT_OTA_Init(g_product_key, g_device_name, pclient); if (NULL == h_ota) { printf("OTA初始化失败\n"); IOT_MQTT_Destroy(&pclient); fclose(fp); return -1; } /* 上报当前版本号(可选) */ IOT_OTA_ReportVersion(h_ota, "1.0.0"); /* 等待OTA升级命令 */ do { printf("等待OTA升级命令...\n"); /* 处理MQTT消息 */ IOT_MQTT_Yield(pclient, 200); /* 检查是否有固件下载任务 */ if (IOT_OTA_IsFetching(h_ota)) { uint32_t last_percent = 0, percent = 0; char md5sum[33]; char version[128] = {0}; uint64_t size_downloaded, size_file; uint32_t firmware_valid; do { /* 下载固件数据 */ int len = IOT_OTA_FetchYield(h_ota, buf_ota, OTA_BUF_LEN, 1); if (len > 0) { /* 写入文件 */ fwrite(buf_ota, len, 1, fp); } else { /* 下载失败,上报错误 */ IOT_OTA_ReportProgress(h_ota, IOT_OTAP_FETCH_FAILED, NULL); printf("OTA下载失败\n"); break; } /* 获取下载信息 */ IOT_OTA_Ioctl(h_ota, IOT_OTAG_FETCHED_SIZE, &size_downloaded, 4); IOT_OTA_Ioctl(h_ota, IOT_OTAG_FILE_SIZE, &size_file, 4); IOT_OTA_Ioctl(h_ota, IOT_OTAG_MD5SUM, md5sum, 33); IOT_OTA_Ioctl(h_ota, IOT_OTAG_VERSION, version, 128); /* 计算并上报进度 */ last_percent = percent; percent = (size_downloaded * 100) / size_file; if (percent - last_percent > 0) { IOT_OTA_ReportProgress(h_ota, percent, NULL); printf("下载进度: %d%%, 版本: %s\n", percent, version); } IOT_MQTT_Yield(pclient, 100); } while (!IOT_OTA_IsFetchFinish(h_ota)); /* 校验固件 */ IOT_OTA_Ioctl(h_ota, IOT_OTAG_CHECK_FIRMWARE, &firmware_valid, 4); if (firmware_valid) { printf("固件校验通过, MD5: %s\n", md5sum); } else { printf("固件校验失败\n"); } ota_over = 1; } HAL_SleepMs(2000); } while (!ota_over); /* 清理资源 */ IOT_OTA_Deinit(h_ota); IOT_MQTT_Destroy(&pclient); fclose(fp); return 0; } int main(int argc, char *argv[]) { IOT_SetLogLevel(IOT_LOG_DEBUG); ota_mqtt_example(); IOT_DumpMemoryStats(IOT_LOG_DEBUG); return 0; } ``` -------------------------------- ### CoAP Client API Source: https://context7.com/aliyun/iotkit-embedded/llms.txt Functions for initializing CoAP clients, performing device authentication, and sending messages to the server. ```APIDOC ## IOT_CoAP_Init ### Description Initializes the CoAP client context with the provided configuration. ### Method Function Call ### Parameters - **config** (iotx_coap_config_t) - Required - Configuration structure containing URL, device info, and timeout settings ### Response - **context** (iotx_coap_context_t*) - Returns a pointer to the CoAP context on success, or NULL on failure. ``` ```APIDOC ## IOT_CoAP_SendMessage ### Description Sends a CoAP message to a specific path on the server. ### Method Function Call ### Parameters - **p_ctx** (iotx_coap_context_t*) - Required - The CoAP context - **path** (char*) - Required - The target URI path - **message** (iotx_message_t*) - Required - The message structure containing payload, callback, and content type ``` ```APIDOC ## IOT_CoAP_DeviceNameAuth ### Description Performs device authentication using the device name and secret. ### Method Function Call ### Parameters - **p_ctx** (iotx_coap_context_t*) - Required - The CoAP context ### Response - **result** (int) - Returns IOTX_SUCCESS on success. ``` -------------------------------- ### Send Data via CoAP Source: https://context7.com/aliyun/iotkit-embedded/llms.txt This C function constructs and sends a JSON message with a 'hello world' payload using the CoAP protocol. It sets the message type to confirmed and specifies the content type as JSON. ```c /* 发送数据到服务器 */ static void iotx_post_data_to_server(iotx_coap_context_t *p_ctx) { char path[IOTX_URI_MAX_LEN + 1] = {0}; iotx_message_t message; iotx_deviceinfo_t devinfo; memset(&message, 0, sizeof(iotx_message_t)); iotx_get_devinfo(&devinfo); /* 构造消息 */ message.p_payload = (unsigned char *)"{\"name\":\"hello world\"}"; message.payload_len = strlen("{\"name\":\"hello world\"}"); message.resp_callback = iotx_response_handler; message.msg_type = IOTX_MESSAGE_CON; /* 需要确认的消息 */ message.content_type = IOTX_CONTENT_TYPE_JSON; /* 构造路径 */ snprintf(path, IOTX_URI_MAX_LEN, "/topic/%s/%s/update/", devinfo.product_key, devinfo.device_name); /* 发送消息 */ IOT_CoAP_SendMessage(p_ctx, path, &message); } ```