// BLE Provisioning GATT Server implementation // Replaces WiFi AP HTTP provisioning with BLE GATT-based provisioning // Protocol: protocols/ble_provisioning.md #include "ble_prov.h" #include "ssid_manager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // NimBLE os.h defines min/max macros that conflict with C++ #undef min #undef max #define TAG "BleProv" // GATT UUIDs (protocol: 0000FFxx-0000-1000-8000-00805F9B34FB) static const ble_uuid128_t SERVICE_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_DEVICE_INFO_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x02, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_WIFI_SCAN_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x03, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_WIFI_CONFIG_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x04, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_WIFI_RESULT_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x05, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_COMMAND_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x06, 0xff, 0x00, 0x00); static const ble_uuid128_t CHAR_SAVED_WIFI_UUID = BLE_UUID128_INIT(0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00); // GATT characteristic value handles (populated by NimBLE) static uint16_t s_wifi_scan_val_handle; static uint16_t s_wifi_result_val_handle; static uint16_t s_saved_wifi_val_handle; // Forward declarations int ble_prov_gatt_access(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt, void* arg); int ble_prov_gap_event(struct ble_gap_event* event, void* arg); // GATT service definition // Field order per ble_gatt_chr_def: uuid, access_cb, arg, descriptors, flags, min_key_size, val_handle, cpfd static const struct ble_gatt_svc_def kGattServices[] = { { .type = BLE_GATT_SVC_TYPE_PRIMARY, .uuid = &SERVICE_UUID.u, .characteristics = (struct ble_gatt_chr_def[]) { // DeviceInfo: READ { .uuid = &CHAR_DEVICE_INFO_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_READ, }, // WifiScan: WRITE + NOTIFY { .uuid = &CHAR_WIFI_SCAN_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY, .min_key_size = 0, .val_handle = &s_wifi_scan_val_handle, }, // WifiConfig: WRITE { .uuid = &CHAR_WIFI_CONFIG_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_WRITE, }, // WifiResult: NOTIFY { .uuid = &CHAR_WIFI_RESULT_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_NOTIFY, .min_key_size = 0, .val_handle = &s_wifi_result_val_handle, }, // Command: WRITE { .uuid = &CHAR_COMMAND_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_WRITE, }, // SavedWifi: WRITE + NOTIFY { .uuid = &CHAR_SAVED_WIFI_UUID.u, .access_cb = ble_prov_gatt_access, .arg = NULL, .descriptors = NULL, .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY, .min_key_size = 0, .val_handle = &s_saved_wifi_val_handle, }, { 0 }, // End of characteristics }, }, { 0 }, // End of services }; // ============================================================ // Singleton // ============================================================ BleProv& BleProv::GetInstance() { static BleProv instance; return instance; } void BleProv::SetDeviceName(const std::string& suffix) { device_name_ = "Borla-" + suffix; } void BleProv::SetDeviceInfo(const std::string& mac, const std::string& version) { device_mac_ = mac; device_version_ = version; } void BleProv::SetWifiConfigCallback(WifiConfigCallback cb) { wifi_config_cb_ = std::move(cb); } void BleProv::SetRebootCallback(RebootCallback cb) { reboot_cb_ = std::move(cb); } // ============================================================ // Lifecycle // ============================================================ static void ble_host_task(void* param) { ESP_LOGI(TAG, "NimBLE host task started"); nimble_port_run(); nimble_port_freertos_deinit(); } static void on_ble_sync() { // Address configuration ble_hs_util_ensure_addr(0); BleProv::GetInstance().StartAdvertising(); } static void on_ble_reset(int reason) { ESP_LOGW(TAG, "BLE host reset, reason=%d", reason); } void BleProv::Start() { if (running_) return; ESP_LOGI(TAG, "Starting BLE provisioning: %s", device_name_.c_str()); // Initialize NimBLE esp_err_t ret = nimble_port_init(); if (ret != ESP_OK) { ESP_LOGE(TAG, "nimble_port_init() failed: %s", esp_err_to_name(ret)); return; } ble_hs_cfg.reset_cb = on_ble_reset; ble_hs_cfg.sync_cb = on_ble_sync; ble_hs_cfg.store_status_cb = ble_store_util_status_rr; // Set preferred MTU ble_att_set_preferred_mtu(517); // Register GATT services ble_svc_gap_init(); ble_svc_gatt_init(); int rc = ble_gatts_count_cfg(kGattServices); if (rc != 0) { ESP_LOGE(TAG, "GATT count failed: %d", rc); return; } rc = ble_gatts_add_svcs(kGattServices); if (rc != 0) { ESP_LOGE(TAG, "GATT add services failed: %d", rc); return; } // Set device name ble_svc_gap_device_name_set(device_name_.c_str()); // Store value handles wifi_scan_notify_handle_ = s_wifi_scan_val_handle; wifi_result_notify_handle_ = s_wifi_result_val_handle; saved_wifi_notify_handle_ = s_saved_wifi_val_handle; // Start NimBLE host task nimble_port_freertos_init(ble_host_task); running_ = true; ESP_LOGI(TAG, "BLE provisioning started"); } void BleProv::Stop() { if (!running_) return; ESP_LOGI(TAG, "Stopping BLE provisioning"); // Stop advertising ble_gap_adv_stop(); // Close connection if any if (connected_) { ble_gap_terminate(conn_handle_, BLE_ERR_REM_USER_CONN_TERM); } int rc = nimble_port_stop(); if (rc == 0) { nimble_port_deinit(); } running_ = false; connected_ = false; } void BleProv::StartAdvertising() { struct ble_gap_adv_params adv_params = {}; adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; // Advertising data: flags + service UUID + device name struct ble_hs_adv_fields fields = {}; fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; // Include 16-bit service UUID (0xFF01) in advertising for scan filtering ble_uuid16_t svc_uuid16 = BLE_UUID16_INIT(0xFF01); fields.uuids16 = &svc_uuid16; fields.num_uuids16 = 1; fields.uuids16_is_complete = 1; fields.name = (uint8_t*)device_name_.c_str(); fields.name_len = device_name_.length(); fields.name_is_complete = 1; int rc = ble_gap_adv_set_fields(&fields); if (rc != 0) { ESP_LOGE(TAG, "Set adv fields failed: %d", rc); return; } rc = ble_gap_adv_start(BLE_OWN_ADDR_PUBLIC, NULL, BLE_HS_FOREVER, &adv_params, ble_prov_gap_event, this); if (rc != 0) { ESP_LOGE(TAG, "Start advertising failed: %d", rc); } else { ESP_LOGI(TAG, "Advertising started: %s", device_name_.c_str()); } } // ============================================================ // GAP event handler // ============================================================ int ble_prov_gap_event(struct ble_gap_event* event, void* arg) { auto& prov = BleProv::GetInstance(); switch (event->type) { case BLE_GAP_EVENT_CONNECT: if (event->connect.status == 0) { prov.conn_handle_ = event->connect.conn_handle; prov.connected_ = true; prov.current_mtu_ = ble_att_mtu(event->connect.conn_handle); ESP_LOGI(TAG, "BLE connected, handle=%d, mtu=%d", prov.conn_handle_, prov.current_mtu_); } else { ESP_LOGW(TAG, "BLE connect failed: %d", event->connect.status); prov.StartAdvertising(); } break; case BLE_GAP_EVENT_DISCONNECT: ESP_LOGI(TAG, "BLE disconnected, reason=%d", event->disconnect.reason); prov.connected_ = false; prov.conn_handle_ = 0; prov.wifi_config_buffer_.clear(); // Resume advertising prov.StartAdvertising(); break; case BLE_GAP_EVENT_MTU: prov.current_mtu_ = event->mtu.value; ESP_LOGI(TAG, "MTU updated: %d", prov.current_mtu_); break; case BLE_GAP_EVENT_ADV_COMPLETE: ESP_LOGD(TAG, "Advertising complete"); break; default: break; } return 0; } // ============================================================ // GATT access callback // ============================================================ int ble_prov_gatt_access(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt, void* arg) { auto& prov = BleProv::GetInstance(); const ble_uuid_t* uuid = ctxt->chr->uuid; // DeviceInfo READ if (ble_uuid_cmp(uuid, &CHAR_DEVICE_INFO_UUID.u) == 0) { return prov.HandleDeviceInfoRead(ctxt); } // WifiScan WRITE if (ble_uuid_cmp(uuid, &CHAR_WIFI_SCAN_UUID.u) == 0) { return prov.HandleWifiScanWrite(ctxt); } // WifiConfig WRITE if (ble_uuid_cmp(uuid, &CHAR_WIFI_CONFIG_UUID.u) == 0) { return prov.HandleWifiConfigWrite(ctxt); } // Command WRITE if (ble_uuid_cmp(uuid, &CHAR_COMMAND_UUID.u) == 0) { return prov.HandleCommandWrite(ctxt); } // SavedWifi WRITE if (ble_uuid_cmp(uuid, &CHAR_SAVED_WIFI_UUID.u) == 0) { return prov.HandleSavedWifiWrite(ctxt); } // WifiResult: notify-only, no read/write access needed if (ble_uuid_cmp(uuid, &CHAR_WIFI_RESULT_UUID.u) == 0) { return 0; } return BLE_ATT_ERR_UNLIKELY; } // ============================================================ // Characteristic handlers // ============================================================ int BleProv::HandleDeviceInfoRead(struct ble_gatt_access_ctxt* ctxt) { cJSON* root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "mac", device_mac_.c_str()); cJSON_AddStringToObject(root, "version", device_version_.c_str()); cJSON_AddStringToObject(root, "board", "borla_s3"); char* json_str = cJSON_PrintUnformatted(root); int rc = os_mbuf_append(ctxt->om, json_str, strlen(json_str)); cJSON_free(json_str); cJSON_Delete(root); return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES; } void BleProv::SetCachedNetworks(const std::vector& networks) { cached_networks_ = networks; ESP_LOGI(TAG, "Cached %d WiFi networks for BLE provisioning", static_cast(cached_networks_.size())); } void BleProv::WifiScanTask(void* arg) { auto& prov = BleProv::GetInstance(); // Always return the pre-scan cache. Running esp_wifi_scan_start while a // BLE connection is active hangs the BLE notification path on ESP32-S3 // (radio/coexistence contention), so the scan is performed once in // wifi_board.cc BEFORE BLE starts and the result is cached here. // // Give the client a brief moment after enabling notifications and writing // the scan command. Without this, the first notify can race the mobile // stack and get dropped, which shows up as a scan timeout even though the // cache is ready. vTaskDelay(pdMS_TO_TICKS(120)); ESP_LOGI(TAG, "Returning %d cached WiFi networks via BLE notify", static_cast(prov.cached_networks_.size())); prov.NotifyWifiScanResults(prov.cached_networks_); vTaskDelete(NULL); } int BleProv::HandleWifiScanWrite(struct ble_gatt_access_ctxt* ctxt) { uint8_t cmd = 0; uint16_t len = OS_MBUF_PKTLEN(ctxt->om); if (len >= 1) { ble_hs_mbuf_to_flat(ctxt->om, &cmd, sizeof(cmd), NULL); } if (cmd == 0x01) { ESP_LOGI(TAG, "WiFi scan requested via BLE"); // Run scan in separate task to avoid blocking NimBLE thread BaseType_t task_ok = xTaskCreate(WifiScanTask, "ble_wifi_scan", 3072, NULL, 5, NULL); if (task_ok != pdPASS) { ESP_LOGE(TAG, "Failed to create WiFi scan task (stack=3072)"); } } return 0; } int BleProv::HandleWifiConfigWrite(struct ble_gatt_access_ctxt* ctxt) { uint16_t len = OS_MBUF_PKTLEN(ctxt->om); if (len < 3) return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; std::vector buf(len); ble_hs_mbuf_to_flat(ctxt->om, buf.data(), len, NULL); // Chunked protocol: [seq(1B)] [flag(1B)] [payload] uint8_t seq = buf[0]; uint8_t flag = buf[1]; std::string payload(reinterpret_cast(buf.data() + 2), len - 2); if (seq == 0) { wifi_config_buffer_.clear(); } wifi_config_buffer_ += payload; // flag=0x01 means last chunk if (flag != 0x01) { return 0; } ESP_LOGI(TAG, "WiFi config received: %zu bytes", wifi_config_buffer_.size()); // Parse complete JSON cJSON* root = cJSON_Parse(wifi_config_buffer_.c_str()); wifi_config_buffer_.clear(); if (!root) { ESP_LOGE(TAG, "WiFi config JSON parse failed"); NotifyWifiResult(false, "json_parse_error"); return 0; } cJSON* ssid_item = cJSON_GetObjectItem(root, "ssid"); cJSON* password_item = cJSON_GetObjectItem(root, "password"); if (!cJSON_IsString(ssid_item)) { cJSON_Delete(root); NotifyWifiResult(false, "missing_ssid"); return 0; } std::string ssid = ssid_item->valuestring; std::string password = cJSON_IsString(password_item) ? password_item->valuestring : ""; cJSON_Delete(root); ESP_LOGI(TAG, "WiFi config: ssid=%s", ssid.c_str()); // Store for async task and invoke callback off the NimBLE thread pending_ssid_ = ssid; pending_password_ = password; xTaskCreate(WifiConfigTask, "ble_wifi_cfg", 4096, NULL, 5, NULL); return 0; } void BleProv::WifiConfigTask(void* arg) { auto& prov = BleProv::GetInstance(); ESP_LOGI(TAG, "WiFi config task started"); if (prov.wifi_config_cb_) { prov.wifi_config_cb_(prov.pending_ssid_, prov.pending_password_); } vTaskDelete(NULL); } int BleProv::HandleCommandWrite(struct ble_gatt_access_ctxt* ctxt) { uint8_t cmd = 0; uint16_t len = OS_MBUF_PKTLEN(ctxt->om); if (len >= 1) { ble_hs_mbuf_to_flat(ctxt->om, &cmd, sizeof(cmd), NULL); } if (cmd == 0x01) { ESP_LOGI(TAG, "Reboot requested via BLE"); if (reboot_cb_) { reboot_cb_(); } } return 0; } // ============================================================ // Notifications // ============================================================ void BleProv::SendChunkedNotification(uint16_t attr_handle, const std::string& json_data) { if (!connected_) { ESP_LOGW(TAG, "Skip notify: disconnected, handle=%u, bytes=%u", attr_handle, static_cast(json_data.size())); return; } // Effective payload per chunk = MTU - 3 (ATT header) - 2 (seq + flag) uint16_t chunk_payload = current_mtu_ - 5; if (chunk_payload < 18) chunk_payload = 18; ESP_LOGI(TAG, "Notify start: handle=%u, bytes=%u, mtu=%u, chunk_payload=%u", attr_handle, static_cast(json_data.size()), current_mtu_, chunk_payload); size_t offset = 0; uint8_t seq = 0; size_t total = json_data.size(); while (offset < total) { size_t remaining = total - offset; size_t chunk_size = std::min(remaining, (size_t)chunk_payload); bool is_last = (offset + chunk_size >= total); // Build packet: [seq] [flag] [payload] std::vector packet(2 + chunk_size); packet[0] = seq; packet[1] = is_last ? 0x01 : 0x00; memcpy(packet.data() + 2, json_data.data() + offset, chunk_size); struct os_mbuf* om = ble_hs_mbuf_from_flat(packet.data(), packet.size()); if (om) { int rc = ble_gatts_notify_custom(conn_handle_, attr_handle, om); if (rc != 0) { ESP_LOGW(TAG, "Notify failed: rc=%d, seq=%d", rc, seq); break; } } offset += chunk_size; seq++; // Small delay between chunks to avoid BLE congestion. The WeChat BLE // stack on default MTU is noticeably more reliable with a wider gap // for multi-chunk WiFi scan payloads. if (!is_last) { vTaskDelay(pdMS_TO_TICKS(60)); } } ESP_LOGI(TAG, "Sent %d chunks for %zu bytes", seq, total); } void BleProv::NotifyWifiScanResults(const std::vector& networks) { cJSON* root = cJSON_CreateObject(); cJSON* arr = cJSON_AddArrayToObject(root, "networks"); for (const auto& net : networks) { cJSON* item = cJSON_CreateObject(); cJSON_AddStringToObject(item, "ssid", net.ssid.c_str()); cJSON_AddNumberToObject(item, "rssi", net.rssi); cJSON_AddNumberToObject(item, "auth", net.auth); cJSON_AddItemToArray(arr, item); } char* json_str = cJSON_PrintUnformatted(root); SendChunkedNotification(s_wifi_scan_val_handle, json_str); cJSON_free(json_str); cJSON_Delete(root); } void BleProv::NotifyWifiResult(bool success, const std::string& error) { if (!connected_) return; cJSON* root = cJSON_CreateObject(); cJSON_AddBoolToObject(root, "success", success); if (!success && !error.empty()) { cJSON_AddStringToObject(root, "error", error.c_str()); } char* json_str = cJSON_PrintUnformatted(root); std::string json(json_str); cJSON_free(json_str); cJSON_Delete(root); // WifiResult is small enough for a single notification struct os_mbuf* om = ble_hs_mbuf_from_flat(json.data(), json.size()); if (om) { ble_gatts_notify_custom(conn_handle_, s_wifi_result_val_handle, om); } ESP_LOGI(TAG, "WiFi result notified: %s", json.c_str()); } // ============================================================ // Saved WiFi management // ============================================================ int BleProv::HandleSavedWifiWrite(struct ble_gatt_access_ctxt* ctxt) { uint16_t len = OS_MBUF_PKTLEN(ctxt->om); if (len < 1) return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; std::vector buf(len); ble_hs_mbuf_to_flat(ctxt->om, buf.data(), len, NULL); uint8_t cmd = buf[0]; if (cmd == 0x01) { ESP_LOGI(TAG, "Saved WiFi list requested via BLE"); xTaskCreate(SavedWifiListTask, "ble_saved_list", 4096, NULL, 5, NULL); } else if (cmd == 0x02) { if (len < 2) return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; pending_delete_index_ = static_cast(buf[1]); ESP_LOGI(TAG, "Saved WiFi delete requested via BLE, index=%d", pending_delete_index_); xTaskCreate(SavedWifiDeleteTask, "ble_saved_del", 4096, NULL, 5, NULL); } return 0; } void BleProv::SavedWifiListTask(void* arg) { auto& prov = BleProv::GetInstance(); auto& ssid_mgr = SsidManager::GetInstance(); const auto& ssid_list = ssid_mgr.GetSsidList(); cJSON* root = cJSON_CreateObject(); cJSON* arr = cJSON_AddArrayToObject(root, "saved"); for (int i = 0; i < static_cast(ssid_list.size()); i++) { cJSON* item = cJSON_CreateObject(); cJSON_AddNumberToObject(item, "index", i); cJSON_AddStringToObject(item, "ssid", ssid_list[i].ssid.c_str()); cJSON_AddStringToObject(item, "password", ssid_list[i].password.c_str()); cJSON_AddItemToArray(arr, item); } char* json_str = cJSON_PrintUnformatted(root); prov.SendChunkedNotification(s_saved_wifi_val_handle, json_str); ESP_LOGI(TAG, "Saved WiFi list sent: %d items", static_cast(ssid_list.size())); cJSON_free(json_str); cJSON_Delete(root); vTaskDelete(NULL); } void BleProv::SavedWifiDeleteTask(void* arg) { auto& prov = BleProv::GetInstance(); auto& ssid_mgr = SsidManager::GetInstance(); int index = prov.pending_delete_index_; cJSON* root = cJSON_CreateObject(); const auto& ssid_list = ssid_mgr.GetSsidList(); if (index < 0 || index >= static_cast(ssid_list.size())) { cJSON_AddBoolToObject(root, "success", false); cJSON_AddStringToObject(root, "error", "invalid_index"); ESP_LOGW(TAG, "Saved WiFi delete failed: invalid index %d (total %d)", index, static_cast(ssid_list.size())); } else { ESP_LOGI(TAG, "Deleting saved WiFi index %d: %s", index, ssid_list[index].ssid.c_str()); ssid_mgr.RemoveSsid(index); cJSON_AddBoolToObject(root, "success", true); } char* json_str = cJSON_PrintUnformatted(root); prov.SendChunkedNotification(s_saved_wifi_val_handle, json_str); cJSON_free(json_str); cJSON_Delete(root); vTaskDelete(NULL); }