测试blu

张开发
2026/4/10 10:19:36 15 分钟阅读

分享文章

测试blu
// 全局变量 static int provision_active 0; // 配网流程是否激活static int ble_initialized 0;static int wifi_initialized 0;static pthread_t event_thread 0;static int wake_fd -1;static int epoll_fd -1;// 回调static blufi_provision_cb_t user_cb NULL;static void *user_ctx NULL; 事件循环线程常驻 static void *event_loop(void *arg) {struct epoll_event events[10];while (1) {int n epoll_wait(epoll_fd, events, 10, -1);for (int i 0; i n; i) {int fd events[i].data.fd;if (fd wake_fd) {uint64_t val;read(wake_fd, val, sizeof(val));// 外部唤醒可能用于停止配网continue;}// 只有配网激活时才处理蓝牙和Wi-Fi事件if (!provision_active) continue;if (fd ble_fd) { handle_ble_data(); } else if (fd wifi_fd) { handle_wifi_event(); } } } return NULL;} 初始化常驻资源系统启动时调用一次 static int init_event_system(void) {if (event_thread ! 0) return 0; // 已初始化wake_fd eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); if (wake_fd -1) return -1; epoll_fd epoll_create1(0); if (epoll_fd -1) { close(wake_fd); return -1; } struct epoll_event ev; ev.events EPOLLIN; ev.data.fd wake_fd; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, wake_fd, ev); // 注意此时 ble_fd 和 wifi_fd 可能还未初始化 // 可以在它们初始化后动态添加到 epoll见下文 if (pthread_create(event_thread, NULL, event_loop, NULL) ! 0) { close(epoll_fd); close(wake_fd); return -1; } return 0;} 添加或删除 fd 到 epoll动态 static void add_fd_to_epoll(int fd) {struct epoll_event ev;ev.events EPOLLIN;ev.data.fd fd;epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, ev);}static void remove_fd_from_epoll(int fd) {epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL);} 配网启动不创建线程只激活标志和广播 int blufi_provision_start(blufi_provision_cb_t cb, void *user_data) {if (provision_active) return -1;// 确保事件系统已初始化 if (init_event_system() ! 0) return -1; // 保存回调 user_cb cb; user_ctx user_data; // 初始化 BLE如果未初始化 if (!ble_initialized) { if (ble_gatt_server_init() ! 0) return -1; ble_initialized 1; // 将 ble_fd 添加到 epoll假设 ble_gatt_server_init 设置了 ble_fd add_fd_to_epoll(ble_fd); } else { ble_gatt_server_start_advertising(); // 重新开启广播 } // 初始化 Wi-Fi 监控如果未初始化 if (!wifi_initialized) { if (wifi_monitor_init() ! 0) { ble_gatt_server_stop_advertising(); return -1; } wifi_initialized 1; add_fd_to_epoll(wifi_fd); } provision_active 1; return 0;} 配网停止 int blufi_provision_stop(void) {if (!provision_active) return 0;provision_active 0; ble_gatt_server_stop_advertising(); // 可选清空内部队列、重置状态机 // 不销毁线程不删除 fd保留以便下次快速启动 return 0;} 完全释放资源系统关机时调用 void blufi_provision_deinit(void) {blufi_provision_stop();if (event_thread) { // 唤醒并等待线程退出 uint64_t val 1; write(wake_fd, val, sizeof(val)); pthread_join(event_thread, NULL); event_thread 0; } if (epoll_fd ! -1) close(epoll_fd); if (wake_fd ! -1) close(wake_fd); if (ble_initialized) ble_gatt_server_deinit(); if (wifi_initialized) wifi_monitor_deinit();}

更多文章