feat(example): add Classic Bluetooth PAN profile examples

This commit is contained in:
linruihao
2026-07-15 15:32:00 +08:00
parent 4f54340e51
commit 51eacff678
32 changed files with 2378 additions and 0 deletions

View File

@@ -96,6 +96,7 @@ CLASSIC_BT_DOCS = [
'api-reference/bluetooth/esp_hf_client.rst',
'api-reference/bluetooth/esp_hf_ag.rst',
'api-reference/bluetooth/esp_spp.rst',
'api-reference/bluetooth/esp_pan.rst',
'api-reference/bluetooth/esp_gap_bt.rst',
'migration-guides/release-5.x/5.0/bluetooth-classic.rst',
'migration-guides/release-5.x/5.2/bluetooth-classic.rst',

View File

@@ -13,6 +13,7 @@ The Bluetooth Classic API provides the following main features:
- Media playback control (**AVRCP**)
- Hands-free calling support (**HFP**)
- Input device connectivity (**HID** host and device roles)
- Personal Area Networking (**PAN**)
----
@@ -59,6 +60,10 @@ The Bluetooth Classic API in ESP-IDF is organized into the following parts:
- :doc:`Bluetooth HID Device <esp_hidd>`: Implements peripheral roles such as keyboard, mouse, or game controller
- :doc:`Bluetooth HID Host <esp_hidh>`: Implements the host role for connecting to remote HID devices
**Personal Area Networking (PAN)**
- :doc:`Bluetooth PAN <esp_pan>`: BNEP-based networking with PANU, NAP, and GN roles
Each part typically includes an **Overview**, **Application Examples**, and **API Reference**, covering purpose, main functionality, sample usage, and detailed API documentation.
@@ -77,3 +82,4 @@ Each part typically includes an **Overview**, **Application Examples**, and **AP
Bluetooth HFP AG <esp_hf_ag>
Bluetooth HID Device <esp_hidd>
Bluetooth HID Host <esp_hidh>
Bluetooth PAN <esp_pan>

View File

@@ -0,0 +1,23 @@
Bluetooth® PAN API
==================
:link_to_translation:`zh_CN:[中文]`
Overview
--------
PAN (Personal Area Networking) enables IP networking over Classic Bluetooth using BNEP (Bluetooth Network Encapsulation Protocol). Devices can act as a PAN User (PANU), Group Network (GN) hub, or Network Access Point (NAP) so peers can exchange Ethernet frames and obtain network access.
Application Examples
--------------------
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_nap` demonstrates how to use the PAN Network Access Point (NAP) role so that PANU peers can reach the Internet through the ESP device's Wi-Fi STA uplink.
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_panu` demonstrates how to use the PAN User (PANU) role to connect to a NAP (for example ``bt_pan_nap`` or a phone with Bluetooth tethering) and verify IP connectivity.
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_gn` demonstrates how to use the PAN Group Network (GN) role as a hub that bridges multiple PANU clients so they can communicate on the same subnet.
API Reference
-------------
.. include-build-file:: inc/esp_pan_api.inc

View File

@@ -13,6 +13,7 @@
- 媒体播放控制 (**AVRCP**)
- 免提通话支持 (**HFP**)
- 输入设备连接 **HID** 主机和外设角色)
- 个人区域网络 (**PAN**)
----
@@ -59,6 +60,10 @@
- :doc:`Bluetooth HID Device <esp_hidd>`:实现外设角色,如键盘、鼠标或游戏手柄
- :doc:`Bluetooth HID Host <esp_hidh>`:实现主机角色,用于连接远程 HID 外设
**个人区域网络 (PAN)**
- :doc:`Bluetooth PAN <esp_pan>`:基于 BNEP 的组网,支持 PANU、NAP 和 GN 角色
每个部分通常包含 **概述****应用示例****API 参考**,涵盖用途、主要功能、示例用法及详细 API 文档。
@@ -77,3 +82,4 @@
Bluetooth HFP AG <esp_hf_ag>
Bluetooth HID Device <esp_hidd>
Bluetooth HID Host <esp_hidh>
Bluetooth PAN <esp_pan>

View File

@@ -0,0 +1,23 @@
蓝牙\ :sup:`®` PAN API
======================
:link_to_translation:`en:[English]`
概述
----
PANPersonal Area Networking个人区域网络通过 BNEPBluetooth Network Encapsulation Protocol蓝牙网络封装协议在经典蓝牙上实现 IP 组网。设备可作为 PAN 用户PANU、组网中心GN或网络接入点NAP使对端设备能够交换以太网帧并获得网络访问。
应用示例
--------
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_nap` 演示如何使用 PAN 网络接入点NAP角色使 PANU 对端可通过 ESP 设备的 Wi-Fi STA 上行链路访问互联网。
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_panu` 演示如何使用 PAN 用户PANU角色连接 NAP例如 ``bt_pan_nap`` 或开启蓝牙网络共享的手机),并验证 IP 连通性。
- :example:`bluetooth/bluedroid/classic_bt/bt_pan_gn` 演示如何使用 PAN 组网GN角色作为中枢桥接多个 PANU 客户端,使其能在同一子网内通信。
API 参考
--------
.. include-build-file:: inc/esp_pan_api.inc

View File

@@ -0,0 +1,7 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
idf_build_set_property(MINIMAL_BUILD ON)
project(bt_pan_gn_demo)

View File

@@ -0,0 +1,61 @@
| Supported Targets | ESP32 | ESP32-S31 |
| ----------------- | ----- | --------- |
# ESP-IDF BT-PAN-GN Demo
## Required components
- [bt_app_core_utils](../common/bt_app_core_utils)
This example runs as a **Group Network (GN)** hub only. It stays discoverable, accepts incoming **PANU** connections (up to 4 in this example), and bridges Ethernet frames at the Bluetooth PAN layer so connected clients can reach the hub and each other.
## Topology
```
+------------------+
| ESP32 (GN hub) |
| BT: ESP_PAN_GN |
| IP: 192.168.100.1|
+--------+---------+
|
+--------------+--------------+
| PANU | PANU |
+---------+----+ +-----+--------+
| Client A | | Client B |
| .100.10 | | .100.11 |
+--------------+ +--------------+
```
- **This example**: GN role only; static IPv4 `192.168.100.1/24` (no DHCP server).
- **PANU clients**: any peer that connects as PANU → GN (e.g. another ESP app, or a host that supports Bluetooth PAN). Clients need addresses on `192.168.100.0/24` (static IP if the peer has no DHCP).
- **L2 bridging** between clients is done inside the Bluetooth PAN stack on the hub.
## Configure the Project
```
idf.py menuconfig
```
1. Enable PAN: `Component config → Bluetooth → Bluedroid Options → PAN`
2. Optional: `PAN GN Example Configuration → GN Hub Bluetooth name` (default `ESP_PAN_GN`)
## Build and Flash
```
idf.py -p PORT flash monitor
```
Power on the hub first, then connect PANU clients to `ESP_PAN_GN` with `esp_pan_connect(bda, ESP_PAN_ROLE_PANU, ESP_PAN_ROLE_GN)`.
## Expected log
```
I PAN_GN_DEMO: GN hub ready, waiting for PANU clients...
I PAN_GN_DEMO: PANU connected handle=1 peer=[...]
I PAN_NETIF: PAN link up, handle=1, links=1
```
## Notes
- Private PAN LAN only; no Internet uplink. For phone tethering see `bt_pan_panu` / `bt_pan_nap`.
- Pairing may be requested on first connect; the example auto-accepts SSP confirm.

View File

@@ -0,0 +1,3 @@
idf_component_register(SRCS "main.c" "pan_netif.c"
PRIV_REQUIRES bt bt_app_core_utils nvs_flash esp_netif esp_event lwip
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,9 @@
menu "PAN GN Example Configuration"
config EXAMPLE_PAN_GN_BT_NAME
string "GN Hub Bluetooth name"
default "ESP_PAN_GN"
help
Bluetooth name advertised by this GN hub. PANU clients scan for this exact name.
endmenu

View File

@@ -0,0 +1,3 @@
dependencies:
bt_app_core_utils:
path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils

View File

@@ -0,0 +1,213 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdio.h>
#include <string.h>
#include "nvs_flash.h"
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_bt_device.h"
#include "esp_pan_api.h"
#include "bt_app_core_utils.h"
#include "pan_netif.h"
#define PAN_GN_TAG "PAN_GN_DEMO"
/* Static IPv4 on the PAN GN subnet. */
#define PAN_GN_SUBNET_BASE "192.168.100"
#define PAN_GN_HUB_HOST_OCTET 1
static uint8_t s_local_mac[6] = {0};
static void bdaddr_to_eth_mac(const uint8_t *bda, uint8_t *mac)
{
/* PAN/BNEP uses BD_ADDR as the Ethernet MAC. Do not flip the U/L bit:
* the GN stack forwards unicast by matching dst MAC to rem_bda. */
memcpy(mac, bda, 6);
}
static void build_ipv4(char *buf, size_t len, int host_octet)
{
snprintf(buf, len, "%s.%d", PAN_GN_SUBNET_BASE, host_octet);
}
static char *bda2str(uint8_t *bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
return str;
}
static void setup_pan_netif(void)
{
pan_netif_cfg_t cfg = {0};
char ip[16];
char mask[16];
char gw[16];
build_ipv4(ip, sizeof(ip), PAN_GN_HUB_HOST_OCTET);
snprintf(mask, sizeof(mask), "255.255.255.0");
strncpy(gw, ip, sizeof(gw) - 1);
cfg.mac = s_local_mac;
strncpy(cfg.ip_str, ip, sizeof(cfg.ip_str) - 1);
strncpy(cfg.netmask_str, mask, sizeof(cfg.netmask_str) - 1);
strncpy(cfg.gw_str, gw, sizeof(cfg.gw_str) - 1);
ESP_ERROR_CHECK(pan_netif_init(&cfg));
ESP_LOGI(PAN_GN_TAG, "Network: IP=%s/24", ip);
}
static void esp_hdl_pan_cb_evt(uint16_t event, void *p_param)
{
esp_pan_cb_param_t *param = (esp_pan_cb_param_t *)p_param;
char bda_str[18] = {0};
switch (event) {
case ESP_PAN_INIT_EVT:
if (param->init.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_GN_TAG, "GN hub ready, waiting for PANU clients...");
esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
} else {
ESP_LOGE(PAN_GN_TAG, "PAN init failed, status=%d", param->init.status);
}
break;
case ESP_PAN_SET_ROLE_EVT:
ESP_LOGI(PAN_GN_TAG, "Role registered: 0x%02x", param->set_role.role);
break;
case ESP_PAN_OPENING_EVT:
ESP_LOGI(PAN_GN_TAG, "Incoming PANU, handle=%u peer=[%s]",
param->opening.handle,
bda2str(param->opening.remote_bda, bda_str, sizeof(bda_str)));
break;
case ESP_PAN_OPEN_EVT:
if (param->open.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_GN_TAG, "PANU connected handle=%u peer=[%s] local=0x%x peer=0x%x",
param->open.handle,
bda2str(param->open.remote_bda, bda_str, sizeof(bda_str)),
param->open.local_role, param->open.peer_role);
pan_netif_on_connected(param->open.handle, param->open.remote_bda);
} else {
ESP_LOGE(PAN_GN_TAG, "Connect failed, status=%d", param->open.status);
}
break;
case ESP_PAN_CLOSE_EVT:
ESP_LOGW(PAN_GN_TAG, "PANU disconnected handle=%u", param->close.handle);
pan_netif_on_disconnected(param->close.handle);
break;
default:
break;
}
}
static void esp_pan_cb(esp_pan_cb_event_t event, esp_pan_cb_param_t *param)
{
switch (event) {
case ESP_PAN_DATA_IND_EVT:
/* Feed RX to lwIP in callback to avoid an extra app_core deep-copy.
* esp_netif_receive is non-blocking by default (queues to tcpip thread). */
pan_netif_input(param->data_ind.handle, param->data_ind.dst, param->data_ind.src,
param->data_ind.protocol, param->data_ind.data, param->data_ind.len);
break;
case ESP_PAN_INIT_EVT:
case ESP_PAN_SET_ROLE_EVT:
case ESP_PAN_OPENING_EVT:
case ESP_PAN_OPEN_EVT:
case ESP_PAN_CLOSE_EVT:
bt_app_work_dispatch(esp_hdl_pan_cb_evt, event, param, sizeof(esp_pan_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
static void esp_hdl_bt_gap_cb_evt(uint16_t event, void *p_param)
{
esp_bt_gap_cb_param_t *param = (esp_bt_gap_cb_param_t *)p_param;
switch (event) {
case ESP_BT_GAP_AUTH_CMPL_EVT:
if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(PAN_GN_TAG, "Paired with %s", param->auth_cmpl.device_name);
} else {
ESP_LOGE(PAN_GN_TAG, "Pairing failed, status=%d", param->auth_cmpl.stat);
}
break;
case ESP_BT_GAP_CFM_REQ_EVT:
esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
break;
default:
break;
}
}
static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
switch (event) {
case ESP_BT_GAP_AUTH_CMPL_EVT:
case ESP_BT_GAP_CFM_REQ_EVT:
bt_app_work_dispatch(esp_hdl_bt_gap_cb_evt, event, param, sizeof(esp_bt_gap_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
void app_main(void)
{
char bda_str[18] = {0};
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg));
ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT));
esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bluedroid_init_with_cfg(&bluedroid_cfg));
ESP_ERROR_CHECK(esp_bluedroid_enable());
bt_app_task_start_up();
esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
esp_bt_gap_set_security_param(ESP_BT_SP_IOCAP_MODE, &iocap, sizeof(uint8_t));
ESP_ERROR_CHECK(esp_bt_gap_register_callback(esp_bt_gap_cb));
ESP_ERROR_CHECK(esp_pan_register_callback(esp_pan_cb));
ESP_ERROR_CHECK(esp_bt_gap_set_device_name(CONFIG_EXAMPLE_PAN_GN_BT_NAME));
bdaddr_to_eth_mac(esp_bt_dev_get_address(), s_local_mac);
setup_pan_netif();
esp_pan_cfg_t pan_cfg = ESP_PAN_DEFAULT_CONFIG();
pan_cfg.role = ESP_PAN_ROLE_GN;
ESP_ERROR_CHECK(esp_pan_init(&pan_cfg));
ESP_LOGI(PAN_GN_TAG, "GN \"%s\" BD_ADDR [%s]",
CONFIG_EXAMPLE_PAN_GN_BT_NAME,
bda2str((uint8_t *)esp_bt_dev_get_address(), bda_str, sizeof(bda_str)));
ESP_LOGI(PAN_GN_TAG, "PAN subnet: %s.%d/24 (static IP, no DHCP)",
PAN_GN_SUBNET_BASE, PAN_GN_HUB_HOST_OCTET);
}

View File

@@ -0,0 +1,336 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_netif_types.h"
#include "esp_pan_api.h"
#include "freertos/FreeRTOS.h"
#include "lwip/inet.h"
#include "pan_netif.h"
#define PAN_NETIF_TAG "PAN_NETIF"
#define ETH_HEADER_LEN 14
typedef struct {
uint16_t handle;
uint8_t peer_mac[6];
} pan_link_t;
typedef struct {
esp_netif_driver_base_t base;
pan_link_t links[PAN_NETIF_MAX_LINKS];
uint8_t num_handles;
uint8_t mac[6];
portMUX_TYPE lock;
} pan_netif_glue_t;
static esp_netif_t *s_pan_netif = NULL;
static pan_netif_glue_t *s_pan_glue = NULL;
static bool s_netif_up = false;
/* Match example main.c: Ethernet MAC is the peer BD_ADDR (PAN/BNEP). */
static void bdaddr_to_eth_mac(const uint8_t *bda, uint8_t *mac)
{
memcpy(mac, bda, 6);
}
static bool pan_link_add(pan_netif_glue_t *glue, uint16_t handle, const uint8_t *peer_mac)
{
bool ok = true;
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
if (peer_mac) {
memcpy(glue->links[i].peer_mac, peer_mac, 6);
}
portEXIT_CRITICAL(&glue->lock);
return true;
}
}
if (glue->num_handles >= PAN_NETIF_MAX_LINKS) {
ok = false;
} else {
pan_link_t *link = &glue->links[glue->num_handles++];
link->handle = handle;
if (peer_mac) {
memcpy(link->peer_mac, peer_mac, 6);
} else {
memset(link->peer_mac, 0, 6);
}
}
portEXIT_CRITICAL(&glue->lock);
if (!ok) {
ESP_LOGW(PAN_NETIF_TAG, "Too many PAN links (max %d)", PAN_NETIF_MAX_LINKS);
}
return ok;
}
static void pan_link_remove(pan_netif_glue_t *glue, uint16_t handle)
{
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
for (int j = i; j < glue->num_handles - 1; j++) {
glue->links[j] = glue->links[j + 1];
}
glue->num_handles--;
break;
}
}
portEXIT_CRITICAL(&glue->lock);
}
static void pan_link_learn_mac(pan_netif_glue_t *glue, uint16_t handle, const uint8_t *peer_mac)
{
if (peer_mac == NULL) {
return;
}
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
memcpy(glue->links[i].peer_mac, peer_mac, 6);
break;
}
}
portEXIT_CRITICAL(&glue->lock);
}
static uint16_t pan_link_lookup_by_mac(const pan_link_t *links, uint8_t num_handles, const uint8_t *dst_mac)
{
for (uint8_t i = 0; i < num_handles; i++) {
if (memcmp(links[i].peer_mac, dst_mac, 6) == 0) {
return links[i].handle;
}
}
return ESP_PAN_INVALID_HANDLE;
}
static esp_err_t pan_send_frame(uint16_t handle,
uint8_t *dst, uint8_t *src, uint16_t protocol,
uint8_t *payload, uint16_t payload_len)
{
if (handle == ESP_PAN_INVALID_HANDLE) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t ret = esp_pan_write(handle, dst, src, protocol, payload_len, payload, false);
return (ret == ESP_OK) ? ESP_OK : ESP_FAIL;
}
static esp_err_t pan_transmit(void *handle, void *data, size_t len)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)handle;
pan_link_t links_snapshot[PAN_NETIF_MAX_LINKS];
uint8_t num_handles;
if (glue == NULL || data == NULL || len < ETH_HEADER_LEN) {
return ESP_ERR_INVALID_STATE;
}
uint8_t *frame = (uint8_t *)data;
uint16_t protocol = ((uint16_t)frame[12] << 8) | frame[13];
uint16_t payload_len = (uint16_t)(len - ETH_HEADER_LEN);
uint8_t *payload = frame + ETH_HEADER_LEN;
bool is_bcast = (frame[0] & 0x01) != 0;
portENTER_CRITICAL(&glue->lock);
num_handles = glue->num_handles;
if (num_handles > 0) {
memcpy(links_snapshot, glue->links, num_handles * sizeof(links_snapshot[0]));
}
portEXIT_CRITICAL(&glue->lock);
if (num_handles == 0) {
return ESP_ERR_INVALID_STATE;
}
if (is_bcast) {
esp_err_t last = ESP_OK;
for (int i = 0; i < num_handles; i++) {
esp_err_t ret = pan_send_frame(links_snapshot[i].handle, frame, frame + 6,
protocol, payload, payload_len);
if (ret != ESP_OK) {
last = ret;
}
}
return last;
}
uint16_t out_handle = pan_link_lookup_by_mac(links_snapshot, num_handles, frame);
if (out_handle == ESP_PAN_INVALID_HANDLE) {
if (num_handles == 1) {
out_handle = links_snapshot[0].handle;
} else {
ESP_LOGW(PAN_NETIF_TAG, "No link for dst MAC %02x:%02x:%02x:%02x:%02x:%02x",
frame[0], frame[1], frame[2], frame[3], frame[4], frame[5]);
return ESP_ERR_NOT_FOUND;
}
}
return pan_send_frame(out_handle, frame, frame + 6, protocol, payload, payload_len);
}
static void pan_free_rx_buffer(void *handle, void *buffer)
{
(void)handle;
free(buffer);
}
static esp_err_t pan_post_attach(esp_netif_t *esp_netif, void *args)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)args;
glue->base.netif = esp_netif;
esp_netif_driver_ifconfig_t driver_cfg = {
.handle = glue,
.transmit = pan_transmit,
.driver_free_rx_buffer = pan_free_rx_buffer,
};
ESP_ERROR_CHECK(esp_netif_set_driver_config(esp_netif, &driver_cfg));
ESP_ERROR_CHECK(esp_netif_set_mac(esp_netif, glue->mac));
ESP_LOGI(PAN_NETIF_TAG, "PAN netif MAC %02x:%02x:%02x:%02x:%02x:%02x",
glue->mac[0], glue->mac[1], glue->mac[2], glue->mac[3], glue->mac[4], glue->mac[5]);
return ESP_OK;
}
static void pan_apply_static_ip(esp_netif_t *netif, const char *ip, const char *mask, const char *gw)
{
esp_netif_ip_info_t ip_info = {0};
ip_info.ip.addr = ipaddr_addr(ip);
ip_info.netmask.addr = ipaddr_addr(mask);
ip_info.gw.addr = ipaddr_addr(gw);
esp_netif_dhcpc_stop(netif);
esp_netif_set_ip_info(netif, &ip_info);
ESP_LOGI(PAN_NETIF_TAG, "Static IP %s, mask %s, gw %s", ip, mask, gw);
}
esp_err_t pan_netif_init(const pan_netif_cfg_t *cfg)
{
if (s_pan_netif != NULL || cfg == NULL || cfg->mac == NULL) {
return ESP_ERR_INVALID_ARG;
}
s_pan_glue = calloc(1, sizeof(pan_netif_glue_t));
if (s_pan_glue == NULL) {
return ESP_ERR_NO_MEM;
}
s_pan_glue->base.post_attach = pan_post_attach;
s_pan_glue->lock = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED;
memcpy(s_pan_glue->mac, cfg->mac, 6);
esp_netif_inherent_config_t base_cfg = ESP_NETIF_INHERENT_DEFAULT_ETH();
base_cfg.if_key = "PAN_GN";
base_cfg.if_desc = "pan_gn";
base_cfg.route_prio = 60;
esp_netif_config_t netif_cfg = {
.base = &base_cfg,
.stack = ESP_NETIF_NETSTACK_DEFAULT_ETH,
};
s_pan_netif = esp_netif_new(&netif_cfg);
if (s_pan_netif == NULL) {
free(s_pan_glue);
s_pan_glue = NULL;
return ESP_ERR_NO_MEM;
}
ESP_ERROR_CHECK(esp_netif_attach(s_pan_netif, s_pan_glue));
pan_apply_static_ip(s_pan_netif, cfg->ip_str, cfg->netmask_str, cfg->gw_str);
return ESP_OK;
}
esp_netif_t *pan_netif_get(void)
{
return s_pan_netif;
}
void pan_netif_on_connected(uint16_t handle, const uint8_t *peer_bda)
{
uint8_t peer_mac[6] = {0};
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
if (peer_bda) {
bdaddr_to_eth_mac(peer_bda, peer_mac);
}
if (!pan_link_add(s_pan_glue, handle, peer_mac)) {
return;
}
esp_netif_set_default_netif(s_pan_netif);
if (!s_netif_up) {
esp_netif_action_start(s_pan_netif, 0, 0, 0);
esp_netif_action_connected(s_pan_netif, 0, 0, 0);
s_netif_up = true;
}
uint8_t num_handles;
portENTER_CRITICAL(&s_pan_glue->lock);
num_handles = s_pan_glue->num_handles;
portEXIT_CRITICAL(&s_pan_glue->lock);
ESP_LOGI(PAN_NETIF_TAG, "PAN link up, handle=%u, links=%u", handle, num_handles);
}
void pan_netif_on_disconnected(uint16_t handle)
{
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
pan_link_remove(s_pan_glue, handle);
uint8_t num_handles;
portENTER_CRITICAL(&s_pan_glue->lock);
num_handles = s_pan_glue->num_handles;
portEXIT_CRITICAL(&s_pan_glue->lock);
ESP_LOGI(PAN_NETIF_TAG, "PAN link down, handle=%u, links=%u", handle, num_handles);
if (num_handles == 0 && s_netif_up) {
esp_netif_action_disconnected(s_pan_netif, 0, 0, 0);
esp_netif_action_stop(s_pan_netif, 0, 0, 0);
s_netif_up = false;
}
}
esp_err_t pan_netif_input(uint16_t handle, const uint8_t *dst, const uint8_t *src, uint16_t protocol,
const uint8_t *payload, uint16_t len)
{
if (s_pan_netif == NULL || s_pan_glue == NULL || payload == NULL || len == 0) {
return ESP_ERR_INVALID_STATE;
}
/* Learn the peer Ethernet MAC from the frame source for unicast TX routing. */
pan_link_learn_mac(s_pan_glue, handle, src);
size_t frame_len = ETH_HEADER_LEN + len;
uint8_t *frame = malloc(frame_len);
if (frame == NULL) {
return ESP_ERR_NO_MEM;
}
memcpy(frame, dst, 6);
memcpy(frame + 6, src, 6);
frame[12] = (protocol >> 8) & 0xff;
frame[13] = protocol & 0xff;
memcpy(frame + ETH_HEADER_LEN, payload, len);
/* esp_netif_receive takes ownership of frame and frees it via
* pan_free_rx_buffer on both success and failure paths. */
return esp_netif_receive(s_pan_netif, frame, frame_len, NULL);
}

View File

@@ -0,0 +1,27 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#pragma once
#include <stdint.h>
#include "esp_err.h"
#include "esp_netif.h"
#define PAN_NETIF_MAX_LINKS 4
typedef struct {
const uint8_t *mac;
char ip_str[16];
char netmask_str[16];
char gw_str[16];
} pan_netif_cfg_t;
esp_err_t pan_netif_init(const pan_netif_cfg_t *cfg);
esp_netif_t *pan_netif_get(void);
void pan_netif_on_connected(uint16_t handle, const uint8_t *peer_bda);
void pan_netif_on_disconnected(uint16_t handle);
esp_err_t pan_netif_input(uint16_t handle, const uint8_t *dst, const uint8_t *src,
uint16_t protocol, const uint8_t *payload, uint16_t len);

View File

@@ -0,0 +1,7 @@
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=n
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=y
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_CLASSIC_ENABLED=y
CONFIG_BT_PAN_ENABLED=y
CONFIG_BT_BLE_ENABLED=n

View File

@@ -0,0 +1,7 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
idf_build_set_property(MINIMAL_BUILD ON)
project(bt_pan_nap_demo)

View File

@@ -0,0 +1,71 @@
| Supported Targets | ESP32 | ESP32-S31 |
| ----------------- | ----- | --------- |
# ESP-IDF BT-PAN-NAP + Wi-Fi Uplink Demo
## Required components
- [bt_app_core_utils](../common/bt_app_core_utils)
The ESP device acts as **Bluetooth PAN NAP** (like a phone's Bluetooth tethering hotspot, but reversed): PANU devices connect over Bluetooth and reach the Internet through the ESP device's **Wi-Fi STA** link.
## Topology
```
[Internet]
|
[Wi-Fi AP: myssid] <-- sdkconfig: SSID / password
|
[ESP NAP] IP on Wi-Fi: DHCP from AP
| NAPT + IP forward
Bluetooth PAN (192.168.100.0/24, DHCP from ESP)
|
[Phone / PANU client]
```
- **Uplink**: Wi-Fi STA → configurable SSID (default `myssid`, password `mypassword`)
- **Downlink**: PAN NAP, DHCP server for PANU (`192.168.100.1/24`)
- **Forwarding**: lwIP NAPT on the PAN netif after Wi-Fi STA gets IP
## Configure the Project
```
idf.py menuconfig
```
| Menu | Option | Default |
|------|--------|---------|
| Bluetooth → Bluedroid | PAN | enabled |
| PAN NAP Wi-Fi Tether Example | Wi-Fi SSID | `myssid` |
| | Wi-Fi Password | `mypassword` |
| | Bluetooth device name | `ESP_PAN_NAP` |
## Build and Flash
```
idf.py -p PORT flash monitor
```
1. ESP connects to Wi-Fi first (`Wi-Fi uplink IP: ...`).
2. PAN NAP starts, Bluetooth name `ESP_PAN_NAP`.
3. On phone: pair with ESP, enable **Bluetooth tethering / PAN network** (wording varies) or connect as PANU to `ESP_PAN_NAP`.
4. Phone should get IP `192.168.100.x` from ESP and browse via Wi-Fi uplink. NAPT is enabled when the first PANU connects.
## Expected log
```
I PAN_NAP_DEMO: Connecting Wi-Fi SSID "myssid" ...
I PAN_NAP_DEMO: Wi-Fi uplink IP: 192.168.x.x, gw: ...
I PAN_NAP_DEMO: PAN NAP ready, waiting for PANU peers...
I PAN_NAP_DEMO: PANU connected handle=1 peer=[...]
I PAN_NETIF: NAPT enabled on PAN netif (traffic NAT via Wi-Fi uplink)
I PAN_NETIF: DHCP server started for PAN clients
I PAN_NETIF: PANU connected, handle=1, active_links=1
```
## Notes
- Requires **Wi-Fi + Classic BT coexistence** (BR/EDR only + `CONFIG_ESP_COEX_SW_COEXIST_ENABLE`).
- Not all phones expose PANU to third-party NAP; Android with Bluetooth PAN / tethering support works best.
- For phone hotspot use case (ESP as client), see `bt_pan_panu` instead.
- For multi-ESP private LAN without Internet, see `bt_pan_gn`.

View File

@@ -0,0 +1,3 @@
idf_component_register(SRCS "main.c" "pan_netif.c"
PRIV_REQUIRES bt bt_app_core_utils nvs_flash esp_netif esp_event esp_wifi lwip
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,24 @@
menu "PAN NAP Wi-Fi Tether Example"
config EXAMPLE_WIFI_SSID
string "Wi-Fi SSID (uplink)"
default "myssid"
help
Wi-Fi network the ESP32 NAP connects to for Internet uplink.
config EXAMPLE_WIFI_PASSWORD
string "Wi-Fi Password"
default "mypassword"
config EXAMPLE_WIFI_CONN_MAX_RETRY
int "Wi-Fi connection max retry"
default 10
range 0 100
config EXAMPLE_PAN_NAP_BT_NAME
string "Bluetooth device name (NAP)"
default "ESP_PAN_NAP"
help
PANU peers (e.g. phone) discover and connect to this name.
endmenu

View File

@@ -0,0 +1,3 @@
dependencies:
bt_app_core_utils:
path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils

View File

@@ -0,0 +1,306 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include "nvs_flash.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_bt_device.h"
#include "esp_pan_api.h"
#include "bt_app_core_utils.h"
#include "pan_netif.h"
#define PAN_NAP_TAG "PAN_NAP_DEMO"
/* PAN downlink subnet for DHCP clients. */
#define PAN_NAP_SUBNET_BASE "192.168.100"
#define PAN_NAP_HOST_OCTET 1
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
static EventGroupHandle_t s_wifi_event_group;
static esp_netif_t *s_wifi_sta_netif;
static int s_wifi_retry;
static bool s_wifi_uplink_ready;
static uint8_t s_pan_mac[6];
static void bdaddr_to_eth_mac(const uint8_t *bda, uint8_t *mac)
{
memcpy(mac, bda, 6);
mac[0] = (mac[0] | 0x02) & 0xFE;
}
static void build_ipv4(char *buf, size_t len, int host_octet)
{
snprintf(buf, len, "%s.%d", PAN_NAP_SUBNET_BASE, host_octet);
}
static char *bda2str(uint8_t *bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
return str;
}
static void wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
/*
* Bound retries only during the initial wifi_uplink_init() wait.
* After the uplink has been up once, keep reconnecting so PANU clients
* do not permanently lose internet when the AP drops briefly.
*/
if (s_wifi_uplink_ready) {
ESP_LOGW(PAN_NAP_TAG, "Wi-Fi uplink lost, reconnecting...");
esp_wifi_connect();
} else if (s_wifi_retry < CONFIG_EXAMPLE_WIFI_CONN_MAX_RETRY) {
esp_wifi_connect();
s_wifi_retry++;
ESP_LOGI(PAN_NAP_TAG, "Wi-Fi retry %d/%d", s_wifi_retry, CONFIG_EXAMPLE_WIFI_CONN_MAX_RETRY);
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
}
}
static void wifi_got_ip_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
s_wifi_retry = 0;
s_wifi_uplink_ready = true;
ESP_LOGI(PAN_NAP_TAG, "Wi-Fi uplink IP: " IPSTR ", gw: " IPSTR,
IP2STR(&event->ip_info.ip), IP2STR(&event->ip_info.gw));
esp_netif_set_default_netif(s_wifi_sta_netif);
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
static esp_err_t wifi_uplink_init(void)
{
s_wifi_event_group = xEventGroupCreate();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
s_wifi_sta_netif = esp_netif_create_default_wifi_sta();
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_got_ip_handler, NULL));
wifi_config_t wifi_config = {0};
/* ssid[32]/password[64] are fixed-size octets; do not reserve a trailing NUL. */
strncpy((char *)wifi_config.sta.ssid, CONFIG_EXAMPLE_WIFI_SSID,
sizeof(wifi_config.sta.ssid));
strncpy((char *)wifi_config.sta.password, CONFIG_EXAMPLE_WIFI_PASSWORD,
sizeof(wifi_config.sta.password));
wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(PAN_NAP_TAG, "Connecting Wi-Fi SSID \"%s\" ...", CONFIG_EXAMPLE_WIFI_SSID);
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE, pdFALSE, portMAX_DELAY);
if (bits & WIFI_FAIL_BIT) {
ESP_LOGE(PAN_NAP_TAG, "Wi-Fi connect failed");
return ESP_FAIL;
}
return ESP_OK;
}
static void setup_pan_netif(void)
{
pan_netif_cfg_t cfg = {0};
char ip[16];
char mask[16];
char gw[16];
build_ipv4(ip, sizeof(ip), PAN_NAP_HOST_OCTET);
snprintf(mask, sizeof(mask), "255.255.255.0");
strncpy(gw, ip, sizeof(gw) - 1);
cfg.mac = s_pan_mac;
strncpy(cfg.ip_str, ip, sizeof(cfg.ip_str) - 1);
strncpy(cfg.netmask_str, mask, sizeof(cfg.netmask_str) - 1);
strncpy(cfg.gw_str, gw, sizeof(cfg.gw_str) - 1);
ESP_ERROR_CHECK(pan_netif_init(&cfg));
}
static void esp_hdl_pan_cb_evt(uint16_t event, void *p_param)
{
esp_pan_cb_param_t *param = (esp_pan_cb_param_t *)p_param;
char bda_str[18] = {0};
switch (event) {
case ESP_PAN_INIT_EVT:
if (param->init.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_NAP_TAG, "PAN NAP ready, waiting for PANU peers...");
esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
} else {
ESP_LOGE(PAN_NAP_TAG, "PAN init failed, status=%d", param->init.status);
}
break;
case ESP_PAN_SET_ROLE_EVT:
ESP_LOGI(PAN_NAP_TAG, "NAP role registered: 0x%02x", param->set_role.role);
break;
case ESP_PAN_OPENING_EVT:
ESP_LOGI(PAN_NAP_TAG, "Incoming PANU, handle=%u peer=[%s]",
param->opening.handle,
bda2str(param->opening.remote_bda, bda_str, sizeof(bda_str)));
break;
case ESP_PAN_OPEN_EVT:
if (param->open.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_NAP_TAG, "PANU connected handle=%u peer=[%s]",
param->open.handle,
bda2str(param->open.remote_bda, bda_str, sizeof(bda_str)));
pan_netif_on_connected(param->open.handle, param->open.remote_bda);
} else {
ESP_LOGE(PAN_NAP_TAG, "PANU connect failed, status=%d", param->open.status);
}
break;
case ESP_PAN_CLOSE_EVT:
ESP_LOGW(PAN_NAP_TAG, "PANU disconnected handle=%u", param->close.handle);
pan_netif_on_disconnected(param->close.handle);
break;
case ESP_PAN_CONG_EVT:
/* Wi-Fi uplink is much faster than Classic BT; pause TX while BNEP is congested. */
pan_netif_on_cong(param->cong.handle, param->cong.cong);
break;
default:
break;
}
}
static void esp_pan_cb(esp_pan_cb_event_t event, esp_pan_cb_param_t *param)
{
switch (event) {
case ESP_PAN_DATA_IND_EVT:
/* Feed RX to lwIP in callback to avoid an extra app_core deep-copy.
* esp_netif_receive is non-blocking by default (queues to tcpip thread). */
pan_netif_input(param->data_ind.handle, param->data_ind.dst, param->data_ind.src,
param->data_ind.protocol, param->data_ind.data, param->data_ind.len);
break;
case ESP_PAN_INIT_EVT:
case ESP_PAN_SET_ROLE_EVT:
case ESP_PAN_OPENING_EVT:
case ESP_PAN_OPEN_EVT:
case ESP_PAN_CLOSE_EVT:
case ESP_PAN_CONG_EVT:
bt_app_work_dispatch(esp_hdl_pan_cb_evt, event, param, sizeof(esp_pan_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
static void esp_hdl_bt_gap_cb_evt(uint16_t event, void *p_param)
{
esp_bt_gap_cb_param_t *param = (esp_bt_gap_cb_param_t *)p_param;
switch (event) {
case ESP_BT_GAP_AUTH_CMPL_EVT:
if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(PAN_NAP_TAG, "Paired with %s", param->auth_cmpl.device_name);
} else {
ESP_LOGE(PAN_NAP_TAG, "Pairing failed, status=%d", param->auth_cmpl.stat);
}
break;
case ESP_BT_GAP_CFM_REQ_EVT:
esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
break;
default:
break;
}
}
static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
switch (event) {
case ESP_BT_GAP_AUTH_CMPL_EVT:
case ESP_BT_GAP_CFM_REQ_EVT:
bt_app_work_dispatch(esp_hdl_bt_gap_cb_evt, event, param, sizeof(esp_bt_gap_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
void app_main(void)
{
char bda_str[18] = {0};
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(wifi_uplink_init());
pan_netif_set_uplink(s_wifi_sta_netif);
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg));
ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT));
esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bluedroid_init_with_cfg(&bluedroid_cfg));
ESP_ERROR_CHECK(esp_bluedroid_enable());
bt_app_task_start_up();
esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
esp_bt_gap_set_security_param(ESP_BT_SP_IOCAP_MODE, &iocap, sizeof(uint8_t));
ESP_ERROR_CHECK(esp_bt_gap_register_callback(esp_bt_gap_cb));
ESP_ERROR_CHECK(esp_pan_register_callback(esp_pan_cb));
ESP_ERROR_CHECK(esp_bt_gap_set_device_name(CONFIG_EXAMPLE_PAN_NAP_BT_NAME));
bdaddr_to_eth_mac(esp_bt_dev_get_address(), s_pan_mac);
setup_pan_netif();
esp_pan_cfg_t pan_cfg = ESP_PAN_DEFAULT_CONFIG();
pan_cfg.role = ESP_PAN_ROLE_NAP;
ESP_ERROR_CHECK(esp_pan_init(&pan_cfg));
ESP_LOGI(PAN_NAP_TAG, "NAP \"%s\" BD_ADDR [%s]",
CONFIG_EXAMPLE_PAN_NAP_BT_NAME,
bda2str((uint8_t *)esp_bt_dev_get_address(), bda_str, sizeof(bda_str)));
ESP_LOGI(PAN_NAP_TAG, "Wi-Fi uplink: %s | PAN DHCP: %s.%d/24",
CONFIG_EXAMPLE_WIFI_SSID,
PAN_NAP_SUBNET_BASE, PAN_NAP_HOST_OCTET);
ESP_LOGI(PAN_NAP_TAG, "Pair phone/PANU and connect Bluetooth network to this device");
}

View File

@@ -0,0 +1,440 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_netif_types.h"
#include "esp_pan_api.h"
#include "freertos/FreeRTOS.h"
#include "lwip/inet.h"
#include "dhcpserver/dhcpserver.h"
#include "pan_netif.h"
#define PAN_NETIF_TAG "PAN_NETIF"
#define ETH_HEADER_LEN 14
typedef struct {
uint16_t handle;
uint8_t peer_mac[6];
bool congested;
} pan_link_t;
typedef struct {
esp_netif_driver_base_t base;
pan_link_t links[PAN_NETIF_MAX_LINKS];
uint8_t num_handles;
uint8_t mac[6];
portMUX_TYPE lock;
} pan_netif_glue_t;
static esp_netif_t *s_pan_netif = NULL;
static esp_netif_t *s_uplink_netif = NULL;
static pan_netif_glue_t *s_pan_glue = NULL;
static bool s_netif_up = false;
static bool s_dhcps_running = false;
static bool s_forwarding_ready = false;
static void bdaddr_to_eth_mac(const uint8_t *bda, uint8_t *mac)
{
memcpy(mac, bda, 6);
mac[0] = (mac[0] | 0x02) & 0xFE;
}
static void pan_netif_setup_forwarding(void)
{
if (s_pan_netif == NULL || s_forwarding_ready) {
return;
}
esp_netif_dns_info_t dns = {0};
if (s_uplink_netif != NULL &&
esp_netif_get_dns_info(s_uplink_netif, ESP_NETIF_DNS_MAIN, &dns) == ESP_OK &&
dns.ip.u_addr.ip4.addr != 0) {
ESP_LOGI(PAN_NETIF_TAG, "DHCP DNS from Wi-Fi uplink: " IPSTR, IP2STR(&dns.ip.u_addr.ip4));
} else {
dns.ip.u_addr.ip4.addr = ESP_IP4TOADDR(8, 8, 8, 8);
dns.ip.type = IPADDR_TYPE_V4;
ESP_LOGI(PAN_NETIF_TAG, "DHCP DNS fallback: 8.8.8.8");
}
dhcps_offer_t dhcps_dns_offer = OFFER_DNS;
ESP_ERROR_CHECK(esp_netif_dhcps_option(s_pan_netif, ESP_NETIF_OP_SET,
ESP_NETIF_DOMAIN_NAME_SERVER,
&dhcps_dns_offer, sizeof(dhcps_dns_offer)));
ESP_ERROR_CHECK(esp_netif_set_dns_info(s_pan_netif, ESP_NETIF_DNS_MAIN, &dns));
#if CONFIG_LWIP_IPV4_NAPT
if (esp_netif_napt_enable(s_pan_netif) == ESP_OK) {
ESP_LOGI(PAN_NETIF_TAG, "NAPT enabled on PAN netif (traffic NAT via Wi-Fi uplink)");
} else {
ESP_LOGW(PAN_NETIF_TAG, "NAPT enable failed on PAN netif");
}
#else
ESP_LOGW(PAN_NETIF_TAG, "Enable CONFIG_LWIP_IPV4_NAPT for Internet forwarding");
#endif
s_forwarding_ready = true;
}
static bool pan_link_add(pan_netif_glue_t *glue, uint16_t handle, const uint8_t *peer_mac)
{
bool ok = true;
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
if (peer_mac) {
memcpy(glue->links[i].peer_mac, peer_mac, 6);
}
portEXIT_CRITICAL(&glue->lock);
return true;
}
}
if (glue->num_handles >= PAN_NETIF_MAX_LINKS) {
ok = false;
} else {
pan_link_t *link = &glue->links[glue->num_handles++];
link->handle = handle;
link->congested = false;
if (peer_mac) {
memcpy(link->peer_mac, peer_mac, 6);
} else {
memset(link->peer_mac, 0, 6);
}
}
portEXIT_CRITICAL(&glue->lock);
if (!ok) {
ESP_LOGW(PAN_NETIF_TAG, "Too many PAN links (max %d)", PAN_NETIF_MAX_LINKS);
}
return ok;
}
static void pan_link_remove(pan_netif_glue_t *glue, uint16_t handle)
{
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
for (int j = i; j < glue->num_handles - 1; j++) {
glue->links[j] = glue->links[j + 1];
}
glue->num_handles--;
break;
}
}
portEXIT_CRITICAL(&glue->lock);
}
static void pan_link_learn_mac(pan_netif_glue_t *glue, uint16_t handle, const uint8_t *peer_mac)
{
if (peer_mac == NULL) {
return;
}
portENTER_CRITICAL(&glue->lock);
for (int i = 0; i < glue->num_handles; i++) {
if (glue->links[i].handle == handle) {
memcpy(glue->links[i].peer_mac, peer_mac, 6);
break;
}
}
portEXIT_CRITICAL(&glue->lock);
}
static uint16_t pan_link_lookup_by_mac(const pan_link_t *links, uint8_t num_handles, const uint8_t *dst_mac)
{
for (uint8_t i = 0; i < num_handles; i++) {
if (memcmp(links[i].peer_mac, dst_mac, 6) == 0) {
return links[i].handle;
}
}
return ESP_PAN_INVALID_HANDLE;
}
static bool pan_link_is_congested(const pan_link_t *links, uint8_t num_handles, uint16_t handle)
{
for (uint8_t i = 0; i < num_handles; i++) {
if (links[i].handle == handle) {
return links[i].congested;
}
}
return false;
}
static esp_err_t pan_send_frame(uint16_t handle, uint8_t *dst, uint8_t *src, uint16_t protocol,
uint8_t *payload, uint16_t payload_len)
{
if (handle == ESP_PAN_INVALID_HANDLE) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t ret = esp_pan_write(handle, dst, src, protocol, payload_len, payload, false);
return (ret == ESP_OK) ? ESP_OK : ESP_FAIL;
}
static esp_err_t pan_transmit(void *handle, void *data, size_t len)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)handle;
pan_link_t links_snapshot[PAN_NETIF_MAX_LINKS];
uint8_t num_handles;
if (glue == NULL || data == NULL || len < ETH_HEADER_LEN) {
return ESP_ERR_INVALID_STATE;
}
uint8_t *frame = (uint8_t *)data;
uint16_t protocol = ((uint16_t)frame[12] << 8) | frame[13];
uint16_t payload_len = (uint16_t)(len - ETH_HEADER_LEN);
uint8_t *payload = frame + ETH_HEADER_LEN;
bool is_bcast = (frame[0] & 0x01) != 0;
portENTER_CRITICAL(&glue->lock);
num_handles = glue->num_handles;
if (num_handles > 0) {
memcpy(links_snapshot, glue->links, num_handles * sizeof(links_snapshot[0]));
}
portEXIT_CRITICAL(&glue->lock);
if (num_handles == 0) {
return ESP_ERR_INVALID_STATE;
}
if (is_bcast) {
esp_err_t last = ESP_OK;
bool sent_any = false;
for (int i = 0; i < num_handles; i++) {
if (links_snapshot[i].congested) {
last = ESP_ERR_NO_MEM;
continue;
}
esp_err_t ret = pan_send_frame(links_snapshot[i].handle, frame, frame + 6, protocol,
payload, payload_len);
if (ret == ESP_OK) {
sent_any = true;
} else {
last = ret;
}
}
return sent_any ? ESP_OK : last;
}
uint16_t out_handle = pan_link_lookup_by_mac(links_snapshot, num_handles, frame);
if (out_handle == ESP_PAN_INVALID_HANDLE) {
if (num_handles == 1) {
out_handle = links_snapshot[0].handle;
} else {
ESP_LOGW(PAN_NETIF_TAG, "No link for dst MAC %02x:%02x:%02x:%02x:%02x:%02x",
frame[0], frame[1], frame[2], frame[3], frame[4], frame[5]);
return ESP_ERR_NOT_FOUND;
}
}
if (pan_link_is_congested(links_snapshot, num_handles, out_handle)) {
/* Drop and let TCP/IP back off; keeps writing would flood BNEP xmit_q. */
return ESP_ERR_NO_MEM;
}
return pan_send_frame(out_handle, frame, frame + 6, protocol, payload, payload_len);
}
static void pan_free_rx_buffer(void *handle, void *buffer)
{
(void)handle;
free(buffer);
}
static esp_err_t pan_post_attach(esp_netif_t *esp_netif, void *args)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)args;
glue->base.netif = esp_netif;
esp_netif_driver_ifconfig_t driver_cfg = {
.handle = glue,
.transmit = pan_transmit,
.driver_free_rx_buffer = pan_free_rx_buffer,
};
ESP_ERROR_CHECK(esp_netif_set_driver_config(esp_netif, &driver_cfg));
ESP_ERROR_CHECK(esp_netif_set_mac(esp_netif, glue->mac));
ESP_LOGI(PAN_NETIF_TAG, "PAN NAP netif MAC %02x:%02x:%02x:%02x:%02x:%02x",
glue->mac[0], glue->mac[1], glue->mac[2], glue->mac[3], glue->mac[4], glue->mac[5]);
return ESP_OK;
}
esp_err_t pan_netif_init(const pan_netif_cfg_t *cfg)
{
static esp_netif_ip_info_t pan_ip_info;
if (s_pan_netif != NULL || cfg == NULL || cfg->mac == NULL) {
return ESP_ERR_INVALID_ARG;
}
s_pan_glue = calloc(1, sizeof(pan_netif_glue_t));
if (s_pan_glue == NULL) {
return ESP_ERR_NO_MEM;
}
s_pan_glue->base.post_attach = pan_post_attach;
s_pan_glue->lock = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED;
memcpy(s_pan_glue->mac, cfg->mac, 6);
pan_ip_info.ip.addr = ipaddr_addr(cfg->ip_str);
pan_ip_info.netmask.addr = ipaddr_addr(cfg->netmask_str);
pan_ip_info.gw.addr = ipaddr_addr(cfg->gw_str);
esp_netif_inherent_config_t base_cfg = ESP_NETIF_INHERENT_DEFAULT_ETH();
base_cfg.if_key = "PAN_NAP";
base_cfg.if_desc = "pan_nap";
base_cfg.route_prio = 30;
base_cfg.flags = ESP_NETIF_DHCP_SERVER;
base_cfg.ip_info = &pan_ip_info;
esp_netif_config_t netif_cfg = {
.base = &base_cfg,
.stack = ESP_NETIF_NETSTACK_DEFAULT_ETH,
};
s_pan_netif = esp_netif_new(&netif_cfg);
if (s_pan_netif == NULL) {
free(s_pan_glue);
s_pan_glue = NULL;
return ESP_ERR_NO_MEM;
}
ESP_ERROR_CHECK(esp_netif_attach(s_pan_netif, s_pan_glue));
ESP_LOGI(PAN_NETIF_TAG, "PAN subnet %s/24, gateway %s (DHCP server)", cfg->ip_str, cfg->gw_str);
return ESP_OK;
}
esp_netif_t *pan_netif_get(void)
{
return s_pan_netif;
}
void pan_netif_set_uplink(esp_netif_t *wifi_sta_netif)
{
s_uplink_netif = wifi_sta_netif;
}
void pan_netif_on_connected(uint16_t handle, const uint8_t *peer_bda)
{
uint8_t peer_mac[6] = {0};
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
if (peer_bda) {
bdaddr_to_eth_mac(peer_bda, peer_mac);
}
if (!pan_link_add(s_pan_glue, handle, peer_mac)) {
return;
}
if (!s_netif_up) {
esp_netif_action_start(s_pan_netif, 0, 0, 0);
esp_netif_action_connected(s_pan_netif, 0, 0, 0);
s_netif_up = true;
pan_netif_setup_forwarding();
}
if (!s_dhcps_running) {
if (esp_netif_dhcps_start(s_pan_netif) == ESP_OK) {
s_dhcps_running = true;
ESP_LOGI(PAN_NETIF_TAG, "DHCP server started for PAN clients");
}
}
uint8_t num_handles;
portENTER_CRITICAL(&s_pan_glue->lock);
num_handles = s_pan_glue->num_handles;
portEXIT_CRITICAL(&s_pan_glue->lock);
ESP_LOGI(PAN_NETIF_TAG, "PANU connected, handle=%u, active_links=%u", handle, num_handles);
}
void pan_netif_on_cong(uint16_t handle, bool congested)
{
if (s_pan_glue == NULL) {
return;
}
portENTER_CRITICAL(&s_pan_glue->lock);
for (int i = 0; i < s_pan_glue->num_handles; i++) {
if (s_pan_glue->links[i].handle == handle) {
s_pan_glue->links[i].congested = congested;
break;
}
}
portEXIT_CRITICAL(&s_pan_glue->lock);
ESP_LOGD(PAN_NETIF_TAG, "PAN handle=%u congested=%d", handle, congested);
}
void pan_netif_on_disconnected(uint16_t handle)
{
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
pan_link_remove(s_pan_glue, handle);
uint8_t num_handles;
portENTER_CRITICAL(&s_pan_glue->lock);
num_handles = s_pan_glue->num_handles;
portEXIT_CRITICAL(&s_pan_glue->lock);
ESP_LOGI(PAN_NETIF_TAG, "PANU disconnected, handle=%u, active_links=%u", handle, num_handles);
if (num_handles == 0) {
if (s_dhcps_running) {
esp_netif_dhcps_stop(s_pan_netif);
s_dhcps_running = false;
}
if (s_netif_up) {
/*
* esp_netif_action_stop() removes the lwIP netif, which drops the
* NAPT flag. Clear s_forwarding_ready so the next PANU reconnect
* re-runs pan_netif_setup_forwarding() and re-enables NAPT.
*/
#if CONFIG_LWIP_IPV4_NAPT
esp_netif_napt_disable(s_pan_netif);
#endif
esp_netif_action_disconnected(s_pan_netif, 0, 0, 0);
esp_netif_action_stop(s_pan_netif, 0, 0, 0);
s_netif_up = false;
s_forwarding_ready = false;
}
}
}
esp_err_t pan_netif_input(uint16_t handle, const uint8_t *dst, const uint8_t *src, uint16_t protocol,
const uint8_t *payload, uint16_t len)
{
if (s_pan_netif == NULL || s_pan_glue == NULL || payload == NULL || len == 0) {
return ESP_ERR_INVALID_STATE;
}
/* Learn the peer Ethernet MAC from the frame source for unicast TX routing. */
pan_link_learn_mac(s_pan_glue, handle, src);
size_t frame_len = ETH_HEADER_LEN + len;
uint8_t *frame = malloc(frame_len);
if (frame == NULL) {
return ESP_ERR_NO_MEM;
}
memcpy(frame, dst, 6);
memcpy(frame + 6, src, 6);
frame[12] = (protocol >> 8) & 0xff;
frame[13] = protocol & 0xff;
memcpy(frame + ETH_HEADER_LEN, payload, len);
/* esp_netif_receive takes ownership of frame and frees it via
* pan_free_rx_buffer on both success and failure paths. */
return esp_netif_receive(s_pan_netif, frame, frame_len, NULL);
}

View File

@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#pragma once
#include <stdint.h>
#include "esp_err.h"
#include "esp_netif.h"
#define PAN_NETIF_MAX_LINKS 4
typedef struct {
const uint8_t *mac;
char ip_str[16];
char netmask_str[16];
char gw_str[16];
} pan_netif_cfg_t;
esp_err_t pan_netif_init(const pan_netif_cfg_t *cfg);
esp_netif_t *pan_netif_get(void);
void pan_netif_set_uplink(esp_netif_t *wifi_sta_netif);
void pan_netif_on_connected(uint16_t handle, const uint8_t *peer_bda);
void pan_netif_on_disconnected(uint16_t handle);
void pan_netif_on_cong(uint16_t handle, bool congested);
esp_err_t pan_netif_input(uint16_t handle, const uint8_t *dst, const uint8_t *src,
uint16_t protocol, const uint8_t *payload, uint16_t len);

View File

@@ -0,0 +1,14 @@
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=n
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=y
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_CLASSIC_ENABLED=y
CONFIG_BT_PAN_ENABLED=y
CONFIG_BT_BLE_ENABLED=n
CONFIG_ESP_COEX_SW_COEXIST_ENABLE=y
CONFIG_LWIP_IP_FORWARD=y
CONFIG_LWIP_IPV4_NAPT=y
CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE=y

View File

@@ -0,0 +1,7 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
idf_build_set_property(MINIMAL_BUILD ON)
project(bt_pan_panu_demo)

View File

@@ -0,0 +1,81 @@
| Supported Targets | ESP32 | ESP32-S31 |
| ----------------- | ----- | --------- |
# ESP-IDF BT-PAN-PANU Demo
## Required components
- [bt_app_core_utils](../common/bt_app_core_utils)
This example shows how to use the **Personal Area Networking (PAN)** profile as **PANU** (PAN User) to connect to a **NAP** (Network Access Point).
By default it looks for the Bluetooth name `ESP_PAN_NAP`, which matches the companion example `bt_pan_nap`. You can also connect to a phone that shares Internet via Bluetooth tethering.
The ESP32 discovers the NAP by Bluetooth name, pairs with it, establishes a PAN connection, obtains an IP address via DHCP through lwIP, and **pings a configurable target** to verify connectivity.
## Prerequisites
### Option A: ESP32 NAP (`bt_pan_nap`)
1. Flash and run `examples/bluetooth/bluedroid/classic_bt/bt_pan_nap` on another ESP32.
2. Ensure its Bluetooth name is `ESP_PAN_NAP` (the default).
3. Keep the default `Target NAP Bluetooth Name` in this example, or set it to match.
### Option B: Phone NAP
1. Pair the ESP32 with the phone in system Bluetooth settings (recommended), or let pairing happen during connection.
2. Enable **Bluetooth tethering** / **Bluetooth PAN** / **Internet sharing via Bluetooth** (wording varies by vendor).
3. Set the phone's Bluetooth name in menuconfig (`Target NAP Bluetooth Name`).
On Android: Settings → Network → Hotspot & tethering → Bluetooth tethering.
On iPhone: Settings → Personal Hotspot → enable *Allow Others to Join*, and ensure Bluetooth is on.
## Configure the Project
```
idf.py menuconfig
```
1. Enable PAN: `Component config → Bluetooth → Bluedroid Options → PAN (Personal Area Networking)`
2. Set NAP name: `PAN PANU Example Configuration → Target NAP Bluetooth Name` (default `ESP_PAN_NAP`)
3. Set ping target: `PAN PANU Example Configuration → Ping Target` (default `8.8.8.8`)
## Build and Flash
```
idf.py -p PORT flash monitor
```
## Example Flow
1. Initialize Classic Bluetooth, lwIP (`esp_netif`), and PAN (PANU role only).
2. Start GAP inquiry for the configured NAP name.
3. Call `esp_pan_connect()` as PANU to the peer's NAP service.
4. On `ESP_PAN_OPEN_EVT`, bring up the PAN netif and start DHCP client.
5. Feed received PAN Ethernet frames into lwIP; transmit lwIP frames via `esp_pan_write()`.
6. On `IP_EVENT_ETH_GOT_IP`, automatically ping the configured target.
## Expected log
```
I (1234) PAN_PANU_DEMO: Looking for NAP "ESP_PAN_NAP"
I (1234) PAN_PANU_DEMO: Will ping 8.8.8.8 after DHCP
I (5678) PAN_PANU_DEMO: PAN connected, handle=1, peer=[...], local_role=0x1, peer_role=0x4
I (5680) PAN_NETIF: PAN link up, DHCP client started
I (6200) PAN_NETIF: Got IP: 192.168.100.2, mask: 255.255.255.0, gw: 192.168.100.1
I (6200) PAN_NETIF: Start ping 8.8.8.8 (20 packets)
I (6450) PAN_NETIF: 64 bytes from 8.8.8.8 icmp_seq=1 ttl=118 time=180 ms
I (6700) PAN_NETIF: --- 8.8.8.8 ping statistics ---
I (6700) PAN_NETIF: 20 packets transmitted, 20 received, 0% packet loss, time 3200 ms
```
## Troubleshooting
| Symptom | Suggestion |
| ------- | ---------- |
| NAP not found | Check Bluetooth name in menuconfig (default `ESP_PAN_NAP`); move devices closer |
| Connect failed | Confirm NAP is running / phone tethering is on; delete old pairing and retry |
| PAN connected but no IP | Wait a few seconds; some NAPs delay DHCP |
| Ping timeout | Try `8.8.8.8` first; ensure uplink Internet is available |
| Pairing failed | Accept pairing on peer; check SSP/passkey logs |

View File

@@ -0,0 +1,3 @@
idf_component_register(SRCS "main.c" "pan_netif.c"
PRIV_REQUIRES bt bt_app_core_utils nvs_flash esp_netif esp_event lwip
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,26 @@
menu "PAN PANU Example Configuration"
config EXAMPLE_PEER_DEVICE_NAME
string "Target NAP Bluetooth Name"
default "ESP_PAN_NAP"
help
Bluetooth name of the NAP device that shares network access.
Default matches bt_pan_nap example device name.
config EXAMPLE_PING_TARGET
string "Ping Target (IPv4 address)"
default "8.8.8.8"
help
IPv4 address to ping after PAN link obtains an IP via DHCP
(e.g. 8.8.8.8). Hostnames are not resolved; use a dotted-quad
address only.
config EXAMPLE_PING_COUNT
int "Ping Count"
default 20
range 1 1000
config EXAMPLE_PING_TIMEOUT_MS
int "Ping Timeout (ms)"
default 3000
range 500 30000
endmenu

View File

@@ -0,0 +1,3 @@
dependencies:
bt_app_core_utils:
path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils

View File

@@ -0,0 +1,325 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#include "nvs_flash.h"
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_bt_device.h"
#include "esp_pan_api.h"
#include "bt_app_core_utils.h"
#include "pan_netif.h"
#define PAN_TAG "PAN_PANU_DEMO"
#define EXAMPLE_DEVICE_NAME "ESP_PAN_PANU"
#define ETH_ADDR_LEN 6
static const char remote_device_name[] = CONFIG_EXAMPLE_PEER_DEVICE_NAME;
static esp_bd_addr_t peer_bd_addr = {0};
static uint8_t peer_bdname_len = 0;
static char peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1] = {0};
static uint8_t s_local_mac[ETH_ADDR_LEN] = {0};
static bool s_peer_found = false;
static const esp_bt_inq_mode_t inq_mode = ESP_BT_INQ_MODE_GENERAL_INQUIRY;
static const uint8_t inq_len = 5;
static const uint8_t inq_num_rsps = 0;
static char *bda2str(uint8_t *bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
return str;
}
static void bdaddr_to_eth_mac(const uint8_t *bda, uint8_t *mac)
{
memcpy(mac, bda, ETH_ADDR_LEN);
mac[0] = (mac[0] | 0x02) & 0xFE;
}
static bool get_name_from_eir(uint8_t *eir, char *bdname, uint8_t *bdname_len)
{
uint8_t *rmt_bdname = NULL;
uint8_t rmt_bdname_len = 0;
if (!eir) {
return false;
}
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len);
if (!rmt_bdname) {
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len);
}
if (rmt_bdname) {
if (rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN) {
rmt_bdname_len = ESP_BT_GAP_MAX_BDNAME_LEN;
}
if (bdname) {
memcpy(bdname, rmt_bdname, rmt_bdname_len);
bdname[rmt_bdname_len] = '\0';
}
if (bdname_len) {
*bdname_len = rmt_bdname_len;
}
return true;
}
return false;
}
static void start_pan_connect(void)
{
char bda_str[18] = {0};
ESP_LOGI(PAN_TAG, "Connect PANU -> NAP, peer [%s]",
bda2str(peer_bd_addr, bda_str, sizeof(bda_str)));
esp_err_t ret = esp_pan_connect(peer_bd_addr, ESP_PAN_ROLE_PANU, ESP_PAN_ROLE_NAP);
if (ret != ESP_OK) {
ESP_LOGE(PAN_TAG, "esp_pan_connect failed: %s", esp_err_to_name(ret));
s_peer_found = false;
esp_bt_gap_start_discovery(inq_mode, inq_len, inq_num_rsps);
}
}
static void restart_peer_inquiry(const char *reason)
{
ESP_LOGW(PAN_TAG, "%s, restart inquiry for \"%s\"", reason, remote_device_name);
s_peer_found = false;
esp_bt_gap_start_discovery(inq_mode, inq_len, inq_num_rsps);
}
static void esp_hdl_pan_cb_evt(uint16_t event, void *p_param)
{
esp_pan_cb_param_t *param = (esp_pan_cb_param_t *)p_param;
char bda_str[18] = {0};
switch (event) {
case ESP_PAN_INIT_EVT:
if (param->init.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_TAG, "PAN initialized, start inquiry for \"%s\"", remote_device_name);
esp_bt_gap_set_device_name(EXAMPLE_DEVICE_NAME);
esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
esp_bt_gap_start_discovery(inq_mode, inq_len, inq_num_rsps);
} else {
ESP_LOGE(PAN_TAG, "ESP_PAN_INIT_EVT failed, status=%d", param->init.status);
}
break;
case ESP_PAN_SET_ROLE_EVT:
ESP_LOGI(PAN_TAG, "PAN role set: 0x%02x, status=%d",
param->set_role.role, param->set_role.status);
break;
case ESP_PAN_OPENING_EVT:
ESP_LOGI(PAN_TAG, "PAN opening, handle=%u, peer=[%s]",
param->opening.handle,
bda2str(param->opening.remote_bda, bda_str, sizeof(bda_str)));
break;
case ESP_PAN_OPEN_EVT:
if (param->open.status == ESP_PAN_SUCCESS) {
ESP_LOGI(PAN_TAG, "PAN connected, handle=%u, peer=[%s], local_role=0x%x, peer_role=0x%x",
param->open.handle,
bda2str(param->open.remote_bda, bda_str, sizeof(bda_str)),
param->open.local_role, param->open.peer_role);
pan_netif_on_connected(param->open.handle);
} else {
ESP_LOGE(PAN_TAG, "PAN connect failed, status=%d", param->open.status);
restart_peer_inquiry("connect failed");
}
break;
case ESP_PAN_CLOSE_EVT:
ESP_LOGW(PAN_TAG, "PAN disconnected, handle=%u", param->close.handle);
pan_netif_on_disconnected();
restart_peer_inquiry("disconnected");
break;
case ESP_PAN_CONG_EVT:
ESP_LOGI(PAN_TAG, "PAN congestion, handle=%u, cong=%d",
param->cong.handle, param->cong.cong);
break;
case ESP_PAN_DEINIT_EVT:
ESP_LOGI(PAN_TAG, "PAN deinitialized, status=%d", param->deinit.status);
break;
default:
break;
}
}
static void esp_pan_cb(esp_pan_cb_event_t event, esp_pan_cb_param_t *param)
{
switch (event) {
case ESP_PAN_DATA_IND_EVT:
/* Feed RX to lwIP in callback to avoid an extra app_core deep-copy.
* esp_netif_receive is non-blocking by default (queues to tcpip thread). */
pan_netif_input(param->data_ind.dst, param->data_ind.src, param->data_ind.protocol,
param->data_ind.data, param->data_ind.len);
break;
case ESP_PAN_INIT_EVT:
case ESP_PAN_SET_ROLE_EVT:
case ESP_PAN_OPENING_EVT:
case ESP_PAN_OPEN_EVT:
case ESP_PAN_CLOSE_EVT:
case ESP_PAN_CONG_EVT:
case ESP_PAN_DEINIT_EVT:
bt_app_work_dispatch(esp_hdl_pan_cb_evt, event, param, sizeof(esp_pan_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
static void esp_hdl_bt_gap_cb_evt(uint16_t event, void *p_param)
{
esp_bt_gap_cb_param_t *param = (esp_bt_gap_cb_param_t *)p_param;
switch (event) {
case ESP_BT_GAP_DISC_RES_EVT:
/* peer_bd_addr already saved in GAP callback before dispatch */
ESP_LOGI(PAN_TAG, "Found NAP \"%s\"", peer_bdname);
esp_bt_gap_cancel_discovery();
start_pan_connect();
break;
case ESP_BT_GAP_DISC_STATE_CHANGED_EVT:
if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED && !s_peer_found) {
ESP_LOGW(PAN_TAG, "NAP \"%s\" not found, restart inquiry", remote_device_name);
esp_bt_gap_start_discovery(inq_mode, inq_len, inq_num_rsps);
}
break;
case ESP_BT_GAP_AUTH_CMPL_EVT:
if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(PAN_TAG, "Pairing success: %s", param->auth_cmpl.device_name);
} else {
ESP_LOGE(PAN_TAG, "Pairing failed, status=%d", param->auth_cmpl.stat);
}
break;
case ESP_BT_GAP_PIN_REQ_EVT:
ESP_LOGI(PAN_TAG, "PIN requested, reply 1234");
{
esp_bt_pin_code_t pin_code = {'1', '2', '3', '4'};
esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
}
break;
case ESP_BT_GAP_CFM_REQ_EVT:
ESP_LOGI(PAN_TAG, "SSP confirm: %" PRIu32, param->cfm_req.num_val);
esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
break;
case ESP_BT_GAP_KEY_NOTIF_EVT:
ESP_LOGI(PAN_TAG, "SSP passkey: %06" PRIu32, param->key_notif.passkey);
break;
default:
break;
}
}
static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
switch (event) {
case ESP_BT_GAP_DISC_RES_EVT:
/*
* Discovery properties (EIR) are only valid in the GAP callback context.
* Match the peer name here, then dispatch API work (cancel/connect) to app_core.
*/
for (int i = 0; i < param->disc_res.num_prop; i++) {
if (param->disc_res.prop[i].type == ESP_BT_GAP_DEV_PROP_EIR
&& get_name_from_eir(param->disc_res.prop[i].val, peer_bdname, &peer_bdname_len)) {
if (!s_peer_found
&& strlen(remote_device_name) == peer_bdname_len
&& strncmp(peer_bdname, remote_device_name, peer_bdname_len) == 0) {
s_peer_found = true;
memcpy(peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN);
bt_app_work_dispatch(esp_hdl_bt_gap_cb_evt, event, NULL, 0, NULL, NULL);
}
}
}
break;
case ESP_BT_GAP_DISC_STATE_CHANGED_EVT:
case ESP_BT_GAP_AUTH_CMPL_EVT:
case ESP_BT_GAP_PIN_REQ_EVT:
case ESP_BT_GAP_CFM_REQ_EVT:
case ESP_BT_GAP_KEY_NOTIF_EVT:
bt_app_work_dispatch(esp_hdl_bt_gap_cb_evt, event, param, sizeof(esp_bt_gap_cb_param_t), NULL, NULL);
break;
default:
break;
}
}
void app_main(void)
{
esp_err_t ret;
char bda_str[18] = {0};
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg));
ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT));
esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_bluedroid_init_with_cfg(&bluedroid_cfg));
ESP_ERROR_CHECK(esp_bluedroid_enable());
bt_app_task_start_up();
esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
esp_bt_gap_set_security_param(ESP_BT_SP_IOCAP_MODE, &iocap, sizeof(uint8_t));
ESP_ERROR_CHECK(esp_bt_gap_register_callback(esp_bt_gap_cb));
ESP_ERROR_CHECK(esp_pan_register_callback(esp_pan_cb));
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
esp_bt_pin_code_t pin_code;
esp_bt_gap_set_pin(pin_type, 0, pin_code);
bdaddr_to_eth_mac(esp_bt_dev_get_address(), s_local_mac);
ESP_ERROR_CHECK(pan_netif_init(s_local_mac));
esp_pan_cfg_t pan_cfg = ESP_PAN_DEFAULT_CONFIG();
pan_cfg.role = ESP_PAN_ROLE_PANU;
ESP_ERROR_CHECK(esp_pan_init(&pan_cfg));
ESP_LOGI(PAN_TAG, "Own BD_ADDR [%s]", bda2str((uint8_t *)esp_bt_dev_get_address(), bda_str, sizeof(bda_str)));
ESP_LOGI(PAN_TAG, "Looking for NAP \"%s\"", remote_device_name);
ESP_LOGI(PAN_TAG, "Will ping %s after DHCP", CONFIG_EXAMPLE_PING_TARGET);
}

View File

@@ -0,0 +1,284 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_netif_types.h"
#include "esp_pan_api.h"
#include "lwip/inet.h"
#include "ping/ping_sock.h"
#include "pan_netif.h"
#define PAN_NETIF_TAG "PAN_NETIF"
#define ETH_HEADER_LEN 14
typedef struct {
esp_netif_driver_base_t base;
uint16_t pan_handle;
uint8_t mac[6];
} pan_netif_glue_t;
static esp_netif_t *s_pan_netif = NULL;
static pan_netif_glue_t *s_pan_glue = NULL;
static esp_ping_handle_t s_ping = NULL;
static bool s_ping_started = false;
static esp_err_t pan_transmit(void *handle, void *data, size_t len)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)handle;
if (glue == NULL || glue->pan_handle == ESP_PAN_INVALID_HANDLE || data == NULL || len < ETH_HEADER_LEN) {
return ESP_ERR_INVALID_STATE;
}
uint8_t *frame = (uint8_t *)data;
uint16_t protocol = ((uint16_t)frame[12] << 8) | frame[13];
uint16_t payload_len = (uint16_t)(len - ETH_HEADER_LEN);
esp_err_t ret = esp_pan_write(glue->pan_handle, frame, frame + 6, protocol,
payload_len, frame + ETH_HEADER_LEN, false);
return (ret == ESP_OK) ? ESP_OK : ESP_FAIL;
}
static void pan_free_rx_buffer(void *handle, void *buffer)
{
(void)handle;
free(buffer);
}
static esp_err_t pan_post_attach(esp_netif_t *esp_netif, void *args)
{
pan_netif_glue_t *glue = (pan_netif_glue_t *)args;
glue->base.netif = esp_netif;
esp_netif_driver_ifconfig_t driver_cfg = {
.handle = glue,
.transmit = pan_transmit,
.driver_free_rx_buffer = pan_free_rx_buffer,
};
ESP_ERROR_CHECK(esp_netif_set_driver_config(esp_netif, &driver_cfg));
ESP_ERROR_CHECK(esp_netif_set_mac(esp_netif, glue->mac));
ESP_LOGI(PAN_NETIF_TAG, "PAN netif attached, MAC %02x:%02x:%02x:%02x:%02x:%02x",
glue->mac[0], glue->mac[1], glue->mac[2], glue->mac[3], glue->mac[4], glue->mac[5]);
return ESP_OK;
}
static void pan_ping_on_success(esp_ping_handle_t hdl, void *args)
{
uint8_t ttl;
uint16_t seqno;
uint32_t elapsed_time, recv_len;
ip_addr_t target_addr;
esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno));
esp_ping_get_profile(hdl, ESP_PING_PROF_TTL, &ttl, sizeof(ttl));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr));
esp_ping_get_profile(hdl, ESP_PING_PROF_SIZE, &recv_len, sizeof(recv_len));
esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_time));
ESP_LOGI(PAN_NETIF_TAG, "%" PRIu32 " bytes from %s icmp_seq=%u ttl=%u time=%" PRIu32 " ms",
recv_len, ipaddr_ntoa(&target_addr), seqno, ttl, elapsed_time);
}
static void pan_ping_on_timeout(esp_ping_handle_t hdl, void *args)
{
uint16_t seqno;
ip_addr_t target_addr;
esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr));
ESP_LOGW(PAN_NETIF_TAG, "From %s icmp_seq=%u timeout", ipaddr_ntoa(&target_addr), seqno);
}
static void pan_ping_on_end(esp_ping_handle_t hdl, void *args)
{
ip_addr_t target_addr;
uint32_t transmitted;
uint32_t received;
uint32_t total_time_ms;
esp_ping_get_profile(hdl, ESP_PING_PROF_REQUEST, &transmitted, sizeof(transmitted));
esp_ping_get_profile(hdl, ESP_PING_PROF_REPLY, &received, sizeof(received));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr));
esp_ping_get_profile(hdl, ESP_PING_PROF_DURATION, &total_time_ms, sizeof(total_time_ms));
uint32_t loss = transmitted ? (uint32_t)((1.0f - ((float)received / transmitted)) * 100) : 100;
ESP_LOGI(PAN_NETIF_TAG, "--- %s ping statistics ---", ipaddr_ntoa(&target_addr));
ESP_LOGI(PAN_NETIF_TAG, "%" PRIu32 " packets transmitted, %" PRIu32 " received, %" PRIu32 "%% packet loss, time %" PRIu32 " ms",
transmitted, received, loss, total_time_ms);
if (s_ping == hdl) {
s_ping = NULL;
s_ping_started = false;
}
esp_ping_delete_session(hdl);
}
static void pan_stop_ping(void)
{
if (s_ping == NULL) {
s_ping_started = false;
return;
}
esp_ping_handle_t hdl = s_ping;
s_ping = NULL;
s_ping_started = false;
esp_ping_stop(hdl);
esp_ping_delete_session(hdl);
}
static void pan_start_ping(void)
{
if (s_ping_started || s_pan_netif == NULL) {
return;
}
ip_addr_t target_addr = {0};
if (!ipaddr_aton(CONFIG_EXAMPLE_PING_TARGET, &target_addr)) {
ESP_LOGE(PAN_NETIF_TAG, "Invalid ping target: %s", CONFIG_EXAMPLE_PING_TARGET);
return;
}
esp_ping_config_t config = ESP_PING_DEFAULT_CONFIG();
config.target_addr = target_addr;
config.count = CONFIG_EXAMPLE_PING_COUNT;
config.timeout_ms = CONFIG_EXAMPLE_PING_TIMEOUT_MS;
config.interface = esp_netif_get_netif_impl_index(s_pan_netif);
esp_ping_callbacks_t cbs = {
.on_ping_success = pan_ping_on_success,
.on_ping_timeout = pan_ping_on_timeout,
.on_ping_end = pan_ping_on_end,
};
esp_ping_handle_t ping = NULL;
if (esp_ping_new_session(&config, &cbs, &ping) != ESP_OK) {
ESP_LOGE(PAN_NETIF_TAG, "Failed to create ping session");
return;
}
s_ping = ping;
s_ping_started = true;
ESP_LOGI(PAN_NETIF_TAG, "Start ping %s (%u packets)", CONFIG_EXAMPLE_PING_TARGET, config.count);
esp_ping_start(ping);
}
static void pan_on_got_ip(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
ESP_LOGI(PAN_NETIF_TAG, "Got IP: " IPSTR ", mask: " IPSTR ", gw: " IPSTR,
IP2STR(&event->ip_info.ip), IP2STR(&event->ip_info.netmask), IP2STR(&event->ip_info.gw));
pan_start_ping();
}
static void pan_on_lost_ip(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGW(PAN_NETIF_TAG, "IP lost");
pan_stop_ping();
}
esp_err_t pan_netif_init(const uint8_t *mac)
{
if (s_pan_netif != NULL) {
return ESP_ERR_INVALID_STATE;
}
s_pan_glue = calloc(1, sizeof(pan_netif_glue_t));
if (s_pan_glue == NULL) {
return ESP_ERR_NO_MEM;
}
s_pan_glue->base.post_attach = pan_post_attach;
s_pan_glue->pan_handle = ESP_PAN_INVALID_HANDLE;
memcpy(s_pan_glue->mac, mac, 6);
esp_netif_inherent_config_t base_cfg = ESP_NETIF_INHERENT_DEFAULT_ETH();
base_cfg.if_key = "PAN_DEF";
base_cfg.if_desc = "pan";
base_cfg.route_prio = 60;
esp_netif_config_t cfg = {
.base = &base_cfg,
.stack = ESP_NETIF_NETSTACK_DEFAULT_ETH,
};
s_pan_netif = esp_netif_new(&cfg);
if (s_pan_netif == NULL) {
free(s_pan_glue);
s_pan_glue = NULL;
return ESP_ERR_NO_MEM;
}
ESP_ERROR_CHECK(esp_netif_attach(s_pan_netif, s_pan_glue));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, pan_on_got_ip, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_LOST_IP, pan_on_lost_ip, NULL));
return ESP_OK;
}
esp_netif_t *pan_netif_get(void)
{
return s_pan_netif;
}
void pan_netif_on_connected(uint16_t handle)
{
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
s_pan_glue->pan_handle = handle;
pan_stop_ping();
esp_netif_set_default_netif(s_pan_netif);
esp_netif_action_start(s_pan_netif, 0, 0, 0);
esp_netif_action_connected(s_pan_netif, 0, 0, 0);
ESP_LOGI(PAN_NETIF_TAG, "PAN link up, DHCP client started");
}
void pan_netif_on_disconnected(void)
{
if (s_pan_glue == NULL || s_pan_netif == NULL) {
return;
}
s_pan_glue->pan_handle = ESP_PAN_INVALID_HANDLE;
pan_stop_ping();
esp_netif_action_disconnected(s_pan_netif, 0, 0, 0);
esp_netif_action_stop(s_pan_netif, 0, 0, 0);
ESP_LOGI(PAN_NETIF_TAG, "PAN link down");
}
esp_err_t pan_netif_input(const uint8_t *dst, const uint8_t *src, uint16_t protocol,
const uint8_t *payload, uint16_t len)
{
if (s_pan_netif == NULL || payload == NULL || len == 0) {
return ESP_ERR_INVALID_STATE;
}
size_t frame_len = ETH_HEADER_LEN + len;
uint8_t *frame = malloc(frame_len);
if (frame == NULL) {
return ESP_ERR_NO_MEM;
}
memcpy(frame, dst, 6);
memcpy(frame + 6, src, 6);
frame[12] = (protocol >> 8) & 0xff;
frame[13] = protocol & 0xff;
memcpy(frame + ETH_HEADER_LEN, payload, len);
/* esp_netif_receive takes ownership of frame and frees it via
* pan_free_rx_buffer on both success and failure paths. */
return esp_netif_receive(s_pan_netif, frame, frame_len, NULL);
}

View File

@@ -0,0 +1,19 @@
/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#pragma once
#include <stdint.h>
#include "esp_err.h"
#include "esp_netif.h"
#include "esp_pan_api.h"
esp_err_t pan_netif_init(const uint8_t *mac);
esp_netif_t *pan_netif_get(void);
void pan_netif_on_connected(uint16_t handle);
void pan_netif_on_disconnected(void);
esp_err_t pan_netif_input(const uint8_t *dst, const uint8_t *src, uint16_t protocol,
const uint8_t *payload, uint16_t len);

View File

@@ -0,0 +1,8 @@
# Override some defaults so BT stack is enabled
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=n
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=y
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_CLASSIC_ENABLED=y
CONFIG_BT_PAN_ENABLED=y
CONFIG_BT_BLE_ENABLED=n