From 4f54340e51f391bb058b220d8a40f741319c909c Mon Sep 17 00:00:00 2001 From: linruihao Date: Fri, 10 Jul 2026 19:54:48 +0800 Subject: [PATCH 1/2] feat(bt/bluedroid): support Classic Bluetooth PAN profile - Port part of PAN/BNEP code from Android - Add ESP API and BTC layer --- components/bt/common/btc/core/btc_task.c | 6 + .../bt/common/btc/include/btc/btc_task.h | 3 + components/bt/host/bluedroid/CMakeLists.txt | 16 + components/bt/host/bluedroid/Kconfig.in | 7 + .../bt/host/bluedroid/api/esp_pan_api.c | 204 +++ .../bluedroid/api/include/api/esp_pan_api.h | 411 +++++ .../bt/host/bluedroid/bta/dm/bta_dm_cfg.c | 62 +- .../bluedroid/bta/include/bta/bta_pan_api.h | 187 ++ .../bluedroid/bta/include/bta/bta_pan_ci.h | 157 ++ .../bluedroid/bta/include/bta/bta_pan_co.h | 201 +++ .../bt/host/bluedroid/bta/pan/bta_pan_act.c | 763 ++++++++ .../bt/host/bluedroid/bta/pan/bta_pan_api.c | 215 +++ .../bt/host/bluedroid/bta/pan/bta_pan_ci.c | 338 ++++ .../bt/host/bluedroid/bta/pan/bta_pan_int.h | 213 +++ .../bt/host/bluedroid/bta/pan/bta_pan_main.c | 397 +++++ .../btc/profile/std/include/btc_pan.h | 86 + .../btc/profile/std/pan/bta_pan_co.c | 230 +++ .../bluedroid/btc/profile/std/pan/btc_pan.c | 667 +++++++ .../include/common/bluedroid_user_config.h | 7 + .../common/include/common/bt_target.h | 26 +- components/bt/host/bluedroid/main/bte_init.c | 4 +- .../bt/host/bluedroid/stack/bnep/bnep_api.c | 812 +++++++++ .../bt/host/bluedroid/stack/bnep/bnep_main.c | 794 +++++++++ .../bt/host/bluedroid/stack/bnep/bnep_utils.c | 1544 +++++++++++++++++ .../bluedroid/stack/bnep/include/bnep_int.h | 241 +++ .../bt/host/bluedroid/stack/btu/btu_task.c | 2 +- .../bluedroid/stack/include/stack/bnep_api.h | 455 +++++ .../bluedroid/stack/include/stack/pan_api.h | 449 +++++ .../bluedroid/stack/pan/include/pan_int.h | 133 ++ .../bt/host/bluedroid/stack/pan/pan_api.c | 784 +++++++++ .../bt/host/bluedroid/stack/pan/pan_main.c | 724 ++++++++ .../bt/host/bluedroid/stack/pan/pan_utils.c | 335 ++++ docs/doxygen/Doxyfile | 1 + tools/ci/check_copyright_ignore.txt | 19 + 34 files changed, 10485 insertions(+), 8 deletions(-) create mode 100644 components/bt/host/bluedroid/api/esp_pan_api.c create mode 100644 components/bt/host/bluedroid/api/include/api/esp_pan_api.h create mode 100644 components/bt/host/bluedroid/bta/include/bta/bta_pan_api.h create mode 100644 components/bt/host/bluedroid/bta/include/bta/bta_pan_ci.h create mode 100644 components/bt/host/bluedroid/bta/include/bta/bta_pan_co.h create mode 100644 components/bt/host/bluedroid/bta/pan/bta_pan_act.c create mode 100644 components/bt/host/bluedroid/bta/pan/bta_pan_api.c create mode 100644 components/bt/host/bluedroid/bta/pan/bta_pan_ci.c create mode 100644 components/bt/host/bluedroid/bta/pan/bta_pan_int.h create mode 100644 components/bt/host/bluedroid/bta/pan/bta_pan_main.c create mode 100644 components/bt/host/bluedroid/btc/profile/std/include/btc_pan.h create mode 100644 components/bt/host/bluedroid/btc/profile/std/pan/bta_pan_co.c create mode 100644 components/bt/host/bluedroid/btc/profile/std/pan/btc_pan.c create mode 100644 components/bt/host/bluedroid/stack/bnep/bnep_api.c create mode 100644 components/bt/host/bluedroid/stack/bnep/bnep_main.c create mode 100644 components/bt/host/bluedroid/stack/bnep/bnep_utils.c create mode 100644 components/bt/host/bluedroid/stack/bnep/include/bnep_int.h create mode 100644 components/bt/host/bluedroid/stack/include/stack/bnep_api.h create mode 100644 components/bt/host/bluedroid/stack/include/stack/pan_api.h create mode 100644 components/bt/host/bluedroid/stack/pan/include/pan_int.h create mode 100644 components/bt/host/bluedroid/stack/pan/pan_api.c create mode 100644 components/bt/host/bluedroid/stack/pan/pan_main.c create mode 100644 components/bt/host/bluedroid/stack/pan/pan_utils.c diff --git a/components/bt/common/btc/core/btc_task.c b/components/bt/common/btc/core/btc_task.c index 82364d6ca72..b4f2117749f 100644 --- a/components/bt/common/btc/core/btc_task.c +++ b/components/bt/common/btc/core/btc_task.c @@ -44,6 +44,9 @@ #if (BTC_SPP_INCLUDED == TRUE) #include "btc_spp.h" #endif /* #if (BTC_SPP_INCLUDED == TRUE) */ +#if (BTC_PAN_INCLUDED == TRUE) +#include "btc_pan.h" +#endif /* #if (BTC_PAN_INCLUDED == TRUE) */ #if (BTC_L2CAP_INCLUDED == TRUE) #include "btc_l2cap.h" #endif /* #if (BTC_L2CAP_INCLUDED == TRUE) */ @@ -146,6 +149,9 @@ static const btc_func_t profile_tab[BTC_PID_NUM] = { #if (BTC_SPP_INCLUDED == TRUE) [BTC_PID_SPP] = {btc_spp_call_handler, btc_spp_cb_handler }, #endif /* #if (BTC_SPP_INCLUDED == TRUE) */ +#if (BTC_PAN_INCLUDED == TRUE) + [BTC_PID_PAN] = {btc_pan_call_handler, btc_pan_cb_handler }, +#endif /* #if (BTC_PAN_INCLUDED == TRUE) */ #if (BTC_L2CAP_INCLUDED == TRUE) [BTC_PID_L2CAP] = {btc_l2cap_call_handler, btc_l2cap_cb_handler }, #endif /* #if (BTC_L2CAP_INCLUDED == TRUE) */ diff --git a/components/bt/common/btc/include/btc/btc_task.h b/components/bt/common/btc/include/btc/btc_task.h index b83d52f6ec4..f45d937bb26 100644 --- a/components/bt/common/btc/include/btc/btc_task.h +++ b/components/bt/common/btc/include/btc/btc_task.h @@ -57,6 +57,9 @@ typedef enum { BTC_PID_AVRC_CT, BTC_PID_AVRC_TG, BTC_PID_SPP, +#if (BTC_PAN_INCLUDED == TRUE) + BTC_PID_PAN, +#endif /* BTC_PAN_INCLUDED */ BTC_PID_HD, BTC_PID_HH, BTC_PID_L2CAP, diff --git a/components/bt/host/bluedroid/CMakeLists.txt b/components/bt/host/bluedroid/CMakeLists.txt index 4b9e59da9ec..81ee5570b25 100644 --- a/components/bt/host/bluedroid/CMakeLists.txt +++ b/components/bt/host/bluedroid/CMakeLists.txt @@ -66,6 +66,7 @@ list(APPEND bluedroid_host_srcs "${CMAKE_CURRENT_LIST_DIR}/api/esp_sdp_api.c" "${CMAKE_CURRENT_LIST_DIR}/api/esp_l2cap_bt_api.c" "${CMAKE_CURRENT_LIST_DIR}/api/esp_pbac_api.c" + "${CMAKE_CURRENT_LIST_DIR}/api/esp_pan_api.c" "${CMAKE_CURRENT_LIST_DIR}/bta/ar/bta_ar.c" "${CMAKE_CURRENT_LIST_DIR}/bta/av/bta_av_aact.c" "${CMAKE_CURRENT_LIST_DIR}/bta/av/bta_av_act.c" @@ -134,6 +135,10 @@ list(APPEND bluedroid_host_srcs "${CMAKE_CURRENT_LIST_DIR}/bta/pba/bta_pba_client_api.c" "${CMAKE_CURRENT_LIST_DIR}/bta/pba/bta_pba_client_main.c" "${CMAKE_CURRENT_LIST_DIR}/bta/pba/bta_pba_client_sdp.c" + "${CMAKE_CURRENT_LIST_DIR}/bta/pan/bta_pan_act.c" + "${CMAKE_CURRENT_LIST_DIR}/bta/pan/bta_pan_api.c" + "${CMAKE_CURRENT_LIST_DIR}/bta/pan/bta_pan_ci.c" + "${CMAKE_CURRENT_LIST_DIR}/bta/pan/bta_pan_main.c" "${CMAKE_CURRENT_LIST_DIR}/bta/sdp/bta_sdp.c" "${CMAKE_CURRENT_LIST_DIR}/bta/sdp/bta_sdp_act.c" "${CMAKE_CURRENT_LIST_DIR}/bta/sdp/bta_sdp_api.c" @@ -180,6 +185,8 @@ list(APPEND bluedroid_host_srcs "${CMAKE_CURRENT_LIST_DIR}/btc/profile/std/sdp/btc_sdp.c" "${CMAKE_CURRENT_LIST_DIR}/btc/profile/std/l2cap/btc_l2cap.c" "${CMAKE_CURRENT_LIST_DIR}/btc/profile/std/pba/btc_pba_client.c" + "${CMAKE_CURRENT_LIST_DIR}/btc/profile/std/pan/bta_pan_co.c" + "${CMAKE_CURRENT_LIST_DIR}/btc/profile/std/pan/btc_pan.c" "${CMAKE_CURRENT_LIST_DIR}/device/bdaddr.c" "${CMAKE_CURRENT_LIST_DIR}/device/controller.c" "${CMAKE_CURRENT_LIST_DIR}/device/interop.c" @@ -215,6 +222,9 @@ list(APPEND bluedroid_host_srcs "${CMAKE_CURRENT_LIST_DIR}/stack/avrc/avrc_pars_tg.c" "${CMAKE_CURRENT_LIST_DIR}/stack/avrc/avrc_sdp.c" "${CMAKE_CURRENT_LIST_DIR}/stack/avrc/avrc_utils.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/bnep/bnep_api.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/bnep/bnep_main.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/bnep/bnep_utils.c" "${CMAKE_CURRENT_LIST_DIR}/stack/hid/hidd_api.c" "${CMAKE_CURRENT_LIST_DIR}/stack/hid/hidd_conn.c" "${CMAKE_CURRENT_LIST_DIR}/stack/hid/hidh_api.c" @@ -272,6 +282,9 @@ list(APPEND bluedroid_host_srcs "${CMAKE_CURRENT_LIST_DIR}/stack/obex/obex_main.c" "${CMAKE_CURRENT_LIST_DIR}/stack/obex/obex_tl_l2cap.c" "${CMAKE_CURRENT_LIST_DIR}/stack/obex/obex_tl_rfcomm.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/pan/pan_api.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/pan/pan_main.c" + "${CMAKE_CURRENT_LIST_DIR}/stack/pan/pan_utils.c" "${CMAKE_CURRENT_LIST_DIR}/stack/rfcomm/port_api.c" "${CMAKE_CURRENT_LIST_DIR}/stack/rfcomm/port_rfc.c" "${CMAKE_CURRENT_LIST_DIR}/stack/rfcomm/port_utils.c" @@ -369,6 +382,7 @@ list(APPEND bluedroid_host_priv_include_dirs ${CMAKE_CURRENT_LIST_DIR}/bta/hh/include ${CMAKE_CURRENT_LIST_DIR}/bta/jv/include ${CMAKE_CURRENT_LIST_DIR}/bta/pba/include + ${CMAKE_CURRENT_LIST_DIR}/bta/pan ${CMAKE_CURRENT_LIST_DIR}/bta/sdp/include ${CMAKE_CURRENT_LIST_DIR}/bta/sys/include ${CMAKE_CURRENT_LIST_DIR}/device/include @@ -391,6 +405,8 @@ list(APPEND bluedroid_host_priv_include_dirs ${CMAKE_CURRENT_LIST_DIR}/stack/rfcomm/include ${CMAKE_CURRENT_LIST_DIR}/stack/obex/include ${CMAKE_CURRENT_LIST_DIR}/stack/goep/include + ${CMAKE_CURRENT_LIST_DIR}/stack/bnep/include + ${CMAKE_CURRENT_LIST_DIR}/stack/pan/include ${CMAKE_CURRENT_LIST_DIR}/stack/include ${CMAKE_CURRENT_LIST_DIR}/common/include ${CMAKE_CURRENT_LIST_DIR}/config/include diff --git a/components/bt/host/bluedroid/Kconfig.in b/components/bt/host/bluedroid/Kconfig.in index adcb4548da6..ac9f5e0ed16 100644 --- a/components/bt/host/bluedroid/Kconfig.in +++ b/components/bt/host/bluedroid/Kconfig.in @@ -153,6 +153,13 @@ config BT_SPP_ENABLED help This enables the Serial Port Profile +config BT_PAN_ENABLED + bool "PAN (Personal Area Networking)" + depends on BT_CLASSIC_ENABLED + default n + help + This enables the Personal Area Networking Profile + config BT_L2CAP_ENABLED bool "BT L2CAP" depends on BT_CLASSIC_ENABLED diff --git a/components/bt/host/bluedroid/api/esp_pan_api.c b/components/bt/host/bluedroid/api/esp_pan_api.c new file mode 100644 index 00000000000..ba2d6c910fe --- /dev/null +++ b/components/bt/host/bluedroid/api/esp_pan_api.c @@ -0,0 +1,204 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include + +#include "esp_bt_main.h" +#include "btc/btc_manage.h" +#include "btc_pan.h" +#include "esp_pan_api.h" +#include "common/bt_target.h" + +#if (defined BTC_PAN_INCLUDED && BTC_PAN_INCLUDED == TRUE) + +_Static_assert(ESP_PAN_MAX_WRITE_LEN == PAN_MAX_WRITE_LEN, + "ESP_PAN_MAX_WRITE_LEN must match PAN_MAX_WRITE_LEN"); +_Static_assert(ESP_PAN_MAX_PROTOCOL_FILTERS == BNEP_MAX_PROT_FILTERS, + "ESP_PAN_MAX_PROTOCOL_FILTERS must match BNEP_MAX_PROT_FILTERS"); +_Static_assert(ESP_PAN_MAX_MULTICAST_FILTERS == BNEP_MAX_MULTI_FILTERS, + "ESP_PAN_MAX_MULTICAST_FILTERS must match BNEP_MAX_MULTI_FILTERS"); + +esp_err_t esp_pan_register_callback(esp_pan_cb_t callback) +{ + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (callback == NULL) { + return ESP_ERR_INVALID_ARG; + } + + return (btc_profile_cb_set(BTC_PID_PAN, callback) == 0 ? ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_init(const esp_pan_cfg_t *cfg) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (cfg == NULL || cfg->role == 0) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_INIT; + + arg.init.cfg = *cfg; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), + btc_pan_arg_deep_copy, btc_pan_arg_deep_free) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_deinit(void) +{ + btc_msg_t msg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_DEINIT; + + return (btc_transfer_context(&msg, NULL, 0, NULL, NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_connect(esp_bd_addr_t remote_bda, esp_pan_role_t local_role, esp_pan_role_t peer_role) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (remote_bda == NULL || + (local_role != ESP_PAN_ROLE_PANU && local_role != ESP_PAN_ROLE_GN && + local_role != ESP_PAN_ROLE_NAP) || + (peer_role != ESP_PAN_ROLE_PANU && peer_role != ESP_PAN_ROLE_GN && + peer_role != ESP_PAN_ROLE_NAP)) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_CONNECT; + + memcpy(arg.connect.bd_addr, remote_bda, ESP_BD_ADDR_LEN); + arg.connect.local_role = local_role; + arg.connect.peer_role = peer_role; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), NULL, NULL) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_disconnect(uint16_t handle) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (handle == ESP_PAN_INVALID_HANDLE) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_DISCONNECT; + + arg.disconnect.handle = handle; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), NULL, NULL) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_write(uint16_t handle, const uint8_t *dst, const uint8_t *src, uint16_t protocol, + uint16_t len, const uint8_t *data, bool ext) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (handle == ESP_PAN_INVALID_HANDLE || dst == NULL || src == NULL || data == NULL || + len == 0 || len > ESP_PAN_MAX_WRITE_LEN) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_WRITE; + + arg.write.handle = handle; + memcpy(arg.write.dst, dst, ESP_BD_ADDR_LEN); + memcpy(arg.write.src, src, ESP_BD_ADDR_LEN); + arg.write.protocol = protocol; + arg.write.len = len; + arg.write.data = (uint8_t *)data; + arg.write.ext = ext; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), + btc_pan_arg_deep_copy, btc_pan_arg_deep_free) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_set_protocol_filters(uint16_t handle, uint16_t num_filters, + const uint16_t *start_array, const uint16_t *end_array) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (handle == ESP_PAN_INVALID_HANDLE || + num_filters > ESP_PAN_MAX_PROTOCOL_FILTERS || + (num_filters > 0 && (start_array == NULL || end_array == NULL))) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_SET_PFILTER; + + arg.set_pfilter.handle = handle; + arg.set_pfilter.num_filters = num_filters; + arg.set_pfilter.start_array = (num_filters > 0) ? (uint16_t *)start_array : NULL; + arg.set_pfilter.end_array = (num_filters > 0) ? (uint16_t *)end_array : NULL; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), + btc_pan_arg_deep_copy, btc_pan_arg_deep_free) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +esp_err_t esp_pan_set_multicast_filters(uint16_t handle, uint16_t num_filters, + const esp_bd_addr_t *start_array, const esp_bd_addr_t *end_array) +{ + btc_msg_t msg = {0}; + btc_pan_args_t arg = {0}; + + ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED); + + if (handle == ESP_PAN_INVALID_HANDLE || + num_filters > ESP_PAN_MAX_MULTICAST_FILTERS || + (num_filters > 0 && (start_array == NULL || end_array == NULL))) { + return ESP_ERR_INVALID_ARG; + } + + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_PAN; + msg.act = BTC_PAN_ACT_SET_MFILTER; + + arg.set_mfilter.handle = handle; + arg.set_mfilter.num_filters = num_filters; + arg.set_mfilter.start_array = (num_filters > 0) ? (esp_bd_addr_t *)start_array : NULL; + arg.set_mfilter.end_array = (num_filters > 0) ? (esp_bd_addr_t *)end_array : NULL; + + return (btc_transfer_context(&msg, &arg, sizeof(btc_pan_args_t), + btc_pan_arg_deep_copy, btc_pan_arg_deep_free) == BT_STATUS_SUCCESS ? + ESP_OK : ESP_FAIL); +} + +#endif /* BTC_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/api/include/api/esp_pan_api.h b/components/bt/host/bluedroid/api/include/api/esp_pan_api.h new file mode 100644 index 00000000000..9d5216aab8b --- /dev/null +++ b/components/bt/host/bluedroid/api/include/api/esp_pan_api.h @@ -0,0 +1,411 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Invalid PAN connection handle. + * + * Returned when a connection is not established. This value must not be passed + * to PAN API functions that require a valid handle. + */ +#define ESP_PAN_INVALID_HANDLE 0xFFFF + +/** + * @brief Maximum Ethernet payload length accepted by esp_pan_write(). + * + * Matches the fixed PAN write buffer capacity after BT_HDR and protocol header + * overhead: PAN_BUF_SIZE(4112) - sizeof(BT_HDR)(8) - PAN_MINIMUM_OFFSET(28). + */ +#define ESP_PAN_MAX_WRITE_LEN 4076 + +/** + * @brief Maximum number of protocol filter ranges accepted by esp_pan_set_protocol_filters(). + * + * Must match BNEP_MAX_PROT_FILTERS. + */ +#define ESP_PAN_MAX_PROTOCOL_FILTERS 5 + +/** + * @brief Maximum number of multicast filter ranges accepted by esp_pan_set_multicast_filters(). + * + * Must match BNEP_MAX_MULTI_FILTERS. + */ +#define ESP_PAN_MAX_MULTICAST_FILTERS 5 + +/** + * @brief Ethernet protocol type for IPv4 over PAN/BNEP. + */ +#define ESP_PAN_PROTO_IP 0x0800 + +/** + * @brief Ethernet protocol type for ARP over PAN/BNEP. + */ +#define ESP_PAN_PROTO_ARP 0x0806 + +/** + * @brief PAN role type. + * + * Each role is a single bit. Combine values with bitwise OR into an + * esp_pan_role_mask_t when registering multiple local roles at initialization. + * + * Typical connection role pairs: + * - PANU (client) -> NAP (server) + * - PANU (client) -> GN (server) + * - GN (client) -> GN (server) + * - NAP (server) <- PANU (client, incoming connection) + */ +typedef enum { + ESP_PAN_ROLE_PANU = 0x01, /*!< PAN User role. Connects to NAP or GN for network access. */ + ESP_PAN_ROLE_GN = 0x02, /*!< Group Network role. Bridges multiple PAN devices in a subnet. */ + ESP_PAN_ROLE_NAP = 0x04, /*!< Network Access Point role. Provides network access to PANU peers. */ +} esp_pan_role_t; + +/** + * @brief Bitmap of esp_pan_role_t values for local role registration. + */ +typedef uint8_t esp_pan_role_mask_t; + +/* Security Setting Mask + * + * Use these combinations on both sides: + * 1. ESP_PAN_SEC_NONE + * 2. ESP_PAN_SEC_AUTHENTICATE + * 3. (ESP_PAN_SEC_AUTHENTICATE | ESP_PAN_SEC_ENCRYPT) + */ +#define ESP_PAN_SEC_NONE 0x0000 /*!< No security. */ +#define ESP_PAN_SEC_AUTHENTICATE 0x0012 /*!< Authentication required. */ +#define ESP_PAN_SEC_ENCRYPT 0x0024 /*!< Encryption required. */ +typedef uint16_t esp_pan_sec_t; /*!< PAN security type. */ + +/** + * @brief PAN status type. + */ +typedef enum { + ESP_PAN_SUCCESS = 0, /*!< Successful operation. */ + ESP_PAN_FAILURE, /*!< Generic failure. */ + ESP_PAN_BUSY, /*!< Temporarily cannot handle this request. */ + ESP_PAN_NO_RESOURCE, /*!< No more resources. */ + ESP_PAN_NEED_INIT, /*!< PAN module shall init first. */ + ESP_PAN_NEED_DEINIT, /*!< PAN module shall deinit first. */ + ESP_PAN_NO_CONNECTION, /*!< Connection may have been closed. */ +} esp_pan_status_t; + +/** + * @brief PAN initialization configuration parameters. + */ +typedef struct { + esp_pan_role_mask_t role; /*!< Local PAN roles to register. Bitmap of esp_pan_role_t values. */ + esp_pan_sec_t panu_sec; /*!< Security mask for PANU role registration. */ + esp_pan_sec_t gn_sec; /*!< Security mask for GN role registration. */ + esp_pan_sec_t nap_sec; /*!< Security mask for NAP role registration. */ + const char *panu_service_name; /*!< SDP service name for PANU. Set NULL to use the default name. */ + const char *gn_service_name; /*!< SDP service name for GN. Set NULL to use the default name. */ + const char *nap_service_name; /*!< SDP service name for NAP. Set NULL to use the default name. */ +} esp_pan_cfg_t; + +/** + * @brief PAN default configuration. + * + * Registers PANU role only with authentication and encryption enabled. + */ +#define ESP_PAN_DEFAULT_CONFIG() { \ + .role = ESP_PAN_ROLE_PANU, \ + .panu_sec = ESP_PAN_SEC_AUTHENTICATE | ESP_PAN_SEC_ENCRYPT, \ + .gn_sec = ESP_PAN_SEC_AUTHENTICATE | ESP_PAN_SEC_ENCRYPT, \ + .nap_sec = ESP_PAN_SEC_AUTHENTICATE | ESP_PAN_SEC_ENCRYPT, \ + .panu_service_name = NULL, \ + .gn_service_name = NULL, \ + .nap_service_name = NULL, \ +} + +/** + * @brief PAN callback function events. + */ +typedef enum { + ESP_PAN_INIT_EVT = 0, /*!< When PAN is initialized, the event comes. */ + ESP_PAN_DEINIT_EVT, /*!< When PAN is deinitialized, the event comes. */ + ESP_PAN_SET_ROLE_EVT, /*!< When PAN role registration completes, the event comes. */ + ESP_PAN_OPENING_EVT, /*!< When an incoming PAN connection is being established, the event comes. */ + ESP_PAN_OPEN_EVT, /*!< When a PAN connection is opened, the event comes. */ + ESP_PAN_CLOSE_EVT, /*!< When a PAN connection is closed, the event comes. */ + ESP_PAN_DATA_IND_EVT, /*!< When PAN connection received data, the event comes. */ + ESP_PAN_CONG_EVT, /*!< When PAN connection congestion status changed, the event comes. */ + ESP_PAN_PFILTER_EVT, /*!< When protocol filter indication/result is available, the event comes. */ + ESP_PAN_MFILTER_EVT, /*!< When multicast filter indication/result is available, the event comes. */ + ESP_PAN_WRITE_EVT, /*!< When PAN write operation completes, the event comes. */ +} esp_pan_cb_event_t; + +/** + * @brief PAN callback parameters union. + */ +typedef union { + /** + * @brief ESP_PAN_INIT_EVT + */ + struct pan_init_evt_param { + esp_pan_status_t status; /*!< Initialization status. */ + } init; /*!< PAN callback param of ESP_PAN_INIT_EVT */ + + /** + * @brief ESP_PAN_DEINIT_EVT + */ + struct pan_deinit_evt_param { + esp_pan_status_t status; /*!< Deinitialization status. */ + } deinit; /*!< PAN callback param of ESP_PAN_DEINIT_EVT */ + + /** + * @brief ESP_PAN_SET_ROLE_EVT + */ + struct pan_set_role_evt_param { + esp_pan_status_t status; /*!< Role registration status. */ + esp_pan_role_mask_t role; /*!< Registered local role bitmap. */ + } set_role; /*!< PAN callback param of ESP_PAN_SET_ROLE_EVT */ + + /** + * @brief ESP_PAN_OPENING_EVT + */ + struct pan_opening_evt_param { + esp_bd_addr_t remote_bda; /*!< Remote Bluetooth device address. */ + uint16_t handle; /*!< Connection handle assigned by PAN stack. */ + } opening; /*!< PAN callback param of ESP_PAN_OPENING_EVT */ + + /** + * @brief ESP_PAN_OPEN_EVT + */ + struct pan_open_evt_param { + esp_pan_status_t status; /*!< Connection open status. */ + esp_bd_addr_t remote_bda; /*!< Remote Bluetooth device address. */ + uint16_t handle; /*!< Connection handle assigned by PAN stack. */ + esp_pan_role_t local_role; /*!< Local role used for this connection. */ + esp_pan_role_t peer_role; /*!< Peer role used for this connection. */ + } open; /*!< PAN callback param of ESP_PAN_OPEN_EVT */ + + /** + * @brief ESP_PAN_CLOSE_EVT + */ + struct pan_close_evt_param { + uint16_t handle; /*!< Connection handle of the closed link. */ + } close; /*!< PAN callback param of ESP_PAN_CLOSE_EVT */ + + /** + * @brief ESP_PAN_DATA_IND_EVT + */ + struct pan_data_ind_evt_param { + uint16_t handle; /*!< Connection handle on which data was received. */ + uint8_t src[ESP_BD_ADDR_LEN]; /*!< Source Ethernet MAC address of the received frame. */ + uint8_t dst[ESP_BD_ADDR_LEN]; /*!< Destination Ethernet MAC address of the received frame. */ + uint16_t protocol; /*!< Ethernet protocol type, e.g. ESP_PAN_PROTO_IP or ESP_PAN_PROTO_ARP. */ + uint16_t len; /*!< Length of the payload pointed to by data. */ + uint8_t *data; /*!< Pointer to L3 payload. Ethernet header is not included. */ + bool ext; /*!< TRUE if BNEP extension headers are present. */ + bool forward; /*!< TRUE if the frame is forwarded by GN/NAP. */ + } data_ind; /*!< PAN callback param of ESP_PAN_DATA_IND_EVT */ + + /** + * @brief ESP_PAN_CONG_EVT + */ + struct pan_cong_evt_param { + uint16_t handle; /*!< Connection handle whose congestion status changed. */ + bool cong; /*!< TRUE, congested. FALSE, uncongested. Pause esp_pan_write() when TRUE. */ + } cong; /*!< PAN callback param of ESP_PAN_CONG_EVT */ + + /** + * @brief ESP_PAN_PFILTER_EVT + */ + struct pan_pfilter_evt_param { + uint16_t handle; /*!< Connection handle related to the filter event. */ + bool indication; /*!< TRUE if this is an indication from peer. FALSE if this is a local operation result. */ + esp_pan_status_t status; /*!< Operation status. */ + uint16_t len; /*!< Length of the filters buffer in bytes. */ + uint8_t *filters; /*!< Pointer to protocol filter data. Valid only in callback context. */ + } pfilter; /*!< PAN callback param of ESP_PAN_PFILTER_EVT */ + + /** + * @brief ESP_PAN_MFILTER_EVT + */ + struct pan_mfilter_evt_param { + uint16_t handle; /*!< Connection handle related to the filter event. */ + bool indication; /*!< TRUE if this is an indication from peer. FALSE if this is a local operation result. */ + esp_pan_status_t status; /*!< Operation status. */ + uint16_t len; /*!< Length of the filters buffer in bytes. */ + uint8_t *filters; /*!< Pointer to multicast filter data. Valid only in callback context. */ + } mfilter; /*!< PAN callback param of ESP_PAN_MFILTER_EVT */ + + /** + * @brief ESP_PAN_WRITE_EVT + */ + struct pan_write_evt_param { + esp_pan_status_t status; /*!< Write operation status. */ + uint16_t handle; /*!< Connection handle on which data was written. */ + } write; /*!< PAN callback param of ESP_PAN_WRITE_EVT */ +} esp_pan_cb_param_t; /*!< PAN callback parameter union type */ + +/** + * @brief PAN callback function type. + * + * When handling ESP_PAN_DATA_IND_EVT, it is strongly recommended to cache incoming data and + * process it in another lower priority application task rather than performing heavy work directly + * in this callback. + * + * @param event: Event type. + * @param param: Pointer to callback parameter, currently union type. + */ +typedef void (*esp_pan_cb_t)(esp_pan_cb_event_t event, esp_pan_cb_param_t *param); + +/** + * @brief This function is called to register callbacks with the PAN module. + * + * @param[in] callback: Pointer to the callback function. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_pan_register_callback(esp_pan_cb_t callback); + +/** + * @brief This function is called to initialize the PAN module. + * + * When the operation is completed, the callback function will be called with ESP_PAN_INIT_EVT. + * After initialization succeeds, ESP_PAN_SET_ROLE_EVT is reported for the registered roles. + * This function should be called after esp_bluedroid_enable() completes successfully. + * + * @param[in] cfg: PAN initialization configuration. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_pan_init(const esp_pan_cfg_t *cfg); + +/** + * @brief This function is called to deinitialize the PAN module. + * + * Active PAN connections are closed first. For each closed connection, ESP_PAN_CLOSE_EVT is reported. + * When deinitialization completes, ESP_PAN_DEINIT_EVT is reported. + * This function must be called after esp_pan_init() succeeds and before calling esp_pan_init() again. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_pan_deinit(void); + +/** + * @brief This function makes a PAN connection to a remote Bluetooth device. + * + * When the connection is established or fails, the callback function will be called with ESP_PAN_OPEN_EVT. + * For an incoming connection, ESP_PAN_OPENING_EVT is reported before ESP_PAN_OPEN_EVT. + * This function must be called after esp_pan_init() succeeds and before esp_pan_deinit(). + * + * @param[in] remote_bda: Remote Bluetooth device address. + * @param[in] local_role: Local PAN role for this connection. One of ESP_PAN_ROLE_PANU, ESP_PAN_ROLE_GN, ESP_PAN_ROLE_NAP. + * @param[in] peer_role: Expected peer PAN role for this connection. + * + * @note Valid outgoing role pairs include PANU->NAP, PANU->GN, and GN->GN. + * A PANU device can only maintain one PANU-role connection at a time. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_pan_connect(esp_bd_addr_t remote_bda, esp_pan_role_t local_role, esp_pan_role_t peer_role); + +/** + * @brief This function closes a PAN connection. + * + * When the operation is completed, the callback function will be called with ESP_PAN_CLOSE_EVT. + * This function must be called after a valid connection handle is obtained from ESP_PAN_OPEN_EVT. + * + * @param[in] handle: Connection handle obtained from ESP_PAN_OPEN_EVT. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_pan_disconnect(uint16_t handle); + +/** + * @brief This function sends Ethernet payload data over a PAN connection. + * + * The data is encapsulated by BNEP and transmitted to the peer device. + * When the write request is accepted or rejected, ESP_PAN_WRITE_EVT is reported. + * This function must be called after a valid connection handle is obtained from ESP_PAN_OPEN_EVT. + * + * @param[in] handle: Connection handle obtained from ESP_PAN_OPEN_EVT. + * @param[in] dst: Destination Ethernet MAC address. Use broadcast address for ARP requests. + * @param[in] src: Source Ethernet MAC address. Usually the local PAN netif MAC address. + * @param[in] protocol: Ethernet protocol type, e.g. ESP_PAN_PROTO_IP or ESP_PAN_PROTO_ARP. + * @param[in] len: Length of the payload pointed to by data. + * Must be in the range [1, ESP_PAN_MAX_WRITE_LEN]. + * @param[in] data: Pointer to L3 payload. Ethernet header is not included. + * @param[in] ext: TRUE if forwarded BNEP extension headers are present. + * + * @note dst and src are 6-byte Ethernet MAC addresses, not Bluetooth device addresses. + * When integrated with esp_netif, use the Ethernet frame header generated by the TCP/IP stack. + * Pause transmission when ESP_PAN_CONG_EVT reports congestion. + * len greater than ESP_PAN_MAX_WRITE_LEN is rejected with ESP_ERR_INVALID_ARG. + * + * @return + * - ESP_OK: success + * - ESP_ERR_INVALID_ARG: invalid handle, NULL pointer, zero or oversized len + * - other: failed + */ +esp_err_t esp_pan_write(uint16_t handle, const uint8_t *dst, const uint8_t *src, uint16_t protocol, + uint16_t len, const uint8_t *data, bool ext); + +/** + * @brief This function sets protocol filters on the peer device. + * + * Only Ethernet frames whose protocol type falls into one of the configured ranges are accepted. + * When the operation completes or a peer indication is received, ESP_PAN_PFILTER_EVT is reported. + * + * @param[in] handle: Connection handle obtained from ESP_PAN_OPEN_EVT. + * @param[in] num_filters: Number of protocol filter ranges (0 to ESP_PAN_MAX_PROTOCOL_FILTERS). + * Pass 0 with NULL arrays to clear filters. + * @param[in] start_array: Array of range start protocol values. Ignored when num_filters is 0. + * @param[in] end_array: Array of range end protocol values. Ignored when num_filters is 0. + * + * @return + * - ESP_OK: success + * - ESP_ERR_INVALID_ARG: invalid handle, NULL arrays when num_filters > 0, or too many filters + * - other: failed + */ +esp_err_t esp_pan_set_protocol_filters(uint16_t handle, uint16_t num_filters, + const uint16_t *start_array, const uint16_t *end_array); + +/** + * @brief This function sets multicast filters on the peer device. + * + * Only multicast Ethernet frames whose destination MAC falls into one of the configured ranges + * are accepted. When the operation completes or a peer indication is received, + * ESP_PAN_MFILTER_EVT is reported. + * + * @param[in] handle: Connection handle obtained from ESP_PAN_OPEN_EVT. + * @param[in] num_filters: Number of multicast filter ranges (0 to ESP_PAN_MAX_MULTICAST_FILTERS). + * Pass 0 with NULL arrays to clear filters. + * @param[in] start_array: Array of range start MAC addresses (esp_bd_addr_t elements). Ignored when num_filters is 0. + * @param[in] end_array: Array of range end MAC addresses (esp_bd_addr_t elements). Ignored when num_filters is 0. + * + * @return + * - ESP_OK: success + * - ESP_ERR_INVALID_ARG: invalid handle, NULL arrays when num_filters > 0, or too many filters + * - other: failed + */ +esp_err_t esp_pan_set_multicast_filters(uint16_t handle, uint16_t num_filters, + const esp_bd_addr_t *start_array, const esp_bd_addr_t *end_array); + +#ifdef __cplusplus +} +#endif diff --git a/components/bt/host/bluedroid/bta/dm/bta_dm_cfg.c b/components/bt/host/bluedroid/bta/dm/bta_dm_cfg.c index 81bbd4667f8..bdf403aab24 100644 --- a/components/bt/host/bluedroid/bta/dm/bta_dm_cfg.c +++ b/components/bt/host/bluedroid/bta/dm/bta_dm_cfg.c @@ -117,11 +117,21 @@ tBTA_DM_CFG *const p_bta_dm_cfg = (tBTA_DM_CFG *) &bta_dm_cfg; tBTA_DM_RM *const p_bta_dm_rm_cfg = (tBTA_DM_RM *) &bta_dm_rm_cfg; #if BLE_INCLUDED == TRUE -# define BTA_DM_NUM_PM_ENTRY 10 /* number of entries in bta_dm_pm_cfg except the first */ -# define BTA_DM_NUM_PM_SPEC 10 /* number of entries in bta_dm_pm_spec */ +# define BTA_DM_NUM_PM_ENTRY_BASE 10 /* number of entries in bta_dm_pm_cfg except the first */ +# define BTA_DM_NUM_PM_SPEC_BASE 10 /* number of entries in bta_dm_pm_spec */ #else -# define BTA_DM_NUM_PM_ENTRY 8 /* number of entries in bta_dm_pm_cfg except the first */ -# define BTA_DM_NUM_PM_SPEC 8 /* number of entries in bta_dm_pm_spec */ +# define BTA_DM_NUM_PM_ENTRY_BASE 8 /* number of entries in bta_dm_pm_cfg except the first */ +# define BTA_DM_NUM_PM_SPEC_BASE 8 /* number of entries in bta_dm_pm_spec */ +#endif + +#if (BTA_PAN_INCLUDED == TRUE) +# define BTA_DM_NUM_PM_ENTRY (BTA_DM_NUM_PM_ENTRY_BASE + 3) +# define BTA_DM_NUM_PM_SPEC (BTA_DM_NUM_PM_SPEC_BASE + 2) +# define BTA_DM_PM_PANU_SPEC_IDX BTA_DM_NUM_PM_SPEC_BASE +# define BTA_DM_PM_NAP_SPEC_IDX (BTA_DM_NUM_PM_SPEC_BASE + 1) +#else +# define BTA_DM_NUM_PM_ENTRY BTA_DM_NUM_PM_ENTRY_BASE +# define BTA_DM_NUM_PM_SPEC BTA_DM_NUM_PM_SPEC_BASE #endif #if (BTA_DM_PM_INCLUDED == TRUE) @@ -140,6 +150,11 @@ tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_CFG bta_dm_pm_cfg[BTA_DM_NUM_PM_ENTRY + 1] , {BTA_ID_GATTC, BTA_ALL_APP_ID, 8} /* gattc spec table */ , {BTA_ID_GATTS, BTA_ALL_APP_ID, 9} /* gatts spec table */ #endif +#if (BTA_PAN_INCLUDED == TRUE) + , {BTA_ID_PAN, BTUI_PAN_ID_PANU, BTA_DM_PM_PANU_SPEC_IDX} /* PANU spec table */ + , {BTA_ID_PAN, BTUI_PAN_ID_NAP, BTA_DM_PM_NAP_SPEC_IDX} /* NAP spec table */ + , {BTA_ID_PAN, BTUI_PAN_ID_GN, BTA_DM_PM_NAP_SPEC_IDX} /* GN reuses NAP spec table */ +#endif }; #define BTA_DM_PM_SPEC_TO_OFFSET (197) /* timeout offset to avoid conflict with other bluedroid host */ @@ -342,6 +357,45 @@ tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC bta_dm_pm_spec[BTA_DM_NUM_PM_SPEC] = { #endif +#if (BTA_PAN_INCLUDED == TRUE) + /* PANU */ + , { + (BTA_DM_PM_SNIFF), /* allow sniff */ +#if (BTM_SSR_INCLUDED == TRUE) + (BTA_DM_PM_SSR2), /* the SSR entry */ +#endif + { + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000 + BTA_DM_PM_SPEC_TO_OFFSET}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + } + } + /* NAP */ + , { + (BTA_DM_PM_SNIFF), /* allow sniff */ +#if (BTM_SSR_INCLUDED == TRUE) + (BTA_DM_PM_SSR2), /* the SSR entry */ +#endif + { + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000 + BTA_DM_PM_SPEC_TO_OFFSET}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + } + } +#endif /* BTA_PAN_INCLUDED */ + #ifdef BTE_SIM_APP /* For Insight builds only */ /* Entries at the end of the pm_spec table are user-defined (runtime configurable), for power consumption experiments. diff --git a/components/bt/host/bluedroid/bta/include/bta/bta_pan_api.h b/components/bt/host/bluedroid/bta/include/bta/bta_pan_api.h new file mode 100644 index 00000000000..a1d1f210dfc --- /dev/null +++ b/components/bt/host/bluedroid/bta/include/bta/bta_pan_api.h @@ -0,0 +1,187 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the public interface file for the Personal Area Networking (PAN) + * subsystem of BTA, Broadcom's Bluetooth application layer for mobile + * phones. + * + ******************************************************************************/ +#ifndef BTA_PAN_API_H +#define BTA_PAN_API_H + +#include "bta_api.h" +#include "stack/pan_api.h" + +/***************************************************************************** + * Constants and data types + ****************************************************************************/ +#define BTA_PAN_SUCCESS 0 +#define BTA_PAN_FAIL 1 + +typedef UINT8 tBTA_PAN_STATUS; + +/* PAN Callback events */ +#define BTA_PAN_ENABLE_EVT 0 /* PAN service is enabled. */ +#define BTA_PAN_SET_ROLE_EVT 1 /* PAN roles registered */ +#define BTA_PAN_OPENING_EVT 2 /* Connection is being opened. */ +#define BTA_PAN_OPEN_EVT 3 /* Connection has been opened. */ +#define BTA_PAN_CLOSE_EVT 4 /* Connection has been closed. */ + +typedef UINT8 tBTA_PAN_EVT; + +/* pan roles */ +#define BTA_PAN_ROLE_PANU PAN_ROLE_CLIENT +#define BTA_PAN_ROLE_GN PAN_ROLE_GN_SERVER +#define BTA_PAN_ROLE_NAP PAN_ROLE_NAP_SERVER + +typedef UINT8 tBTA_PAN_ROLE; + +/* information regarding PAN roles */ +typedef struct { + const char *p_srv_name; /* service name for the PAN role */ + UINT8 app_id; /* application id */ + tBTA_SEC sec_mask; /* security setting for the role */ + +} tBTA_PAN_ROLE_INFO; + +/* Event associated with BTA_PAN_SET_ROLE_EVT */ +typedef struct { + tBTA_PAN_STATUS status; /* status of set role event */ + tBTA_PAN_ROLE role; /* PAN roles successfully registered */ +} tBTA_PAN_SET_ROLE; + +/* Event associated with BTA_PAN_OPENING_EVT */ +typedef struct { + BD_ADDR bd_addr; /* BD address of peer device. */ + UINT16 handle; /* Handle associated with this connection. */ + +} tBTA_PAN_OPENING; + +/* Event associated with BTA_PAN_OPEN_EVT */ +typedef struct { + BD_ADDR bd_addr; /* BD address of peer device. */ + UINT16 handle; /* Handle associated with this connection. */ + tBTA_PAN_STATUS status; /* status of open event */ + tBTA_PAN_ROLE local_role; /* Local device PAN role for the connection */ + tBTA_PAN_ROLE peer_role; /* Peer device PAN role for the connection */ + +} tBTA_PAN_OPEN; + +/* Event associated with BTA_PAN_CLOSE_EVT */ +typedef struct { + UINT16 handle; /* Handle associated with the connection. */ +} tBTA_PAN_CLOSE; + +/* Union of all PAN callback structures */ +typedef union { + tBTA_PAN_SET_ROLE set_role; /* set_role event */ + tBTA_PAN_OPEN open; /* Connection has been opened. */ + tBTA_PAN_OPENING opening; /* Connection being opened */ + tBTA_PAN_CLOSE close; /* Connection has been closed. */ +} tBTA_PAN; + +/* Number of PAN connections */ +#ifndef BTA_PAN_NUM_CONN +#define BTA_PAN_NUM_CONN 4 +#endif + +/* PAN callback */ +typedef void (tBTA_PAN_CBACK)(tBTA_PAN_EVT event, tBTA_PAN *p_data); + +/***************************************************************************** + * External Function Declarations + ****************************************************************************/ + +/******************************************************************************* + * + * Function BTA_PanEnable + * + * Description Enable PAN service. This function must be + * called before any other functions in the PAN API are called. + * When the enable operation is complete the callback function + * will be called with a BTA_PAN_ENABLE_EVT. + * + * Returns void + * + ******************************************************************************/ +#ifdef __cplusplus +extern "C" { +#endif + +extern void BTA_PanEnable(tBTA_PAN_CBACK p_cback); + +/******************************************************************************* + * + * Function BTA_PanDisable + * + * Description Disable PAN service. + * + * Returns void + * + ******************************************************************************/ +extern void BTA_PanDisable(void); + +/******************************************************************************* + * + * Function BTA_PanSetRole + * + * Description Sets PAN roles. When the enable operation is complete + * the callback function will be called with a + * BTA_PAN_SET_ROLE_EVT. + * + * Returns void + * + ******************************************************************************/ +void BTA_PanSetRole(tBTA_PAN_ROLE role, tBTA_PAN_ROLE_INFO *p_user_info, + tBTA_PAN_ROLE_INFO *p_gn_info, + tBTA_PAN_ROLE_INFO *p_nap_info); + +/******************************************************************************* + * + * Function BTA_PanOpen + * + * Description Opens a connection to a peer device. + * When connection is open callback function is called + * with a BTA_PAN_OPEN_EVT. + * + * + * Returns void + * + ******************************************************************************/ +void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE local_role, + tBTA_PAN_ROLE peer_role); + +/******************************************************************************* + * + * Function BTA_PanClose + * + * Description Close a PAN connection to a peer device. + * + * + * Returns void + * + ******************************************************************************/ +extern void BTA_PanClose(UINT16 handle); + +#ifdef __cplusplus +} +#endif + +#endif /* BTA_PAN_API_H */ diff --git a/components/bt/host/bluedroid/bta/include/bta/bta_pan_ci.h b/components/bt/host/bluedroid/bta/include/bta/bta_pan_ci.h new file mode 100644 index 00000000000..fa434c80a2b --- /dev/null +++ b/components/bt/host/bluedroid/bta/include/bta/bta_pan_ci.h @@ -0,0 +1,157 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the interface file for pan call-in functions. + * + ******************************************************************************/ +#ifndef BTA_PAN_CI_H +#define BTA_PAN_CI_H + +#include "bta_pan_api.h" + +/***************************************************************************** + * Function Declarations + ****************************************************************************/ +/******************************************************************************* + * + * Function bta_pan_ci_tx_ready + * + * Description This function sends an event to PAN indicating the phone is + * ready for more data and PAN should call + * bta_pan_co_tx_path(). + * This function is used when the TX data path is configured + * to use a pull interface. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_tx_ready(UINT16 handle); + +/******************************************************************************* + * + * Function bta_pan_ci_rx_ready + * + * Description This function sends an event to PAN indicating the phone + * has data available to send to PAN and PAN should call + * bta_pan_co_rx_path(). This function is used when the RX + * data path is configured to use a pull interface. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_rx_ready(UINT16 handle); + +/******************************************************************************* + * + * Function bta_pan_ci_tx_flow + * + * Description This function is called to enable or disable data flow on + * the TX path. The phone should call this function to + * disable data flow when it is congested and cannot handle + * any more data sent by bta_pan_co_tx_write() or + * bta_pan_co_tx_writebuf(). This function is used when the + * TX data path is configured to use a push interface. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_tx_flow(UINT16 handle, BOOLEAN enable); + +/******************************************************************************* + * + * Function bta_pan_ci_rx_write + * + * Description This function is called to send data to PAN when the RX path + * is configured to use a push interface. + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_rx_write(UINT16 handle, BD_ADDR dst, BD_ADDR src, + UINT16 protocol, UINT8 *p_data, UINT16 len, + BOOLEAN ext); + +/******************************************************************************* + * + * Function bta_pan_ci_rx_writebuf + * + * Description This function is called to send data to the phone when + * the RX path is configured to use a push interface with + * zero copy. The function sends an event to PAN containing + * the data buffer. The buffer will be freed by BTA; the + * phone must not free the buffer. + * + * + * Returns true if flow enabled + * + ******************************************************************************/ +extern void bta_pan_ci_rx_writebuf(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext); + +/******************************************************************************* + * + * Function bta_pan_ci_readbuf + * + * Description This function is called by the phone to read data from PAN + * when the TX path is configured to use a pull interface. + * The caller must free the buffer when it is through + * processing the buffer. + * + * + * Returns void + * + ******************************************************************************/ +extern BT_HDR *bta_pan_ci_readbuf(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 *p_protocol, + BOOLEAN *p_ext, BOOLEAN *p_forward); + +/******************************************************************************* + * + * Function bta_pan_ci_set_pfilters + * + * Description This function is called to set protocol filters + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_set_pfilters(UINT16 handle, UINT16 num_filters, + UINT16 *p_start_array, + UINT16 *p_end_array); + +/******************************************************************************* + * + * Function bta_pan_ci_set_mfilters + * + * Description This function is called to set multicast filters + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_ci_set_mfilters(UINT16 handle, UINT16 num_mcast_filters, + UINT8 *p_start_array, + UINT8 *p_end_array); + +#endif /* BTA_PAN_CI_H */ diff --git a/components/bt/host/bluedroid/bta/include/bta/bta_pan_co.h b/components/bt/host/bluedroid/bta/include/bta/bta_pan_co.h new file mode 100644 index 00000000000..2e773585d1a --- /dev/null +++ b/components/bt/host/bluedroid/bta/include/bta/bta_pan_co.h @@ -0,0 +1,201 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the interface file for data gateway call-out functions. + * + ******************************************************************************/ +#ifndef BTA_PAN_CO_H +#define BTA_PAN_CO_H + +#include "bta_pan_api.h" + +/***************************************************************************** + * Constants + ****************************************************************************/ + +/* BT_HDR buffer offset */ +#define BTA_PAN_MIN_OFFSET PAN_MINIMUM_OFFSET + +/* Data Flow Mask */ +#define BTA_PAN_RX_PUSH 0x00 /* RX push. */ +#define BTA_PAN_RX_PUSH_BUF 0x01 /* RX push with zero copy. */ +#define BTA_PAN_RX_PULL 0x02 /* RX pull. */ +#define BTA_PAN_TX_PUSH 0x00 /* TX push. */ +#define BTA_PAN_TX_PUSH_BUF 0x10 /* TX push with zero copy. */ +#define BTA_PAN_TX_PULL 0x20 /* TX pull. */ + +/***************************************************************************** + * Function Declarations + ****************************************************************************/ + +/******************************************************************************* + * + * Function bta_pan_co_init + * + * Description This callout function is executed by PAN when a server is + * started by calling BTA_PanEnable(). This function can be + * used by the phone to initialize data paths or for other + * initialization purposes. The function must return the + * data flow mask as described below. + * + * + * Returns Data flow mask. + * + ******************************************************************************/ +extern UINT8 bta_pan_co_init(UINT8 *q_level); + +/******************************************************************************* + * + * Function bta_pan_co_open + * + * Description This function is executed by PAN when a connection + * is opened. The phone can use this function to set + * up data paths or perform any required initialization. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_open(UINT16 handle, UINT8 app_id, + tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role, + BD_ADDR peer_addr); + +/******************************************************************************* + * + * Function bta_pan_co_close + * + * Description This function is called by PAN when a connection to a + * server is closed. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_close(UINT16 handle, UINT8 app_id); + +/******************************************************************************* + * + * Function bta_pan_co_tx_path + * + * Description This function is called by PAN to transfer data on the + * TX path; that is, data being sent from BTA to the phone. + * This function is used when the TX data path is configured + * to use the pull interface. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_tx_path(UINT16 handle, UINT8 app_id); + +/******************************************************************************* + * + * Function bta_pan_co_rx_path + * + * Description This function is called by PAN to transfer data on the + * RX path; that is, data being sent from the phone to BTA. + * This function is used when the RX data path is configured + * to use the pull interface. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_rx_path(UINT16 handle, UINT8 app_id); + +/******************************************************************************* + * + * Function bta_pan_co_tx_write + * + * Description This function is called by PAN to send data to the phone + * when the TX path is configured to use a push interface. + * The implementation of this function must copy the data to + * the phone's memory. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_tx_write(UINT16 handle, UINT8 app_id, + BD_ADDR src, BD_ADDR dst, + UINT16 protocol, UINT8 *p_data, + UINT16 len, BOOLEAN ext, BOOLEAN forward); + +/******************************************************************************* + * + * Function bta_pan_co_tx_writebuf + * + * Description This function is called by PAN to send data to the phone + * when the TX path is configured to use a push interface with + * zero copy. The phone must free the buffer using function + * osi_free() when it is through processing the buffer. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_tx_writebuf(UINT16 handle, UINT8 app_id, + BD_ADDR src, BD_ADDR dst, + UINT16 protocol, BT_HDR *p_buf, BOOLEAN ext, + BOOLEAN forward); + +/******************************************************************************* + * + * Function bta_pan_co_rx_flow + * + * Description This function is called by PAN to enable or disable + * data flow on the RX path when it is configured to use + * a push interface. If data flow is disabled the phone must + * not call bta_pan_ci_rx_write() or bta_pan_ci_rx_writebuf() + * until data flow is enabled again. + * + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_rx_flow(UINT16 handle, UINT8 app_id, BOOLEAN enable); + +/******************************************************************************* + * + * Function bta_pan_co_filt_ind + * + * Description protocol filter indication from peer device + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, + tBTA_PAN_STATUS result, UINT16 len, + UINT8 *p_filters); + +/******************************************************************************* + * + * Function bta_pan_co_mfilt_ind + * + * Description multicast filter indication from peer device + * + * Returns void + * + ******************************************************************************/ +extern void bta_pan_co_mfilt_ind(UINT16 handle, BOOLEAN indication, + tBTA_PAN_STATUS result, UINT16 len, + UINT8 *p_filters); + +#endif /* BTA_PAN_CO_H */ diff --git a/components/bt/host/bluedroid/bta/pan/bta_pan_act.c b/components/bt/host/bluedroid/bta/pan/bta_pan_act.c new file mode 100644 index 00000000000..84d983af942 --- /dev/null +++ b/components/bt/host/bluedroid/bta/pan/bta_pan_act.c @@ -0,0 +1,763 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains the pan action functions for the state machine. + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include + +#include "bt_common.h" +#include "bta/bta_api.h" +#include "bta/bta_pan_api.h" +#include "bta/bta_pan_co.h" +#include "bta_pan_int.h" +#include "bta/bta_sys.h" +#include "osi/osi.h" +#include "osi/allocator.h" +#include "stack/pan_api.h" +#include "bta/utl.h" + +/* RX and TX data flow mask */ +#define BTA_PAN_RX_MASK 0x0F +#define BTA_PAN_TX_MASK 0xF0 + +/******************************************************************************* + * + * Function bta_pan_pm_conn_busy + * + * Description set pan pm connection busy state + * + * Params p_scb: state machine control block of pan connection + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_pm_conn_busy(tBTA_PAN_SCB *p_scb) +{ + if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) { + bta_sys_busy(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + } +} + +/******************************************************************************* + * + * Function bta_pan_pm_conn_idle + * + * Description set pan pm connection idle state + * + * Params p_scb: state machine control block of pan connection + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_pm_conn_idle(tBTA_PAN_SCB *p_scb) +{ + if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) { + bta_sys_idle(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + } +} + +/******************************************************************************* + * + * Function bta_pan_conn_state_cback + * + * Description Connection state callback from Pan profile + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_conn_state_cback(UINT16 handle, BD_ADDR bd_addr, + tPAN_RESULT state, BOOLEAN is_role_change, + UINT8 src_role, UINT8 dst_role) +{ + tBTA_PAN_SCB *p_scb; + tBTA_PAN_CONN *p_buf = (tBTA_PAN_CONN *)osi_malloc(sizeof(tBTA_PAN_CONN)); + + if (p_buf == NULL) { + APPL_TRACE_ERROR("%s: no resources", __func__); + if ((state == PAN_SUCCESS) && !is_role_change && + bta_pan_scb_by_handle(handle) == NULL) { + /* Incoming connection with no SCB yet: drop the BNEP link. */ + PAN_Disconnect(handle); + } + return; + } + + if ((state == PAN_SUCCESS) && !is_role_change) { + p_buf->hdr.event = BTA_PAN_CONN_OPEN_EVT; + p_scb = bta_pan_scb_by_handle(handle); + if (p_scb == NULL) { + /* allocate an scb */ + p_scb = bta_pan_scb_alloc(); + } + /* we have exceeded maximum number of connections */ + if (!p_scb) { + osi_free(p_buf); + PAN_Disconnect(handle); + return; + } + + p_scb->handle = handle; + p_scb->local_role = src_role; + p_scb->peer_role = dst_role; + p_scb->pan_flow_enable = TRUE; + bdcpy(p_scb->bd_addr, bd_addr); + p_scb->data_queue = fixed_queue_new(SIZE_MAX); + + if (src_role == PAN_ROLE_CLIENT) { + p_scb->app_id = bta_pan_cb.app_id[0]; + } else if (src_role == PAN_ROLE_GN_SERVER) { + p_scb->app_id = bta_pan_cb.app_id[1]; + } else if (src_role == PAN_ROLE_NAP_SERVER) { + p_scb->app_id = bta_pan_cb.app_id[2]; + } + } else if ((state != PAN_SUCCESS) && !is_role_change) { + /* Setup failure while still IDLE (e.g. after OPENING_EVT): report + * CONN_OPEN so bta_pan_conn_open can emit OPEN_EVT with FAIL. + * Disconnect of an established (or closing) connection: CLOSE_EVT. */ + p_scb = bta_pan_scb_by_handle(handle); + if (p_scb != NULL && p_scb->state == BTA_PAN_IDLE_ST) { + p_buf->hdr.event = BTA_PAN_CONN_OPEN_EVT; + } else { + p_buf->hdr.event = BTA_PAN_CONN_CLOSE_EVT; + } + } else { + /* Role change: no BTA event is posted, drop the unused buffer. */ + osi_free(p_buf); + return; + } + + p_buf->result = state; + p_buf->hdr.layer_specific = handle; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_data_flow_cb + * + * Description Data flow status callback from PAN + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_data_flow_cb(UINT16 handle, tPAN_RESULT result) +{ + tBTA_PAN_SCB *p_scb; + + p_scb = bta_pan_scb_by_handle(handle); + if (p_scb == NULL) { + return; + } + + if (result == PAN_TX_FLOW_ON) { + p_scb->pan_flow_enable = TRUE; + + BT_HDR *p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf != NULL) { + p_buf->layer_specific = handle; + p_buf->event = BTA_PAN_BNEP_FLOW_ENABLE_EVT; + bta_sys_sendmsg(p_buf); + } else { + APPL_TRACE_ERROR("%s: no resources", __func__); + } + bta_pan_co_rx_flow(handle, p_scb->app_id, TRUE); + } else if (result == PAN_TX_FLOW_OFF) { + p_scb->pan_flow_enable = FALSE; + bta_pan_co_rx_flow(handle, p_scb->app_id, FALSE); + } +} + +/******************************************************************************* + * + * Function bta_pan_data_buf_ind_cback + * + * Description data indication callback from pan profile + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_data_buf_ind_cback(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext, + BOOLEAN forward) +{ + tBTA_PAN_SCB *p_scb; + BT_HDR *p_new_buf; + + if (sizeof(tBTA_PAN_DATA_PARAMS) > p_buf->offset) { + /* offset smaller than data structure in front of actual data */ + p_new_buf = (BT_HDR *)osi_malloc(PAN_BUF_SIZE); + if (p_new_buf == NULL) { + APPL_TRACE_ERROR("%s: no resources", __func__); + osi_free(p_buf); + return; + } + memcpy((UINT8 *)(p_new_buf + 1) + sizeof(tBTA_PAN_DATA_PARAMS), + (UINT8 *)(p_buf + 1) + p_buf->offset, p_buf->len); + p_new_buf->len = p_buf->len; + p_new_buf->offset = sizeof(tBTA_PAN_DATA_PARAMS); + osi_free(p_buf); + } else { + p_new_buf = p_buf; + } + /* copy params into the space before the data */ + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_new_buf)->src, src); + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_new_buf)->dst, dst); + ((tBTA_PAN_DATA_PARAMS *)p_new_buf)->protocol = protocol; + ((tBTA_PAN_DATA_PARAMS *)p_new_buf)->ext = ext; + ((tBTA_PAN_DATA_PARAMS *)p_new_buf)->forward = forward; + + p_scb = bta_pan_scb_by_handle(handle); + if (p_scb == NULL) { + osi_free(p_new_buf); + return; + } + + BT_HDR *p_event = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_event == NULL) { + APPL_TRACE_ERROR("%s: no resources for event", __func__); + osi_free(p_new_buf); + return; + } + + fixed_queue_enqueue(p_scb->data_queue, p_new_buf, FIXED_QUEUE_MAX_TIMEOUT); + p_event->layer_specific = handle; + p_event->event = BTA_PAN_RX_FROM_BNEP_READY_EVT; + bta_sys_sendmsg(p_event); +} + +/******************************************************************************* + * + * Function bta_pan_pfilt_ind_cback + * + * Description + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_pfilt_ind_cback(UINT16 handle, BOOLEAN indication, + tPAN_RESULT result, UINT16 num_filters, + UINT8 *p_filters) +{ + bta_pan_co_pfilt_ind( + handle, indication, + (tBTA_PAN_STATUS)((result == PAN_SUCCESS) ? BTA_PAN_SUCCESS + : BTA_PAN_FAIL), + num_filters, p_filters); +} + +/******************************************************************************* + * + * Function bta_pan_mfilt_ind_cback + * + * Description + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_mfilt_ind_cback(UINT16 handle, BOOLEAN indication, + tPAN_RESULT result, UINT16 num_mfilters, + UINT8 *p_mfilters) +{ + bta_pan_co_mfilt_ind( + handle, indication, + (tBTA_PAN_STATUS)((result == PAN_SUCCESS) ? BTA_PAN_SUCCESS + : BTA_PAN_FAIL), + num_mfilters, p_mfilters); +} + +/******************************************************************************* + * + * Function bta_pan_has_multiple_connections + * + * Description Check whether there are multiple GN/NAP connections to + * different devices + * + * + * Returns bool + * + ******************************************************************************/ +static BOOLEAN bta_pan_has_multiple_connections(UINT8 app_id) +{ + tBTA_PAN_SCB *p_scb = NULL; + BOOLEAN found = FALSE; + BD_ADDR bd_addr; + + for (UINT8 index = 0; index < BTA_PAN_NUM_CONN; index++) { + p_scb = &bta_pan_cb.scb[index]; + if (p_scb->in_use == TRUE && app_id == p_scb->app_id) { + /* save temp bd_addr */ + bdcpy(bd_addr, p_scb->bd_addr); + found = TRUE; + break; + } + } + + /* If cannot find a match then there is no connection at all */ + if (found == FALSE) { + return FALSE; + } + + /* Find whether there is another connection with different device other than + PANU. + Could be same service or different service */ + for (UINT8 index = 0; index < BTA_PAN_NUM_CONN; index++) { + p_scb = &bta_pan_cb.scb[index]; + if (p_scb->in_use == TRUE && p_scb->app_id != bta_pan_cb.app_id[0] && + bdcmp(bd_addr, p_scb->bd_addr)) { + return TRUE; + } + } + return FALSE; +} + +/******************************************************************************* + * + * Function bta_pan_enable + * + * Description + * + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_enable(tBTA_PAN_DATA *p_data) +{ + tPAN_REGISTER reg_data; + + bta_pan_cb.p_cback = p_data->api_enable.p_cback; + + reg_data.pan_conn_state_cb = bta_pan_conn_state_cback; + reg_data.pan_bridge_req_cb = NULL; + reg_data.pan_data_buf_ind_cb = bta_pan_data_buf_ind_cback; + reg_data.pan_data_ind_cb = NULL; + reg_data.pan_pfilt_ind_cb = bta_pan_pfilt_ind_cback; + reg_data.pan_mfilt_ind_cb = bta_pan_mfilt_ind_cback; + reg_data.pan_tx_data_flow_cb = bta_pan_data_flow_cb; + + PAN_Register(®_data); + + bta_pan_cb.flow_mask = bta_pan_co_init(&bta_pan_cb.q_level); + bta_pan_cb.p_cback(BTA_PAN_ENABLE_EVT, NULL); +} + +/******************************************************************************* + * + * Function bta_pan_set_role + * + * Description + * + * Returns void + * + ******************************************************************************/ +void bta_pan_set_role(tBTA_PAN_DATA *p_data) +{ + tPAN_RESULT status; + tBTA_PAN bta_pan; + UINT8 sec[3]; + + bta_pan_cb.app_id[0] = p_data->api_set_role.user_app_id; + bta_pan_cb.app_id[1] = p_data->api_set_role.gn_app_id; + bta_pan_cb.app_id[2] = p_data->api_set_role.nap_app_id; + + sec[0] = p_data->api_set_role.user_sec_mask; + sec[1] = p_data->api_set_role.gn_sec_mask; + sec[2] = p_data->api_set_role.nap_sec_mask; + + /* set security correctly in api and here */ + status = PAN_SetRole( + p_data->api_set_role.role, sec, p_data->api_set_role.user_name, + p_data->api_set_role.gn_name, p_data->api_set_role.nap_name); + + bta_pan.set_role.role = p_data->api_set_role.role; + if (status == PAN_SUCCESS) { + if (p_data->api_set_role.role & PAN_ROLE_NAP_SERVER) { + bta_sys_add_uuid(UUID_SERVCLASS_NAP); + } else { + bta_sys_remove_uuid(UUID_SERVCLASS_NAP); + } + + if (p_data->api_set_role.role & PAN_ROLE_GN_SERVER) { + bta_sys_add_uuid(UUID_SERVCLASS_GN); + } else { + bta_sys_remove_uuid(UUID_SERVCLASS_GN); + } + + if (p_data->api_set_role.role & PAN_ROLE_CLIENT) { + bta_sys_add_uuid(UUID_SERVCLASS_PANU); + } else { + bta_sys_remove_uuid(UUID_SERVCLASS_PANU); + } + + bta_pan.set_role.status = BTA_PAN_SUCCESS; + } + /* if status is not success clear everything */ + else { + PAN_SetRole(0, 0, NULL, NULL, NULL); + bta_sys_remove_uuid(UUID_SERVCLASS_NAP); + bta_sys_remove_uuid(UUID_SERVCLASS_GN); + bta_sys_remove_uuid(UUID_SERVCLASS_PANU); + bta_pan.set_role.status = BTA_PAN_FAIL; + } + bta_pan_cb.p_cback(BTA_PAN_SET_ROLE_EVT, &bta_pan); +} + +/******************************************************************************* + * + * Function bta_pan_disable + * + * Description + * + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_disable(void) +{ + BT_HDR *p_buf; + tBTA_PAN_SCB *p_scb = &bta_pan_cb.scb[0]; + UINT8 i; + + /* close all connections */ + PAN_SetRole(0, NULL, NULL, NULL, NULL); + +#if (BTA_EIR_CANNED_UUID_LIST != TRUE) + bta_sys_remove_uuid(UUID_SERVCLASS_NAP); + bta_sys_remove_uuid(UUID_SERVCLASS_GN); + bta_sys_remove_uuid(UUID_SERVCLASS_PANU); +#endif // BTA_EIR_CANNED_UUID_LIST + /* free queued buffers and the queue itself for every active SCB */ + for (i = 0; i < BTA_PAN_NUM_CONN; i++, p_scb++) { + if (p_scb->in_use) { + if (p_scb->data_queue != NULL) { + while ((p_buf = (BT_HDR *)fixed_queue_try_dequeue(p_scb->data_queue)) != + NULL) { + osi_free(p_buf); + } + } + + bta_pan_co_close(p_scb->handle, p_scb->app_id); + bta_pan_scb_dealloc(p_scb); + } + } + + PAN_Deregister(); +} + +/******************************************************************************* + * + * Function bta_pan_open + * + * Description + * + * Returns void + * + ******************************************************************************/ +void bta_pan_open(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + tPAN_RESULT status; + tBTA_PAN bta_pan; + + status = PAN_Connect(p_data->api_open.bd_addr, p_data->api_open.local_role, + p_data->api_open.peer_role, &p_scb->handle); + APPL_TRACE_DEBUG("%s pan connect status: %d", __func__, status); + + if (status == PAN_SUCCESS) { + bdcpy(p_scb->bd_addr, p_data->api_open.bd_addr); + p_scb->local_role = p_data->api_open.local_role; + p_scb->peer_role = p_data->api_open.peer_role; + bdcpy(bta_pan.opening.bd_addr, p_data->api_open.bd_addr); + bta_pan.opening.handle = p_scb->handle; + bta_pan_cb.p_cback(BTA_PAN_OPENING_EVT, &bta_pan); + + } else { + bta_pan_scb_dealloc(p_scb); + bdcpy(bta_pan.open.bd_addr, p_data->api_open.bd_addr); + bta_pan.open.handle = PAN_INVALID_HANDLE; + bta_pan.open.status = BTA_PAN_FAIL; + bta_pan.open.local_role = p_data->api_open.local_role; + bta_pan.open.peer_role = p_data->api_open.peer_role; + bta_pan_cb.p_cback(BTA_PAN_OPEN_EVT, &bta_pan); + } +} + +/******************************************************************************* + * + * Function bta_pan_close + * + * Description + * + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_api_close(tBTA_PAN_SCB *p_scb, UNUSED_ATTR tBTA_PAN_DATA *p_data) +{ + tBTA_PAN_CONN *p_buf = (tBTA_PAN_CONN *)osi_malloc(sizeof(tBTA_PAN_CONN)); + + PAN_Disconnect(p_scb->handle); + + /* + * Send an event to BTA so that application will get the connection + * close event. BNEP_Disconnect does not deliver a conn_state CLOSE. + */ + if (p_buf != NULL) { + p_buf->hdr.event = BTA_PAN_CONN_CLOSE_EVT; + p_buf->hdr.layer_specific = p_scb->handle; + bta_sys_sendmsg(p_buf); + } else { + APPL_TRACE_ERROR("%s: no resources", __func__); + } +} + +/******************************************************************************* + * + * Function bta_pan_conn_open + * + * Description process connection open event + * + * Returns void + * + ******************************************************************************/ +void bta_pan_conn_open(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + tBTA_PAN bta_pan; + + APPL_TRACE_DEBUG("%s pan connection result: %d", __func__, + p_data->conn.result); + + bdcpy(bta_pan.open.bd_addr, p_scb->bd_addr); + bta_pan.open.handle = p_scb->handle; + bta_pan.open.local_role = p_scb->local_role; + bta_pan.open.peer_role = p_scb->peer_role; + + if (p_data->conn.result == PAN_SUCCESS) { + bta_pan.open.status = BTA_PAN_SUCCESS; + p_scb->pan_flow_enable = TRUE; + p_scb->app_flow_enable = TRUE; + + /* If app_id is NAP/GN, check whether there are multiple connections. + * If there are, provide a special app_id to dm to enforce master role only. + */ + if ((p_scb->app_id == bta_pan_cb.app_id[1] || + p_scb->app_id == bta_pan_cb.app_id[2]) && + bta_pan_has_multiple_connections(p_scb->app_id)) { + p_scb->app_id = BTA_APP_ID_PAN_MULTI; + } + + bta_sys_conn_open(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + } else { + bta_pan_scb_dealloc(p_scb); + bta_pan.open.status = BTA_PAN_FAIL; + } + + bta_pan_cb.p_cback(BTA_PAN_OPEN_EVT, &bta_pan); +} + +/******************************************************************************* + * + * Function bta_pan_conn_close + * + * Description process connection close event + * + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_conn_close(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + tBTA_PAN bta_pan; + BT_HDR *p_buf; + + bta_pan.close.handle = p_data->hdr.layer_specific; + + bta_sys_conn_close(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + + /* free all queued up data buffers */ + while ((p_buf = (BT_HDR *)fixed_queue_try_dequeue(p_scb->data_queue)) != NULL) { + osi_free(p_buf); + } + + bta_pan_scb_dealloc(p_scb); + + bta_pan_cb.p_cback(BTA_PAN_CLOSE_EVT, &bta_pan); +} + +/******************************************************************************* + * + * Function bta_pan_rx_path + * + * Description Handle data on the RX path (data sent from the phone to + * BTA). + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_rx_path(tBTA_PAN_SCB *p_scb, UNUSED_ATTR tBTA_PAN_DATA *p_data) +{ + /* if data path configured for rx pull */ + if ((bta_pan_cb.flow_mask & BTA_PAN_RX_MASK) == BTA_PAN_RX_PULL) { + /* if we can accept data */ + if (p_scb->pan_flow_enable == TRUE) { + /* call application callout function for rx path */ + bta_pan_co_rx_path(p_scb->handle, p_scb->app_id); + } + } + /* else data path configured for rx push */ + else { + } +} + +/******************************************************************************* + * + * Function bta_pan_tx_path + * + * Description Handle the TX data path (data sent from BTA to the phone). + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_tx_path(tBTA_PAN_SCB *p_scb, UNUSED_ATTR tBTA_PAN_DATA *p_data) +{ + /* if data path configured for tx pull */ + if ((bta_pan_cb.flow_mask & BTA_PAN_TX_MASK) == BTA_PAN_TX_PULL) { + bta_pan_pm_conn_busy(p_scb); + /* call application callout function for tx path */ + bta_pan_co_tx_path(p_scb->handle, p_scb->app_id); + + /* free data that exceeds queue level */ + while (fixed_queue_length(p_scb->data_queue) > bta_pan_cb.q_level) { + osi_free(fixed_queue_try_dequeue(p_scb->data_queue)); + } + bta_pan_pm_conn_idle(p_scb); + } + /* if configured for zero copy push */ + else if ((bta_pan_cb.flow_mask & BTA_PAN_TX_MASK) == BTA_PAN_TX_PUSH_BUF) { + /* if app can accept data */ + if (p_scb->app_flow_enable == TRUE) { + BT_HDR *p_buf; + + /* read data from the queue */ + p_buf = (BT_HDR *)fixed_queue_try_dequeue(p_scb->data_queue); + if (p_buf != NULL) { + /* send data to application */ + bta_pan_co_tx_writebuf(p_scb->handle, p_scb->app_id, + ((tBTA_PAN_DATA_PARAMS *)p_buf)->src, + ((tBTA_PAN_DATA_PARAMS *)p_buf)->dst, + ((tBTA_PAN_DATA_PARAMS *)p_buf)->protocol, p_buf, + ((tBTA_PAN_DATA_PARAMS *)p_buf)->ext, + ((tBTA_PAN_DATA_PARAMS *)p_buf)->forward); + } + + /* if there is more data to be passed to + upper layer */ + if (!fixed_queue_is_empty(p_scb->data_queue)) { + p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf != NULL) { + p_buf->layer_specific = p_scb->handle; + p_buf->event = BTA_PAN_RX_FROM_BNEP_READY_EVT; + bta_sys_sendmsg(p_buf); + } else { + APPL_TRACE_ERROR("%s: no resources", __func__); + } + } + } + + /* free data that exceeds queue level */ + while (fixed_queue_length(p_scb->data_queue) > bta_pan_cb.q_level) { + osi_free(fixed_queue_try_dequeue(p_scb->data_queue)); + } + } +} + +/******************************************************************************* + * + * Function bta_pan_tx_flow + * + * Description Set the application flow control state. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_tx_flow(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + p_scb->app_flow_enable = p_data->ci_tx_flow.enable; +} + +/******************************************************************************* + * + * Function bta_pan_write_buf + * + * Description Handle a bta_pan_ci_rx_writebuf() and send data to PAN. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_write_buf(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + if ((bta_pan_cb.flow_mask & BTA_PAN_RX_MASK) == BTA_PAN_RX_PUSH_BUF) { + bta_pan_pm_conn_busy(p_scb); + + PAN_WriteBuf(p_scb->handle, ((tBTA_PAN_DATA_PARAMS *)p_data)->dst, + ((tBTA_PAN_DATA_PARAMS *)p_data)->src, + ((tBTA_PAN_DATA_PARAMS *)p_data)->protocol, (BT_HDR *)p_data, + ((tBTA_PAN_DATA_PARAMS *)p_data)->ext); + bta_pan_pm_conn_idle(p_scb); + } else { + osi_free(p_data); + } +} + +/******************************************************************************* + * + * Function bta_pan_free_buf + * + * Description Frees the data buffer during closing state + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_free_buf(UNUSED_ATTR tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data) +{ + osi_free(p_data); +} + +#endif /* PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/bta/pan/bta_pan_api.c b/components/bt/host/bluedroid/bta/pan/bta_pan_api.c new file mode 100644 index 00000000000..a001fc00900 --- /dev/null +++ b/components/bt/host/bluedroid/bta/pan/bta_pan_api.c @@ -0,0 +1,215 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the implementation of the API for PAN subsystem of BTA, + * Broadcom's Bluetooth application layer for mobile phones. + * + ******************************************************************************/ +#include + +#include "common/bt_target.h" + +#include "bt_common.h" +#include "bta/bta_api.h" +#include "bta/bta_pan_api.h" +#include "bta_pan_int.h" +#include "bta/bta_sys.h" +#include "osi/osi.h" +#include "osi/allocator.h" +#include "stack/pan_api.h" + +#if (BTA_PAN_INCLUDED == TRUE) + +static const tBTA_SYS_REG bta_pan_reg = {bta_pan_hdl_event, BTA_PanDisable}; + +/******************************************************************************* + * + * Function BTA_PanEnable + * + * Description Enable PAN service. This function must be + * called before any other functions in the PAN API are called. + * When the enable operation is complete the callback function + * will be called with a BTA_PAN_ENABLE_EVT. + * + * Returns void + * + ******************************************************************************/ +void BTA_PanEnable(tBTA_PAN_CBACK p_cback) +{ + tBTA_PAN_API_ENABLE *p_buf = + (tBTA_PAN_API_ENABLE *)osi_malloc(sizeof(tBTA_PAN_API_ENABLE)); + + if (p_buf != NULL) { + /* register with BTA system manager */ + bta_sys_register(BTA_ID_PAN, &bta_pan_reg); + + p_buf->hdr.event = BTA_PAN_API_ENABLE_EVT; + p_buf->p_cback = p_cback; + + bta_sys_sendmsg(p_buf); + } +} + +/******************************************************************************* + * + * Function BTA_PanDisable + * + * Description Disables PAN service. + * + * + * Returns void + * + ******************************************************************************/ +void BTA_PanDisable(void) +{ + BT_HDR *p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf == NULL) { + return; + } + + bta_sys_deregister(BTA_ID_PAN); + p_buf->event = BTA_PAN_API_DISABLE_EVT; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function BTA_PanSetRole + * + * Description Sets PAN roles. When the enable operation is complete + * the callback function will be called with a + * BTA_PAN_SET_ROLE_EVT. + * + * Returns void + * + ******************************************************************************/ +void BTA_PanSetRole(tBTA_PAN_ROLE role, tBTA_PAN_ROLE_INFO *p_user_info, + tBTA_PAN_ROLE_INFO *p_gn_info, + tBTA_PAN_ROLE_INFO *p_nap_info) +{ + tBTA_PAN_API_SET_ROLE *p_buf = + (tBTA_PAN_API_SET_ROLE *)osi_calloc(sizeof(tBTA_PAN_API_SET_ROLE)); + if (p_buf == NULL) { + return; + } + + p_buf->hdr.event = BTA_PAN_API_SET_ROLE_EVT; + p_buf->role = role; + + if (p_user_info && (role & BTA_PAN_ROLE_PANU)) { + if (p_user_info->p_srv_name) { + strlcpy(p_buf->user_name, p_user_info->p_srv_name, BTA_SERVICE_NAME_LEN + 1); + } + + p_buf->user_app_id = p_user_info->app_id; + p_buf->user_sec_mask = p_user_info->sec_mask; + } + + if (p_gn_info && (role & BTA_PAN_ROLE_GN)) { + if (p_gn_info->p_srv_name) { + strlcpy(p_buf->gn_name, p_gn_info->p_srv_name, BTA_SERVICE_NAME_LEN + 1); + } + + p_buf->gn_app_id = p_gn_info->app_id; + p_buf->gn_sec_mask = p_gn_info->sec_mask; + } + + if (p_nap_info && (role & BTA_PAN_ROLE_NAP)) { + if (p_nap_info->p_srv_name) { + strlcpy(p_buf->nap_name, p_nap_info->p_srv_name, BTA_SERVICE_NAME_LEN + 1); + } + + p_buf->nap_app_id = p_nap_info->app_id; + p_buf->nap_sec_mask = p_nap_info->sec_mask; + } + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function BTA_PanOpen + * + * Description Opens a connection to a peer device. + * When connection is open callback function is called + * with a BTA_PAN_OPEN_EVT. + * + * + * Returns void + * + ******************************************************************************/ +void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE local_role, + tBTA_PAN_ROLE peer_role) +{ + tBTA_PAN_API_OPEN *p_buf = + (tBTA_PAN_API_OPEN *)osi_malloc(sizeof(tBTA_PAN_API_OPEN)); + if (p_buf == NULL) { + return; + } + + p_buf->hdr.event = BTA_PAN_API_OPEN_EVT; + p_buf->local_role = local_role; + p_buf->peer_role = peer_role; + bdcpy(p_buf->bd_addr, bd_addr); + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function BTA_PanClose + * + * Description Close a PAN connection to a peer device. + * + * + * Returns void + * + ******************************************************************************/ +void BTA_PanClose(UINT16 handle) +{ + BT_HDR *p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf == NULL) { + return; + } + + p_buf->event = BTA_PAN_API_CLOSE_EVT; + p_buf->layer_specific = handle; + + bta_sys_sendmsg(p_buf); +} +#else + +void BTA_PanEnable(UNUSED_ATTR tBTA_PAN_CBACK p_cback) {} + +void BTA_PanDisable(void) {} + +void BTA_PanSetRole(UNUSED_ATTR tBTA_PAN_ROLE role, + UNUSED_ATTR tBTA_PAN_ROLE_INFO *p_user_info, + UNUSED_ATTR tBTA_PAN_ROLE_INFO *p_gn_info, + UNUSED_ATTR tBTA_PAN_ROLE_INFO *p_nap_info) {} + +void BTA_PanOpen(UNUSED_ATTR BD_ADDR bd_addr, + UNUSED_ATTR tBTA_PAN_ROLE local_role, + UNUSED_ATTR tBTA_PAN_ROLE peer_role) {} + +void BTA_PanClose(UNUSED_ATTR UINT16 handle) {} + +#endif /* BTA_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/bta/pan/bta_pan_ci.c b/components/bt/host/bluedroid/bta/pan/bta_pan_ci.c new file mode 100644 index 00000000000..046a2e55865 --- /dev/null +++ b/components/bt/host/bluedroid/bta/pan/bta_pan_ci.c @@ -0,0 +1,338 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the implementation file for data gateway call-in functions. + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#include + +#include "bt_common.h" +#include "bta/bta_api.h" +#include "bta/bta_pan_api.h" +#include "bta/bta_pan_ci.h" +#include "bta_pan_int.h" +#include "osi/osi.h" +#include "osi/allocator.h" +#include "stack/pan_api.h" + +#if (BTA_PAN_INCLUDED == TRUE) + +/******************************************************************************* + * + * Function bta_pan_ci_tx_ready + * + * Description This function sends an event to PAN indicating the phone is + * ready for more data and PAN should call + * bta_pan_co_tx_path(). + * This function is used when the TX data path is configured + * to use a pull interface. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_tx_ready(UINT16 handle) +{ + BT_HDR *p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf == NULL) { + return; + } + + p_buf->layer_specific = handle; + p_buf->event = BTA_PAN_CI_TX_READY_EVT; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_rx_ready + * + * Description This function sends an event to PAN indicating the phone + * has data available to send to PAN and PAN should call + * bta_pan_co_rx_path(). This function is used when the RX + * data path is configured to use a pull interface. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_rx_ready(UINT16 handle) +{ + BT_HDR *p_buf = (BT_HDR *)osi_malloc(sizeof(BT_HDR)); + if (p_buf == NULL) { + return; + } + + p_buf->layer_specific = handle; + p_buf->event = BTA_PAN_CI_RX_READY_EVT; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_tx_flow + * + * Description This function is called to enable or disable data flow on + * the TX path. The phone should call this function to + * disable data flow when it is congested and cannot handle + * any more data sent by bta_pan_co_tx_write() or + * bta_pan_co_tx_writebuf(). This function is used when the + * TX data path is configured to use a push interface. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_tx_flow(UINT16 handle, BOOLEAN enable) +{ + tBTA_PAN_CI_TX_FLOW *p_buf = + (tBTA_PAN_CI_TX_FLOW *)osi_malloc(sizeof(tBTA_PAN_CI_TX_FLOW)); + if (p_buf == NULL) { + return; + } + + p_buf->hdr.layer_specific = handle; + p_buf->hdr.event = BTA_PAN_CI_TX_FLOW_EVT; + p_buf->enable = enable; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_rx_write + * + * Description This function is called to send data to PAN when the RX path + * is configured to use a push interface. The function copies + * data to an event buffer and sends it to PAN. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_rx_write(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN ext) +{ + BT_HDR *p_buf; + + /* Reject oversized payloads: data is copied at + * sizeof(BT_HDR) + PAN_MINIMUM_OFFSET within a PAN_BUF_SIZE allocation. */ + if (p_data == NULL || len == 0 || len > PAN_MAX_WRITE_LEN) { + return; + } + + p_buf = (BT_HDR *)osi_malloc(PAN_BUF_SIZE); + if (p_buf == NULL) { + return; + } + + p_buf->offset = PAN_MINIMUM_OFFSET; + + /* copy all other params before the data */ + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_buf)->src, src); + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_buf)->dst, dst); + ((tBTA_PAN_DATA_PARAMS *)p_buf)->protocol = protocol; + ((tBTA_PAN_DATA_PARAMS *)p_buf)->ext = ext; + p_buf->len = len; + + /* copy data */ + memcpy((UINT8 *)(p_buf + 1) + p_buf->offset, p_data, len); + + p_buf->layer_specific = handle; + p_buf->event = BTA_PAN_CI_RX_WRITEBUF_EVT; + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_rx_writebuf + * + * Description This function is called to send data to the phone when + * the RX path is configured to use a push interface with + * zero copy. The function sends an event to PAN containing + * the data buffer. The buffer will be freed by BTA; the + * phone must not free the buffer. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_rx_writebuf(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext) +{ + /* copy all other params before the data */ + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_buf)->src, src); + bdcpy(((tBTA_PAN_DATA_PARAMS *)p_buf)->dst, dst); + ((tBTA_PAN_DATA_PARAMS *)p_buf)->protocol = protocol; + ((tBTA_PAN_DATA_PARAMS *)p_buf)->ext = ext; + + p_buf->layer_specific = handle; + p_buf->event = BTA_PAN_CI_RX_WRITEBUF_EVT; + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_readbuf + * + * Description + * + * + * Returns void + * + ******************************************************************************/ +BT_HDR *bta_pan_ci_readbuf(UINT16 handle, BD_ADDR src, BD_ADDR dst, + UINT16 *p_protocol, BOOLEAN *p_ext, + BOOLEAN *p_forward) +{ + tBTA_PAN_SCB *p_scb; + BT_HDR *p_buf; + + p_scb = bta_pan_scb_by_handle(handle); + if (p_scb == NULL) { + return NULL; + } + + p_buf = (BT_HDR *)fixed_queue_try_dequeue(p_scb->data_queue); + if (p_buf != NULL) { + bdcpy(src, ((tBTA_PAN_DATA_PARAMS *)p_buf)->src); + bdcpy(dst, ((tBTA_PAN_DATA_PARAMS *)p_buf)->dst); + *p_protocol = ((tBTA_PAN_DATA_PARAMS *)p_buf)->protocol; + *p_ext = ((tBTA_PAN_DATA_PARAMS *)p_buf)->ext; + *p_forward = ((tBTA_PAN_DATA_PARAMS *)p_buf)->forward; + } + + return p_buf; +} + +/******************************************************************************* + * + * Function bta_pan_ci_set_mfilters + * + * Description This function is called to set multicast filters + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_set_mfilters(UINT16 handle, UINT16 num_mcast_filters, + UINT8 *p_start_array, UINT8 *p_end_array) +{ + tBTA_PAN_CI_SET_MFILTER *p_buf; + + if (num_mcast_filters > BNEP_MAX_MULTI_FILTERS || + (num_mcast_filters > 0 && (p_start_array == NULL || p_end_array == NULL))) { + return; + } + + p_buf = (tBTA_PAN_CI_SET_MFILTER *)osi_malloc(sizeof(tBTA_PAN_CI_SET_MFILTER)); + if (p_buf == NULL) { + return; + } + + p_buf->hdr.layer_specific = handle; + p_buf->hdr.event = BTA_PAN_CI_SET_MFILTER_EVT; + p_buf->num_filters = num_mcast_filters; + if (num_mcast_filters > 0) { + memcpy(p_buf->start_array, p_start_array, num_mcast_filters * BD_ADDR_LEN); + memcpy(p_buf->end_array, p_end_array, num_mcast_filters * BD_ADDR_LEN); + } + + bta_sys_sendmsg(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_ci_set_pfilters + * + * Description This function is called to set protocol filters + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_ci_set_pfilters(UINT16 handle, UINT16 num_filters, + UINT16 *p_start_array, UINT16 *p_end_array) +{ + tBTA_PAN_CI_SET_PFILTER *p_buf; + + if (num_filters > BNEP_MAX_PROT_FILTERS || + (num_filters > 0 && (p_start_array == NULL || p_end_array == NULL))) { + return; + } + + p_buf = (tBTA_PAN_CI_SET_PFILTER *)osi_malloc(sizeof(tBTA_PAN_CI_SET_PFILTER)); + if (p_buf == NULL) { + return; + } + + p_buf->hdr.layer_specific = handle; + p_buf->hdr.event = BTA_PAN_CI_SET_PFILTER_EVT; + p_buf->num_filters = num_filters; + if (num_filters > 0) { + memcpy(p_buf->start_array, p_start_array, num_filters * sizeof(UINT16)); + memcpy(p_buf->end_array, p_end_array, num_filters * sizeof(UINT16)); + } + + bta_sys_sendmsg(p_buf); +} +#else + +void bta_pan_ci_tx_ready(UNUSED_ATTR UINT16 handle) {} + +void bta_pan_ci_rx_ready(UNUSED_ATTR UINT16 handle) {} + +void bta_pan_ci_tx_flow(UNUSED_ATTR UINT16 handle, UNUSED_ATTR BOOLEAN enable) {} + +void bta_pan_ci_rx_writebuf(UNUSED_ATTR UINT16 handle, + UNUSED_ATTR BD_ADDR dst, + UNUSED_ATTR BD_ADDR src, + UNUSED_ATTR UINT16 protocol, + UNUSED_ATTR BT_HDR *p_buf, UNUSED_ATTR BOOLEAN ext) {} + +BT_HDR *bta_pan_ci_readbuf(UNUSED_ATTR UINT16 handle, + UNUSED_ATTR BD_ADDR src, + UNUSED_ATTR BD_ADDR dst, + UNUSED_ATTR UINT16 *p_protocol, + UNUSED_ATTR BOOLEAN *p_ext, + UNUSED_ATTR BOOLEAN *p_forward) +{ + return NULL; +} + +void bta_pan_ci_set_pfilters(UNUSED_ATTR UINT16 handle, + UNUSED_ATTR UINT16 num_filters, + UNUSED_ATTR UINT16 *p_start_array, + UNUSED_ATTR UINT16 *p_end_array) {} + +void bta_pan_ci_set_mfilters(UNUSED_ATTR UINT16 handle, + UNUSED_ATTR UINT16 num_mcast_filters, + UNUSED_ATTR UINT8 *p_start_array, + UNUSED_ATTR UINT8 *p_end_array) {} + +#endif /* BTA_PAN_API */ diff --git a/components/bt/host/bluedroid/bta/pan/bta_pan_int.h b/components/bt/host/bluedroid/bta/pan/bta_pan_int.h new file mode 100644 index 00000000000..06c858c99ad --- /dev/null +++ b/components/bt/host/bluedroid/bta/pan/bta_pan_int.h @@ -0,0 +1,213 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the private interface file for the BTA data gateway. + * + ******************************************************************************/ +#ifndef BTA_PAN_INT_H +#define BTA_PAN_INT_H + +#include "common/bt_target.h" +#include "bta/bta_pan_api.h" +#include "bta/bta_sys.h" +#include "osi/fixed_queue.h" + +#if (BTA_PAN_INCLUDED == TRUE) + +#define fixed_queue_try_dequeue(q) fixed_queue_dequeue((q), 0) + +/***************************************************************************** + * Constants + ****************************************************************************/ + +/* PAN events */ +enum { + /* these events are handled by the state machine */ + BTA_PAN_API_CLOSE_EVT = BTA_SYS_EVT_START(BTA_ID_PAN), + BTA_PAN_CI_TX_READY_EVT, + BTA_PAN_CI_RX_READY_EVT, + BTA_PAN_CI_TX_FLOW_EVT, + BTA_PAN_CI_RX_WRITE_EVT, + BTA_PAN_CI_RX_WRITEBUF_EVT, + BTA_PAN_CONN_OPEN_EVT, + BTA_PAN_CONN_CLOSE_EVT, + BTA_PAN_BNEP_FLOW_ENABLE_EVT, + BTA_PAN_RX_FROM_BNEP_READY_EVT, + + /* these events are handled outside of the state machine */ + BTA_PAN_API_ENABLE_EVT, + BTA_PAN_API_DISABLE_EVT, + BTA_PAN_API_SET_ROLE_EVT, + BTA_PAN_API_OPEN_EVT, + BTA_PAN_CI_SET_PFILTER_EVT, + BTA_PAN_CI_SET_MFILTER_EVT +}; + +/* state machine states */ +enum { BTA_PAN_IDLE_ST, BTA_PAN_OPEN_ST, BTA_PAN_CLOSING_ST }; + +/***************************************************************************** + * Data types + ****************************************************************************/ + +/* data type for BTA_PAN_API_ENABLE_EVT */ +typedef struct { + BT_HDR hdr; /* Event header */ + tBTA_PAN_CBACK *p_cback; /* PAN callback function */ +} tBTA_PAN_API_ENABLE; + +/* data type for BTA_PAN_API_REG_ROLE_EVT */ +typedef struct { + BT_HDR hdr; /* Event header */ + char user_name[BTA_SERVICE_NAME_LEN + 1]; /* Service name */ + char gn_name[BTA_SERVICE_NAME_LEN + 1]; /* Service name */ + char nap_name[BTA_SERVICE_NAME_LEN + 1]; /* Service name */ + tBTA_PAN_ROLE role; + UINT8 user_app_id; + UINT8 gn_app_id; + UINT8 nap_app_id; + tBTA_SEC user_sec_mask; /* Security mask */ + tBTA_SEC gn_sec_mask; /* Security mask */ + tBTA_SEC nap_sec_mask; /* Security mask */ + +} tBTA_PAN_API_SET_ROLE; + +/* data type for BTA_PAN_API_OPEN_EVT */ +typedef struct { + BT_HDR hdr; /* Event header */ + tBTA_PAN_ROLE local_role; /* local role */ + tBTA_PAN_ROLE peer_role; /* peer role */ + BD_ADDR bd_addr; /* peer bdaddr */ +} tBTA_PAN_API_OPEN; + +/* data type for BTA_PAN_CI_TX_FLOW_EVT */ +typedef struct { + BT_HDR hdr; /* Event header */ + BOOLEAN enable; /* Flow control setting */ +} tBTA_PAN_CI_TX_FLOW; + +/* data type for BTA_PAN_CI_SET_PFILTER_EVT */ +typedef struct { + BT_HDR hdr; + UINT16 num_filters; + UINT16 start_array[BNEP_MAX_PROT_FILTERS]; + UINT16 end_array[BNEP_MAX_PROT_FILTERS]; +} tBTA_PAN_CI_SET_PFILTER; + +/* data type for BTA_PAN_CI_SET_MFILTER_EVT */ +typedef struct { + BT_HDR hdr; + UINT16 num_filters; + UINT8 start_array[BNEP_MAX_MULTI_FILTERS * BD_ADDR_LEN]; + UINT8 end_array[BNEP_MAX_MULTI_FILTERS * BD_ADDR_LEN]; +} tBTA_PAN_CI_SET_MFILTER; + +/* data type for BTA_PAN_CONN_OPEN_EVT */ +typedef struct { + BT_HDR hdr; /* Event header */ + tPAN_RESULT result; + +} tBTA_PAN_CONN; + +/* union of all data types */ +typedef union { + BT_HDR hdr; + tBTA_PAN_API_ENABLE api_enable; + tBTA_PAN_API_SET_ROLE api_set_role; + tBTA_PAN_API_OPEN api_open; + tBTA_PAN_CI_TX_FLOW ci_tx_flow; + tBTA_PAN_CI_SET_PFILTER ci_set_pfilter; + tBTA_PAN_CI_SET_MFILTER ci_set_mfilter; + tBTA_PAN_CONN conn; +} tBTA_PAN_DATA; + +/* state machine control block */ +typedef struct { + BD_ADDR bd_addr; /* peer bdaddr */ + fixed_queue_t * + data_queue; /* Queue of buffers waiting to be passed to application */ + UINT16 handle; /* BTA PAN/BNEP handle */ + BOOLEAN in_use; /* scb in use */ + tBTA_SEC sec_mask; /* Security mask */ + BOOLEAN pan_flow_enable; /* BNEP flow control state */ + BOOLEAN app_flow_enable; /* Application flow control state */ + UINT8 state; /* State machine state */ + tBTA_PAN_ROLE local_role; /* local role */ + tBTA_PAN_ROLE peer_role; /* peer role */ + UINT8 app_id; /* application id for the connection */ + +} tBTA_PAN_SCB; + +/* main control block */ +typedef struct { + tBTA_PAN_SCB scb[BTA_PAN_NUM_CONN]; /* state machine control blocks */ + tBTA_PAN_CBACK *p_cback; /* PAN callback function */ + UINT8 app_id[3]; /* application id for PAN roles */ + UINT8 flow_mask; /* Data flow mask */ + UINT8 q_level; /* queue level set by application for TX data */ + +} tBTA_PAN_CB; + +/* pan data param */ +typedef struct { + BT_HDR hdr; + BD_ADDR src; + BD_ADDR dst; + UINT16 protocol; + BOOLEAN ext; + BOOLEAN forward; + +} tBTA_PAN_DATA_PARAMS; + +/***************************************************************************** + * Global data + ****************************************************************************/ + +/* PAN control block */ +extern tBTA_PAN_CB bta_pan_cb; + +/***************************************************************************** + * Function prototypes + ****************************************************************************/ +extern tBTA_PAN_SCB *bta_pan_scb_alloc(void); +extern void bta_pan_scb_dealloc(tBTA_PAN_SCB *p_scb); +extern UINT8 bta_pan_scb_to_idx(tBTA_PAN_SCB *p_scb); +extern tBTA_PAN_SCB *bta_pan_scb_by_handle(UINT16 handle); +extern BOOLEAN bta_pan_hdl_event(BT_HDR *p_msg); + +/* action functions */ +extern void bta_pan_enable(tBTA_PAN_DATA *p_data); +extern void bta_pan_disable(void); +extern void bta_pan_set_role(tBTA_PAN_DATA *p_data); +extern void bta_pan_open(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_api_close(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_set_shutdown(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_rx_path(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_tx_path(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_tx_flow(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_conn_open(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_conn_close(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_writebuf(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_write_buf(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); +extern void bta_pan_free_buf(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); + +#endif /* BTA_PAN_INCLUDED */ + +#endif /* BTA_PAN_INT_H */ diff --git a/components/bt/host/bluedroid/bta/pan/bta_pan_main.c b/components/bt/host/bluedroid/bta/pan/bta_pan_main.c new file mode 100644 index 00000000000..75c4c4f8a5e --- /dev/null +++ b/components/bt/host/bluedroid/bta/pan/bta_pan_main.c @@ -0,0 +1,397 @@ +/****************************************************************************** + * + * Copyright (C) 2004-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains the PAN main functions and state machine. + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (BTA_PAN_INCLUDED == TRUE) + +#include + +#include "bt_common.h" +#include "bta/bta_api.h" +#include "bta/bta_pan_api.h" +#include "bta_pan_int.h" +#include "bta/bta_sys.h" +#include "osi/osi.h" +#include "osi/allocator.h" +#include "stack/pan_api.h" +#include "bta/utl.h" + +/***************************************************************************** + * Constants and types + ****************************************************************************/ + +/* state machine action enumeration list */ +enum { + BTA_PAN_API_CLOSE, + BTA_PAN_TX_PATH, + BTA_PAN_RX_PATH, + BTA_PAN_TX_FLOW, + BTA_PAN_WRITE_BUF, + BTA_PAN_CONN_OPEN, + BTA_PAN_CONN_CLOSE, + BTA_PAN_FREE_BUF, + BTA_PAN_IGNORE +}; + +/* type for action functions */ +typedef void (*tBTA_PAN_ACTION)(tBTA_PAN_SCB *p_scb, tBTA_PAN_DATA *p_data); + +/* action function list */ +const tBTA_PAN_ACTION bta_pan_action[] = { + bta_pan_api_close, + bta_pan_tx_path, + bta_pan_rx_path, + bta_pan_tx_flow, + bta_pan_write_buf, + bta_pan_conn_open, + bta_pan_conn_close, + bta_pan_free_buf, +}; + +/* state table information */ +#define BTA_PAN_ACTIONS 1 /* number of actions */ +#define BTA_PAN_NEXT_STATE 1 /* position of next state */ +#define BTA_PAN_NUM_COLS 2 /* number of columns in state tables */ + +/* state table for listen state */ +const UINT8 bta_pan_st_idle[][BTA_PAN_NUM_COLS] = { + /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_IDLE_ST}, + /* CI_TX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_TX_FLOW */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_FREE_BUF, BTA_PAN_IDLE_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_CONN_OPEN, BTA_PAN_OPEN_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* BNEP_DATA */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST} +}; + +/* state table for open state */ +const UINT8 bta_pan_st_open[][BTA_PAN_NUM_COLS] = { + /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_CLOSING_ST}, + /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}, + /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, + /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_OPEN_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_WRITE_BUF, BTA_PAN_OPEN_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST} +}; + +/* state table for closing state */ +const UINT8 bta_pan_st_closing[][BTA_PAN_NUM_COLS] = { + /* API_CLOSE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}, + /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, + /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_CLOSING_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_FREE_BUF, BTA_PAN_CLOSING_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST} +}; + +/* type for state table */ +typedef const UINT8(*tBTA_PAN_ST_TBL)[BTA_PAN_NUM_COLS]; + +/* state table */ +const tBTA_PAN_ST_TBL bta_pan_st_tbl[] = {bta_pan_st_idle, bta_pan_st_open, + bta_pan_st_closing + }; + +/***************************************************************************** + * Global data + ****************************************************************************/ + +/* PAN control block */ +tBTA_PAN_CB bta_pan_cb; + +/******************************************************************************* + * + * Function bta_pan_scb_alloc + * + * Description Allocate a PAN server control block. + * + * + * Returns pointer to the scb, or NULL if none could be allocated. + * + ******************************************************************************/ +tBTA_PAN_SCB *bta_pan_scb_alloc(void) +{ + tBTA_PAN_SCB *p_scb = &bta_pan_cb.scb[0]; + int i; + + for (i = 0; i < BTA_PAN_NUM_CONN; i++, p_scb++) { + if (!p_scb->in_use) { + p_scb->in_use = TRUE; + APPL_TRACE_DEBUG("bta_pan_scb_alloc %d", i); + break; + } + } + + if (i == BTA_PAN_NUM_CONN) { + /* out of scbs */ + p_scb = NULL; + APPL_TRACE_WARNING("Out of scbs"); + } + return p_scb; +} + +/******************************************************************************* + * + * Function bta_pan_sm_execute + * + * Description State machine event handling function for PAN + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_sm_execute(tBTA_PAN_SCB *p_scb, UINT16 event, + tBTA_PAN_DATA *p_data) +{ + tBTA_PAN_ST_TBL state_table; + UINT8 action; + int i; + + APPL_TRACE_EVENT("PAN scb=%d event=0x%x state=%d", bta_pan_scb_to_idx(p_scb), + event, p_scb->state); + + /* look up the state table for the current state */ + state_table = bta_pan_st_tbl[p_scb->state]; + + event &= 0x00FF; + + /* set next state */ + p_scb->state = state_table[event][BTA_PAN_NEXT_STATE]; + + /* execute action functions */ + for (i = 0; i < BTA_PAN_ACTIONS; i++) { + action = state_table[event][i]; + if (action != BTA_PAN_IGNORE) { + (*bta_pan_action[action])(p_scb, p_data); + } else { + break; + } + } +} + +/******************************************************************************* + * + * Function bta_pan_api_enable + * + * Description Handle an API enable event. + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_api_enable(tBTA_PAN_DATA *p_data) +{ + /* initialize control block */ + memset(&bta_pan_cb, 0, sizeof(bta_pan_cb)); + + /* store callback function */ + bta_pan_cb.p_cback = p_data->api_enable.p_cback; + bta_pan_enable(p_data); +} + +/******************************************************************************* + * + * Function bta_pan_api_disable + * + * Description Handle an API disable event. + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_api_disable(UNUSED_ATTR tBTA_PAN_DATA *p_data) +{ + bta_pan_disable(); +} + +/******************************************************************************* + * + * Function bta_pan_api_open + * + * Description Handle an API listen event. + * + * + * Returns void + * + ******************************************************************************/ +static void bta_pan_api_open(tBTA_PAN_DATA *p_data) +{ + tBTA_PAN_SCB *p_scb; + tBTA_PAN bta_pan; + + /* allocate an scb */ + p_scb = bta_pan_scb_alloc(); + if (p_scb != NULL) { + bta_pan_open(p_scb, p_data); + } else { + bdcpy(bta_pan.open.bd_addr, p_data->api_open.bd_addr); + bta_pan.open.handle = PAN_INVALID_HANDLE; + bta_pan.open.status = BTA_PAN_FAIL; + bta_pan.open.local_role = p_data->api_open.local_role; + bta_pan.open.peer_role = p_data->api_open.peer_role; + bta_pan_cb.p_cback(BTA_PAN_OPEN_EVT, &bta_pan); + } +} +/******************************************************************************* + * + * Function bta_pan_scb_dealloc + * + * Description Deallocate a link control block. + * + * + * Returns void + * + ******************************************************************************/ +void bta_pan_scb_dealloc(tBTA_PAN_SCB *p_scb) +{ + APPL_TRACE_DEBUG("bta_pan_scb_dealloc %d", bta_pan_scb_to_idx(p_scb)); + fixed_queue_free(p_scb->data_queue, NULL); + memset(p_scb, 0, sizeof(tBTA_PAN_SCB)); +} + +/******************************************************************************* + * + * Function bta_pan_scb_to_idx + * + * Description Given a pointer to an scb, return its index. + * + * + * Returns Index of scb. + * + ******************************************************************************/ +UINT8 bta_pan_scb_to_idx(tBTA_PAN_SCB *p_scb) +{ + return ((UINT8)(p_scb - bta_pan_cb.scb)) + 1; +} + +/******************************************************************************* + * + * Function bta_pan_scb_by_handle + * + * Description Find scb associated with handle. + * + * + * Returns Pointer to scb or NULL if not found. + * + ******************************************************************************/ +tBTA_PAN_SCB *bta_pan_scb_by_handle(UINT16 handle) +{ + tBTA_PAN_SCB *p_scb = &bta_pan_cb.scb[0]; + UINT8 i; + + for (i = 0; i < BTA_PAN_NUM_CONN; i++, p_scb++) { + if (p_scb->in_use && p_scb->handle == handle) { + return p_scb; + } + } + + return NULL; +} + +/******************************************************************************* + * + * Function bta_pan_hdl_event + * + * Description Data gateway main event handling function. + * + * + * Returns void + * + ******************************************************************************/ +BOOLEAN bta_pan_hdl_event(BT_HDR *p_msg) +{ + tBTA_PAN_SCB *p_scb; + BOOLEAN freebuf = TRUE; + + switch (p_msg->event) { + /* handle enable event */ + case BTA_PAN_API_ENABLE_EVT: + bta_pan_api_enable((tBTA_PAN_DATA *)p_msg); + break; + + /* handle disable event */ + case BTA_PAN_API_DISABLE_EVT: + bta_pan_api_disable((tBTA_PAN_DATA *)p_msg); + break; + + /* handle set role event */ + case BTA_PAN_API_SET_ROLE_EVT: + bta_pan_set_role((tBTA_PAN_DATA *)p_msg); + break; + + /* handle open event */ + case BTA_PAN_API_OPEN_EVT: + bta_pan_api_open((tBTA_PAN_DATA *)p_msg); + break; + + /* set protocol filters on peer (must run in BTU context) */ + case BTA_PAN_CI_SET_PFILTER_EVT: { + tBTA_PAN_CI_SET_PFILTER *p_filt = (tBTA_PAN_CI_SET_PFILTER *)p_msg; + PAN_SetProtocolFilters(p_filt->hdr.layer_specific, p_filt->num_filters, + (p_filt->num_filters > 0) ? p_filt->start_array : NULL, + (p_filt->num_filters > 0) ? p_filt->end_array : NULL); + break; + } + + /* set multicast filters on peer (must run in BTU context) */ + case BTA_PAN_CI_SET_MFILTER_EVT: { + tBTA_PAN_CI_SET_MFILTER *p_filt = (tBTA_PAN_CI_SET_MFILTER *)p_msg; + PAN_SetMulticastFilters(p_filt->hdr.layer_specific, p_filt->num_filters, + (p_filt->num_filters > 0) ? p_filt->start_array : NULL, + (p_filt->num_filters > 0) ? p_filt->end_array : NULL); + break; + } + + /* events that require buffer not be released when an SCB handles them */ + case BTA_PAN_CI_RX_WRITEBUF_EVT: + p_scb = bta_pan_scb_by_handle(p_msg->layer_specific); + if (p_scb != NULL) { + freebuf = FALSE; + bta_pan_sm_execute(p_scb, p_msg->event, (tBTA_PAN_DATA *)p_msg); + } + break; + + /* all other events */ + default: + p_scb = bta_pan_scb_by_handle(p_msg->layer_specific); + if (p_scb != NULL) { + bta_pan_sm_execute(p_scb, p_msg->event, (tBTA_PAN_DATA *)p_msg); + } + break; + } + return freebuf; +} +#endif /* BTA_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/btc/profile/std/include/btc_pan.h b/components/bt/host/bluedroid/btc/profile/std/include/btc_pan.h new file mode 100644 index 00000000000..eaca7c693cf --- /dev/null +++ b/components/bt/host/bluedroid/btc/profile/std/include/btc_pan.h @@ -0,0 +1,86 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "btc/btc_task.h" +#include "esp_pan_api.h" +#include "common/bt_target.h" +#include "stack/bt_types.h" +#include "bta/bta_pan_api.h" + +#if (defined BTC_PAN_INCLUDED && BTC_PAN_INCLUDED == TRUE) + +#define BTC_PAN_APP_ID_PANU 0 +#define BTC_PAN_APP_ID_NAP 1 +#define BTC_PAN_APP_ID_GN 2 + +typedef enum { + BTC_PAN_ACT_INIT = 0, + BTC_PAN_ACT_DEINIT, + BTC_PAN_ACT_CONNECT, + BTC_PAN_ACT_DISCONNECT, + BTC_PAN_ACT_WRITE, + BTC_PAN_ACT_SET_PFILTER, + BTC_PAN_ACT_SET_MFILTER, +} btc_pan_act_t; + +typedef union { + struct init_arg { + esp_pan_cfg_t cfg; + } init; + + struct connect_arg { + BD_ADDR bd_addr; + esp_pan_role_t local_role; + esp_pan_role_t peer_role; + } connect; + + struct disconnect_arg { + uint16_t handle; + } disconnect; + + struct write_arg { + uint16_t handle; + BD_ADDR dst; + BD_ADDR src; + uint16_t protocol; + uint16_t len; + uint8_t *data; + bool ext; + } write; + + struct set_pfilter_arg { + uint16_t handle; + uint16_t num_filters; + uint16_t *start_array; + uint16_t *end_array; + } set_pfilter; + + struct set_mfilter_arg { + uint16_t handle; + uint16_t num_filters; + esp_bd_addr_t *start_array; + esp_bd_addr_t *end_array; + } set_mfilter; +} btc_pan_args_t; + +void btc_pan_call_handler(btc_msg_t *msg); +void btc_pan_cb_handler(btc_msg_t *msg); +void btc_pan_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); +void btc_pan_arg_deep_free(btc_msg_t *msg); +void btc_pan_cb_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); +void btc_pan_cb_deep_free(btc_msg_t *msg); + +void btc_pan_co_data_ind(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN ext, BOOLEAN forward); +void btc_pan_co_rx_flow(UINT16 handle, BOOLEAN enable); +void btc_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters); +void btc_pan_co_mfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters); + +#endif /* BTC_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/btc/profile/std/pan/bta_pan_co.c b/components/bt/host/bluedroid/btc/profile/std/pan/bta_pan_co.c new file mode 100644 index 00000000000..f7e9a763865 --- /dev/null +++ b/components/bt/host/bluedroid/btc/profile/std/pan/bta_pan_co.c @@ -0,0 +1,230 @@ +/****************************************************************************** + * + * Copyright (C) 2009-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * Filename: bta_pan_co.c + * + * Description: PAN stack callout api for ESP-IDF + * + ******************************************************************************/ +#include "common/bt_target.h" + +#if (defined BTC_PAN_INCLUDED && BTC_PAN_INCLUDED == TRUE) + +#include + +#include "bt_common.h" +#include "osi/allocator.h" +#include "bta/bta_pan_co.h" +#include "bta/bta_api.h" +#include "bta/bta_pan_api.h" +#include "bta/bta_pan_ci.h" +#include "btc_pan.h" + +/******************************************************************************* + * + * Function bta_pan_co_init + * + * Description Initialize PAN data path configuration. + * + * Returns Data flow mask. + * + ******************************************************************************/ +UINT8 bta_pan_co_init(UINT8 *q_level) +{ + APPL_TRACE_API("%s", __func__); + + *q_level = 30; + return (BTA_PAN_RX_PUSH_BUF | BTA_PAN_RX_PUSH | BTA_PAN_TX_PULL); +} + +/****************************************************************************** + * + * Function bta_pan_co_open + * + * Description PAN connection opened. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_open(UINT16 handle, UINT8 app_id, tBTA_PAN_ROLE local_role, + tBTA_PAN_ROLE peer_role, BD_ADDR peer_addr) +{ + APPL_TRACE_API("%s: handle:%d app_id:%d local_role:%d peer_role:%d", + __func__, handle, app_id, local_role, peer_role); + (void)peer_addr; + bta_pan_ci_rx_ready(handle); +} + +/******************************************************************************* + * + * Function bta_pan_co_close + * + * Description PAN connection closed. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_close(UINT16 handle, UINT8 app_id) +{ + APPL_TRACE_API("%s: handle:%d app_id:%d", __func__, handle, app_id); +} + +/******************************************************************************* + * + * Function bta_pan_co_tx_path + * + * Description Deliver received Ethernet frames to application. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_tx_path(UINT16 handle, UINT8 app_id) +{ + BT_HDR *p_buf; + BD_ADDR src; + BD_ADDR dst; + UINT16 protocol; + BOOLEAN ext; + BOOLEAN forward; + + APPL_TRACE_API("%s: handle:%d app_id:%d", __func__, handle, app_id); + + do { + p_buf = bta_pan_ci_readbuf(handle, src, dst, &protocol, &ext, &forward); + if (p_buf) { + btc_pan_co_data_ind(handle, src, dst, protocol, + (UINT8 *)(p_buf + 1) + p_buf->offset, p_buf->len, + ext, forward); + osi_free(p_buf); + } + } while (p_buf != NULL); +} + +/******************************************************************************* + * + * Function bta_pan_co_rx_path + * + * Description Not used in push RX mode. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_rx_path(UINT16 handle, UINT8 app_id) +{ + APPL_TRACE_API("%s: handle:%d app_id:%d", __func__, handle, app_id); +} + +/******************************************************************************* + * + * Function bta_pan_co_tx_write + * + * Description Not used in pull TX mode. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_tx_write(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, + UINT16 protocol, UINT8 *p_data, UINT16 len, BOOLEAN ext, + BOOLEAN forward) +{ + APPL_TRACE_API("%s: handle:%d len:%d", __func__, handle, len); + (void)app_id; + (void)src; + (void)dst; + (void)protocol; + (void)p_data; + (void)ext; + (void)forward; +} + +/******************************************************************************* + * + * Function bta_pan_co_tx_writebuf + * + * Description Zero-copy TX push path. Not used while TX is configured + * for pull mode (BTA_PAN_TX_PULL). Caller transfers buffer + * ownership; free it even if the data is unused. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_tx_writebuf(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, + UINT16 protocol, BT_HDR *p_buf, BOOLEAN ext, + BOOLEAN forward) +{ + APPL_TRACE_API("%s: handle:%d", __func__, handle); + (void)app_id; + (void)src; + (void)dst; + (void)protocol; + (void)ext; + (void)forward; + osi_free(p_buf); +} + +/******************************************************************************* + * + * Function bta_pan_co_rx_flow + * + * Description Notify application of TX flow control state. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_rx_flow(UINT16 handle, UINT8 app_id, BOOLEAN enable) +{ + APPL_TRACE_API("%s: handle:%d enable:%d", __func__, handle, enable); + (void)app_id; + btc_pan_co_rx_flow(handle, enable); +} + +/******************************************************************************* + * + * Function bta_pan_co_pfilt_ind + * + * Description Protocol filter indication from peer device. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters) +{ + APPL_TRACE_API("%s: handle:%d indication:%d len:%d", __func__, handle, indication, len); + btc_pan_co_pfilt_ind(handle, indication, result, len, p_filters); +} + +/******************************************************************************* + * + * Function bta_pan_co_mfilt_ind + * + * Description Multicast filter indication from peer device. + * + * Returns void + * + ******************************************************************************/ +void bta_pan_co_mfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters) +{ + APPL_TRACE_API("%s: handle:%d indication:%d len:%d", __func__, handle, indication, len); + btc_pan_co_mfilt_ind(handle, indication, result, len, p_filters); +} + +#endif /* BTC_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/btc/profile/std/pan/btc_pan.c b/components/bt/host/bluedroid/btc/profile/std/pan/btc_pan.c new file mode 100644 index 00000000000..5c7fb274dad --- /dev/null +++ b/components/bt/host/bluedroid/btc/profile/std/pan/btc_pan.c @@ -0,0 +1,667 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include + +#include "btc_pan.h" +#include "btc/btc_manage.h" +#include "btc/btc_task.h" +#include "bta/bta_pan_api.h" +#include "bta/bta_pan_ci.h" +#include "common/bt_trace.h" +#include "osi/allocator.h" +#include "esp_pan_api.h" + +#if (defined BTC_PAN_INCLUDED && BTC_PAN_INCLUDED == TRUE) + +static bool s_btc_pan_init = false; +static esp_pan_cfg_t s_btc_pan_cfg; + +static esp_pan_status_t btc_pan_status_from_bta(tBTA_PAN_STATUS status) +{ + return (status == BTA_PAN_SUCCESS) ? ESP_PAN_SUCCESS : ESP_PAN_FAILURE; +} + +static void btc_pan_cb_to_app(esp_pan_cb_event_t event, esp_pan_cb_param_t *param) +{ + esp_pan_cb_t callback = (esp_pan_cb_t)btc_profile_cb_get(BTC_PID_PAN); + if (callback) { + callback(event, param); + } +} + +static void bte_pan_evt(tBTA_PAN_EVT event, tBTA_PAN *p_data) +{ + btc_msg_t msg; + int param_len = 0; + + switch (event) { + case BTA_PAN_ENABLE_EVT: + case BTA_PAN_SET_ROLE_EVT: + param_len = (event == BTA_PAN_SET_ROLE_EVT) ? sizeof(tBTA_PAN_SET_ROLE) : 0; + break; + case BTA_PAN_OPENING_EVT: + param_len = sizeof(tBTA_PAN_OPENING); + break; + case BTA_PAN_OPEN_EVT: + param_len = sizeof(tBTA_PAN_OPEN); + break; + case BTA_PAN_CLOSE_EVT: + param_len = sizeof(tBTA_PAN_CLOSE); + break; + default: + return; + } + + msg.sig = BTC_SIG_API_CB; + msg.pid = BTC_PID_PAN; + msg.act = event; + + if (btc_transfer_context(&msg, p_data, param_len, NULL, NULL) != BT_STATUS_SUCCESS) { + BTC_TRACE_ERROR("%s: context transfer failed", __func__); + } +} + +static void btc_pan_set_role(void) +{ + tBTA_PAN_ROLE_INFO user_info = {0}; + tBTA_PAN_ROLE_INFO gn_info = {0}; + tBTA_PAN_ROLE_INFO nap_info = {0}; + + if (s_btc_pan_cfg.role & ESP_PAN_ROLE_PANU) { + user_info.p_srv_name = s_btc_pan_cfg.panu_service_name; + user_info.app_id = BTC_PAN_APP_ID_PANU; + user_info.sec_mask = s_btc_pan_cfg.panu_sec; + } + + if (s_btc_pan_cfg.role & ESP_PAN_ROLE_GN) { + gn_info.p_srv_name = s_btc_pan_cfg.gn_service_name; + gn_info.app_id = BTC_PAN_APP_ID_GN; + gn_info.sec_mask = s_btc_pan_cfg.gn_sec; + } + + if (s_btc_pan_cfg.role & ESP_PAN_ROLE_NAP) { + nap_info.p_srv_name = s_btc_pan_cfg.nap_service_name; + nap_info.app_id = BTC_PAN_APP_ID_NAP; + nap_info.sec_mask = s_btc_pan_cfg.nap_sec; + } + + BTA_PanSetRole((tBTA_PAN_ROLE)s_btc_pan_cfg.role, &user_info, &gn_info, &nap_info); +} + +static void btc_pan_free_cfg_strings(void) +{ + if (s_btc_pan_cfg.panu_service_name) { + osi_free((void *)s_btc_pan_cfg.panu_service_name); + s_btc_pan_cfg.panu_service_name = NULL; + } + if (s_btc_pan_cfg.gn_service_name) { + osi_free((void *)s_btc_pan_cfg.gn_service_name); + s_btc_pan_cfg.gn_service_name = NULL; + } + if (s_btc_pan_cfg.nap_service_name) { + osi_free((void *)s_btc_pan_cfg.nap_service_name); + s_btc_pan_cfg.nap_service_name = NULL; + } +} + +static void btc_pan_store_cfg(const esp_pan_cfg_t *cfg) +{ + btc_pan_free_cfg_strings(); + s_btc_pan_cfg = *cfg; + + if (cfg->panu_service_name) { + size_t len = strlen(cfg->panu_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, cfg->panu_service_name, len); + s_btc_pan_cfg.panu_service_name = name; + } else { + s_btc_pan_cfg.panu_service_name = NULL; + } + } + if (cfg->gn_service_name) { + size_t len = strlen(cfg->gn_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, cfg->gn_service_name, len); + s_btc_pan_cfg.gn_service_name = name; + } else { + s_btc_pan_cfg.gn_service_name = NULL; + } + } + if (cfg->nap_service_name) { + size_t len = strlen(cfg->nap_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, cfg->nap_service_name, len); + s_btc_pan_cfg.nap_service_name = name; + } else { + s_btc_pan_cfg.nap_service_name = NULL; + } + } +} + +static void btc_pan_init(const esp_pan_cfg_t *cfg) +{ + if (s_btc_pan_init) { + esp_pan_cb_param_t param = { + .init.status = ESP_PAN_NEED_DEINIT, + }; + btc_pan_cb_to_app(ESP_PAN_INIT_EVT, ¶m); + return; + } + + if (cfg == NULL || cfg->role == 0) { + esp_pan_cb_param_t param = { + .init.status = ESP_PAN_FAILURE, + }; + btc_pan_cb_to_app(ESP_PAN_INIT_EVT, ¶m); + return; + } + + btc_pan_store_cfg(cfg); + s_btc_pan_init = true; + BTA_PanEnable(bte_pan_evt); +} + +static void btc_pan_deinit(void) +{ + if (!s_btc_pan_init) { + esp_pan_cb_param_t param = { + .deinit.status = ESP_PAN_NEED_INIT, + }; + btc_pan_cb_to_app(ESP_PAN_DEINIT_EVT, ¶m); + return; + } + + s_btc_pan_init = false; + BTA_PanDisable(); + btc_pan_free_cfg_strings(); + memset(&s_btc_pan_cfg, 0, sizeof(s_btc_pan_cfg)); + + esp_pan_cb_param_t param = { + .deinit.status = ESP_PAN_SUCCESS, + }; + btc_pan_cb_to_app(ESP_PAN_DEINIT_EVT, ¶m); +} + +static void btc_pan_connect(btc_pan_args_t *arg) +{ + if (!s_btc_pan_init) { + esp_pan_cb_param_t param = { + .open.status = ESP_PAN_NEED_INIT, + }; + memcpy(param.open.remote_bda, arg->connect.bd_addr, ESP_BD_ADDR_LEN); + btc_pan_cb_to_app(ESP_PAN_OPEN_EVT, ¶m); + return; + } + + BTA_PanOpen(arg->connect.bd_addr, (tBTA_PAN_ROLE)arg->connect.local_role, + (tBTA_PAN_ROLE)arg->connect.peer_role); +} + +static void btc_pan_disconnect(uint16_t handle) +{ + if (!s_btc_pan_init) { + return; + } + + BTA_PanClose(handle); +} + +static void btc_pan_write(btc_pan_args_t *arg) +{ + esp_pan_cb_param_t param = { + .write.handle = arg->write.handle, + .write.status = ESP_PAN_SUCCESS, + }; + + if (!s_btc_pan_init) { + param.write.status = ESP_PAN_NEED_INIT; + btc_pan_cb_to_app(ESP_PAN_WRITE_EVT, ¶m); + return; + } + + if (arg->write.data == NULL || arg->write.len == 0 || arg->write.len > PAN_MAX_WRITE_LEN) { + param.write.status = ESP_PAN_FAILURE; + btc_pan_cb_to_app(ESP_PAN_WRITE_EVT, ¶m); + return; + } + + bta_pan_ci_rx_write(arg->write.handle, arg->write.dst, arg->write.src, + arg->write.protocol, arg->write.data, arg->write.len, + arg->write.ext); + btc_pan_cb_to_app(ESP_PAN_WRITE_EVT, ¶m); +} + +static void btc_pan_set_protocol_filters(btc_pan_args_t *arg) +{ + if (!s_btc_pan_init || + (arg->set_pfilter.num_filters > 0 && + (arg->set_pfilter.start_array == NULL || arg->set_pfilter.end_array == NULL))) { + return; + } + + bta_pan_ci_set_pfilters(arg->set_pfilter.handle, arg->set_pfilter.num_filters, + arg->set_pfilter.start_array, arg->set_pfilter.end_array); +} + +static void btc_pan_set_multicast_filters(btc_pan_args_t *arg) +{ + if (!s_btc_pan_init || + (arg->set_mfilter.num_filters > 0 && + (arg->set_mfilter.start_array == NULL || arg->set_mfilter.end_array == NULL))) { + return; + } + + bta_pan_ci_set_mfilters(arg->set_mfilter.handle, arg->set_mfilter.num_filters, + (UINT8 *)arg->set_mfilter.start_array, + (UINT8 *)arg->set_mfilter.end_array); +} + +void btc_pan_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src) +{ + btc_pan_args_t *dst = (btc_pan_args_t *)p_dest; + btc_pan_args_t *src = (btc_pan_args_t *)p_src; + + memcpy(dst, src, sizeof(btc_pan_args_t)); + + switch (msg->act) { + case BTC_PAN_ACT_INIT: + if (src->init.cfg.panu_service_name) { + size_t len = strlen(src->init.cfg.panu_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, src->init.cfg.panu_service_name, len); + dst->init.cfg.panu_service_name = name; + } else { + dst->init.cfg.panu_service_name = NULL; + } + } + if (src->init.cfg.gn_service_name) { + size_t len = strlen(src->init.cfg.gn_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, src->init.cfg.gn_service_name, len); + dst->init.cfg.gn_service_name = name; + } else { + dst->init.cfg.gn_service_name = NULL; + } + } + if (src->init.cfg.nap_service_name) { + size_t len = strlen(src->init.cfg.nap_service_name) + 1; + char *name = (char *)osi_malloc(len); + if (name) { + memcpy(name, src->init.cfg.nap_service_name, len); + dst->init.cfg.nap_service_name = name; + } else { + dst->init.cfg.nap_service_name = NULL; + } + } + break; + case BTC_PAN_ACT_WRITE: + if (src->write.len > 0 && src->write.data) { + dst->write.data = (uint8_t *)osi_malloc(src->write.len); + if (dst->write.data) { + memcpy(dst->write.data, src->write.data, src->write.len); + } else { + dst->write.len = 0; + } + } + break; + case BTC_PAN_ACT_SET_PFILTER: + if (src->set_pfilter.num_filters > 0) { + size_t size = src->set_pfilter.num_filters * sizeof(uint16_t); + dst->set_pfilter.start_array = (uint16_t *)osi_malloc(size); + dst->set_pfilter.end_array = (uint16_t *)osi_malloc(size); + if (dst->set_pfilter.start_array && dst->set_pfilter.end_array) { + memcpy(dst->set_pfilter.start_array, src->set_pfilter.start_array, size); + memcpy(dst->set_pfilter.end_array, src->set_pfilter.end_array, size); + } else { + if (dst->set_pfilter.start_array) { + osi_free(dst->set_pfilter.start_array); + dst->set_pfilter.start_array = NULL; + } + if (dst->set_pfilter.end_array) { + osi_free(dst->set_pfilter.end_array); + dst->set_pfilter.end_array = NULL; + } + dst->set_pfilter.num_filters = 0; + } + } + break; + case BTC_PAN_ACT_SET_MFILTER: + if (src->set_mfilter.num_filters > 0) { + size_t size = src->set_mfilter.num_filters * sizeof(esp_bd_addr_t); + dst->set_mfilter.start_array = (esp_bd_addr_t *)osi_malloc(size); + dst->set_mfilter.end_array = (esp_bd_addr_t *)osi_malloc(size); + if (dst->set_mfilter.start_array && dst->set_mfilter.end_array) { + memcpy(dst->set_mfilter.start_array, src->set_mfilter.start_array, size); + memcpy(dst->set_mfilter.end_array, src->set_mfilter.end_array, size); + } else { + if (dst->set_mfilter.start_array) { + osi_free(dst->set_mfilter.start_array); + dst->set_mfilter.start_array = NULL; + } + if (dst->set_mfilter.end_array) { + osi_free(dst->set_mfilter.end_array); + dst->set_mfilter.end_array = NULL; + } + dst->set_mfilter.num_filters = 0; + } + } + break; + default: + break; + } +} + +void btc_pan_arg_deep_free(btc_msg_t *msg) +{ + btc_pan_args_t *arg = (btc_pan_args_t *)msg->arg; + + switch (msg->act) { + case BTC_PAN_ACT_INIT: + if (arg->init.cfg.panu_service_name) { + osi_free((void *)arg->init.cfg.panu_service_name); + arg->init.cfg.panu_service_name = NULL; + } + if (arg->init.cfg.gn_service_name) { + osi_free((void *)arg->init.cfg.gn_service_name); + arg->init.cfg.gn_service_name = NULL; + } + if (arg->init.cfg.nap_service_name) { + osi_free((void *)arg->init.cfg.nap_service_name); + arg->init.cfg.nap_service_name = NULL; + } + break; + case BTC_PAN_ACT_WRITE: + if (arg->write.data) { + osi_free(arg->write.data); + arg->write.data = NULL; + } + break; + case BTC_PAN_ACT_SET_PFILTER: + if (arg->set_pfilter.start_array) { + osi_free(arg->set_pfilter.start_array); + arg->set_pfilter.start_array = NULL; + } + if (arg->set_pfilter.end_array) { + osi_free(arg->set_pfilter.end_array); + arg->set_pfilter.end_array = NULL; + } + break; + case BTC_PAN_ACT_SET_MFILTER: + if (arg->set_mfilter.start_array) { + osi_free(arg->set_mfilter.start_array); + arg->set_mfilter.start_array = NULL; + } + if (arg->set_mfilter.end_array) { + osi_free(arg->set_mfilter.end_array); + arg->set_mfilter.end_array = NULL; + } + break; + default: + break; + } +} + +void btc_pan_cb_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src) +{ + esp_pan_cb_param_t *dst = (esp_pan_cb_param_t *)p_dest; + esp_pan_cb_param_t *src = (esp_pan_cb_param_t *)p_src; + + /* btc_transfer_context() already did a shallow memcpy; only deep-copy + * pointer fields so variable-length payload is allocated once. */ + switch (msg->act) { + case ESP_PAN_DATA_IND_EVT: + dst->data_ind.data = NULL; + if (src->data_ind.len > 0 && src->data_ind.data) { + dst->data_ind.data = (uint8_t *)osi_malloc(src->data_ind.len); + if (dst->data_ind.data) { + memcpy(dst->data_ind.data, src->data_ind.data, src->data_ind.len); + } else { + BTC_TRACE_ERROR("%s: malloc data_ind failed len=%u", __func__, src->data_ind.len); + dst->data_ind.len = 0; + } + } + break; + case ESP_PAN_PFILTER_EVT: + dst->pfilter.filters = NULL; + if (src->pfilter.len > 0 && src->pfilter.filters) { + dst->pfilter.filters = (uint8_t *)osi_malloc(src->pfilter.len); + if (dst->pfilter.filters) { + memcpy(dst->pfilter.filters, src->pfilter.filters, src->pfilter.len); + } else { + BTC_TRACE_ERROR("%s: malloc pfilter failed len=%u", __func__, src->pfilter.len); + dst->pfilter.len = 0; + } + } + break; + case ESP_PAN_MFILTER_EVT: + dst->mfilter.filters = NULL; + if (src->mfilter.len > 0 && src->mfilter.filters) { + dst->mfilter.filters = (uint8_t *)osi_malloc(src->mfilter.len); + if (dst->mfilter.filters) { + memcpy(dst->mfilter.filters, src->mfilter.filters, src->mfilter.len); + } else { + BTC_TRACE_ERROR("%s: malloc mfilter failed len=%u", __func__, src->mfilter.len); + dst->mfilter.len = 0; + } + } + break; + default: + break; + } +} + +void btc_pan_cb_deep_free(btc_msg_t *msg) +{ + esp_pan_cb_param_t *param = (esp_pan_cb_param_t *)msg->arg; + + switch (msg->act) { + case ESP_PAN_DATA_IND_EVT: + if (param->data_ind.data) { + osi_free(param->data_ind.data); + param->data_ind.data = NULL; + } + break; + case ESP_PAN_PFILTER_EVT: + if (param->pfilter.filters) { + osi_free(param->pfilter.filters); + param->pfilter.filters = NULL; + } + break; + case ESP_PAN_MFILTER_EVT: + if (param->mfilter.filters) { + osi_free(param->mfilter.filters); + param->mfilter.filters = NULL; + } + break; + default: + break; + } +} + +void btc_pan_call_handler(btc_msg_t *msg) +{ + btc_pan_args_t *arg = (btc_pan_args_t *)msg->arg; + + switch (msg->act) { + case BTC_PAN_ACT_INIT: + btc_pan_init(&arg->init.cfg); + break; + case BTC_PAN_ACT_DEINIT: + btc_pan_deinit(); + break; + case BTC_PAN_ACT_CONNECT: + btc_pan_connect(arg); + break; + case BTC_PAN_ACT_DISCONNECT: + btc_pan_disconnect(arg->disconnect.handle); + break; + case BTC_PAN_ACT_WRITE: + btc_pan_write(arg); + break; + case BTC_PAN_ACT_SET_PFILTER: + btc_pan_set_protocol_filters(arg); + break; + case BTC_PAN_ACT_SET_MFILTER: + btc_pan_set_multicast_filters(arg); + break; + default: + BTC_TRACE_ERROR("%s: unhandled act %d", __func__, msg->act); + break; + } + + btc_pan_arg_deep_free(msg); +} + +void btc_pan_cb_handler(btc_msg_t *msg) +{ + esp_pan_cb_param_t param = {0}; + tBTA_PAN *p_data = (tBTA_PAN *)msg->arg; + + switch (msg->act) { + case BTA_PAN_ENABLE_EVT: + /* Ignore stale enable completion after esp_pan_deinit(). */ + if (!s_btc_pan_init) { + break; + } + btc_pan_set_role(); + break; + case BTA_PAN_SET_ROLE_EVT: + if (!s_btc_pan_init) { + break; + } + param.init.status = btc_pan_status_from_bta(p_data->set_role.status); + btc_pan_cb_to_app(ESP_PAN_INIT_EVT, ¶m); + param.set_role.status = param.init.status; + param.set_role.role = (esp_pan_role_mask_t)p_data->set_role.role; + btc_pan_cb_to_app(ESP_PAN_SET_ROLE_EVT, ¶m); + break; + case BTA_PAN_OPENING_EVT: + param.opening.handle = p_data->opening.handle; + memcpy(param.opening.remote_bda, p_data->opening.bd_addr, ESP_BD_ADDR_LEN); + btc_pan_cb_to_app(ESP_PAN_OPENING_EVT, ¶m); + break; + case BTA_PAN_OPEN_EVT: + param.open.status = btc_pan_status_from_bta(p_data->open.status); + param.open.handle = p_data->open.handle; + param.open.local_role = (esp_pan_role_t)p_data->open.local_role; + param.open.peer_role = (esp_pan_role_t)p_data->open.peer_role; + memcpy(param.open.remote_bda, p_data->open.bd_addr, ESP_BD_ADDR_LEN); + btc_pan_cb_to_app(ESP_PAN_OPEN_EVT, ¶m); + break; + case BTA_PAN_CLOSE_EVT: + param.close.handle = p_data->close.handle; + btc_pan_cb_to_app(ESP_PAN_CLOSE_EVT, ¶m); + break; + case ESP_PAN_DATA_IND_EVT: + case ESP_PAN_PFILTER_EVT: + case ESP_PAN_MFILTER_EVT: + btc_pan_cb_to_app(msg->act, (esp_pan_cb_param_t *)msg->arg); + break; + case ESP_PAN_CONG_EVT: + memcpy(¶m.cong, msg->arg, sizeof(param.cong)); + btc_pan_cb_to_app(ESP_PAN_CONG_EVT, ¶m); + break; + default: + BTC_TRACE_ERROR("%s: unhandled event %d", __func__, msg->act); + break; + } + + btc_pan_cb_deep_free(msg); +} + +void btc_pan_co_data_ind(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN ext, BOOLEAN forward) +{ + btc_msg_t msg; + esp_pan_cb_param_t param = {0}; + + param.data_ind.handle = handle; + memcpy(param.data_ind.src, src, ESP_BD_ADDR_LEN); + memcpy(param.data_ind.dst, dst, ESP_BD_ADDR_LEN); + param.data_ind.protocol = protocol; + param.data_ind.len = len; + param.data_ind.data = p_data; + param.data_ind.ext = ext; + param.data_ind.forward = forward; + + msg.sig = BTC_SIG_API_CB; + msg.pid = BTC_PID_PAN; + msg.act = ESP_PAN_DATA_IND_EVT; + + if (btc_transfer_context(&msg, ¶m, sizeof(esp_pan_cb_param_t), + btc_pan_cb_deep_copy, btc_pan_cb_deep_free) != BT_STATUS_SUCCESS) { + BTC_TRACE_ERROR("%s: context transfer failed", __func__); + } +} + +void btc_pan_co_rx_flow(UINT16 handle, BOOLEAN enable) +{ + btc_msg_t msg; + esp_pan_cb_param_t param; + + param.cong.handle = handle; + param.cong.cong = !enable; + + msg.sig = BTC_SIG_API_CB; + msg.pid = BTC_PID_PAN; + msg.act = ESP_PAN_CONG_EVT; + + if (btc_transfer_context(&msg, ¶m.cong, sizeof(param.cong), NULL, NULL) != BT_STATUS_SUCCESS) { + BTC_TRACE_ERROR("%s: context transfer failed", __func__); + } +} + +void btc_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters) +{ + btc_msg_t msg; + esp_pan_cb_param_t param = {0}; + + param.pfilter.handle = handle; + param.pfilter.indication = indication; + param.pfilter.status = btc_pan_status_from_bta(result); + param.pfilter.len = len; + param.pfilter.filters = p_filters; + + msg.sig = BTC_SIG_API_CB; + msg.pid = BTC_PID_PAN; + msg.act = ESP_PAN_PFILTER_EVT; + + if (btc_transfer_context(&msg, ¶m, sizeof(esp_pan_cb_param_t), + btc_pan_cb_deep_copy, btc_pan_cb_deep_free) != BT_STATUS_SUCCESS) { + BTC_TRACE_ERROR("%s: context transfer failed", __func__); + } +} + +void btc_pan_co_mfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result, + UINT16 len, UINT8 *p_filters) +{ + btc_msg_t msg; + esp_pan_cb_param_t param = {0}; + + param.mfilter.handle = handle; + param.mfilter.indication = indication; + param.mfilter.status = btc_pan_status_from_bta(result); + param.mfilter.len = len; + param.mfilter.filters = p_filters; + + msg.sig = BTC_SIG_API_CB; + msg.pid = BTC_PID_PAN; + msg.act = ESP_PAN_MFILTER_EVT; + + if (btc_transfer_context(&msg, ¶m, sizeof(esp_pan_cb_param_t), + btc_pan_cb_deep_copy, btc_pan_cb_deep_free) != BT_STATUS_SUCCESS) { + BTC_TRACE_ERROR("%s: context transfer failed", __func__); + } +} + +#endif /* BTC_PAN_INCLUDED */ diff --git a/components/bt/host/bluedroid/common/include/common/bluedroid_user_config.h b/components/bt/host/bluedroid/common/include/common/bluedroid_user_config.h index 25c5d6a5be3..ad0319a386a 100644 --- a/components/bt/host/bluedroid/common/include/common/bluedroid_user_config.h +++ b/components/bt/host/bluedroid/common/include/common/bluedroid_user_config.h @@ -189,6 +189,13 @@ #define UC_BT_PBAC_ENABLED FALSE #endif +//PAN +#ifdef CONFIG_BT_PAN_ENABLED +#define UC_BT_PAN_ENABLED CONFIG_BT_PAN_ENABLED +#else +#define UC_BT_PAN_ENABLED FALSE +#endif + #ifdef CONFIG_BT_PBAC_SUPPORTED_FEAT #define UC_BT_PBAC_SUPPORTED_FEAT CONFIG_BT_PBAC_SUPPORTED_FEAT #else diff --git a/components/bt/host/bluedroid/common/include/common/bt_target.h b/components/bt/host/bluedroid/common/include/common/bt_target.h index d9dc52e63f8..5428bd0a302 100644 --- a/components/bt/host/bluedroid/common/include/common/bt_target.h +++ b/components/bt/host/bluedroid/common/include/common/bt_target.h @@ -219,6 +219,16 @@ #define BTA_PBA_CLIENT_INCLUDED TRUE #endif +#if UC_BT_PAN_ENABLED +#define BTC_PAN_INCLUDED TRUE +#define BTA_PAN_INCLUDED TRUE +#define PAN_INCLUDED TRUE +#define BNEP_INCLUDED TRUE +#define PAN_SUPPORTS_ROLE_PANU TRUE +#define PAN_SUPPORTS_ROLE_GN TRUE +#define PAN_SUPPORTS_ROLE_NAP TRUE +#endif + #endif /* UC_BT_CLASSIC_ENABLED */ /* This is set to enable use of GAP L2CAP connections. */ @@ -716,6 +726,14 @@ #define BTC_SPP_INCLUDED FALSE #endif +#ifndef BTC_PAN_INCLUDED +#define BTC_PAN_INCLUDED FALSE +#endif + +#ifndef BTA_PAN_INCLUDED +#define BTA_PAN_INCLUDED FALSE +#endif + #ifndef BTC_HH_INCLUDED #define BTC_HH_INCLUDED FALSE #endif @@ -1292,6 +1310,12 @@ #define BTM_PBA_SEC_SERVICE_RECORDS 0 #endif +#if BTA_PAN_INCLUDED +#define BTM_PAN_SEC_SERVICE_RECORDS 6 +#else +#define BTM_PAN_SEC_SERVICE_RECORDS 0 +#endif + #if BTA_AV_CA_INCLUDED #define BTM_AC_VA_SEC_SERVICE_RECORDS 1 #else @@ -1350,7 +1374,7 @@ + BTM_AVCT_SEC_SERVICE_RECORDS + BTM_AVDT_SEC_SERVICE_RECORDS + BTM_GAP_SEC_SERVICE_RECORDS \ + BTM_HIDD_SEC_SERVICE_RECORDS + BTM_GATT_SEC_SERVICE_RECORDS + BTM_PBA_SEC_SERVICE_RECORDS \ + BTM_HIDH_SEC_SERVICE_RECORDS + BTM_SEC_DEV_SERVICE_RECORDS + BTM_HF_SEC_SERVICE_RECORDS \ - + BTM_JV_SEC_SERVICE_RECORDS + BTM_AC_VA_SEC_SERVICE_RECORDS ) + + BTM_JV_SEC_SERVICE_RECORDS + BTM_PAN_SEC_SERVICE_RECORDS + BTM_AC_VA_SEC_SERVICE_RECORDS ) #endif /* If True, force a retrieval of remote device name for each bond in case it's changed */ diff --git a/components/bt/host/bluedroid/main/bte_init.c b/components/bt/host/bluedroid/main/bte_init.c index b688d7a27d2..0dc3aa61e31 100644 --- a/components/bt/host/bluedroid/main/bte_init.c +++ b/components/bt/host/bluedroid/main/bte_init.c @@ -41,7 +41,7 @@ #endif #if (defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE) -#include "bnep_api.h" +#include "stack/bnep_api.h" #endif #if (defined(GAP_INCLUDED) && GAP_INCLUDED == TRUE) @@ -49,7 +49,7 @@ #endif #if (defined(PAN_INCLUDED) && PAN_INCLUDED == TRUE) -#include "pan_api.h" +#include "stack/pan_api.h" #endif #if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE) diff --git a/components/bt/host/bluedroid/stack/bnep/bnep_api.c b/components/bt/host/bluedroid/stack/bnep/bnep_api.c new file mode 100644 index 00000000000..339bf153449 --- /dev/null +++ b/components/bt/host/bluedroid/stack/bnep/bnep_api.c @@ -0,0 +1,812 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains the BNEP API code + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (BNEP_INCLUDED == TRUE) + +#include + +#include "osi/allocator.h" +#include "osi/fixed_queue.h" + +#include "stack/bnep_api.h" +#include "bnep_int.h" + +extern fixed_queue_t* btu_general_alarm_queue; + +/******************************************************************************* + * + * Function BNEP_Init + * + * Description This function initializes the BNEP unit. It should be called + * before accessing any other APIs to initialize the control + * block. + * + * Returns void + * + ******************************************************************************/ +void BNEP_Init(void) +{ + memset(&bnep_cb, 0, sizeof(tBNEP_CB)); + +#if defined(BNEP_INITIAL_TRACE_LEVEL) + bnep_cb.trace_level = BNEP_INITIAL_TRACE_LEVEL; +#else + bnep_cb.trace_level = BT_TRACE_LEVEL_NONE; /* No traces */ +#endif +} + +/******************************************************************************* + * + * Function BNEP_Register + * + * Description This function is called by the upper layer to register + * its callbacks with BNEP + * + * Parameters: p_reg_info - contains all callback function pointers + * + * + * Returns BNEP_SUCCESS if registered successfully + * BNEP_FAILURE if connection state callback is missing + * + ******************************************************************************/ +tBNEP_RESULT BNEP_Register(tBNEP_REGISTER *p_reg_info) +{ + /* There should be connection state call back registered */ + if ((!p_reg_info) || (!(p_reg_info->p_conn_state_cb))) { + return BNEP_SECURITY_FAIL; + } + + bnep_cb.p_conn_ind_cb = p_reg_info->p_conn_ind_cb; + bnep_cb.p_conn_state_cb = p_reg_info->p_conn_state_cb; + bnep_cb.p_data_ind_cb = p_reg_info->p_data_ind_cb; + bnep_cb.p_data_buf_cb = p_reg_info->p_data_buf_cb; + bnep_cb.p_filter_ind_cb = p_reg_info->p_filter_ind_cb; + bnep_cb.p_mfilter_ind_cb = p_reg_info->p_mfilter_ind_cb; + bnep_cb.p_tx_data_flow_cb = p_reg_info->p_tx_data_flow_cb; + + if (bnep_register_with_l2cap()) { + return BNEP_SECURITY_FAIL; + } + + bnep_cb.profile_registered = TRUE; + return BNEP_SUCCESS; +} + +/******************************************************************************* + * + * Function BNEP_Deregister + * + * Description This function is called by the upper layer to de-register + * its callbacks. + * + * Parameters: void + * + * + * Returns void + * + ******************************************************************************/ +void BNEP_Deregister(void) +{ + /* Clear all the call backs registered */ + bnep_cb.p_conn_ind_cb = NULL; + bnep_cb.p_conn_state_cb = NULL; + bnep_cb.p_data_ind_cb = NULL; + bnep_cb.p_data_buf_cb = NULL; + bnep_cb.p_filter_ind_cb = NULL; + bnep_cb.p_mfilter_ind_cb = NULL; + bnep_cb.p_tx_data_flow_cb = NULL; + + bnep_cb.profile_registered = FALSE; + L2CA_Deregister(BT_PSM_BNEP); +} + +/******************************************************************************* + * + * Function BNEP_Connect + * + * Description This function creates a BNEP connection to a remote + * device. + * + * Parameters: p_rem_addr - BD_ADDR of the peer + * src_uuid - source uuid for the connection + * dst_uuid - destination uuid for the connection + * p_handle - pointer to return the handle for the + * connection + * + * Returns BNEP_SUCCESS if connection started + * BNEP_NO_RESOURCES if no resources + * + ******************************************************************************/ +tBNEP_RESULT BNEP_Connect(BD_ADDR p_rem_bda, tBT_UUID *src_uuid, + tBT_UUID *dst_uuid, UINT16 *p_handle) +{ + UINT16 cid; + tBNEP_CONN * p_bcb = bnepu_find_bcb_by_bd_addr(p_rem_bda); + + BNEP_TRACE_DEBUG("%s BDA:%02x:%02x:%02x:%02x:%02x:%02x", __func__, + p_rem_bda[0], p_rem_bda[1], p_rem_bda[2], p_rem_bda[3], + p_rem_bda[4], p_rem_bda[5]); + + if (!bnep_cb.profile_registered) { + return BNEP_WRONG_STATE; + } + + /* Both source and destination UUID lengths should be same */ + if (src_uuid->len != dst_uuid->len) { + return BNEP_CONN_FAILED_UUID_SIZE; + } + + if (!p_bcb) { + p_bcb = bnepu_allocate_bcb(p_rem_bda); + if (p_bcb == NULL) { + return (BNEP_NO_RESOURCES); + } + } else if (p_bcb->con_state != BNEP_STATE_CONNECTED) { + return BNEP_WRONG_STATE; + } else { + /* Backup current UUID values to restore if role change fails */ + memcpy((UINT8 *) & (p_bcb->prv_src_uuid), (UINT8 *) & (p_bcb->src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8 *) & (p_bcb->prv_dst_uuid), (UINT8 *) & (p_bcb->dst_uuid), + sizeof(tBT_UUID)); + } + + /* We are the originator of this connection */ + p_bcb->con_flags |= BNEP_FLAGS_IS_ORIG; + + memcpy((UINT8*) & (p_bcb->src_uuid), (UINT8*)src_uuid, sizeof(tBT_UUID)); + memcpy((UINT8*) & (p_bcb->dst_uuid), (UINT8*)dst_uuid, sizeof(tBT_UUID)); + + if (p_bcb->con_state == BNEP_STATE_CONNECTED) { + /* Transition to the next appropriate state, waiting for connection confirm. + */ + p_bcb->con_state = BNEP_STATE_SEC_CHECKING; + + BNEP_TRACE_API("BNEP initiating security procedures for src uuid 0x%x", + p_bcb->src_uuid.uu.uuid16); + +#if (BNEP_DO_AUTH_FOR_ROLE_SWITCH == TRUE) + btm_sec_mx_access_request(p_bcb->rem_bda, BT_PSM_BNEP, TRUE, + BTM_SEC_PROTO_BNEP, bnep_get_uuid32(src_uuid), + &bnep_sec_check_complete, p_bcb); +#else + bnep_sec_check_complete(p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb, + BTM_SUCCESS); +#endif + + } else { + /* Transition to the next appropriate state, waiting for connection confirm. + */ + p_bcb->con_state = BNEP_STATE_CONN_START; + + cid = L2CA_ConnectReq(BT_PSM_BNEP, p_bcb->rem_bda); + if (cid != 0) { + p_bcb->l2cap_cid = cid; + + } else { + BNEP_TRACE_ERROR("BNEP - Originate failed"); + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED, FALSE); + bnepu_release_bcb(p_bcb); + return BNEP_CONN_FAILED; + } + + /* Start timer waiting for connect */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_CONN_TIMEOUT_SEC); + } + + *p_handle = p_bcb->handle; + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_ConnectResp + * + * Description This function is called in response to connection indication + * + * + * Parameters: handle - handle given in the connection indication + * resp - response for the connection indication + * + * Returns BNEP_SUCCESS if connection started + * BNEP_WRONG_HANDLE if the connection is not found + * BNEP_WRONG_STATE if the response is not expected + * + ******************************************************************************/ +tBNEP_RESULT BNEP_ConnectResp(UINT16 handle, tBNEP_RESULT resp) +{ + tBNEP_CONN * p_bcb; + UINT16 resp_code = BNEP_SETUP_CONN_OK; + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + if (p_bcb->con_state != BNEP_STATE_CONN_SETUP || + (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD))) { + return (BNEP_WRONG_STATE); + } + + BNEP_TRACE_API("BNEP_ConnectResp() for handle %d, response %d", handle, + resp); + + /* Form appropriate response based on profile response */ + if (resp == BNEP_CONN_FAILED_SRC_UUID) { + resp_code = BNEP_SETUP_INVALID_SRC_UUID; + } else if (resp == BNEP_CONN_FAILED_DST_UUID) { + resp_code = BNEP_SETUP_INVALID_DEST_UUID; + } else if (resp == BNEP_CONN_FAILED_UUID_SIZE) { + resp_code = BNEP_SETUP_INVALID_UUID_SIZE; + } else if (resp == BNEP_SUCCESS) { + resp_code = BNEP_SETUP_CONN_OK; + } else { + resp_code = BNEP_SETUP_CONN_NOT_ALLOWED; + } + + bnep_send_conn_responce(p_bcb, resp_code); + p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); + + if (resp == BNEP_SUCCESS) { + bnep_connected(p_bcb); + } else if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + /* Restore the original parameters */ + p_bcb->con_state = BNEP_STATE_CONNECTED; + p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); + + memcpy((UINT8*) & (p_bcb->src_uuid), (UINT8*) & (p_bcb->prv_src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8*) & (p_bcb->dst_uuid), (UINT8*) & (p_bcb->prv_dst_uuid), + sizeof(tBT_UUID)); + } + + /* Process remaining part of the setup message (extension headers) */ + if (p_bcb->p_pending_data) { + UINT8 extension_present = TRUE, *p, ext_type; + UINT16 rem_len; + + rem_len = p_bcb->p_pending_data->len; + p = (UINT8*)(p_bcb->p_pending_data + 1) + p_bcb->p_pending_data->offset; + while (extension_present && p && rem_len) { + ext_type = *p++; + rem_len--; + extension_present = ext_type >> 7; + ext_type &= 0x7F; + + /* if unknown extension present stop processing */ + if (ext_type) { + break; + } + + p = bnep_process_control_packet(p_bcb, p, &rem_len, TRUE); + } + + osi_free(p_bcb->p_pending_data); + p_bcb->p_pending_data = NULL; + } + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_Disconnect + * + * Description This function is called to close the specified connection. + * + * Parameters: handle - handle of the connection + * + * Returns BNEP_SUCCESS if connection is disconnected + * BNEP_WRONG_HANDLE if no connection is not found + * + ******************************************************************************/ +tBNEP_RESULT BNEP_Disconnect(UINT16 handle) +{ + tBNEP_CONN * p_bcb; + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + if (p_bcb->con_state == BNEP_STATE_IDLE) { + return (BNEP_WRONG_HANDLE); + } + + BNEP_TRACE_API("BNEP_Disconnect() for handle %d", handle); + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + bnepu_release_bcb(p_bcb); + + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_WriteBuf + * + * Description This function sends data in a GKI buffer on BNEP connection + * + * Parameters: handle - handle of the connection to write + * p_dest_addr - BD_ADDR/Ethernet addr of the destination + * p_buf - pointer to address of buffer with data + * protocol - protocol type of the packet + * p_src_addr - (optional) BD_ADDR/ethernet address of the + * source + * (should be NULL if it is local BD Addr) + * fw_ext_present - forwarded extensions present + * + * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid + * BNEP_WRONG_STATE - if connection is not active + * BNEP_MTU_EXCEDED - If the data length is greater than + * the MTU + * BNEP_IGNORE_CMD - If the packet is filtered out + * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full + * BNEP_SUCCESS - If written successfully + * + ******************************************************************************/ +tBNEP_RESULT BNEP_WriteBuf(UINT16 handle, BD_ADDR p_dest_addr, + BT_HDR *p_buf, UINT16 protocol, + BD_ADDR p_src_addr, BOOLEAN fw_ext_present) +{ + tBNEP_CONN * p_bcb; + UINT8* p_data; + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + osi_free(p_buf); + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + /* Check the connection state */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + osi_free(p_buf); + return (BNEP_WRONG_STATE); + } + + /* Check MTU size */ + if (p_buf->len > BNEP_MTU_SIZE) { + BNEP_TRACE_ERROR("BNEP_Write() length %d exceeded MTU %d", p_buf->len, + BNEP_MTU_SIZE); + osi_free(p_buf); + return (BNEP_MTU_EXCEDED); + } + + /* Check if the packet should be filtered out */ + p_data = (UINT8*)(p_buf + 1) + p_buf->offset; + if (bnep_is_packet_allowed(p_bcb, p_dest_addr, protocol, fw_ext_present, + p_data, p_buf->len) != BNEP_SUCCESS) { + /* + ** If packet is filtered and ext headers are present + ** drop the data and forward the ext headers + */ + if (fw_ext_present) { + UINT8 ext, length; + UINT16 org_len, new_len; + /* parse the extension headers and find out the new packet len */ + org_len = p_buf->len; + new_len = 0; + do { + if ((UINT16)(org_len - new_len) < 2) { + osi_free(p_buf); + return BNEP_IGNORE_CMD; + } + ext = *p_data++; + length = *p_data++; + new_len += 2; + if ((UINT16)(org_len - new_len) < length) { + osi_free(p_buf); + return BNEP_IGNORE_CMD; + } + p_data += length; + new_len += length; + + } while (ext & 0x80); + + if (protocol != BNEP_802_1_P_PROTOCOL) { + protocol = 0; + } else { + /* Need 4 bytes for 802.1Q tag + ethertype after extensions */ + if (new_len + 4 > org_len) { + osi_free(p_buf); + return BNEP_IGNORE_CMD; + } + new_len += 4; + p_data[2] = 0; + p_data[3] = 0; + } + p_buf->len = new_len; + } else { + osi_free(p_buf); + return BNEP_IGNORE_CMD; + } + } + + /* Callers must leave BNEP_MINIMUM_OFFSET headroom. In-place payload + * shifting is unsafe with exact-sized heap buffers (no capacity field). */ + if (p_buf->offset < BNEP_MINIMUM_OFFSET) { + BNEP_TRACE_ERROR("BNEP_WriteBuf() offset %d < minimum %d", + p_buf->offset, BNEP_MINIMUM_OFFSET); + osi_free(p_buf); + return (BNEP_INVALID_OFFSET); + } + + /* Check transmit queue */ + if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { + osi_free(p_buf); + return (BNEP_Q_SIZE_EXCEEDED); + } + + /* Build the BNEP header */ + bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, p_src_addr, p_dest_addr, + fw_ext_present); + + /* Send the data or queue it up */ + bnepu_check_send_packet(p_bcb, p_buf); + + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_Write + * + * Description This function sends data over a BNEP connection + * + * Parameters: handle - handle of the connection to write + * p_dest_addr - BD_ADDR/Ethernet addr of the destination + * p_data - pointer to data start + * protocol - protocol type of the packet + * p_src_addr - (optional) BD_ADDR/ethernet address of the + * source + * (should be NULL if it is local BD Addr) + * fw_ext_present - forwarded extensions present + * + * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid + * BNEP_WRONG_STATE - if connection is not active + * BNEP_MTU_EXCEDED - If the data length is greater than + * the MTU + * BNEP_IGNORE_CMD - If the packet is filtered out + * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full + * BNEP_NO_RESOURCES - If not able to allocate a buffer + * BNEP_SUCCESS - If written successfully + * + ******************************************************************************/ +tBNEP_RESULT BNEP_Write(UINT16 handle, BD_ADDR p_dest_addr, + UINT8 *p_data, UINT16 len, UINT16 protocol, + BD_ADDR p_src_addr, BOOLEAN fw_ext_present) +{ + tBNEP_CONN * p_bcb; + UINT8* p; + /* Offset of 802.1Q ethertype to clear in the private copy; UINT16_MAX = none */ + UINT16 clear_etype_off = 0xFFFF; + + /* Check MTU size. Consider the possibility of having extension headers */ + if (len > BNEP_MTU_SIZE) { + BNEP_TRACE_ERROR("BNEP_Write() length %d exceeded MTU %d", len, + BNEP_MTU_SIZE); + return (BNEP_MTU_EXCEDED); + } + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + /* Check the connection state */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return (BNEP_WRONG_STATE); + } + + /* Check if the packet should be filtered out */ + if (bnep_is_packet_allowed(p_bcb, p_dest_addr, protocol, fw_ext_present, + p_data, len) != BNEP_SUCCESS) { + /* + ** If packet is filtered and ext headers are present + ** drop the data and forward the ext headers + */ + if (fw_ext_present) { + UINT8 ext, length; + UINT16 org_len, new_len; + /* parse the extension headers and find out the new packet len */ + org_len = len; + new_len = 0; + p = p_data; + do { + if ((UINT16)(org_len - new_len) < 2) { + return BNEP_IGNORE_CMD; + } + ext = *p_data++; + length = *p_data++; + new_len += 2; + if ((UINT16)(org_len - new_len) < length) { + return BNEP_IGNORE_CMD; + } + p_data += length; + new_len += length; + + } while (ext & 0x80); + + if (protocol != BNEP_802_1_P_PROTOCOL) { + protocol = 0; + } else { + /* Need 4 bytes for 802.1Q tag + ethertype after extensions */ + if (new_len + 4 > org_len) { + return BNEP_IGNORE_CMD; + } + /* Do not mutate the caller's buffer (may be shared across peers). */ + clear_etype_off = new_len + 2; + new_len += 4; + } + len = new_len; + p_data = p; + } else { + return BNEP_IGNORE_CMD; + } + } + + /* Check transmit queue */ + if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { + return (BNEP_Q_SIZE_EXCEEDED); + } + + /* Get a buffer to copy the data into */ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + if (p_buf == NULL) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return (BNEP_NO_RESOURCES); + } + + p_buf->len = len; + p_buf->offset = BNEP_MINIMUM_OFFSET; + p = (UINT8*)(p_buf + 1) + BNEP_MINIMUM_OFFSET; + + memcpy(p, p_data, len); + if (clear_etype_off != 0xFFFF) { + p[clear_etype_off] = 0; + p[clear_etype_off + 1] = 0; + } + + /* Build the BNEP header */ + bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, p_src_addr, p_dest_addr, + fw_ext_present); + + /* Send the data or queue it up */ + bnepu_check_send_packet(p_bcb, p_buf); + + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_SetProtocolFilters + * + * Description This function sets the protocol filters on peer device + * + * Parameters: handle - Handle for the connection + * num_filters - total number of filter ranges + * p_start_array - Array of beginnings of all protocol ranges + * p_end_array - Array of ends of all protocol ranges + * + * Returns BNEP_WRONG_HANDLE - if the connection handle is + * not valid + * BNEP_SET_FILTER_FAIL - if the connection is in wrong + * state + * BNEP_TOO_MANY_FILTERS - if too many filters + * BNEP_SUCCESS - if request sent successfully + * + ******************************************************************************/ +tBNEP_RESULT BNEP_SetProtocolFilters(UINT16 handle, UINT16 num_filters, + UINT16 *p_start_array, + UINT16 *p_end_array) +{ + UINT16 xx; + tBNEP_CONN * p_bcb; + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + /* Check the connection state */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return (BNEP_WRONG_STATE); + } + + /* Validate the parameters */ + if (num_filters && (!p_start_array || !p_end_array)) { + return (BNEP_SET_FILTER_FAIL); + } + + if (num_filters > BNEP_MAX_PROT_FILTERS) { + return (BNEP_TOO_MANY_FILTERS); + } + + /* Fill the filter values in connection block */ + for (xx = 0; xx < num_filters; xx++) { + p_bcb->sent_prot_filter_start[xx] = *p_start_array++; + p_bcb->sent_prot_filter_end[xx] = *p_end_array++; + } + + p_bcb->sent_num_filters = num_filters; + + bnepu_send_peer_our_filters(p_bcb); + + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_SetMulticastFilters + * + * Description This function sets the filters for multicast addresses for + * BNEP. + * + * Parameters: handle - Handle for the connection + * num_filters - total number of filter ranges + * p_start_array - Pointer to sequence of beginnings of all + * multicast address ranges + * p_end_array - Pointer to sequence of ends of all + * multicast address ranges + * + * Returns BNEP_WRONG_HANDLE - if the connection handle is + * not valid + * BNEP_SET_FILTER_FAIL - if the connection is in wrong + * state + * BNEP_TOO_MANY_FILTERS - if too many filters + * BNEP_SUCCESS - if request sent successfully + * + ******************************************************************************/ +tBNEP_RESULT BNEP_SetMulticastFilters(UINT16 handle, UINT16 num_filters, + UINT8 *p_start_array, + UINT8 *p_end_array) +{ + UINT16 xx; + tBNEP_CONN * p_bcb; + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + /* Check the connection state */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return (BNEP_WRONG_STATE); + } + + /* Validate the parameters */ + if (num_filters && (!p_start_array || !p_end_array)) { + return (BNEP_SET_FILTER_FAIL); + } + + if (num_filters > BNEP_MAX_MULTI_FILTERS) { + return (BNEP_TOO_MANY_FILTERS); + } + + /* Fill the multicast filter values in connection block */ + for (xx = 0; xx < num_filters; xx++) { + memcpy(p_bcb->sent_mcast_filter_start[xx], p_start_array, + BD_ADDR_LEN); + memcpy(p_bcb->sent_mcast_filter_end[xx], p_end_array, BD_ADDR_LEN); + + p_start_array += BD_ADDR_LEN; + p_end_array += BD_ADDR_LEN; + } + + p_bcb->sent_mcast_filters = num_filters; + + bnepu_send_peer_our_multi_filters(p_bcb); + + return (BNEP_SUCCESS); +} + +/******************************************************************************* + * + * Function BNEP_SetTraceLevel + * + * Description This function sets the trace level for BNEP. If called with + * a value of 0xFF, it simply reads the current trace level. + * + * Returns the new (current) trace level + * + ******************************************************************************/ +UINT8 BNEP_SetTraceLevel(UINT8 new_level) +{ + if (new_level != 0xFF) { + bnep_cb.trace_level = new_level; + } + + return (bnep_cb.trace_level); +} + +/******************************************************************************* + * + * Function BNEP_GetStatus + * + * Description This function gets the status information for BNEP + * connection + * + * Returns BNEP_SUCCESS - if the status is available + * BNEP_NO_RESOURCES - if no structure is passed for + * output + * BNEP_WRONG_HANDLE - if the handle is invalid + * BNEP_WRONG_STATE - if not in connected state + * + ******************************************************************************/ +tBNEP_RESULT BNEP_GetStatus(UINT16 handle, tBNEP_STATUS *p_status) +{ +#if (BNEP_SUPPORTS_STATUS_API == TRUE) + tBNEP_CONN * p_bcb; + + if (!p_status) { + return BNEP_NO_RESOURCES; + } + + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return (BNEP_WRONG_HANDLE); + } + + p_bcb = &(bnep_cb.bcb[handle - 1]); + + memset(p_status, 0, sizeof(tBNEP_STATUS)); + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return BNEP_WRONG_STATE; + } + + /* Read the status parameters from the connection control block */ + p_status->con_status = BNEP_STATUS_CONNECTED; + p_status->l2cap_cid = p_bcb->l2cap_cid; + p_status->rem_mtu_size = p_bcb->rem_mtu_size; + p_status->xmit_q_depth = fixed_queue_length(p_bcb->xmit_q); + p_status->sent_num_filters = p_bcb->sent_num_filters; + p_status->sent_mcast_filters = p_bcb->sent_mcast_filters; + p_status->rcvd_num_filters = p_bcb->rcvd_num_filters; + p_status->rcvd_mcast_filters = p_bcb->rcvd_mcast_filters; + + bdcpy(p_status->rem_bda, p_bcb->rem_bda); + memcpy(&(p_status->src_uuid), &(p_bcb->src_uuid), sizeof(tBT_UUID)); + memcpy(&(p_status->dst_uuid), &(p_bcb->dst_uuid), sizeof(tBT_UUID)); + + return BNEP_SUCCESS; +#else + return (BNEP_IGNORE_CMD); +#endif +} + +#endif /* (BNEP_INCLUDED == TRUE) */ diff --git a/components/bt/host/bluedroid/stack/bnep/bnep_main.c b/components/bt/host/bluedroid/stack/bnep/bnep_main.c new file mode 100644 index 00000000000..feaa3141c9f --- /dev/null +++ b/components/bt/host/bluedroid/stack/bnep/bnep_main.c @@ -0,0 +1,794 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * this file contains the main BNEP functions + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (BNEP_INCLUDED == TRUE) + +#include +#include +#include + +#include "stack/bt_types.h" +#include "stack/hcidefs.h" +#include "stack/hcimsgs.h" + +#include "stack/l2c_api.h" +#include "stack/l2cdefs.h" + +#include "device/controller.h" + +#include "osi/allocator.h" +#include "osi/fixed_queue.h" + +#include "stack/btm_api.h" +#include "stack/btu.h" + +#include "stack/bnep_api.h" +#include "bnep_int.h" + +extern fixed_queue_t* btu_general_alarm_queue; + +/******************************************************************************/ +/* G L O B A L B N E P D A T A */ +/******************************************************************************/ +tBNEP_CB bnep_cb; + +const UINT16 bnep_frame_hdr_sizes[] = {14, 1, 2, 8, 8}; + +/******************************************************************************/ +/* L O C A L F U N C T I O N P R O T O T Y P E S */ +/******************************************************************************/ +static void bnep_connect_ind(BD_ADDR bd_addr, UINT16 l2cap_cid, + UINT16 psm, UINT8 l2cap_id); +static void bnep_connect_cfm(UINT16 l2cap_cid, UINT16 result); +static void bnep_config_ind(UINT16 l2cap_cid, tL2CAP_CFG_INFO* p_cfg); +static void bnep_config_cfm(UINT16 l2cap_cid, tL2CAP_CFG_INFO* p_cfg); +static void bnep_disconnect_ind(UINT16 l2cap_cid, BOOLEAN ack_needed); +static void bnep_disconnect_cfm(UINT16 l2cap_cid, UINT16 result); +static void bnep_data_ind(UINT16 l2cap_cid, BT_HDR * p_msg); +static void bnep_congestion_ind(UINT16 lcid, BOOLEAN is_congested); + +/******************************************************************************* + * + * Function bnep_register_with_l2cap + * + * Description This function registers BNEP PSM with L2CAP + * + * Returns void + * + ******************************************************************************/ +tBNEP_RESULT bnep_register_with_l2cap(void) +{ + /* Initialize the L2CAP configuration. We only care about MTU and flush */ + memset(&bnep_cb.l2cap_my_cfg, 0, sizeof(tL2CAP_CFG_INFO)); + + bnep_cb.l2cap_my_cfg.mtu_present = TRUE; + bnep_cb.l2cap_my_cfg.mtu = BNEP_MTU_SIZE; + bnep_cb.l2cap_my_cfg.flush_to_present = TRUE; + bnep_cb.l2cap_my_cfg.flush_to = BNEP_FLUSH_TO; + + bnep_cb.reg_info.pL2CA_ConnectInd_Cb = bnep_connect_ind; + bnep_cb.reg_info.pL2CA_ConnectCfm_Cb = bnep_connect_cfm; + bnep_cb.reg_info.pL2CA_ConfigInd_Cb = bnep_config_ind; + bnep_cb.reg_info.pL2CA_ConfigCfm_Cb = bnep_config_cfm; + bnep_cb.reg_info.pL2CA_DisconnectInd_Cb = bnep_disconnect_ind; + bnep_cb.reg_info.pL2CA_DisconnectCfm_Cb = bnep_disconnect_cfm; + bnep_cb.reg_info.pL2CA_DataInd_Cb = bnep_data_ind; + bnep_cb.reg_info.pL2CA_CongestionStatus_Cb = bnep_congestion_ind; + + /* Now, register with L2CAP */ + if (!L2CA_Register(BT_PSM_BNEP, &bnep_cb.reg_info)) { + BNEP_TRACE_ERROR("BNEP - Registration failed"); + return BNEP_SECURITY_FAIL; + } + + return BNEP_SUCCESS; +} + +/******************************************************************************* + * + * Function bnep_connect_ind + * + * Description This function handles an inbound connection indication + * from L2CAP. This is the case where we are acting as a + * server. + * + * Returns void + * + ******************************************************************************/ +static void bnep_connect_ind(BD_ADDR bd_addr, UINT16 l2cap_cid, + UNUSED_ATTR UINT16 psm, UINT8 l2cap_id) +{ + tBNEP_CONN * p_bcb = bnepu_find_bcb_by_bd_addr(bd_addr); + + /* If we are not acting as server, or already have a connection, or have */ + /* no more resources to handle the connection, reject the connection. */ + if (!(bnep_cb.profile_registered) || (p_bcb) || + ((p_bcb = bnepu_allocate_bcb(bd_addr)) == NULL)) { + L2CA_ConnectRsp(bd_addr, l2cap_id, l2cap_cid, L2CAP_CONN_NO_PSM, 0); + return; + } + + /* Transition to the next appropriate state, waiting for config setup. */ + p_bcb->con_state = BNEP_STATE_CFG_SETUP; + + /* Save the L2CAP Channel ID. */ + p_bcb->l2cap_cid = l2cap_cid; + + /* Send response to the L2CAP layer. */ + L2CA_ConnectRsp(bd_addr, l2cap_id, l2cap_cid, L2CAP_CONN_OK, L2CAP_CONN_OK); + + /* Send a Configuration Request. */ + L2CA_ConfigReq(l2cap_cid, &bnep_cb.l2cap_my_cfg); + + /* Start timer waiting for config setup */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_CONN_TIMEOUT_SEC); + + BNEP_TRACE_EVENT("BNEP - Rcvd L2CAP conn ind, CID: 0x%x", p_bcb->l2cap_cid); +} + +/******************************************************************************* + * + * Function bnep_connect_cfm + * + * Description This function handles the connect confirm events + * from L2CAP. This is the case when we are acting as a + * client and have sent a connect request. + * + * Returns void + * + ******************************************************************************/ +static void bnep_connect_cfm(UINT16 l2cap_cid, UINT16 result) +{ + tBNEP_CONN * p_bcb; + + /* Find CCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd conn cnf for unknown CID 0x%x", l2cap_cid); + return; + } + + /* If the connection response contains success status, then */ + /* Transition to the next state and startup the timer. */ + if ((result == L2CAP_CONN_OK) && + (p_bcb->con_state == BNEP_STATE_CONN_START)) { + p_bcb->con_state = BNEP_STATE_CFG_SETUP; + + /* Send a Configuration Request. */ + L2CA_ConfigReq(l2cap_cid, &bnep_cb.l2cap_my_cfg); + + /* Start timer waiting for config results */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_CONN_TIMEOUT_SEC); + + BNEP_TRACE_EVENT("BNEP - got conn cnf, sent cfg req, CID: 0x%x", + p_bcb->l2cap_cid); + } else { + BNEP_TRACE_WARNING("BNEP - Rcvd conn cnf with error: 0x%x CID 0x%x", + result, p_bcb->l2cap_cid); + + /* Tell the upper layer, if he has a callback */ + if (bnep_cb.p_conn_state_cb && p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED, FALSE); + } + + bnepu_release_bcb(p_bcb); + } +} + +/******************************************************************************* + * + * Function bnep_config_ind + * + * Description This function processes the L2CAP configuration indication + * event. + * + * Returns void + * + ******************************************************************************/ +static void bnep_config_ind(UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg) +{ + tBNEP_CONN * p_bcb; + UINT16 result, mtu = 0; + + /* Find CCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd L2CAP cfg ind, unknown CID: 0x%x", + l2cap_cid); + return; + } + + BNEP_TRACE_EVENT("BNEP - Rcvd cfg ind, CID: 0x%x", l2cap_cid); + + /* Remember the remote MTU size */ + if ((!p_cfg->mtu_present) || (p_cfg->mtu < BNEP_MIN_MTU_SIZE)) { + mtu = p_cfg->mtu; + p_cfg->flush_to_present = FALSE; + p_cfg->mtu_present = TRUE; + p_cfg->mtu = BNEP_MIN_MTU_SIZE; + p_cfg->result = result = L2CAP_CFG_UNACCEPTABLE_PARAMS; + } else { + if (p_cfg->mtu > BNEP_MTU_SIZE) { + p_bcb->rem_mtu_size = BNEP_MTU_SIZE; + } else { + p_bcb->rem_mtu_size = p_cfg->mtu; + } + + /* For now, always accept configuration from the other side */ + p_cfg->flush_to_present = FALSE; + p_cfg->mtu_present = FALSE; + p_cfg->result = result = L2CAP_CFG_OK; + } + + L2CA_ConfigRsp(l2cap_cid, p_cfg); + + if (result != L2CAP_CFG_OK) { + BNEP_TRACE_EVENT("BNEP - Rcvd cfg ind with bad MTU %d, CID: 0x%x", mtu, + l2cap_cid); + return; + } + + p_bcb->con_flags |= BNEP_FLAGS_HIS_CFG_DONE; + + if (p_bcb->con_flags & BNEP_FLAGS_MY_CFG_DONE) { + p_bcb->con_state = BNEP_STATE_SEC_CHECKING; + + /* Start timer waiting for setup or response */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_HOST_TIMEOUT_SEC); + + if (p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) { + btm_sec_mx_access_request( + p_bcb->rem_bda, BT_PSM_BNEP, TRUE, BTM_SEC_PROTO_BNEP, + bnep_get_uuid32(&(p_bcb->src_uuid)), &bnep_sec_check_complete, p_bcb); + } + } +} + +/******************************************************************************* + * + * Function bnep_config_cfm + * + * Description This function processes the L2CAP configuration confirmation + * event. + * + * Returns void + * + ******************************************************************************/ +static void bnep_config_cfm(UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg) +{ + tBNEP_CONN * p_bcb; + + BNEP_TRACE_EVENT("BNEP - Rcvd cfg cfm, CID: 0x%x Result: %d", l2cap_cid, + p_cfg->result); + + /* Find CCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd L2CAP cfg ind, unknown CID: 0x%x", + l2cap_cid); + return; + } + + /* For now, always accept configuration from the other side */ + if (p_cfg->result == L2CAP_CFG_OK) { + p_bcb->con_flags |= BNEP_FLAGS_MY_CFG_DONE; + + if (p_bcb->con_flags & BNEP_FLAGS_HIS_CFG_DONE) { + p_bcb->con_state = BNEP_STATE_SEC_CHECKING; + + /* Start timer waiting for setup or response */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_HOST_TIMEOUT_SEC); + + if (p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) { + btm_sec_mx_access_request(p_bcb->rem_bda, BT_PSM_BNEP, TRUE, + BTM_SEC_PROTO_BNEP, + bnep_get_uuid32(&(p_bcb->src_uuid)), + &bnep_sec_check_complete, p_bcb); + } + } + } else { + /* Tell the upper layer, if he has a callback */ + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED_CFG, FALSE); + } + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + bnepu_release_bcb(p_bcb); + } +} + +/******************************************************************************* + * + * Function bnep_disconnect_ind + * + * Description This function handles a disconnect event from L2CAP. If + * requested to, we ack the disconnect before dropping the CCB + * + * Returns void + * + ******************************************************************************/ +static void bnep_disconnect_ind(UINT16 l2cap_cid, BOOLEAN ack_needed) +{ + tBNEP_CONN * p_bcb; + + if (ack_needed) { + L2CA_DisconnectRsp(l2cap_cid); + } + + /* Find CCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd L2CAP disc, unknown CID: 0x%x", l2cap_cid); + return; + } + + BNEP_TRACE_EVENT("BNEP - Rcvd L2CAP disc, CID: 0x%x", l2cap_cid); + + /* Tell the user if he has a callback */ + if (p_bcb->con_state == BNEP_STATE_CONNECTED) { + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_DISCONNECTED, FALSE); + } else { + if ((bnep_cb.p_conn_state_cb) && + ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) || + (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED, FALSE); + } + + bnepu_release_bcb(p_bcb); +} + +/******************************************************************************* + * + * Function bnep_disconnect_cfm + * + * Description This function gets the disconnect confirm event from L2CAP + * + * Returns void + * + ******************************************************************************/ +static void bnep_disconnect_cfm(UINT16 l2cap_cid, UINT16 result) +{ + BNEP_TRACE_EVENT("BNEP - Rcvd L2CAP disc cfm, CID: 0x%x, Result 0x%x", + l2cap_cid, result); +} + +/******************************************************************************* + * + * Function bnep_congestion_ind + * + * Description This is a callback function called by L2CAP when + * congestion status changes + * + ******************************************************************************/ +static void bnep_congestion_ind(UINT16 l2cap_cid, BOOLEAN is_congested) +{ + tBNEP_CONN * p_bcb; + + /* Find BCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd L2CAP cong, unknown CID: 0x%x", l2cap_cid); + return; + } + + if (is_congested) { + p_bcb->con_flags |= BNEP_FLAGS_L2CAP_CONGESTED; + if (bnep_cb.p_tx_data_flow_cb) { + bnep_cb.p_tx_data_flow_cb(p_bcb->handle, BNEP_TX_FLOW_OFF); + } + } else { + p_bcb->con_flags &= ~BNEP_FLAGS_L2CAP_CONGESTED; + + if (bnep_cb.p_tx_data_flow_cb) { + bnep_cb.p_tx_data_flow_cb(p_bcb->handle, BNEP_TX_FLOW_ON); + } + + /* While not congested, send as many buffers as we can */ + while (!(p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED)) { + BT_HDR * p_buf = (BT_HDR *)fixed_queue_dequeue(p_bcb->xmit_q, 0); + + if (!p_buf) { + break; + } + + L2CA_DataWrite(l2cap_cid, p_buf); + } + } +} + +/******************************************************************************* + * + * Function bnep_data_ind + * + * Description This function is called when data is received from L2CAP. + * if we are the originator of the connection, we are the SDP + * client, and the received message is queued for the client. + * + * If we are the destination of the connection, we are the SDP + * server, so the message is passed to the server processing + * function. + * + * Returns void + * + ******************************************************************************/ +static void bnep_data_ind(UINT16 l2cap_cid, BT_HDR *p_buf) +{ + tBNEP_CONN *p_bcb; + UINT8 *p = (UINT8 *)(p_buf + 1) + p_buf->offset; + UINT16 rem_len = p_buf->len; + UINT8 type, ctrl_type, ext_type = 0; + BOOLEAN extension_present, fw_ext_present; + UINT16 protocol = 0; + + /* Find CCB based on CID */ + p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); + if (p_bcb == NULL) { + BNEP_TRACE_WARNING("BNEP - Rcvd L2CAP data, unknown CID: 0x%x", l2cap_cid); + osi_free(p_buf); + return; + } + + /* Check rem_len before any reading from the buffer */ + if (rem_len == 0) { + BNEP_TRACE_EVENT("BNEP - rcvd frame, bad len: %d", p_buf->len); + osi_free(p_buf); + return; + } + + /* Get the type and extension bits */ + type = *p++; + extension_present = type >> 7; + type &= 0x7f; + if (type > BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY || + (rem_len <= bnep_frame_hdr_sizes[type]) || (rem_len > BNEP_MTU_SIZE)) { + BNEP_TRACE_EVENT("BNEP - rcvd frame, bad len: %d type: 0x%02x", p_buf->len, + type); + osi_free(p_buf); + return; + } + + rem_len--; + + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED)) && + (type != BNEP_FRAME_CONTROL)) { + BNEP_TRACE_WARNING( + "BNEP - Ignored L2CAP data while in state: %d, CID: 0x%x", + p_bcb->con_state, l2cap_cid); + + if (extension_present) { + /* + ** When there is no connection if a data packet is received + ** with unknown control extension headers then those should be processed + ** according to complain/ignore law. + ** Extensions follow the type-specific networking header (e.g. 14-byte + ** Ethernet header for GENERAL_ETHERNET), not the BNEP type byte. + */ + UINT8 ext, length; + UINT16 org_len, new_len; + UINT16 hdr_len = bnep_frame_hdr_sizes[type]; + + if (rem_len < hdr_len) { + osi_free(p_buf); + return; + } + p += hdr_len; + org_len = rem_len - hdr_len; + do { + if (org_len < 2) { + break; + } + ext = *p++; + length = *p++; + + new_len = (length + 2); + if (new_len > org_len) { + break; + } + + if ((ext & 0x7F) == BNEP_EXTENSION_FILTER_CONTROL) { + if (length == 0) { + break; + } + if (*p > BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG) { + bnep_send_command_not_understood(p_bcb, *p); + } + } + + p += length; + org_len -= new_len; + + } while (ext & 0x80); + } + + osi_free(p_buf); + return; + } + + BNEP_TRACE_DEBUG("BNEP - rcv frame, type: %d len: %d Ext: %d", type, + p_buf->len, extension_present); + + /* Initialize addresses to 'not supplied' */ + UINT8 *p_src_addr, *p_dst_addr; + p_src_addr = p_dst_addr = NULL; + + switch (type) { + case BNEP_FRAME_GENERAL_ETHERNET: + p_dst_addr = p; + p += BD_ADDR_LEN; + p_src_addr = p; + p += BD_ADDR_LEN; + BE_STREAM_TO_UINT16(protocol, p); + rem_len -= 14; + break; + + case BNEP_FRAME_CONTROL: + ctrl_type = *p; + p = bnep_process_control_packet(p_bcb, p, &rem_len, FALSE); + + /* Failed setup response releases the BCB; do not parse extensions. */ + if (p_bcb->con_state == BNEP_STATE_IDLE) { + osi_free(p_buf); + return; + } + + if (ctrl_type == BNEP_SETUP_CONNECTION_REQUEST_MSG && + p_bcb->con_state != BNEP_STATE_CONNECTED && extension_present && p && + rem_len) { + /* Allocate BT_HDR header plus payload; data is stored after the header. */ + if (p_bcb->p_pending_data) { + osi_free(p_bcb->p_pending_data); + p_bcb->p_pending_data = NULL; + } + p_bcb->p_pending_data = (BT_HDR *)osi_malloc(sizeof(BT_HDR) + rem_len); + if (p_bcb->p_pending_data) { + memcpy((UINT8 *)(p_bcb->p_pending_data + 1), p, rem_len); + p_bcb->p_pending_data->len = rem_len; + p_bcb->p_pending_data->offset = 0; + } + } else { + while (extension_present && p && rem_len) { + ext_type = *p++; + rem_len--; + extension_present = ext_type >> 7; + ext_type &= 0x7F; + + /* if unknown extension present stop processing */ + if (ext_type) { + break; + } + + p = bnep_process_control_packet(p_bcb, p, &rem_len, TRUE); + if (p_bcb->con_state == BNEP_STATE_IDLE) { + break; + } + } + } + osi_free(p_buf); + return; + + case BNEP_FRAME_COMPRESSED_ETHERNET: + BE_STREAM_TO_UINT16(protocol, p); + rem_len -= 2; + break; + + case BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY: + p_src_addr = p; + p += BD_ADDR_LEN; + BE_STREAM_TO_UINT16(protocol, p); + rem_len -= 8; + break; + + case BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY: + p_dst_addr = p; + p += BD_ADDR_LEN; + BE_STREAM_TO_UINT16(protocol, p); + rem_len -= 8; + break; + } + + /* Process the header extension if there is one */ + while (extension_present && p && rem_len) { + ext_type = *p; + extension_present = ext_type >> 7; + ext_type &= 0x7F; + + /* if unknown extension present stop processing */ + if (ext_type) { + BNEP_TRACE_EVENT("Data extension type 0x%x found", ext_type); + break; + } + + p++; + rem_len--; + p = bnep_process_control_packet(p_bcb, p, &rem_len, TRUE); + if (p_bcb->con_state == BNEP_STATE_IDLE) { + osi_free(p_buf); + return; + } + } + + p_buf->offset += p_buf->len - rem_len; + p_buf->len = rem_len; + + /* Always give the upper layer MAC addresses */ + if (!p_src_addr) { + p_src_addr = (UINT8 *)p_bcb->rem_bda; + } + + if (!p_dst_addr) { + p_dst_addr = (UINT8 *)controller_get_interface()->get_address(); + } + + /* check whether there are any extensions to be forwarded */ + if (ext_type) { + fw_ext_present = TRUE; + } else { + fw_ext_present = FALSE; + } + + if (bnep_cb.p_data_buf_cb) { + (*bnep_cb.p_data_buf_cb)(p_bcb->handle, p_src_addr, p_dst_addr, protocol, + p_buf, fw_ext_present); + } else if (bnep_cb.p_data_ind_cb) { + (*bnep_cb.p_data_ind_cb)(p_bcb->handle, p_src_addr, p_dst_addr, protocol, + p, rem_len, fw_ext_present); + osi_free(p_buf); + } else { + osi_free(p_buf); + } +} + +/******************************************************************************* + * + * Function bnep_conn_timer_timeout + * + * Description This function processes a timeout. If it is a startup + * timeout, we check for reading our BD address. If it + * is an L2CAP timeout, we send a disconnect req to L2CAP. + * + * Returns void + * + ******************************************************************************/ +void bnep_conn_timer_timeout(void *data) +{ + tBNEP_CONN * p_bcb = (tBNEP_CONN *)data; + + BNEP_TRACE_EVENT( + "BNEP - CCB timeout in state: %d CID: 0x%x flags %x, re_transmit %d", + p_bcb->con_state, p_bcb->l2cap_cid, p_bcb->con_flags, + p_bcb->re_transmits); + + if (p_bcb->con_state == BNEP_STATE_CONN_SETUP) { + BNEP_TRACE_EVENT("BNEP - CCB timeout in state: %d CID: 0x%x", + p_bcb->con_state, p_bcb->l2cap_cid); + + if (!(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) { + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + bnepu_release_bcb(p_bcb); + return; + } + + if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { + bnep_send_conn_req(p_bcb); + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_CONN_TIMEOUT_SEC); + } else { + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED, FALSE); + + bnepu_release_bcb(p_bcb); + return; + } + } else if (p_bcb->con_state != BNEP_STATE_CONNECTED) { + BNEP_TRACE_EVENT("BNEP - CCB timeout in state: %d CID: 0x%x", + p_bcb->con_state, p_bcb->l2cap_cid); + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + /* Tell the user if he has a callback */ + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_CONN_FAILED, FALSE); + + bnepu_release_bcb(p_bcb); + } else if (p_bcb->con_flags & BNEP_FLAGS_FILTER_RESP_PEND) { + if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { + bnepu_send_peer_our_filters(p_bcb); + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT_SEC); + } else { + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + /* Tell the user if he has a callback */ + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_SET_FILTER_FAIL, FALSE); + + bnepu_release_bcb(p_bcb); + return; + } + } else if (p_bcb->con_flags & BNEP_FLAGS_MULTI_RESP_PEND) { + if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { + bnepu_send_peer_our_multi_filters(p_bcb); + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT_SEC); + } else { + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + /* Tell the user if he has a callback */ + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_SET_FILTER_FAIL, FALSE); + + bnepu_release_bcb(p_bcb); + return; + } + } +} + +/******************************************************************************* + * + * Function bnep_connected + * + * Description This function is called when a connection is established + * (after config). + * + * Returns void + * + ******************************************************************************/ +void bnep_connected(tBNEP_CONN *p_bcb) +{ + BOOLEAN is_role_change; + + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + is_role_change = TRUE; + } else { + is_role_change = FALSE; + } + + p_bcb->con_state = BNEP_STATE_CONNECTED; + p_bcb->con_flags |= BNEP_FLAGS_CONN_COMPLETED; + p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); + + /* Ensure timer is stopped */ + btu_stop_timer(&p_bcb->conn_timer); + p_bcb->re_transmits = 0; + + /* Tell the upper layer, if he has a callback */ + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_SUCCESS, + is_role_change); +} + +#endif /* (BNEP_INCLUDED == TRUE) */ diff --git a/components/bt/host/bluedroid/stack/bnep/bnep_utils.c b/components/bt/host/bluedroid/stack/bnep/bnep_utils.c new file mode 100644 index 00000000000..879199af9fb --- /dev/null +++ b/components/bt/host/bluedroid/stack/bnep/bnep_utils.c @@ -0,0 +1,1544 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains BNEP utility functions + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (BNEP_INCLUDED == TRUE) + +#include +#include + +#include "device/controller.h" +#include "osi/allocator.h" +#include "osi/fixed_queue.h" + +#include "bnep_int.h" +#include "stack/bt_types.h" + +#include "btm_int.h" +#include "stack/btu.h" + +extern fixed_queue_t* btu_general_alarm_queue; + +/******************************************************************************/ +/* L O C A L F U N C T I O N P R O T O T Y P E S */ +/******************************************************************************/ +static UINT8* bnepu_init_hdr(BT_HDR * p_buf, UINT16 hdr_len, + UINT8 pkt_type); + +void bnepu_process_peer_multicast_filter_set(tBNEP_CONN * p_bcb, + UINT8* p_filters, UINT16 len); +void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN * p_bcb, + UINT16 response_code); + +/******************************************************************************* + * + * Function bnepu_find_bcb_by_cid + * + * Description This function searches the bcb table for an entry with the + * passed CID. + * + * Returns the BCB address, or NULL if not found. + * + ******************************************************************************/ +tBNEP_CONN *bnepu_find_bcb_by_cid(UINT16 cid) +{ + UINT16 xx; + tBNEP_CONN * p_bcb; + + /* Look through each connection control block */ + for (xx = 0, p_bcb = bnep_cb.bcb; xx < BNEP_MAX_CONNECTIONS; xx++, p_bcb++) { + if ((p_bcb->con_state != BNEP_STATE_IDLE) && (p_bcb->l2cap_cid == cid)) { + return (p_bcb); + } + } + + /* If here, not found */ + return (NULL); +} + +/******************************************************************************* + * + * Function bnepu_find_bcb_by_bd_addr + * + * Description This function searches the BCB table for an entry with the + * passed Bluetooth Address. + * + * Returns the BCB address, or NULL if not found. + * + ******************************************************************************/ +tBNEP_CONN *bnepu_find_bcb_by_bd_addr(BD_ADDR p_bda) +{ + UINT16 xx; + tBNEP_CONN * p_bcb; + + /* Look through each connection control block */ + for (xx = 0, p_bcb = bnep_cb.bcb; xx < BNEP_MAX_CONNECTIONS; xx++, p_bcb++) { + if (p_bcb->con_state != BNEP_STATE_IDLE) { + if (!bdcmp(p_bcb->rem_bda, p_bda)) { + return (p_bcb); + } + } + } + + /* If here, not found */ + return (NULL); +} + +/******************************************************************************* + * + * Function bnepu_allocate_bcb + * + * Description This function allocates a new BCB. + * + * Returns BCB address, or NULL if none available. + * + ******************************************************************************/ +tBNEP_CONN *bnepu_allocate_bcb(BD_ADDR p_rem_bda) +{ + UINT16 xx; + tBNEP_CONN * p_bcb; + + /* Look through each connection control block for a free one */ + for (xx = 0, p_bcb = bnep_cb.bcb; xx < BNEP_MAX_CONNECTIONS; xx++, p_bcb++) { + if (p_bcb->con_state == BNEP_STATE_IDLE) { + /* Preserve sec_gen across recycle so stale BTM callbacks that still + * hold this BCB pointer cannot match a new connection's generation. */ + UINT32 prev_sec_gen = p_bcb->sec_gen; + + /* Todo: this free operation may be redundant */ + btu_free_timer(&p_bcb->conn_timer); + memset((UINT8 *)p_bcb, 0, sizeof(tBNEP_CONN)); + p_bcb->sec_gen = prev_sec_gen; + + /* Initialize timer parameter */ + p_bcb->conn_timer.param = (uint32_t)p_bcb; + bdcpy(p_bcb->rem_bda, p_rem_bda); + p_bcb->handle = xx + 1; + p_bcb->xmit_q = fixed_queue_new(SIZE_MAX); + + return (p_bcb); + } + } + + /* If here, no free BCB found */ + return (NULL); +} + +/******************************************************************************* + * + * Function bnepu_release_bcb + * + * Description This function releases a BCB. + * + * Returns void + * + ******************************************************************************/ +void bnepu_release_bcb(tBNEP_CONN *p_bcb) +{ + /* Ensure timer is stopped */ + btu_free_timer(&p_bcb->conn_timer); + + /* Free any pending setup extension data we may be holding */ + p_bcb->con_state = BNEP_STATE_IDLE; + p_bcb->con_flags = 0; + p_bcb->l2cap_cid = 0; + /* Invalidate outstanding BTM security callbacks bound to this BCB. */ + p_bcb->sec_gen++; + memset(p_bcb->rem_bda, 0, BD_ADDR_LEN); + if (p_bcb->p_pending_data) { + osi_free(p_bcb->p_pending_data); + p_bcb->p_pending_data = NULL; + } + + /* Free transmit queue */ + if (p_bcb->xmit_q) { + while (!fixed_queue_is_empty(p_bcb->xmit_q)) { + osi_free(fixed_queue_dequeue(p_bcb->xmit_q, 0)); + } + fixed_queue_free(p_bcb->xmit_q, NULL); + p_bcb->xmit_q = NULL; + } +} + +/******************************************************************************* + * + * Function bnep_send_conn_req + * + * Description This function sends a BNEP connection request to peer + * + * Returns void + * + ******************************************************************************/ +void bnep_send_conn_req(tBNEP_CONN *p_bcb) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8 *p, *p_start; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_DEBUG("%s: sending setup req with dst uuid %x", __func__, + p_bcb->dst_uuid.uu.uuid16); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = p_start = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_SETUP_CONNECTION_REQUEST_MSG); + + UINT8_TO_BE_STREAM(p, p_bcb->dst_uuid.len); + + if (p_bcb->dst_uuid.len == 2) { + UINT16_TO_BE_STREAM(p, p_bcb->dst_uuid.uu.uuid16); + UINT16_TO_BE_STREAM(p, p_bcb->src_uuid.uu.uuid16); + } else if (p_bcb->dst_uuid.len == 4) { + UINT32_TO_BE_STREAM(p, p_bcb->dst_uuid.uu.uuid32); + UINT32_TO_BE_STREAM(p, p_bcb->src_uuid.uu.uuid32); + } else if (p_bcb->dst_uuid.len == 16) { + memcpy(p, p_bcb->dst_uuid.uu.uuid128, p_bcb->dst_uuid.len); + p += p_bcb->dst_uuid.len; + memcpy(p, p_bcb->src_uuid.uu.uuid128, p_bcb->dst_uuid.len); + p += p_bcb->dst_uuid.len; + } else { + BNEP_TRACE_ERROR("%s: uuid: %x, invalid length: %x", __func__, + p_bcb->dst_uuid.uu.uuid16, p_bcb->dst_uuid.len); + osi_free(p_buf); + return; + } + + p_buf->len = (UINT16)(p - p_start); + + bnepu_check_send_packet(p_bcb, p_buf); +} + +/******************************************************************************* + * + * Function bnep_send_conn_responce + * + * Description This function sends a BNEP setup response to peer + * + * Returns void + * + ******************************************************************************/ +void bnep_send_conn_responce(tBNEP_CONN *p_bcb, UINT16 resp_code) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_EVENT("BNEP - bnep_send_conn_responce for CID: 0x%x", + p_bcb->l2cap_cid); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_SETUP_CONNECTION_RESPONSE_MSG); + + UINT16_TO_BE_STREAM(p, resp_code); + + p_buf->len = 4; + + bnepu_check_send_packet(p_bcb, p_buf); +} + +/******************************************************************************* + * + * Function bnepu_send_peer_our_filters + * + * Description This function sends our filters to a peer + * + * Returns void + * + ******************************************************************************/ +void bnepu_send_peer_our_filters(tBNEP_CONN *p_bcb) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + UINT16 xx; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_DEBUG("BNEP sending peer our filters"); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_FILTER_NET_TYPE_SET_MSG); + + UINT16_TO_BE_STREAM(p, (4 * p_bcb->sent_num_filters)); + for (xx = 0; xx < p_bcb->sent_num_filters; xx++) { + UINT16_TO_BE_STREAM(p, p_bcb->sent_prot_filter_start[xx]); + UINT16_TO_BE_STREAM(p, p_bcb->sent_prot_filter_end[xx]); + } + + p_buf->len = 4 + (4 * p_bcb->sent_num_filters); + + bnepu_check_send_packet(p_bcb, p_buf); + + p_bcb->con_flags |= BNEP_FLAGS_FILTER_RESP_PEND; + + /* Start timer waiting for setup response */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT_SEC); +} + +/******************************************************************************* + * + * Function bnepu_send_peer_our_multi_filters + * + * Description This function sends our multicast filters to a peer + * + * Returns void + * + ******************************************************************************/ +void bnepu_send_peer_our_multi_filters(tBNEP_CONN *p_bcb) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + UINT16 xx; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_DEBUG("BNEP sending peer our multicast filters"); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_FILTER_MULTI_ADDR_SET_MSG); + + UINT16_TO_BE_STREAM(p, (2 * BD_ADDR_LEN * p_bcb->sent_mcast_filters)); + for (xx = 0; xx < p_bcb->sent_mcast_filters; xx++) { + memcpy(p, p_bcb->sent_mcast_filter_start[xx], BD_ADDR_LEN); + p += BD_ADDR_LEN; + memcpy(p, p_bcb->sent_mcast_filter_end[xx], BD_ADDR_LEN); + p += BD_ADDR_LEN; + } + + p_buf->len = 4 + (2 * BD_ADDR_LEN * p_bcb->sent_mcast_filters); + + bnepu_check_send_packet(p_bcb, p_buf); + + p_bcb->con_flags |= BNEP_FLAGS_MULTI_RESP_PEND; + + /* Start timer waiting for setup response */ + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT_SEC); +} + +/******************************************************************************* + * + * Function bnepu_send_peer_filter_rsp + * + * Description This function sends a filter response to a peer + * + * Returns void + * + ******************************************************************************/ +void bnepu_send_peer_filter_rsp(tBNEP_CONN *p_bcb, UINT16 response_code) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_DEBUG("BNEP sending filter response"); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_FILTER_NET_TYPE_RESPONSE_MSG); + + UINT16_TO_BE_STREAM(p, response_code); + + p_buf->len = 4; + + bnepu_check_send_packet(p_bcb, p_buf); +} + +/******************************************************************************* + * + * Function bnep_send_command_not_understood + * + * Description This function sends a BNEP command not understood message + * + * Returns void + * + ******************************************************************************/ +void bnep_send_command_not_understood(tBNEP_CONN *p_bcb, UINT8 cmd_code) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_EVENT( + "BNEP - bnep_send_command_not_understood for CID: 0x%x, cmd 0x%x", + p_bcb->l2cap_cid, cmd_code); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD); + + UINT8_TO_BE_STREAM(p, cmd_code); + + p_buf->len = 3; + + bnepu_check_send_packet(p_bcb, p_buf); +} + +/******************************************************************************* + * + * Function bnepu_check_send_packet + * + * Description This function tries to send a packet to L2CAP. + * If L2CAP is flow controlled, it enqueues the + * packet to the transmit queue + * + * Returns void + * + ******************************************************************************/ +void bnepu_check_send_packet(tBNEP_CONN *p_bcb, BT_HDR *p_buf) +{ + BNEP_TRACE_EVENT("BNEP - bnepu_check_send_packet for CID: 0x%x", + p_bcb->l2cap_cid); + + /* BCB may have been released while still processing the same RX frame + * (e.g. failed setup response followed by extension headers). */ + if (p_bcb->con_state == BNEP_STATE_IDLE || p_bcb->xmit_q == NULL) { + BNEP_TRACE_WARNING("BNEP - drop TX on idle/released BCB"); + osi_free(p_buf); + return; + } + + if (p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED) { + if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { + BNEP_TRACE_EVENT("BNEP - congested, dropping buf, CID: 0x%x", + p_bcb->l2cap_cid); + + osi_free(p_buf); + } else { + fixed_queue_enqueue(p_bcb->xmit_q, p_buf, FIXED_QUEUE_MAX_TIMEOUT); + } + } else { + L2CA_DataWrite(p_bcb->l2cap_cid, p_buf); + } +} + +/******************************************************************************* + * + * Function bnepu_build_bnep_hdr + * + * Description This function builds the BNEP header for a packet + * Extension headers are not sent yet, so there is no + * check for that. + * + * Returns void + * + ******************************************************************************/ +void bnepu_build_bnep_hdr(tBNEP_CONN *p_bcb, BT_HDR *p_buf, UINT16 protocol, + BD_ADDR p_src_addr, BD_ADDR p_dest_addr, + BOOLEAN fw_ext_present) +{ + const controller_t *controller = controller_get_interface(); + const UINT8 *local_addr = (const UINT8 *)controller->get_address(); + const UINT8 *src_addr = p_src_addr ? (const UINT8 *)p_src_addr : local_addr; + UINT8 ext_bit, *p = (UINT8 *)NULL; + UINT8 type = BNEP_FRAME_COMPRESSED_ETHERNET; + + ext_bit = fw_ext_present ? 0x80 : 0x00; + + if (bdcmp(src_addr, local_addr)) { + type = BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY; + } + + if (bdcmp(p_dest_addr, p_bcb->rem_bda)) + type = (type == BNEP_FRAME_COMPRESSED_ETHERNET) + ? BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY + : BNEP_FRAME_GENERAL_ETHERNET; + + switch (type) { + case BNEP_FRAME_GENERAL_ETHERNET: + p = bnepu_init_hdr(p_buf, 15, + (UINT8)(ext_bit | BNEP_FRAME_GENERAL_ETHERNET)); + if (!p) { + return; + } + + memcpy(p, p_dest_addr, BD_ADDR_LEN); + p += BD_ADDR_LEN; + + memcpy(p, src_addr, BD_ADDR_LEN); + p += BD_ADDR_LEN; + break; + + case BNEP_FRAME_COMPRESSED_ETHERNET: + p = bnepu_init_hdr(p_buf, 3, + (UINT8)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET)); + break; + + case BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY: + p = bnepu_init_hdr( + p_buf, 9, + (UINT8)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY)); + if (!p) { + return; + } + + memcpy(p, src_addr, BD_ADDR_LEN); + p += BD_ADDR_LEN; + break; + + case BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY: + p = bnepu_init_hdr( + p_buf, 9, + (UINT8)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY)); + if (!p) { + return; + } + + memcpy(p, p_dest_addr, BD_ADDR_LEN); + p += BD_ADDR_LEN; + break; + } + + if (!p) { + return; + } + + UINT16_TO_BE_STREAM(p, protocol); +} + +/******************************************************************************* + * + * Function bnepu_init_hdr + * + * Description This function initializes the BNEP header + * + * Returns pointer to header in buffer + * + ******************************************************************************/ +static UINT8 *bnepu_init_hdr(BT_HDR *p_buf, UINT16 hdr_len, + UINT8 pkt_type) +{ + UINT8 *p = (UINT8 *)(p_buf + 1) + p_buf->offset; + + /* Headroom must already be present. Do not shift the payload: BT_HDR does + * not record allocation size, so moving data forward can overrun + * exact-sized heap buffers used in ESP-IDF. */ + if (p_buf->offset < (hdr_len + L2CAP_MIN_OFFSET)) { + BNEP_TRACE_ERROR("BNEP init_hdr: offset %d too small for hdr_len %d", + p_buf->offset, hdr_len); + return NULL; + } + + p_buf->len += hdr_len; + p_buf->offset -= hdr_len; + p -= hdr_len; + + *p++ = pkt_type; + + return (p); +} + +/******************************************************************************* + * + * Function bnep_process_setup_conn_req + * + * Description This function processes a peer's setup connection request + * message. The destination UUID is verified and response sent + * Connection open indication will be given to PAN profile + * + * Returns void + * + ******************************************************************************/ +void bnep_process_setup_conn_req(tBNEP_CONN *p_bcb, UINT8 *p_setup, + UINT8 len) +{ + BNEP_TRACE_EVENT("BNEP - bnep_process_setup_conn_req for CID: 0x%x", + p_bcb->l2cap_cid); + + if (p_bcb->con_state != BNEP_STATE_CONN_SETUP && + p_bcb->con_state != BNEP_STATE_SEC_CHECKING && + p_bcb->con_state != BNEP_STATE_CONNECTED) { + BNEP_TRACE_ERROR("BNEP - setup request in bad state %d", p_bcb->con_state); + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED); + return; + } + + /* Check if we already initiated security check or if waiting for user + * response */ + if (p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD) { + BNEP_TRACE_EVENT( + "BNEP - Duplicate Setup message received while doing security check"); + return; + } + + /* Check if peer is the originator */ + if (p_bcb->con_state != BNEP_STATE_CONNECTED && + (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)) && + (p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) { + BNEP_TRACE_ERROR("BNEP - setup request when we are originator", + p_bcb->con_state); + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED); + return; + } + + if (p_bcb->con_state == BNEP_STATE_CONNECTED) { + memcpy((UINT8 *) & (p_bcb->prv_src_uuid), (UINT8 *) & (p_bcb->src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8 *) & (p_bcb->prv_dst_uuid), (UINT8 *) & (p_bcb->dst_uuid), + sizeof(tBT_UUID)); + } + + p_bcb->dst_uuid.len = p_bcb->src_uuid.len = len; + + if (p_bcb->dst_uuid.len == 2) { + /* because peer initiated connection keep src uuid as dst uuid */ + BE_STREAM_TO_UINT16(p_bcb->src_uuid.uu.uuid16, p_setup); + BE_STREAM_TO_UINT16(p_bcb->dst_uuid.uu.uuid16, p_setup); + + /* If nothing has changed don't bother the profile */ + if (p_bcb->con_state == BNEP_STATE_CONNECTED && + p_bcb->prv_src_uuid.len == 2 && + p_bcb->prv_dst_uuid.len == 2 && + p_bcb->src_uuid.uu.uuid16 == p_bcb->prv_src_uuid.uu.uuid16 && + p_bcb->dst_uuid.uu.uuid16 == p_bcb->prv_dst_uuid.uu.uuid16) { + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_OK); + return; + } + } else if (p_bcb->dst_uuid.len == 4) { + BE_STREAM_TO_UINT32(p_bcb->src_uuid.uu.uuid32, p_setup); + BE_STREAM_TO_UINT32(p_bcb->dst_uuid.uu.uuid32, p_setup); + + if (p_bcb->con_state == BNEP_STATE_CONNECTED && + p_bcb->prv_src_uuid.len == 4 && + p_bcb->prv_dst_uuid.len == 4 && + p_bcb->src_uuid.uu.uuid32 == p_bcb->prv_src_uuid.uu.uuid32 && + p_bcb->dst_uuid.uu.uuid32 == p_bcb->prv_dst_uuid.uu.uuid32) { + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_OK); + return; + } + } else if (p_bcb->dst_uuid.len == 16) { + memcpy(p_bcb->src_uuid.uu.uuid128, p_setup, p_bcb->src_uuid.len); + p_setup += p_bcb->src_uuid.len; + memcpy(p_bcb->dst_uuid.uu.uuid128, p_setup, p_bcb->dst_uuid.len); + p_setup += p_bcb->dst_uuid.len; + + if (p_bcb->con_state == BNEP_STATE_CONNECTED && + p_bcb->prv_src_uuid.len == 16 && + p_bcb->prv_dst_uuid.len == 16 && + memcmp(p_bcb->src_uuid.uu.uuid128, + p_bcb->prv_src_uuid.uu.uuid128, 16) == 0 && + memcmp(p_bcb->dst_uuid.uu.uuid128, + p_bcb->prv_dst_uuid.uu.uuid128, 16) == 0) { + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_OK); + return; + } + } else { + BNEP_TRACE_ERROR("BNEP - Bad UID len %d in ConnReq", p_bcb->dst_uuid.len); + bnep_send_conn_responce(p_bcb, BNEP_SETUP_INVALID_UUID_SIZE); + return; + } + + p_bcb->con_state = BNEP_STATE_SEC_CHECKING; + p_bcb->con_flags |= BNEP_FLAGS_SETUP_RCVD; + + BNEP_TRACE_EVENT( + "BNEP initiating security check for incoming call for uuid 0x%x", + p_bcb->src_uuid.uu.uuid16); +#if (BNEP_DO_AUTH_FOR_ROLE_SWITCH == FALSE) + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) + bnep_sec_check_complete(p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb, + BTM_SUCCESS); + else +#endif + btm_sec_mx_access_request( + p_bcb->rem_bda, BT_PSM_BNEP, FALSE, BTM_SEC_PROTO_BNEP, + bnep_get_uuid32(&(p_bcb->src_uuid)), &bnep_sec_check_complete, p_bcb); + + return; +} + +/******************************************************************************* + * + * Function bnep_process_setup_conn_responce + * + * Description This function processes a peer's setup connection response + * message. The response code is verified and + * Connection open indication will be given to PAN profile + * + * Returns void + * + ******************************************************************************/ +void bnep_process_setup_conn_responce(tBNEP_CONN *p_bcb, UINT8 *p_setup) +{ + tBNEP_RESULT resp; + UINT16 resp_code; + + BNEP_TRACE_DEBUG("BNEP received setup response"); + /* The state should be either SETUP or CONNECTED */ + if (p_bcb->con_state != BNEP_STATE_CONN_SETUP) { + /* Should we disconnect ? */ + BNEP_TRACE_ERROR("BNEP - setup response in bad state %d", p_bcb->con_state); + return; + } + + /* Check if we are the originator */ + if (!(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) { + BNEP_TRACE_ERROR("BNEP - setup response when we are not originator", + p_bcb->con_state); + return; + } + + BE_STREAM_TO_UINT16(resp_code, p_setup); + + switch (resp_code) { + case BNEP_SETUP_INVALID_SRC_UUID: + resp = BNEP_CONN_FAILED_SRC_UUID; + break; + + case BNEP_SETUP_INVALID_DEST_UUID: + resp = BNEP_CONN_FAILED_DST_UUID; + break; + + case BNEP_SETUP_INVALID_UUID_SIZE: + resp = BNEP_CONN_FAILED_UUID_SIZE; + break; + + case BNEP_SETUP_CONN_NOT_ALLOWED: + default: + resp = BNEP_CONN_FAILED; + break; + } + + /* Check the response code */ + if (resp_code != BNEP_SETUP_CONN_OK) { + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + BNEP_TRACE_EVENT("BNEP - role change response is %d", resp_code); + + /* Restore the earlier BNEP status */ + p_bcb->con_state = BNEP_STATE_CONNECTED; + p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); + memcpy((UINT8*) & (p_bcb->src_uuid), (UINT8*) & (p_bcb->prv_src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8*) & (p_bcb->dst_uuid), (UINT8*) & (p_bcb->prv_dst_uuid), + sizeof(tBT_UUID)); + + /* Ensure timer is stopped */ + btu_stop_timer(&p_bcb->conn_timer); + p_bcb->re_transmits = 0; + + /* Tell the user if he has a callback */ + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, resp, TRUE); + } + + return; + } else { + BNEP_TRACE_ERROR("BNEP - setup response %d is not OK", resp_code); + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + /* Tell the user if he has a callback */ + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, resp, FALSE); + } + + bnepu_release_bcb(p_bcb); + return; + } + } + + /* Received successful response */ + bnep_connected(p_bcb); +} + +/******************************************************************************* + * + * Function bnep_process_control_packet + * + * Description This function processes a peer's setup connection request + * message. The destination UUID is verified and response sent + * Connection open indication will be given to PAN profile + * + * Returns void + * + ******************************************************************************/ +UINT8 *bnep_process_control_packet(tBNEP_CONN *p_bcb, UINT8 *p, + UINT16 *rem_len, BOOLEAN is_ext) +{ + UINT8 control_type; + BOOLEAN bad_pkt = FALSE; + UINT16 len, ext_len = 0; + UINT16 rem_len_prev = *rem_len; + /* When is_ext, rem_len is temporarily limited to this extension body. */ + UINT16 ext_body = 0; + UINT16 pkt_rem_after_type = 0; + + /* is_ext: need extension length + control type (2 bytes); + * otherwise need at least the control type (1 byte). */ + if (*rem_len < (is_ext ? 2 : 1)) { + BNEP_TRACE_ERROR("BNEP control packet truncated: rem_len %d is_ext %d", + *rem_len, is_ext); + *rem_len = 0; + return NULL; + } + + if (is_ext) { + ext_len = *p++; + *rem_len = *rem_len - 1; + /* Length covers the control type and optional payload; zero is invalid + * and would underflow (ext_len - 1) in the unknown-control path. */ + if (ext_len == 0 || *rem_len < ext_len) { + BNEP_TRACE_ERROR( + "BNEP control extension bad length: ext_len %d rem_len %d", + ext_len, *rem_len); + *rem_len = 0; + return NULL; + } + } + + control_type = *p++; + *rem_len = *rem_len - 1; + + if (is_ext) { + /* Only parse within this extension; do not consume following + * extensions or network payload as control fields. */ + ext_body = (UINT16)(ext_len - 1); + pkt_rem_after_type = *rem_len; + *rem_len = ext_body; + } + + BNEP_TRACE_EVENT( + "BNEP processing control packet rem_len %d, is_ext %d, ctrl_type %d", + *rem_len, is_ext, control_type); + + switch (control_type) { + case BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD: + if (*rem_len < 1) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR( + "BNEP Received Cmd not understood with bad length"); + break; + } + BNEP_TRACE_ERROR("BNEP Received Cmd not understood for ctl pkt type: %d", + *p); + p++; + *rem_len = *rem_len - 1; + break; + + case BNEP_SETUP_CONNECTION_REQUEST_MSG: + if (*rem_len < 1) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Setup message with bad length"); + break; + } + len = *p++; + if (*rem_len < ((2 * len) + 1)) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Setup message with bad length"); + break; + } + if (!is_ext) { + bnep_process_setup_conn_req(p_bcb, p, (UINT8)len); + } + p += (2 * len); + *rem_len = *rem_len - (2 * len) - 1; + break; + + case BNEP_SETUP_CONNECTION_RESPONSE_MSG: + if (*rem_len < 2) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Setup response with bad length"); + break; + } + if (!is_ext) { + bnep_process_setup_conn_responce(p_bcb, p); + } + p += 2; + *rem_len = *rem_len - 2; + break; + + case BNEP_FILTER_NET_TYPE_SET_MSG: + if (*rem_len < 2) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Filter set message with bad length"); + break; + } + BE_STREAM_TO_UINT16(len, p); + if (*rem_len < (len + 2)) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Filter set message with bad length"); + break; + } + bnepu_process_peer_filter_set(p_bcb, p, len); + p += len; + *rem_len = *rem_len - len - 2; + break; + + case BNEP_FILTER_NET_TYPE_RESPONSE_MSG: + if (*rem_len < 2) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR("BNEP Received Filter response with bad length"); + break; + } + bnepu_process_peer_filter_rsp(p_bcb, p); + p += 2; + *rem_len = *rem_len - 2; + break; + + case BNEP_FILTER_MULTI_ADDR_SET_MSG: + if (*rem_len < 2) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR( + "BNEP Received Multicast Filter Set message with bad length"); + break; + } + BE_STREAM_TO_UINT16(len, p); + if (*rem_len < (len + 2)) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR( + "BNEP Received Multicast Filter Set message with bad length"); + break; + } + bnepu_process_peer_multicast_filter_set(p_bcb, p, len); + p += len; + *rem_len = *rem_len - len - 2; + break; + + case BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG: + if (*rem_len < 2) { + bad_pkt = TRUE; + BNEP_TRACE_ERROR( + "BNEP Received Multicast Filter response with bad length"); + break; + } + bnepu_process_multicast_filter_rsp(p_bcb, p); + p += 2; + *rem_len = *rem_len - 2; + break; + + default: + BNEP_TRACE_ERROR("BNEP - bad ctl pkt type: %d", control_type); + bnep_send_command_not_understood(p_bcb, control_type); + /* Remaining extension body is skipped in the is_ext epilogue below. */ + break; + } + + if (bad_pkt || + (is_ext ? (*rem_len > ext_body) : (*rem_len > rem_len_prev))) { + BNEP_TRACE_ERROR("BNEP - bad ctl pkt length: %d", *rem_len); + *rem_len = 0; + return NULL; + } + + if (is_ext) { + /* Consume any unused bytes in this extension, then restore rem_len for + * the rest of the BNEP frame (next extension or network payload). */ + p += *rem_len; + *rem_len = (UINT16)(pkt_rem_after_type - ext_body); + } + + /* Setup failure (and similar) may release the BCB mid-packet. Signal the + * caller to stop parsing further extension headers on this buffer. */ + if (p_bcb->con_state == BNEP_STATE_IDLE) { + *rem_len = 0; + return NULL; + } + + return p; +} + +/******************************************************************************* + * + * Function bnepu_process_peer_filter_set + * + * Description This function processes a peer's filter control + * 'set' message. The filters are stored in the BCB, + * and an appropriate filter response message sent. + * + * Returns void + * + ******************************************************************************/ +void bnepu_process_peer_filter_set(tBNEP_CONN *p_bcb, UINT8 *p_filters, + UINT16 len) +{ + UINT16 num_filters = 0; + UINT16 xx, resp_code = BNEP_FILTER_CRL_OK; + UINT16 start, end; + UINT8* p_temp_filters; + + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + BNEP_TRACE_DEBUG( + "BNEP received filter set from peer when there is no connection"); + return; + } + + BNEP_TRACE_DEBUG("BNEP received filter set from peer"); + /* Check for length not a multiple of 4 */ + if (len & 3) { + BNEP_TRACE_EVENT("BNEP - bad filter len: %d", len); + bnepu_send_peer_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE); + return; + } + + if (len) { + num_filters = (UINT16)(len >> 2); + } + + /* Validate filter values */ + if (num_filters <= BNEP_MAX_PROT_FILTERS) { + p_temp_filters = p_filters; + for (xx = 0; xx < num_filters; xx++) { + BE_STREAM_TO_UINT16(start, p_temp_filters); + BE_STREAM_TO_UINT16(end, p_temp_filters); + + if (start > end) { + resp_code = BNEP_FILTER_CRL_BAD_RANGE; + break; + } + } + } else { + resp_code = BNEP_FILTER_CRL_MAX_REACHED; + } + + if (resp_code != BNEP_FILTER_CRL_OK) { + bnepu_send_peer_filter_rsp(p_bcb, resp_code); + return; + } + + if (bnep_cb.p_filter_ind_cb) { + (*bnep_cb.p_filter_ind_cb)(p_bcb->handle, TRUE, 0, len, p_filters); + } + + p_bcb->rcvd_num_filters = num_filters; + for (xx = 0; xx < num_filters; xx++) { + BE_STREAM_TO_UINT16(start, p_filters); + BE_STREAM_TO_UINT16(end, p_filters); + + p_bcb->rcvd_prot_filter_start[xx] = start; + p_bcb->rcvd_prot_filter_end[xx] = end; + } + + bnepu_send_peer_filter_rsp(p_bcb, resp_code); +} + +/******************************************************************************* + * + * Function bnepu_process_peer_filter_rsp + * + * Description This function processes a peer's filter control + * 'response' message. + * + * Returns void + * + ******************************************************************************/ +void bnepu_process_peer_filter_rsp(tBNEP_CONN *p_bcb, UINT8 *p_data) +{ + UINT16 resp_code; + tBNEP_RESULT result; + + BNEP_TRACE_DEBUG("BNEP received filter response"); + /* The state should be CONNECTED */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + BNEP_TRACE_ERROR("BNEP - filter response in bad state %d", + p_bcb->con_state); + return; + } + + /* Check if we are the originator */ + if (!(p_bcb->con_flags & BNEP_FLAGS_FILTER_RESP_PEND)) { + BNEP_TRACE_ERROR("BNEP - filter response when not expecting"); + return; + } + + /* Ensure timer is stopped */ + btu_stop_timer(&p_bcb->conn_timer); + p_bcb->con_flags &= ~BNEP_FLAGS_FILTER_RESP_PEND; + p_bcb->re_transmits = 0; + + BE_STREAM_TO_UINT16(resp_code, p_data); + + result = BNEP_SUCCESS; + if (resp_code != BNEP_FILTER_CRL_OK) { + result = BNEP_SET_FILTER_FAIL; + } + + if (bnep_cb.p_filter_ind_cb) { + (*bnep_cb.p_filter_ind_cb)(p_bcb->handle, FALSE, result, 0, NULL); + } +} + +/******************************************************************************* + * + * Function bnepu_process_multicast_filter_rsp + * + * Description This function processes multicast filter control + * 'response' message. + * + * Returns void + * + ******************************************************************************/ +void bnepu_process_multicast_filter_rsp(tBNEP_CONN *p_bcb, UINT8 *p_data) +{ + UINT16 resp_code; + tBNEP_RESULT result; + + BNEP_TRACE_DEBUG("BNEP received multicast filter response"); + /* The state should be CONNECTED */ + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + BNEP_TRACE_ERROR("BNEP - multicast filter response in bad state %d", + p_bcb->con_state); + return; + } + + /* Check if we are the originator */ + if (!(p_bcb->con_flags & BNEP_FLAGS_MULTI_RESP_PEND)) { + BNEP_TRACE_ERROR("BNEP - multicast filter response when not expecting"); + return; + } + + /* Ensure timer is stopped */ + btu_stop_timer(&p_bcb->conn_timer); + p_bcb->con_flags &= ~BNEP_FLAGS_MULTI_RESP_PEND; + p_bcb->re_transmits = 0; + + BE_STREAM_TO_UINT16(resp_code, p_data); + + result = BNEP_SUCCESS; + if (resp_code != BNEP_FILTER_CRL_OK) { + result = BNEP_SET_FILTER_FAIL; + } + + if (bnep_cb.p_mfilter_ind_cb) { + (*bnep_cb.p_mfilter_ind_cb)(p_bcb->handle, FALSE, result, 0, NULL); + } +} + +/******************************************************************************* + * + * Function bnepu_process_peer_multicast_filter_set + * + * Description This function processes a peer's filter control + * 'set' message. The filters are stored in the BCB, + * and an appropriate filter response message sent. + * + * Returns void + * + ******************************************************************************/ +void bnepu_process_peer_multicast_filter_set(tBNEP_CONN *p_bcb, + UINT8 *p_filters, UINT16 len) +{ + UINT16 resp_code = BNEP_FILTER_CRL_OK; + UINT16 num_filters, xx; + UINT8 *p_temp_filters, null_bda[BD_ADDR_LEN] = {0, 0, 0, 0, 0, 0}; + + if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + BNEP_TRACE_DEBUG( + "BNEP received multicast filter set from peer when there is no " + "connection"); + return; + } + + if (len % 12) { + BNEP_TRACE_EVENT("BNEP - bad filter len: %d", len); + bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE); + return; + } + + if (len > (BNEP_MAX_MULTI_FILTERS * 2 * BD_ADDR_LEN)) { + BNEP_TRACE_EVENT("BNEP - Too many filters"); + bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_MAX_REACHED); + return; + } + + num_filters = 0; + if (len) { + num_filters = (UINT16)(len / 12); + } + + /* Validate filter values */ + if (num_filters <= BNEP_MAX_MULTI_FILTERS) { + p_temp_filters = p_filters; + for (xx = 0; xx < num_filters; xx++) { + if (memcmp(p_temp_filters, p_temp_filters + BD_ADDR_LEN, BD_ADDR_LEN) > + 0) { + bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE); + return; + } + + p_temp_filters += (BD_ADDR_LEN * 2); + } + } + + p_bcb->rcvd_mcast_filters = num_filters; + p_temp_filters = p_filters; + for (xx = 0; xx < num_filters; xx++) { + memcpy(p_bcb->rcvd_mcast_filter_start[xx], p_temp_filters, BD_ADDR_LEN); + memcpy(p_bcb->rcvd_mcast_filter_end[xx], p_temp_filters + BD_ADDR_LEN, + BD_ADDR_LEN); + p_temp_filters += (BD_ADDR_LEN * 2); + + /* Check if any of the ranges have all zeros as both starting and ending + * addresses */ + if ((memcmp(null_bda, p_bcb->rcvd_mcast_filter_start[xx], + BD_ADDR_LEN) == 0) && + (memcmp(null_bda, p_bcb->rcvd_mcast_filter_end[xx], + BD_ADDR_LEN) == 0)) { + p_bcb->rcvd_mcast_filters = 0xFFFF; + break; + } + } + + BNEP_TRACE_EVENT("BNEP multicast filters %d", p_bcb->rcvd_mcast_filters); + bnepu_send_peer_multicast_filter_rsp(p_bcb, resp_code); + + if (bnep_cb.p_mfilter_ind_cb) { + (*bnep_cb.p_mfilter_ind_cb)(p_bcb->handle, TRUE, 0, len, p_filters); + } +} + +/******************************************************************************* + * + * Function bnepu_send_peer_multicast_filter_rsp + * + * Description This function sends a filter response to a peer + * + * Returns void + * + ******************************************************************************/ +void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN *p_bcb, + UINT16 response_code) +{ + BT_HDR * p_buf = (BT_HDR *)osi_malloc(BNEP_BUF_SIZE); + UINT8* p; + + if (!p_buf) { + BNEP_TRACE_ERROR("%s: no buffer", __func__); + return; + } + + BNEP_TRACE_DEBUG("BNEP sending multicast filter response %d", response_code); + + p_buf->offset = L2CAP_MIN_OFFSET; + p = (UINT8*)(p_buf + 1) + L2CAP_MIN_OFFSET; + + /* Put in BNEP frame type - filter control */ + UINT8_TO_BE_STREAM(p, BNEP_FRAME_CONTROL); + + /* Put in filter message type - set filters */ + UINT8_TO_BE_STREAM(p, BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG); + + UINT16_TO_BE_STREAM(p, response_code); + + p_buf->len = 4; + + bnepu_check_send_packet(p_bcb, p_buf); +} + +/******************************************************************************* + * + * Function bnep_sec_check_complete + * + * Description This function is registered with BTM and will be called + * after completing the security procedures + * + * Returns void + * + ******************************************************************************/ +void bnep_sec_check_complete(BD_ADDR bd_addr, + UNUSED_ATTR tBT_TRANSPORT transport, + void *p_ref_data, UINT8 result) +{ + tBNEP_CONN * p_bcb = (tBNEP_CONN *)p_ref_data; + UINT16 resp_code = BNEP_SETUP_CONN_OK; + BOOLEAN is_role_change; + + if (!p_bcb) { + return; + } + + /* check if the port is still waiting for security to complete */ + if (p_bcb->con_state != BNEP_STATE_SEC_CHECKING) { + BNEP_TRACE_ERROR( + "BNEP Connection in wrong state %d when security is completed", + p_bcb->con_state); + return; + } + + /* + * After L2CAP drop, bnepu_release_bcb may recycle this BCB for another + * peer while a BTM security request is still outstanding. Ignore callbacks + * whose address does not match the connection currently using the BCB. + */ + if (bd_addr == NULL || bdcmp(bd_addr, p_bcb->rem_bda)) { + BNEP_TRACE_WARNING( + "BNEP ignoring security callback (stale or mismatched address)"); + return; + } + + BNEP_TRACE_EVENT("BNEP security callback returned result %d", result); + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + is_role_change = TRUE; + } else { + is_role_change = FALSE; + } + + /* if it is outgoing call and result is FAILURE return security fail error */ + if (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)) { + if (result != BTM_SUCCESS) { + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + /* Tell the user that role change is failed because of security */ + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_SECURITY_FAIL, is_role_change); + + p_bcb->con_state = BNEP_STATE_CONNECTED; + memcpy((UINT8*) & (p_bcb->src_uuid), (UINT8*) & (p_bcb->prv_src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8*) & (p_bcb->dst_uuid), (UINT8*) & (p_bcb->prv_dst_uuid), + sizeof(tBT_UUID)); + return; + } + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + /* Tell the user if he has a callback */ + if (bnep_cb.p_conn_state_cb) + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, + BNEP_SECURITY_FAIL, is_role_change); + + bnepu_release_bcb(p_bcb); + return; + } + + /* Transition to the next appropriate state, waiting for connection confirm. + */ + p_bcb->con_state = BNEP_STATE_CONN_SETUP; + + bnep_send_conn_req(p_bcb); + btu_start_timer(&p_bcb->conn_timer, BTU_TTYPE_BNEP, BNEP_CONN_TIMEOUT_SEC); + return; + } + + /* it is an incoming call respond appropriately */ + if (result != BTM_SUCCESS) { + bnep_send_conn_responce(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED); + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + /* Role change is failed because of security. Revert back to connected + * state */ + p_bcb->con_state = BNEP_STATE_CONNECTED; + p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); + memcpy((UINT8*) & (p_bcb->src_uuid), (UINT8*) & (p_bcb->prv_src_uuid), + sizeof(tBT_UUID)); + memcpy((UINT8*) & (p_bcb->dst_uuid), (UINT8*) & (p_bcb->prv_dst_uuid), + sizeof(tBT_UUID)); + return; + } + + L2CA_DisconnectReq(p_bcb->l2cap_cid); + + bnepu_release_bcb(p_bcb); + return; + } + + if (bnep_cb.p_conn_ind_cb) { + p_bcb->con_state = BNEP_STATE_CONN_SETUP; + (*bnep_cb.p_conn_ind_cb)(p_bcb->handle, p_bcb->rem_bda, &p_bcb->dst_uuid, + &p_bcb->src_uuid, is_role_change); + } else { + /* Profile didn't register connection indication call back */ + bnep_send_conn_responce(p_bcb, resp_code); + bnep_connected(p_bcb); + } + + return; +} + +/******************************************************************************* + * + * Function bnep_is_packet_allowed + * + * Description This function verifies whether the protocol passes through + * the protocol filters set by the peer + * + * Returns BNEP_SUCCESS - if the protocol is allowed + * BNEP_IGNORE_CMD - if the protocol is filtered out + * + ******************************************************************************/ +tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN *p_bcb, + BD_ADDR p_dest_addr, + UINT16 protocol, BOOLEAN fw_ext_present, + UINT8 *p_data, UINT16 data_len) +{ + if (p_bcb->rcvd_num_filters) { + UINT16 i, proto; + + /* Find out the actual protocol to check for the filtering */ + proto = protocol; + if (proto == BNEP_802_1_P_PROTOCOL) { + if (fw_ext_present) { + UINT8 ext_len, ext; + /* parse the extension headers and find out actual protocol */ + do { + if (data_len < 2) { + return BNEP_IGNORE_CMD; + } + ext = *p_data++; + ext_len = *p_data++; + data_len -= 2; + if (data_len < ext_len) { + return BNEP_IGNORE_CMD; + } + p_data += ext_len; + data_len -= ext_len; + + } while (ext & 0x80); + } + /* 802.1Q tag (2) + ethertype (2) */ + if (data_len < 4) { + return BNEP_IGNORE_CMD; + } + p_data += 2; + BE_STREAM_TO_UINT16(proto, p_data); + } + + for (i = 0; i < p_bcb->rcvd_num_filters; i++) { + if ((p_bcb->rcvd_prot_filter_start[i] <= proto) && + (proto <= p_bcb->rcvd_prot_filter_end[i])) { + break; + } + } + + if (i == p_bcb->rcvd_num_filters) { + BNEP_TRACE_DEBUG("Ignoring protocol 0x%x in BNEP data write", proto); + return BNEP_IGNORE_CMD; + } + } + + /* Check for multicast address filtering */ + if ((p_dest_addr[0] & 0x01) && p_bcb->rcvd_mcast_filters) { + UINT16 i = 0; + + /* Check if every multicast should be filtered */ + if (p_bcb->rcvd_mcast_filters != 0xFFFF) { + /* Check if the address is mentioned in the filter range */ + for (i = 0; i < p_bcb->rcvd_mcast_filters; i++) { + if ((memcmp(p_bcb->rcvd_mcast_filter_start[i], + p_dest_addr, BD_ADDR_LEN) <= 0) && + (memcmp(p_bcb->rcvd_mcast_filter_end[i], + p_dest_addr, BD_ADDR_LEN) >= 0)) { + break; + } + } + } + + /* + ** If every multicast should be filtered or the address is not in the filter + *range + ** drop the packet + */ + if ((p_bcb->rcvd_mcast_filters == 0xFFFF) || + (i == p_bcb->rcvd_mcast_filters)) { + BNEP_TRACE_DEBUG( + "Ignoring multicast address %02x:%02x:%02x:%02x:%02x:%02x in BNEP data write", + p_dest_addr[0], p_dest_addr[1], p_dest_addr[2], p_dest_addr[3], + p_dest_addr[4], p_dest_addr[5]); + return BNEP_IGNORE_CMD; + } + } + + return BNEP_SUCCESS; +} + +/******************************************************************************* + * + * Function bnep_get_uuid32 + * + * Description This function returns the 32-bit equivalent of the UUID + * + * Returns UINT32 - 32-bit equivalent of the UUID + * + ******************************************************************************/ +UINT32 bnep_get_uuid32(tBT_UUID *src_uuid) +{ + UINT32 result; + + if (src_uuid->len == 2) { + return ((UINT32)src_uuid->uu.uuid16); + } else if (src_uuid->len == 4) { + return (src_uuid->uu.uuid32 & 0x0000FFFF); + } else { + result = src_uuid->uu.uuid128[2]; + result = (result << 8) | (src_uuid->uu.uuid128[3]); + return result; + } +} + +#endif /* (BNEP_INCLUDED == TRUE) */ diff --git a/components/bt/host/bluedroid/stack/bnep/include/bnep_int.h b/components/bt/host/bluedroid/stack/bnep/include/bnep_int.h new file mode 100644 index 00000000000..1d32a43e8fb --- /dev/null +++ b/components/bt/host/bluedroid/stack/bnep/include/bnep_int.h @@ -0,0 +1,241 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains internally used BNEP definitions + * + ******************************************************************************/ + +#ifndef BNEP_INT_H +#define BNEP_INT_H + +#include "common/bt_target.h" + +#if (BNEP_INCLUDED == TRUE) + +#include "stack/bnep_api.h" +#include "btm_int.h" +#include "stack/btu.h" + +/* BNEP frame types +*/ +#define BNEP_FRAME_GENERAL_ETHERNET 0x00 +#define BNEP_FRAME_CONTROL 0x01 +#define BNEP_FRAME_COMPRESSED_ETHERNET 0x02 +#define BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY 0x03 +#define BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY 0x04 + +/* BNEP filter control message types +*/ +#define BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD 0x00 +#define BNEP_SETUP_CONNECTION_REQUEST_MSG 0x01 +#define BNEP_SETUP_CONNECTION_RESPONSE_MSG 0x02 +#define BNEP_FILTER_NET_TYPE_SET_MSG 0x03 +#define BNEP_FILTER_NET_TYPE_RESPONSE_MSG 0x04 +#define BNEP_FILTER_MULTI_ADDR_SET_MSG 0x05 +#define BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG 0x06 + +/* BNEP header extension types +*/ +#define BNEP_EXTENSION_FILTER_CONTROL 0x00 + +/* BNEP Setup Connection response codes +*/ +#define BNEP_SETUP_CONN_OK 0x0000 +#define BNEP_SETUP_INVALID_DEST_UUID 0x0001 +#define BNEP_SETUP_INVALID_SRC_UUID 0x0002 +#define BNEP_SETUP_INVALID_UUID_SIZE 0x0003 +#define BNEP_SETUP_CONN_NOT_ALLOWED 0x0004 + +/* BNEP filter control response codes +*/ +#define BNEP_FILTER_CRL_OK 0x0000 +#define BNEP_FILTER_CRL_UNSUPPORTED 0x0001 +#define BNEP_FILTER_CRL_BAD_RANGE 0x0002 +#define BNEP_FILTER_CRL_MAX_REACHED 0x0003 +#define BNEP_FILTER_CRL_SECURITY_ERR 0x0004 + +/* 802.1p protocol packet will have actual protocol field in side the payload */ +#define BNEP_802_1_P_PROTOCOL 0x8100 + +/* Timeout definitions in seconds (btu_start_timer expects seconds). */ +/* Connection related timeout */ +#define BNEP_CONN_TIMEOUT_SEC 20 +/* host response timeout */ +#define BNEP_HOST_TIMEOUT_SEC 200 +#define BNEP_FILTER_SET_TIMEOUT_SEC 10 + +/* Define the Out-Flow default values. */ +#define BNEP_OFLOW_QOS_FLAG 0 +#define BNEP_OFLOW_SERV_TYPE 0 +#define BNEP_OFLOW_TOKEN_RATE 0 +#define BNEP_OFLOW_TOKEN_BUCKET_SIZE 0 +#define BNEP_OFLOW_PEAK_BANDWIDTH 0 +#define BNEP_OFLOW_LATENCY 0 +#define BNEP_OFLOW_DELAY_VARIATION 0 + +/* Define the In-Flow default values. */ +#define BNEP_IFLOW_QOS_FLAG 0 +#define BNEP_IFLOW_SERV_TYPE 0 +#define BNEP_IFLOW_TOKEN_RATE 0 +#define BNEP_IFLOW_TOKEN_BUCKET_SIZE 0 +#define BNEP_IFLOW_PEAK_BANDWIDTH 0 +#define BNEP_IFLOW_LATENCY 0 +#define BNEP_IFLOW_DELAY_VARIATION 0 + +#define BNEP_FLUSH_TO 0xFFFF + +#define BNEP_MAX_RETRANSMITS 3 + +/* Define the BNEP Connection Control Block +*/ +typedef struct { +#define BNEP_STATE_IDLE 0 +#define BNEP_STATE_CONN_START 1 +#define BNEP_STATE_CFG_SETUP 2 +#define BNEP_STATE_CONN_SETUP 3 +#define BNEP_STATE_SEC_CHECKING 4 +#define BNEP_STATE_SETUP_RCVD 5 +#define BNEP_STATE_CONNECTED 6 + UINT8 con_state; + +#define BNEP_FLAGS_IS_ORIG 0x01 +#define BNEP_FLAGS_HIS_CFG_DONE 0x02 +#define BNEP_FLAGS_MY_CFG_DONE 0x04 +#define BNEP_FLAGS_L2CAP_CONGESTED 0x08 +#define BNEP_FLAGS_FILTER_RESP_PEND 0x10 +#define BNEP_FLAGS_MULTI_RESP_PEND 0x20 +#define BNEP_FLAGS_SETUP_RCVD 0x40 +#define BNEP_FLAGS_CONN_COMPLETED 0x80 + UINT8 con_flags; + BT_HDR *p_pending_data; + + UINT16 l2cap_cid; + BD_ADDR rem_bda; + UINT16 rem_mtu_size; + TIMER_LIST_ENT conn_timer; + fixed_queue_t *xmit_q; + + UINT16 sent_num_filters; + UINT16 sent_prot_filter_start[BNEP_MAX_PROT_FILTERS]; + UINT16 sent_prot_filter_end[BNEP_MAX_PROT_FILTERS]; + + UINT16 sent_mcast_filters; + BD_ADDR sent_mcast_filter_start[BNEP_MAX_MULTI_FILTERS]; + BD_ADDR sent_mcast_filter_end[BNEP_MAX_MULTI_FILTERS]; + + UINT16 rcvd_num_filters; + UINT16 rcvd_prot_filter_start[BNEP_MAX_PROT_FILTERS]; + UINT16 rcvd_prot_filter_end[BNEP_MAX_PROT_FILTERS]; + + UINT16 rcvd_mcast_filters; + BD_ADDR rcvd_mcast_filter_start[BNEP_MAX_MULTI_FILTERS]; + BD_ADDR rcvd_mcast_filter_end[BNEP_MAX_MULTI_FILTERS]; + + UINT16 bad_pkts_rcvd; + UINT8 re_transmits; + UINT16 handle; + UINT32 sec_gen; /* invalidated on release; detects stale BTM callbacks */ + tBT_UUID prv_src_uuid; + tBT_UUID prv_dst_uuid; + tBT_UUID src_uuid; + tBT_UUID dst_uuid; + +} tBNEP_CONN; + +/* The main BNEP control block +*/ +typedef struct { + tL2CAP_CFG_INFO l2cap_my_cfg; /* My L2CAP config */ + tBNEP_CONN bcb[BNEP_MAX_CONNECTIONS]; + + tBNEP_CONNECT_IND_CB *p_conn_ind_cb; + tBNEP_CONN_STATE_CB *p_conn_state_cb; + tBNEP_DATA_IND_CB *p_data_ind_cb; + tBNEP_DATA_BUF_CB *p_data_buf_cb; + tBNEP_FILTER_IND_CB *p_filter_ind_cb; + tBNEP_MFILTER_IND_CB *p_mfilter_ind_cb; + tBNEP_TX_DATA_FLOW_CB *p_tx_data_flow_cb; + + tL2CAP_APPL_INFO reg_info; + + BOOLEAN profile_registered; /* TRUE when we got our BD addr */ + UINT8 trace_level; + +} tBNEP_CB; + +/* Global BNEP data +*/ +extern tBNEP_CB bnep_cb; + +/* Functions provided by bnep_main.c +*/ +extern tBNEP_RESULT bnep_register_with_l2cap(void); +extern void bnep_disconnect(tBNEP_CONN *p_bcb, UINT16 reason); +extern tBNEP_CONN *bnep_conn_originate(UINT8 *p_bd_addr); +extern void bnep_conn_timer_timeout(void *data); +extern void bnep_connected(tBNEP_CONN *p_bcb); + +/* Functions provided by bnep_utils.c +*/ +extern tBNEP_CONN *bnepu_find_bcb_by_cid(UINT16 cid); +extern tBNEP_CONN *bnepu_find_bcb_by_bd_addr(BD_ADDR p_bda); +extern tBNEP_CONN *bnepu_allocate_bcb(BD_ADDR p_rem_bda); +extern void bnepu_release_bcb(tBNEP_CONN *p_bcb); +extern void bnepu_send_peer_our_filters(tBNEP_CONN *p_bcb); +extern void bnepu_send_peer_our_multi_filters(tBNEP_CONN *p_bcb); +extern BOOLEAN bnepu_does_dest_support_prot(tBNEP_CONN *p_bcb, UINT16 protocol); +extern void bnepu_build_bnep_hdr(tBNEP_CONN *p_bcb, BT_HDR *p_buf, + UINT16 protocol, + BD_ADDR p_src_addr, + BD_ADDR p_dest_addr, BOOLEAN ext_bit); +extern void test_bnepu_build_bnep_hdr(tBNEP_CONN *p_bcb, BT_HDR *p_buf, + UINT16 protocol, UINT8 *p_src_addr, + UINT8 *p_dest_addr, UINT8 type); + +extern tBNEP_CONN *bnepu_get_route_to_dest(UINT8 *p_bda); +extern void bnepu_check_send_packet(tBNEP_CONN *p_bcb, BT_HDR *p_buf); +extern void bnep_send_command_not_understood(tBNEP_CONN *p_bcb, + UINT8 cmd_code); +extern void bnepu_process_peer_filter_set(tBNEP_CONN *p_bcb, UINT8 *p_filters, + UINT16 len); +extern void bnepu_process_peer_filter_rsp(tBNEP_CONN *p_bcb, UINT8 *p_data); +extern void bnepu_process_multicast_filter_rsp(tBNEP_CONN *p_bcb, + UINT8 *p_data); +extern void bnep_send_conn_req(tBNEP_CONN *p_bcb); +extern void bnep_send_conn_responce(tBNEP_CONN *p_bcb, UINT16 resp_code); +extern void bnep_process_setup_conn_req(tBNEP_CONN *p_bcb, UINT8 *p_setup, + UINT8 len); +extern void bnep_process_setup_conn_responce(tBNEP_CONN *p_bcb, + UINT8 *p_setup); +extern UINT8 *bnep_process_control_packet(tBNEP_CONN *p_bcb, UINT8 *p, + UINT16 *len, BOOLEAN is_ext); +extern void bnep_sec_check_complete(BD_ADDR bd_addr, + tBT_TRANSPORT transport, void *p_ref_data, + UINT8 result); +extern tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN *p_bcb, + BD_ADDR p_dest_addr, + UINT16 protocol, + BOOLEAN fw_ext_present, + UINT8 *p_data, UINT16 data_len); +extern UINT32 bnep_get_uuid32(tBT_UUID *src_uuid); + +#endif /* (BNEP_INCLUDED == TRUE) */ + +#endif diff --git a/components/bt/host/bluedroid/stack/btu/btu_task.c b/components/bt/host/bluedroid/stack/btu/btu_task.c index 4f929f6838a..3468a0f25e5 100644 --- a/components/bt/host/bluedroid/stack/btu/btu_task.c +++ b/components/bt/host/bluedroid/stack/btu/btu_task.c @@ -538,7 +538,7 @@ static void btu_general_alarm_process(void *param) #endif #if ((defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE)) case BTU_TTYPE_BNEP: - bnep_process_timeout(p_tle); + bnep_conn_timer_timeout((void *)p_tle->param); break; #endif diff --git a/components/bt/host/bluedroid/stack/include/stack/bnep_api.h b/components/bt/host/bluedroid/stack/include/stack/bnep_api.h new file mode 100644 index 00000000000..279704e047c --- /dev/null +++ b/components/bt/host/bluedroid/stack/include/stack/bnep_api.h @@ -0,0 +1,455 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This interface file contains the interface to the Bluetooth Network + * Encapsilation Protocol (BNEP). + * + ******************************************************************************/ +#ifndef BNEP_API_H +#define BNEP_API_H + +#include "common/bt_target.h" + +#if (BNEP_INCLUDED == TRUE) + +#include "stack/l2c_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************** + * Constants + ****************************************************************************/ + +/* Define the minimum offset needed in a buffer for + * sending BNEP packets. Note, we are currently not sending + * extension headers, but may in the future, so allow + * space for them. Callers of BNEP_WriteBuf must leave at + * least this much headroom (p_buf->offset >= BNEP_MINIMUM_OFFSET). + */ +#define BNEP_MINIMUM_OFFSET (15 + L2CAP_MIN_OFFSET) +#define BNEP_INVALID_HANDLE 0xFFFF + +/***************************************************************************** + * Type Definitions + ****************************************************************************/ + +/* Define the result codes from BNEP */ +enum { + BNEP_SUCCESS, /* Success */ + BNEP_CONN_DISCONNECTED, /* Connection terminated */ + BNEP_NO_RESOURCES, /* No resources */ + BNEP_MTU_EXCEDED, /* Attempt to write long data */ + BNEP_INVALID_OFFSET, /* Insufficient offset in buffer */ + BNEP_CONN_FAILED, /* Connection failed */ + BNEP_CONN_FAILED_CFG, /* Connection failed cos of config */ + BNEP_CONN_FAILED_SRC_UUID, /* Connection failed wrong source UUID */ + BNEP_CONN_FAILED_DST_UUID, /* Connection failed wrong destination UUID */ + BNEP_CONN_FAILED_UUID_SIZE, /* Connection failed wrong size UUID */ + BNEP_Q_SIZE_EXCEEDED, /* Too many buffers to dest */ + BNEP_TOO_MANY_FILTERS, /* Too many local filters specified */ + BNEP_SET_FILTER_FAIL, /* Set Filter failed */ + BNEP_WRONG_HANDLE, /* Wrong handle for the connection */ + BNEP_WRONG_STATE, /* Connection is in wrong state */ + BNEP_SECURITY_FAIL, /* Failed because of security */ + BNEP_IGNORE_CMD, /* To ignore the rcvd command */ + BNEP_TX_FLOW_ON, /* tx data flow enabled */ + BNEP_TX_FLOW_OFF /* tx data flow disabled */ + +}; +typedef UINT8 tBNEP_RESULT; + +/*************************** + * Callback Functions + ***************************/ + +/* Connection state change callback prototype. Parameters are + * Connection handle + * BD Address of remote + * Connection state change result + * BNEP_SUCCESS indicates connection is success + * All values are used to indicate the reason for failure + * Flag to indicate if it is just a role change + */ +typedef void(tBNEP_CONN_STATE_CB)(UINT16 handle, BD_ADDR rem_bda, + tBNEP_RESULT result, BOOLEAN is_role_change); + +/* Connection indication callback prototype. Parameters are + * BD Address of remote, remote UUID and local UUID + * and flag to indicate role change and handle to the connection + * When BNEP calls this function profile should + * use BNEP_ConnectResp call to accept or reject the request + */ +typedef void(tBNEP_CONNECT_IND_CB)(UINT16 handle, BD_ADDR bd_addr, + tBT_UUID *remote_uuid, tBT_UUID *local_uuid, + BOOLEAN is_role_change); + +/* Data buffer received indication callback prototype. Parameters are + * Handle to the connection + * Source BD/Ethernet Address + * Dest BD/Ethernet address + * Protocol + * Pointer to the buffer + * Flag to indicate whether extension headers to be forwarded are + * present + */ +typedef void(tBNEP_DATA_BUF_CB)(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN fw_ext_present); + +/* Data received indication callback prototype. Parameters are + * Handle to the connection + * Source BD/Ethernet Address + * Dest BD/Ethernet address + * Protocol + * Pointer to the beginning of the data + * Length of data + * Flag to indicate whether extension headers to be forwarded are + * present + */ +typedef void(tBNEP_DATA_IND_CB)(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + UINT8 *p_data, UINT16 len, + BOOLEAN fw_ext_present); + +/* Flow control callback for TX data. Parameters are + * Handle to the connection + * Event flow status + */ +typedef void(tBNEP_TX_DATA_FLOW_CB)(UINT16 handle, tBNEP_RESULT event); + +/* Filters received indication callback prototype. Parameters are + * Handle to the connection + * true if the cb is called for indication + * Ignore this if it is indication, otherwise it is the result + * for the filter set operation performed by the local + * device + * Number of protocol filters present + * Pointer to the filters start. Filters are present in pairs + * of start of the range and end of the range. + * They will be present in big endian order. First + * two bytes will be starting of the first range and + * next two bytes will be ending of the range. + */ +typedef void(tBNEP_FILTER_IND_CB)(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_filters, + UINT8 *p_filters); + +/* Multicast Filters received indication callback prototype. Parameters are + * Handle to the connection + * true if the cb is called for indication + * Ignore this if it is indication, otherwise it is the result + * for the filter set operation performed by the local + * device + * Number of multicast filters present + * Pointer to the filters start. Filters are present in pairs + * of start of the range and end of the range. + * First six bytes will be starting of the first range and + * next six bytes will be ending of the range. + */ +typedef void(tBNEP_MFILTER_IND_CB)(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_mfilters, + UINT8 *p_mfilters); + +/* This is the structure used by profile to register with BNEP */ +typedef struct { + tBNEP_CONNECT_IND_CB *p_conn_ind_cb; /* To indicate the conn request */ + tBNEP_CONN_STATE_CB *p_conn_state_cb; /* To indicate conn state change */ + tBNEP_DATA_IND_CB *p_data_ind_cb; /* To pass the data received */ + tBNEP_DATA_BUF_CB *p_data_buf_cb; /* To pass the data buffer received */ + tBNEP_TX_DATA_FLOW_CB *p_tx_data_flow_cb; /* data flow callback */ + tBNEP_FILTER_IND_CB * + p_filter_ind_cb; /* To indicate that peer set protocol filters */ + tBNEP_MFILTER_IND_CB * + p_mfilter_ind_cb; /* To indicate that peer set mcast filters */ + +} tBNEP_REGISTER; + +/* This is the structure used by profile to get the status of BNEP */ +#define BNEP_STATUS_FAILED 0 +#define BNEP_STATUS_CONNECTED 1 + +typedef struct { + UINT8 con_status; + + UINT16 l2cap_cid; + BD_ADDR rem_bda; + UINT16 rem_mtu_size; + UINT16 xmit_q_depth; + + UINT16 sent_num_filters; + UINT16 sent_mcast_filters; + UINT16 rcvd_num_filters; + UINT16 rcvd_mcast_filters; + tBT_UUID src_uuid; + tBT_UUID dst_uuid; + +} tBNEP_STATUS; + +/***************************************************************************** + * External Function Declarations + ****************************************************************************/ +/******************************************************************************* + * + * Function BNEP_Register + * + * Description This function is called by the upper layer to register + * its callbacks with BNEP + * + * Parameters: p_reg_info - contains all callback function pointers + * + * + * Returns BNEP_SUCCESS if registered successfully + * BNEP_FAILURE if connection state callback is missing + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_Register(tBNEP_REGISTER *p_reg_info); + +/******************************************************************************* + * + * Function BNEP_Deregister + * + * Description This function is called by the upper layer to de-register + * its callbacks. + * + * Parameters: void + * + * + * Returns void + * + ******************************************************************************/ +extern void BNEP_Deregister(void); + +/******************************************************************************* + * + * Function BNEP_Connect + * + * Description This function creates a BNEP connection to a remote + * device. + * + * Parameters: p_rem_addr - BD_ADDR of the peer + * src_uuid - source uuid for the connection + * dst_uuid - destination uuid for the connection + * p_handle - pointer to return the handle for the connection + * + * Returns BNEP_SUCCESS if connection started + * BNEP_NO_RESOURCES if no resources + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_Connect(BD_ADDR p_rem_bda, + tBT_UUID *src_uuid, tBT_UUID *dst_uuid, + UINT16 *p_handle); + +/******************************************************************************* + * + * Function BNEP_ConnectResp + * + * Description This function is called in response to connection indication + * + * + * Parameters: handle - handle given in the connection indication + * resp - response for the connection indication + * + * Returns BNEP_SUCCESS if connection started + * BNEP_WRONG_HANDLE if the connection is not found + * BNEP_WRONG_STATE if the response is not expected + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_ConnectResp(UINT16 handle, tBNEP_RESULT resp); + +/******************************************************************************* + * + * Function BNEP_Disconnect + * + * Description This function is called to close the specified connection. + * + * Parameters: handle - handle of the connection + * + * Returns BNEP_SUCCESS if connection is disconnected + * BNEP_WRONG_HANDLE if no connection is not found + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_Disconnect(UINT16 handle); + +/******************************************************************************* + * + * Function BNEP_WriteBuf + * + * Description This function sends data in a BT_HDR buffer on a BNEP + * connection. The buffer must leave BNEP_MINIMUM_OFFSET bytes + * of headroom (p_buf->offset >= BNEP_MINIMUM_OFFSET); payload + * will not be shifted in place. + * + * Parameters: handle - handle of the connection to write + * p_dest_addr - BD_ADDR/Ethernet addr of the destination + * p_buf - pointer to address of buffer with data + * protocol - protocol type of the packet + * p_src_addr - (optional) BD_ADDR/ethernet address of the + * source (should be NULL if it is the local BD + * Addr) + * fw_ext_present - forwarded extensions present + * + * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid + * BNEP_WRONG_STATE - if connection is not active + * BNEP_MTU_EXCEDED - If the data length is greater + * than MTU + * BNEP_INVALID_OFFSET - If buffer headroom is insufficient + * BNEP_IGNORE_CMD - If the packet is filtered out + * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full + * BNEP_SUCCESS - If written successfully + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_WriteBuf(UINT16 handle, + BD_ADDR p_dest_addr, + BT_HDR *p_buf, + UINT16 protocol, + BD_ADDR p_src_addr, + BOOLEAN fw_ext_present); + +/******************************************************************************* + * + * Function BNEP_Write + * + * Description This function sends data over a BNEP connection + * + * Parameters: handle - handle of the connection to write + * p_dest_addr - BD_ADDR/Ethernet addr of the destination + * p_data - pointer to data start + * protocol - protocol type of the packet + * p_src_addr - (optional) BD_ADDR/ethernet address of the + * source (should be NULL if it is the local BD + * Addr) + * fw_ext_present - forwarded extensions present + * + * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid + * BNEP_WRONG_STATE - if connection is not active + * BNEP_MTU_EXCEDED - If the data length is greater than + * the MTU + * BNEP_IGNORE_CMD - If the packet is filtered out + * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full + * BNEP_NO_RESOURCES - If not able to allocate a buffer + * BNEP_SUCCESS - If written successfully + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_Write(UINT16 handle, BD_ADDR p_dest_addr, + UINT8 *p_data, UINT16 len, UINT16 protocol, + BD_ADDR p_src_addr, + BOOLEAN fw_ext_present); + +/******************************************************************************* + * + * Function BNEP_SetProtocolFilters + * + * Description This function sets the protocol filters on peer device + * + * Parameters: handle - Handle for the connection + * num_filters - total number of filter ranges + * p_start_array - Array of beginnings of all protocol ranges + * p_end_array - Array of ends of all protocol ranges + * + * Returns BNEP_WRONG_HANDLE - if the connection handle is + * not valid + * BNEP_SET_FILTER_FAIL - if the connection is in the + * wrong state + * BNEP_TOO_MANY_FILTERS - if too many filters + * BNEP_SUCCESS - if request sent successfully + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_SetProtocolFilters(UINT16 handle, + UINT16 num_filters, + UINT16 *p_start_array, + UINT16 *p_end_array); + +/******************************************************************************* + * + * Function BNEP_SetMulticastFilters + * + * Description This function sets the filters for multicast addresses for + * BNEP. + * + * Parameters: handle - Handle for the connection + * num_filters - total number of filter ranges + * p_start_array - Pointer to sequence of beginnings of all + * multicast address ranges + * p_end_array - Pointer to sequence of ends of all + * multicast address ranges + * + * Returns BNEP_WRONG_HANDLE - if the connection handle is + * not valid + * BNEP_SET_FILTER_FAIL - if the connection is in the + * wrong state + * BNEP_TOO_MANY_FILTERS - if too many filters + * BNEP_SUCCESS - if request sent successfully + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_SetMulticastFilters(UINT16 handle, + UINT16 num_filters, + UINT8 *p_start_array, + UINT8 *p_end_array); + +/******************************************************************************* + * + * Function BNEP_SetTraceLevel + * + * Description This function sets the trace level for BNEP. If called with + * a value of 0xFF, it simply reads the current trace level. + * + * Returns the new (current) trace level + * + ******************************************************************************/ +extern UINT8 BNEP_SetTraceLevel(UINT8 new_level); + +/******************************************************************************* + * + * Function BNEP_Init + * + * Description This function initializes the BNEP unit. It should be called + * before accessing any other APIs to initialize the control + * block + * + * Returns void + * + ******************************************************************************/ +extern void BNEP_Init(void); + +/******************************************************************************* + * + * Function BNEP_GetStatus + * + * Description This function gets the status information for BNEP + * connection + * + * Returns BNEP_SUCCESS - if the status is available + * BNEP_NO_RESOURCES - if no structure is passed for + * output + * BNEP_WRONG_HANDLE - if the handle is invalid + * BNEP_WRONG_STATE - if not in connected state + * + ******************************************************************************/ +extern tBNEP_RESULT BNEP_GetStatus(UINT16 handle, tBNEP_STATUS *p_status); + +#ifdef __cplusplus +} +#endif + +#endif /* (BNEP_INCLUDED == TRUE) */ + +#endif diff --git a/components/bt/host/bluedroid/stack/include/stack/pan_api.h b/components/bt/host/bluedroid/stack/include/stack/pan_api.h new file mode 100644 index 00000000000..af0a9ba6763 --- /dev/null +++ b/components/bt/host/bluedroid/stack/include/stack/pan_api.h @@ -0,0 +1,449 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * this file contains the PAN API definitions + * + ******************************************************************************/ +#ifndef PAN_API_H +#define PAN_API_H + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include "stack/bnep_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************** + * Constants + ****************************************************************************/ + +/* Define the minimum offset needed in a GKI buffer for + * sending PAN packets. Note, we are currently not sending + * extension headers, but may in the future, so allow + * space for them +*/ +#define PAN_MINIMUM_OFFSET BNEP_MINIMUM_OFFSET + +/* Maximum Ethernet payload length for PAN write into a PAN_BUF_SIZE buffer. + * Data is copied at (sizeof(BT_HDR) + PAN_MINIMUM_OFFSET) within the buffer. + */ +#define PAN_MAX_WRITE_LEN (PAN_BUF_SIZE - sizeof(BT_HDR) - PAN_MINIMUM_OFFSET) + +/* + * The handle is passed from BNEP to PAN. The same handle is used + * between PAN and application as well +*/ +#define PAN_INVALID_HANDLE BNEP_INVALID_HANDLE + +/* Bit map for PAN roles */ +#define PAN_ROLE_CLIENT 0x01 /* PANU role */ +#define PAN_ROLE_GN_SERVER 0x02 /* GN role */ +#define PAN_ROLE_NAP_SERVER 0x04 /* NAP role */ + +/* Bitmap to indicate the usage of the Data */ +#define PAN_DATA_TO_HOST 0x01 +#define PAN_DATA_TO_LAN 0x02 + +/***************************************************************************** + * Type Definitions + ****************************************************************************/ + +/* Define the result codes from PAN */ +enum { + PAN_SUCCESS, /* Success */ + PAN_DISCONNECTED = BNEP_CONN_DISCONNECTED, /* Connection terminated */ + PAN_CONN_FAILED = BNEP_CONN_FAILED, /* Connection failed */ + PAN_NO_RESOURCES = BNEP_NO_RESOURCES, /* No resources */ + PAN_MTU_EXCEDED = BNEP_MTU_EXCEDED, /* Attempt to write long data */ + PAN_INVALID_OFFSET = + BNEP_INVALID_OFFSET, /* Insufficient offset in GKI buffer */ + PAN_CONN_FAILED_CFG = + BNEP_CONN_FAILED_CFG, /* Connection failed cos of config */ + PAN_INVALID_SRC_ROLE = + BNEP_CONN_FAILED_SRC_UUID, /* Connection failed wrong source UUID */ + PAN_INVALID_DST_ROLE = + BNEP_CONN_FAILED_DST_UUID, /* Connection failed wrong destination UUID */ + PAN_CONN_FAILED_UUID_SIZE = + BNEP_CONN_FAILED_UUID_SIZE, /* Connection failed wrong size UUID */ + PAN_Q_SIZE_EXCEEDED = BNEP_Q_SIZE_EXCEEDED, /* Too many buffers to dest */ + PAN_TOO_MANY_FILTERS = + BNEP_TOO_MANY_FILTERS, /* Too many local filters specified */ + PAN_SET_FILTER_FAIL = BNEP_SET_FILTER_FAIL, /* Set Filter failed */ + PAN_WRONG_HANDLE = BNEP_WRONG_HANDLE, /* Wrong handle for the connection */ + PAN_WRONG_STATE = BNEP_WRONG_STATE, /* Connection is in wrong state */ + PAN_SECURITY_FAIL = BNEP_SECURITY_FAIL, /* Failed because of security */ + PAN_IGNORE_CMD = BNEP_IGNORE_CMD, /* To ignore the rcvd command */ + PAN_TX_FLOW_ON = BNEP_TX_FLOW_ON, /* tx data flow enabled */ + PAN_TX_FLOW_OFF = BNEP_TX_FLOW_OFF, /* tx data flow disabled */ + PAN_FAILURE /* Failure */ + +}; +typedef UINT8 tPAN_RESULT; + +/***************************************************************** + * Callback Function Prototypes + ****************************************************************/ + +/* This is call back function used to report connection status + * to the application. The second parameter true means + * to create the bridge and false means to remove it. +*/ +typedef void (tPAN_CONN_STATE_CB)(UINT16 handle, BD_ADDR bd_addr, + tPAN_RESULT state, BOOLEAN is_role_change, + UINT8 src_role, UINT8 dst_role); + +/* This is call back function used to create bridge for the + * Connected device. The parameter "state" indicates + * whether to create the bridge or remove it. true means + * to create the bridge and false means to remove it. +*/ +typedef void (tPAN_BRIDGE_REQ_CB)(BD_ADDR bd_addr, BOOLEAN state); + +/* Data received indication callback prototype. Parameters are + * Source BD/Ethernet Address + * Dest BD/Ethernet address + * Protocol + * Address of buffer (or data if non-GKI) + * Length of data (non-GKI) + * ext is flag to indicate whether it has aby extension headers + * Flag used to indicate to forward on LAN + * false - Use it for internal stack + * true - Send it across the ethernet as well +*/ +typedef void (tPAN_DATA_IND_CB)(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN ext, + BOOLEAN forward); + +/* Data buffer received indication callback prototype. Parameters are + * Source BD/Ethernet Address + * Dest BD/Ethernet address + * Protocol + * pointer to the data buffer + * ext is flag to indicate whether it has aby extension headers + * Flag used to indicate to forward on LAN + * false - Use it for internal stack + * true - Send it across the ethernet as well +*/ +typedef void (tPAN_DATA_BUF_IND_CB)(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext, BOOLEAN forward); + +/* Flow control callback for TX data. Parameters are + * Handle to the connection + * Event flow status +*/ +typedef void (tPAN_TX_DATA_FLOW_CB)(UINT16 handle, tPAN_RESULT event); + +/* Filters received indication callback prototype. Parameters are + * Handle to the connection + * true if the cb is called for indication + * Ignore this if it is indication, otherwise it is the result + * for the filter set operation performed by the local + * device + * Number of protocol filters present + * Pointer to the filters start. Filters are present in pairs + * of start of the range and end of the range. + * They will be present in big endian order. First + * two bytes will be starting of the first range and + * next two bytes will be ending of the range. +*/ +typedef void (tPAN_FILTER_IND_CB)(UINT16 handle, BOOLEAN indication, + tPAN_RESULT result, UINT16 num_filters, + UINT8 *p_filters); + +/* Multicast Filters received indication callback prototype. Parameters are + * Handle to the connection + * true if the cb is called for indication + * Ignore this if it is indication, otherwise it is the result + * for the filter set operation performed by the local + * device + * Number of multicast filters present + * Pointer to the filters start. Filters are present in pairs + * of start of the range and end of the range. + * First six bytes will be starting of the first range and + * next six bytes will be ending of the range. +*/ +typedef void (tPAN_MFILTER_IND_CB)(UINT16 handle, BOOLEAN indication, + tPAN_RESULT result, UINT16 num_mfilters, + UINT8 *p_mfilters); + +/* This structure is used to register with PAN profile + * It is passed as a parameter to PAN_Register call. +*/ +typedef struct { + tPAN_CONN_STATE_CB *pan_conn_state_cb; /* Connection state callback */ + tPAN_BRIDGE_REQ_CB *pan_bridge_req_cb; /* Bridge request callback */ + tPAN_DATA_IND_CB *pan_data_ind_cb; /* Data indication callback */ + tPAN_DATA_BUF_IND_CB * + pan_data_buf_ind_cb; /* Data buffer indication callback */ + tPAN_FILTER_IND_CB * + pan_pfilt_ind_cb; /* protocol filter indication callback */ + tPAN_MFILTER_IND_CB * + pan_mfilt_ind_cb; /* multicast filter indication callback */ + tPAN_TX_DATA_FLOW_CB *pan_tx_data_flow_cb; /* data flow callback */ + char *user_service_name; /* Service name for PANU role */ + char *gn_service_name; /* Service name for GN role */ + char *nap_service_name; /* Service name for NAP role */ + +} tPAN_REGISTER; + +/***************************************************************************** + * External Function Declarations + ****************************************************************************/ + +/******************************************************************************* + * + * Function PAN_Register + * + * Description This function is called by the application to register + * its callbacks with PAN profile. The application then + * should set the PAN role explicitly. + * + * Parameters: p_register - contains all callback function pointers + * + * + * Returns none + * + ******************************************************************************/ +extern void PAN_Register(tPAN_REGISTER *p_register); + +/******************************************************************************* + * + * Function PAN_Deregister + * + * Description This function is called by the application to de-register + * its callbacks with PAN profile. This will make the PAN to + * become inactive. This will deregister PAN services from SDP + * and close all active connections + * + * Returns none + * + ******************************************************************************/ +extern void PAN_Deregister(void); + +/******************************************************************************* + * + * Function PAN_SetRole + * + * Description This function is called by the application to set the PAN + * profile role. This should be called after PAN_Register. + * This can be called any time to change the PAN role + * + * Parameters: role - is bit map of roles to be active + * PAN_ROLE_CLIENT is for PANU role + * PAN_ROLE_GN_SERVER is for GN role + * PAN_ROLE_NAP_SERVER is for NAP role + * sec_mask - Security mask for different roles + * It is array of UINT8. The bytes + * represent the security for roles PANU, + * GN and NAP in order + * + * p_user_name - Service name for PANU role + * p_gn_name - Service name for GN role + * p_nap_name - Service name for NAP role + * Can be NULL if user wants it to be default + * + * Returns PAN_SUCCESS - if the role is set successfully + * PAN_FAILURE - if the role is not valid + * + ******************************************************************************/ +extern tPAN_RESULT PAN_SetRole(UINT8 role, UINT8 *sec_mask, + const char *p_user_name, const char *p_gn_name, + const char *p_nap_name); + +/******************************************************************************* + * + * Function PAN_Connect + * + * Description This function is called by the application to initiate a + * connection to the remote device + * + * Parameters: rem_bda - BD Addr of the remote device + * src_role - Role of the local device for the connection + * dst_role - Role of the remote device for the connection + * PAN_ROLE_CLIENT is for PANU role + * PAN_ROLE_GN_SERVER is for GN role + * PAN_ROLE_NAP_SERVER is for NAP role + * *handle - Pointer for returning Handle to the connection + * + * Returns PAN_SUCCESS - if the connection is initiated successfully + * PAN_NO_RESOURCES - resources are not sufficient + * PAN_FAILURE - if the connection cannot be initiated + * this can be because of the combination of + * src and dst roles may not be valid or + * allowed at that point of time + * + ******************************************************************************/ +extern tPAN_RESULT PAN_Connect(BD_ADDR rem_bda, UINT8 src_role, + UINT8 dst_role, UINT16 *handle); + +/******************************************************************************* + * + * Function PAN_Disconnect + * + * Description This is used to disconnect the connection + * + * Parameters: handle - handle for the connection + * + * Returns PAN_SUCCESS - if the connection is closed successfully + * PAN_FAILURE - if the connection is not found or + * there is an error in disconnecting + * + ******************************************************************************/ +extern tPAN_RESULT PAN_Disconnect(UINT16 handle); + +/******************************************************************************* + * + * Function PAN_Write + * + * Description This sends data over the PAN connections. If this is called + * on GN or NAP side and the packet is multicast or broadcast + * it will be sent on all the links. Otherwise the correct link + * is found based on the destination address and forwarded on + * it. If the return value is not PAN_SUCCESS the application + * should take care of releasing the message buffer + * + * Parameters: dst - MAC or BD Addr of the destination device + * src - MAC or BD Addr of the source who sent this packet + * protocol - protocol of the ethernet packet like IP or ARP + * p_data - pointer to the data + * len - length of the data + * ext - to indicate that extension headers present + * + * Returns PAN_SUCCESS - if the data is sent successfully + * PAN_MTU_EXCEDED - if len exceeds PAN_MAX_WRITE_LEN + * PAN_NO_RESOURCES - if buffer allocation fails + * PAN_FAILURE - if the connection is not found or + * there is an error in sending data + * + ******************************************************************************/ +extern tPAN_RESULT PAN_Write(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN ext); + +/******************************************************************************* + * + * Function PAN_WriteBuf + * + * Description This sends data over the PAN connections. If this is called + * on GN or NAP side and the packet is multicast or broadcast + * it will be sent on all the links. Otherwise the correct link + * is found based on the destination address and forwarded on + * it. PAN_WriteBuf always takes ownership of p_buf: the buffer + * is either freed or queued by this function (or by + * BNEP_WriteBuf) regardless of the return value. The caller + * must not access or free p_buf after the call. p_buf->offset + * must be at least PAN_MINIMUM_OFFSET. + * + * Parameters: dst - MAC or BD Addr of the destination device + * src - MAC or BD Addr of the source who sent this packet + * protocol - protocol of the ethernet packet like IP or ARP + * p_buf - pointer to the data buffer + * ext - to indicate that extension headers present + * + * Returns PAN_SUCCESS - if the data is sent successfully + * PAN_FAILURE - if the connection is not found or + * there is an error in sending data + * + ******************************************************************************/ +extern tPAN_RESULT PAN_WriteBuf(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext); + +/******************************************************************************* + * + * Function PAN_SetProtocolFilters + * + * Description This function is used to set protocol filters on the peer + * + * Parameters: handle - handle for the connection + * num_filters - number of protocol filter ranges + * start - array of starting protocol numbers + * end - array of ending protocol numbers + * + * + * Returns PAN_SUCCESS if protocol filters are set successfully + * PAN_FAILURE if connection not found or error in setting + * + ******************************************************************************/ +extern tPAN_RESULT PAN_SetProtocolFilters(UINT16 handle, UINT16 num_filters, + UINT16 *p_start_array, + UINT16 *p_end_array); + +/******************************************************************************* + * + * Function PAN_SetMulticastFilters + * + * Description This function is used to set multicast filters on the peer + * + * Parameters: handle - handle for the connection + * num_filters - number of multicast filter ranges + * p_start_array - Pointer to sequence of beginnings of all + * multicast address ranges + * p_end_array - Pointer to sequence of ends of all + * multicast address ranges + * + * + * Returns PAN_SUCCESS if multicast filters are set successfully + * PAN_FAILURE if connection not found or error in setting + * + ******************************************************************************/ +extern tPAN_RESULT PAN_SetMulticastFilters(UINT16 handle, + UINT16 num_mcast_filters, + UINT8 *p_start_array, + UINT8 *p_end_array); + +/******************************************************************************* + * + * Function PAN_SetTraceLevel + * + * Description This function sets the trace level for PAN. If called with + * a value of 0xFF, it simply reads the current trace level. + * + * Returns the new (current) trace level + * + ******************************************************************************/ +extern UINT8 PAN_SetTraceLevel(UINT8 new_level); + +/******************************************************************************* + * + * Function PAN_Init + * + * Description This function initializes the PAN unit. It should be called + * before accessing any other APIs to initialize the control + * block. + * + * Returns void + * + ******************************************************************************/ +extern void PAN_Init(void); + +#ifdef __cplusplus +} +#endif + +#endif /* (PAN_INCLUDED == TRUE) */ + +#endif /* PAN_API_H */ diff --git a/components/bt/host/bluedroid/stack/pan/include/pan_int.h b/components/bt/host/bluedroid/stack/pan/include/pan_int.h new file mode 100644 index 00000000000..64476f518e3 --- /dev/null +++ b/components/bt/host/bluedroid/stack/pan/include/pan_int.h @@ -0,0 +1,133 @@ +/****************************************************************************** + * + * Copyright (C) 2001-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains internally used PAN definitions + * + ******************************************************************************/ + +#ifndef PAN_INT_H +#define PAN_INT_H + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include "stack/pan_api.h" + +/* + * This role is used to shutdown the profile. Used internally + * Applications should call PAN_Deregister to shutdown the profile + */ +#define PAN_ROLE_INACTIVE 0 + +/* Protocols supported by the host internal stack, are registered with SDP */ +#define PAN_PROTOCOL_IP 0x0800 +#define PAN_PROTOCOL_ARP 0x0806 + +#define PAN_PROFILE_VERSION 0x0100 /* Version 1.00 */ + +/* Define the PAN Connection Control Block + */ +typedef struct { +#define PAN_STATE_IDLE 0 +#define PAN_STATE_CONN_START 1 +#define PAN_STATE_CONNECTED 2 + UINT8 con_state; + +#define PAN_FLAGS_CONN_COMPLETED 0x01 + UINT8 con_flags; + + UINT16 handle; + BD_ADDR rem_bda; + + UINT16 bad_pkts_rcvd; + UINT16 src_uuid; + UINT16 dst_uuid; + UINT16 prv_src_uuid; + UINT16 prv_dst_uuid; + UINT16 ip_addr_known; + UINT32 ip_addr; + +} tPAN_CONN; + +/* The main PAN control block + */ +typedef struct { + UINT8 role; + UINT8 active_role; + UINT8 prv_active_role; + tPAN_CONN pcb[MAX_PAN_CONNS]; + + tPAN_CONN_STATE_CB *pan_conn_state_cb; /* Connection state callback */ + tPAN_BRIDGE_REQ_CB *pan_bridge_req_cb; + tPAN_DATA_IND_CB *pan_data_ind_cb; + tPAN_DATA_BUF_IND_CB *pan_data_buf_ind_cb; + tPAN_FILTER_IND_CB *pan_pfilt_ind_cb; /* protocol filter indication callback */ + tPAN_MFILTER_IND_CB *pan_mfilt_ind_cb; /* multicast filter indication callback */ + tPAN_TX_DATA_FLOW_CB *pan_tx_data_flow_cb; + + char *user_service_name; + char *gn_service_name; + char *nap_service_name; + UINT32 pan_user_sdp_handle; + UINT32 pan_gn_sdp_handle; + UINT32 pan_nap_sdp_handle; + UINT8 num_conns; + UINT8 trace_level; +} tPAN_CB; + +/* Global PAN data + */ +extern tPAN_CB pan_cb; + +/******************************************************************************/ +extern void pan_register_with_bnep(void); +extern void pan_conn_ind_cb(UINT16 handle, BD_ADDR p_bda, + tBT_UUID *remote_uuid, tBT_UUID *local_uuid, + BOOLEAN is_role_change); +extern void pan_connect_state_cb(UINT16 handle, BD_ADDR rem_bda, + tBNEP_RESULT result, BOOLEAN is_role_change); +extern void pan_data_ind_cb(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + UINT8 *p_data, UINT16 len, BOOLEAN fw_ext_present); +extern void pan_data_buf_ind_cb(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext); +extern void pan_tx_data_flow_cb(UINT16 handle, tBNEP_RESULT event); +void pan_proto_filt_ind_cb(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_filters, + UINT8 *p_filters); +void pan_mcast_filt_ind_cb(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_filters, + UINT8 *p_filters); +extern UINT32 pan_register_with_sdp(UINT16 uuid, UINT8 sec_mask, + const char *p_name, const char *p_desc); +extern tPAN_CONN *pan_allocate_pcb(BD_ADDR p_bda, UINT16 handle); +extern tPAN_CONN *pan_get_pcb_by_handle(UINT16 handle); +extern tPAN_CONN *pan_get_pcb_by_addr(BD_ADDR p_bda); +extern void pan_close_all_connections(void); +extern void pan_release_pcb(tPAN_CONN *p_pcb); +extern void pan_dump_status(void); + +/******************************************************************************/ + +#endif /* (PAN_INCLUDED == TRUE) */ + +#endif diff --git a/components/bt/host/bluedroid/stack/pan/pan_api.c b/components/bt/host/bluedroid/stack/pan/pan_api.c new file mode 100644 index 00000000000..1174badda7e --- /dev/null +++ b/components/bt/host/bluedroid/stack/pan/pan_api.c @@ -0,0 +1,784 @@ +/****************************************************************************** + * + * Copyright (C) 1999-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/***************************************************************************** + * + * This file contains main functions to support PAN profile + * commands and events. + * + *****************************************************************************/ + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include "osi/allocator.h" +#include "stack/pan_api.h" +#include +#include "stack/bnep_api.h" +#include "bt_common.h" +#include "stack/bt_types.h" +#include "bta/bta_sys.h" +#include "stack/btm_api.h" +#include "stack/hcidefs.h" +#include "stack/l2c_api.h" +#include "pan_int.h" +#include "stack/sdp_api.h" +#include "stack/sdpdefs.h" + +/******************************************************************************* + * + * Function PAN_Register + * + * Description This function is called by the application to register + * its callbacks with PAN profile. The application then + * should set the PAN role explicitly. + * + * Parameters: p_register - contains all callback function pointers + * + * + * Returns none + * + ******************************************************************************/ +void PAN_Register(tPAN_REGISTER *p_register) +{ + pan_register_with_bnep(); + + if (!p_register) { + return; + } + + pan_cb.pan_conn_state_cb = p_register->pan_conn_state_cb; + pan_cb.pan_bridge_req_cb = p_register->pan_bridge_req_cb; + pan_cb.pan_data_buf_ind_cb = p_register->pan_data_buf_ind_cb; + pan_cb.pan_data_ind_cb = p_register->pan_data_ind_cb; + pan_cb.pan_pfilt_ind_cb = p_register->pan_pfilt_ind_cb; + pan_cb.pan_mfilt_ind_cb = p_register->pan_mfilt_ind_cb; + pan_cb.pan_tx_data_flow_cb = p_register->pan_tx_data_flow_cb; + + return; +} + +/******************************************************************************* + * + * Function PAN_Deregister + * + * Description This function is called by the application to de-register + * its callbacks with PAN profile. This will make the PAN to + * become inactive. This will deregister PAN services from SDP + * and close all active connections + * + * Parameters: none + * + * + * Returns none + * + ******************************************************************************/ +void PAN_Deregister(void) +{ + pan_cb.pan_bridge_req_cb = NULL; + pan_cb.pan_data_buf_ind_cb = NULL; + pan_cb.pan_data_ind_cb = NULL; + pan_cb.pan_conn_state_cb = NULL; + pan_cb.pan_pfilt_ind_cb = NULL; + pan_cb.pan_mfilt_ind_cb = NULL; + pan_cb.pan_tx_data_flow_cb = NULL; + + PAN_SetRole(PAN_ROLE_INACTIVE, NULL, NULL, NULL, NULL); + BNEP_Deregister(); + + return; +} + +/******************************************************************************* + * + * Function PAN_SetRole + * + * Description This function is called by the application to set the PAN + * profile role. This should be called after PAN_Register. + * This can be called any time to change the PAN role + * + * Parameters: role - is bit map of roles to be active + * PAN_ROLE_CLIENT is for PANU role + * PAN_ROLE_GN_SERVER is for GN role + * PAN_ROLE_NAP_SERVER is for NAP role + * sec_mask - Security mask for different roles + * It is array of uint8_t. The bytes + * represent the security for roles PANU, + * GN and NAP in order + * p_user_name - Service name for PANU role + * p_gn_name - Service name for GN role + * p_nap_name - Service name for NAP role + * Can be NULL if user wants the default + * + * Returns PAN_SUCCESS - if the role is set successfully + * PAN_FAILURE - if the role is not valid + * + ******************************************************************************/ +tPAN_RESULT PAN_SetRole(UINT8 role, UINT8 *sec_mask, + const char *p_user_name, const char *p_gn_name, + const char *p_nap_name) +{ + const char *p_desc; + UINT8 security[3] = {PAN_PANU_SECURITY_LEVEL, PAN_GN_SECURITY_LEVEL, + PAN_NAP_SECURITY_LEVEL + }; + UINT8 *p_sec; + + /* If the role is not a valid combination reject it */ + if ((!(role & + (PAN_ROLE_CLIENT | PAN_ROLE_GN_SERVER | PAN_ROLE_NAP_SERVER))) && + role != PAN_ROLE_INACTIVE) { + PAN_TRACE_ERROR("PAN role %d is invalid", role); + return PAN_FAILURE; + } + + /* If the current active role is same as the role being set do nothing */ + if (pan_cb.role == role) { + PAN_TRACE_EVENT("PAN role already was set to: %d", role); + return PAN_SUCCESS; + } + + if (!sec_mask) { + p_sec = security; + } else { + p_sec = sec_mask; + } + + /* Register all the roles with SDP */ + PAN_TRACE_API("PAN_SetRole() called with role 0x%x", role); +#if (PAN_SUPPORTS_ROLE_NAP == TRUE) + if (role & PAN_ROLE_NAP_SERVER) { + /* Check the service name */ + if ((p_nap_name == NULL) || (*p_nap_name == 0)) { + p_nap_name = PAN_NAP_DEFAULT_SERVICE_NAME; + } + + /* Registering for NAP service with SDP */ + p_desc = PAN_NAP_DEFAULT_DESCRIPTION; + + if (pan_cb.pan_nap_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_nap_sdp_handle); + pan_cb.pan_nap_sdp_handle = 0; + } + + pan_cb.pan_nap_sdp_handle = + pan_register_with_sdp(UUID_SERVCLASS_NAP, p_sec[2], p_nap_name, p_desc); + /* Only advertise the UUID when SDP registration succeeds; otherwise + * cleanup (gated on handle != 0) would skip bta_sys_remove_uuid. */ + if (pan_cb.pan_nap_sdp_handle != 0) { + bta_sys_add_uuid(UUID_SERVCLASS_NAP); + } + } + /* If the NAP role is already active and now being cleared delete the record + */ + else if (pan_cb.role & PAN_ROLE_NAP_SERVER) { + if (pan_cb.pan_nap_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_nap_sdp_handle); + pan_cb.pan_nap_sdp_handle = 0; + bta_sys_remove_uuid(UUID_SERVCLASS_NAP); + } + } +#endif + +#if (PAN_SUPPORTS_ROLE_GN == TRUE) + if (role & PAN_ROLE_GN_SERVER) { + /* Check the service name */ + if ((p_gn_name == NULL) || (*p_gn_name == 0)) { + p_gn_name = PAN_GN_DEFAULT_SERVICE_NAME; + } + + /* Registering for GN service with SDP */ + p_desc = PAN_GN_DEFAULT_DESCRIPTION; + + if (pan_cb.pan_gn_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_gn_sdp_handle); + pan_cb.pan_gn_sdp_handle = 0; + } + + pan_cb.pan_gn_sdp_handle = + pan_register_with_sdp(UUID_SERVCLASS_GN, p_sec[1], p_gn_name, p_desc); + if (pan_cb.pan_gn_sdp_handle != 0) { + bta_sys_add_uuid(UUID_SERVCLASS_GN); + } + } + /* If the GN role is already active and now being cleared delete the record */ + else if (pan_cb.role & PAN_ROLE_GN_SERVER) { + if (pan_cb.pan_gn_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_gn_sdp_handle); + pan_cb.pan_gn_sdp_handle = 0; + bta_sys_remove_uuid(UUID_SERVCLASS_GN); + } + } +#endif + +#if (PAN_SUPPORTS_ROLE_PANU == TRUE) + if (role & PAN_ROLE_CLIENT) { + /* Check the service name */ + if ((p_user_name == NULL) || (*p_user_name == 0)) { + p_user_name = PAN_PANU_DEFAULT_SERVICE_NAME; + } + + /* Registering for PANU service with SDP */ + p_desc = PAN_PANU_DEFAULT_DESCRIPTION; + if (pan_cb.pan_user_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_user_sdp_handle); + pan_cb.pan_user_sdp_handle = 0; + } + + pan_cb.pan_user_sdp_handle = pan_register_with_sdp( + UUID_SERVCLASS_PANU, p_sec[0], p_user_name, p_desc); + if (pan_cb.pan_user_sdp_handle != 0) { + bta_sys_add_uuid(UUID_SERVCLASS_PANU); + } + } + /* If the PANU role is already active and now being cleared delete the record + */ + else if (pan_cb.role & PAN_ROLE_CLIENT) { + if (pan_cb.pan_user_sdp_handle != 0) { + SDP_DeleteRecord(pan_cb.pan_user_sdp_handle); + pan_cb.pan_user_sdp_handle = 0; + bta_sys_remove_uuid(UUID_SERVCLASS_PANU); + } + } +#endif + + /* Check if it is a shutdown request */ + if (role == PAN_ROLE_INACTIVE) { + pan_close_all_connections(); + } + + pan_cb.role = role; + PAN_TRACE_EVENT("PAN role set to: %d", role); + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_Connect + * + * Description This function is called by the application to initiate a + * connection to the remote device + * + * Parameters: rem_bda - BD Addr of the remote device + * src_role - Role of the local device for the connection + * dst_role - Role of the remote device for the connection + * PAN_ROLE_CLIENT is for PANU role + * PAN_ROLE_GN_SERVER is for GN role + * PAN_ROLE_NAP_SERVER is for NAP role + * *handle - Pointer for returning Handle to the connection + * + * Returns PAN_SUCCESS - if the connection is initiated + * successfully + * PAN_NO_RESOURCES - resources are not sufficient + * PAN_FAILURE - if the connection cannot be initiated + * this can be because of the combination of + * src and dst roles may not be valid or + * allowed at that point of time + * + ******************************************************************************/ +tPAN_RESULT PAN_Connect(BD_ADDR rem_bda, UINT8 src_role, + UINT8 dst_role, UINT16 *handle) +{ + tPAN_CONN *pcb; + tBNEP_RESULT result; + tBT_UUID src_uuid, dst_uuid; + UINT32 mx_chan_id; + + /* + ** Initialize the handle so that in case of failure return values + ** the profile will not get confused + */ + *handle = BNEP_INVALID_HANDLE; + + /* Check if PAN is active or not */ + if (!(pan_cb.role & src_role)) { + PAN_TRACE_ERROR("PAN is not active for the role %d", src_role); + return PAN_FAILURE; + } + + /* Validate the parameters before proceeding */ + if ((src_role != PAN_ROLE_CLIENT && src_role != PAN_ROLE_GN_SERVER && + src_role != PAN_ROLE_NAP_SERVER) || + (dst_role != PAN_ROLE_CLIENT && dst_role != PAN_ROLE_GN_SERVER && + dst_role != PAN_ROLE_NAP_SERVER)) { + PAN_TRACE_ERROR("Either source %d or destination role %d is invalid", + src_role, dst_role); + return PAN_FAILURE; + } + + /* Check if connection exists for this remote device */ + pcb = pan_get_pcb_by_addr(rem_bda); + + /* If we are PANU for this role validate destination role */ + if (src_role == PAN_ROLE_CLIENT) { + if ((pan_cb.num_conns > 1) || (pan_cb.num_conns && (!pcb))) { + /* + ** If the request is not for existing connection reject it + ** because if there is already a connection we cannot accept + ** another connection in PANU role + */ + PAN_TRACE_ERROR( + "Cannot make PANU connections when there are more than one " + "connection"); + return PAN_INVALID_SRC_ROLE; + } + + src_uuid.uu.uuid16 = UUID_SERVCLASS_PANU; + if (dst_role == PAN_ROLE_CLIENT) { + dst_uuid.uu.uuid16 = UUID_SERVCLASS_PANU; + } else if (dst_role == PAN_ROLE_GN_SERVER) { + dst_uuid.uu.uuid16 = UUID_SERVCLASS_GN; + } else { + dst_uuid.uu.uuid16 = UUID_SERVCLASS_NAP; + } + mx_chan_id = dst_uuid.uu.uuid16; + } + /* If destination is PANU role validate source role */ + else if (dst_role == PAN_ROLE_CLIENT) { + if (pan_cb.num_conns && pan_cb.active_role == PAN_ROLE_CLIENT && !pcb) { + PAN_TRACE_ERROR("Device already have a connection in PANU role"); + return PAN_INVALID_SRC_ROLE; + } + + dst_uuid.uu.uuid16 = UUID_SERVCLASS_PANU; + if (src_role == PAN_ROLE_GN_SERVER) { + src_uuid.uu.uuid16 = UUID_SERVCLASS_GN; + } else { + src_uuid.uu.uuid16 = UUID_SERVCLASS_NAP; + } + mx_chan_id = src_uuid.uu.uuid16; + } + /* The role combination is not valid */ + else { + PAN_TRACE_ERROR( + "Source %d and Destination roles %d are not valid combination", + src_role, dst_role); + return PAN_FAILURE; + } + + /* Allocate control block and initiate connection */ + if (!pcb) { + pcb = pan_allocate_pcb(rem_bda, BNEP_INVALID_HANDLE); + } + if (!pcb) { + PAN_TRACE_ERROR("PAN Connection failed because of no resources"); + return PAN_NO_RESOURCES; + } + BTM_SetOutService(rem_bda, BTM_SEC_SERVICE_BNEP_PANU, mx_chan_id); + + PAN_TRACE_DEBUG("%s for BD Addr: %02x:%02x:%02x:%02x:%02x:%02x", __func__, + rem_bda[0], rem_bda[1], rem_bda[2], rem_bda[3], rem_bda[4], + rem_bda[5]); + if (pcb->con_state == PAN_STATE_IDLE) { + pan_cb.num_conns++; + } else if (pcb->con_state == PAN_STATE_CONNECTED) { + pcb->con_flags |= PAN_FLAGS_CONN_COMPLETED; + } else + /* PAN connection is still in progress */ + { + return PAN_WRONG_STATE; + } + + pcb->con_state = PAN_STATE_CONN_START; + pcb->prv_src_uuid = pcb->src_uuid; + pcb->prv_dst_uuid = pcb->dst_uuid; + + pcb->src_uuid = src_uuid.uu.uuid16; + pcb->dst_uuid = dst_uuid.uu.uuid16; + + src_uuid.len = 2; + dst_uuid.len = 2; + + result = BNEP_Connect(rem_bda, &src_uuid, &dst_uuid, &(pcb->handle)); + if (result != BNEP_SUCCESS) { + if (pcb->con_flags & PAN_FLAGS_CONN_COMPLETED) { + /* Role renegotiation failed synchronously; BNEP/L2CAP are still up. + * Restore the PCB like pan_connect_state_cb does for async failures. */ + PAN_TRACE_EVENT("PAN_Connect: restore active connection after renegotiation failure"); + pcb->con_state = PAN_STATE_CONNECTED; + pcb->con_flags &= (~PAN_FLAGS_CONN_COMPLETED); + pcb->src_uuid = pcb->prv_src_uuid; + pcb->dst_uuid = pcb->prv_dst_uuid; + } else { + /* New connection failed before going active. */ + if (pan_cb.num_conns) { + pan_cb.num_conns--; + } + pan_release_pcb(pcb); + } + return result; + } + + PAN_TRACE_DEBUG("PAN_Connect() current active role set to %d", src_role); + pan_cb.prv_active_role = pan_cb.active_role; + pan_cb.active_role = src_role; + *handle = pcb->handle; + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_Disconnect + * + * Description This is used to disconnect the connection + * + * Parameters: handle - handle for the connection + * + * Returns PAN_SUCCESS - if the connection is closed successfully + * PAN_FAILURE - if the connection is not found or + * there is an error in disconnecting + * + ******************************************************************************/ +tPAN_RESULT PAN_Disconnect(UINT16 handle) +{ + tPAN_CONN *pcb; + tBNEP_RESULT result; + + /* Check if the connection exists */ + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN connection not found for the handle %d", handle); + return PAN_FAILURE; + } + + result = BNEP_Disconnect(pcb->handle); + if (pcb->con_state != PAN_STATE_IDLE) { + pan_cb.num_conns--; + } + + if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) { + (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, FALSE); + } + + pan_release_pcb(pcb); + + if (result != BNEP_SUCCESS) { + PAN_TRACE_EVENT("Error in closing PAN connection"); + return PAN_FAILURE; + } + + PAN_TRACE_EVENT("PAN connection closed"); + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_Write + * + * Description This sends data over the PAN connections. If this is called + * on GN or NAP side and the packet is multicast or broadcast + * it will be sent on all the links. Otherwise the correct link + * is found based on the destination address and forwarded on + * it. + * + * Parameters: handle - handle for the connection + * dst - MAC or BD Addr of the destination device + * src - MAC or BD Addr of the source who sent this packet + * protocol - protocol of the ethernet packet like IP or ARP + * p_data - pointer to the data + * len - length of the data + * ext - to indicate that extension headers present + * + * Returns PAN_SUCCESS - if the data is sent successfully + * PAN_MTU_EXCEDED - if len exceeds PAN_MAX_WRITE_LEN + * PAN_NO_RESOURCES - if buffer allocation fails + * PAN_FAILURE - if the connection is not found or + * there is an error in sending data + * + ******************************************************************************/ +tPAN_RESULT PAN_Write(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, UINT8 *p_data, + UINT16 len, BOOLEAN ext) +{ + if (pan_cb.role == PAN_ROLE_INACTIVE || !pan_cb.num_conns) { + PAN_TRACE_ERROR("%s PAN is not active, data write failed.", __func__); + return PAN_FAILURE; + } + + if ((len > 0 && p_data == NULL) || len > PAN_MAX_WRITE_LEN) { + PAN_TRACE_ERROR("%s invalid args: p_data=%p len=%u max=%u", __func__, + p_data, len, (unsigned)PAN_MAX_WRITE_LEN); + return (len > PAN_MAX_WRITE_LEN) ? PAN_MTU_EXCEDED : PAN_FAILURE; + } + + // If the packet is broadcast or multicast, we're going to have to create + // a copy of the packet for each connection. We can save one extra copy + // by fast-pathing here and calling BNEP_Write instead of placing the packet + // in a BT_HDR buffer, calling BNEP_Write, and then freeing the buffer. + if (dst[0] & 0x01) { + int i; + for (i = 0; i < MAX_PAN_CONNS; ++i) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) { + BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, ext); + } + } + return PAN_SUCCESS; + } + + BT_HDR *buffer = (BT_HDR *)osi_malloc(PAN_BUF_SIZE); + if (buffer == NULL) { + PAN_TRACE_ERROR("%s: no resources", __func__); + return PAN_NO_RESOURCES; + } + buffer->len = len; + buffer->offset = PAN_MINIMUM_OFFSET; + if (len > 0) { + memcpy((UINT8 *)(buffer + 1) + buffer->offset, p_data, len); + } + + return PAN_WriteBuf(handle, dst, src, protocol, buffer, ext); +} + +/******************************************************************************* + * + * Function PAN_WriteBuf + * + * Description This sends data over the PAN connections. If this is called + * on GN or NAP side and the packet is multicast or broadcast + * it will be sent on all the links. Otherwise the correct link + * is found based on the destination address and forwarded on + * it. PAN_WriteBuf always takes ownership of p_buf: the buffer + * is either freed or queued by this function (or by + * BNEP_WriteBuf) regardless of the return value. The caller + * must not access or free p_buf after the call. + * + * Parameters: handle - handle for the connection + * dst - MAC or BD Addr of the destination device + * src - MAC or BD Addr of the source who sent this packet + * protocol - protocol of the ethernet packet like IP or ARP + * p_buf - pointer to the data buffer + * ext - to indicate that extension headers present + * + * Returns PAN_SUCCESS - if the data is sent successfully + * PAN_FAILURE - if the connection is not found or + * there is an error in sending data + * + ******************************************************************************/ +tPAN_RESULT PAN_WriteBuf(UINT16 handle, BD_ADDR dst, + BD_ADDR src, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext) +{ + tPAN_CONN *pcb; + UINT16 i; + tBNEP_RESULT result; + + if (pan_cb.role == PAN_ROLE_INACTIVE || (!(pan_cb.num_conns))) { + PAN_TRACE_ERROR("PAN is not active Data write failed"); + osi_free(p_buf); + return PAN_FAILURE; + } + + /* Check if it is broadcast or multicast packet */ + if (dst[0] & 0x01) { + UINT8 *data = (UINT8 *)p_buf + sizeof(BT_HDR) + p_buf->offset; + for (i = 0; i < MAX_PAN_CONNS; ++i) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) + BNEP_Write(pan_cb.pcb[i].handle, dst, data, p_buf->len, protocol, src, + ext); + } + osi_free(p_buf); + return PAN_SUCCESS; + } + + /* Check if the data write is on PANU side */ + if (pan_cb.active_role == PAN_ROLE_CLIENT) { + /* Data write is on PANU connection */ + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && + pan_cb.pcb[i].src_uuid == UUID_SERVCLASS_PANU) { + break; + } + } + + if (i == MAX_PAN_CONNS) { + PAN_TRACE_ERROR("PAN Don't have any user connections"); + osi_free(p_buf); + return PAN_FAILURE; + } + + result = + BNEP_WriteBuf(pan_cb.pcb[i].handle, dst, p_buf, protocol, src, ext); + if (result == BNEP_IGNORE_CMD) { + PAN_TRACE_DEBUG("PAN ignored data write for PANU connection"); + return result; + } else if (result != BNEP_SUCCESS) { + PAN_TRACE_ERROR("PAN failed to write data for the PANU connection"); + return result; + } + + PAN_TRACE_DEBUG("PAN successfully wrote data for the PANU connection"); + return PAN_SUCCESS; + } + + /* find out to which connection the data is meant for */ + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN Buf write for wrong handle"); + osi_free(p_buf); + return PAN_FAILURE; + } + + if (pcb->con_state != PAN_STATE_CONNECTED) { + PAN_TRACE_ERROR("PAN Buf write when conn is not active"); + osi_free(p_buf); + return PAN_FAILURE; + } + + result = BNEP_WriteBuf(pcb->handle, dst, p_buf, protocol, src, ext); + if (result == BNEP_IGNORE_CMD) { + PAN_TRACE_DEBUG("PAN ignored data buf write to PANU"); + return result; + } else if (result != BNEP_SUCCESS) { + PAN_TRACE_ERROR("PAN failed to send data buf to the PANU"); + return result; + } + + PAN_TRACE_DEBUG("PAN successfully sent data buf to the PANU"); + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_SetProtocolFilters + * + * Description This function is used to set protocol filters on the peer + * + * Parameters: handle - handle for the connection + * num_filters - number of protocol filter ranges + * start - array of starting protocol numbers + * end - array of ending protocol numbers + * + * + * Returns PAN_SUCCESS if protocol filters are set successfully + * PAN_FAILURE if connection not found or error in setting + * + ******************************************************************************/ +tPAN_RESULT PAN_SetProtocolFilters(UINT16 handle, UINT16 num_filters, + UINT16 *p_start_array, + UINT16 *p_end_array) +{ + tPAN_CONN *pcb; + tPAN_RESULT result; + + /* Check if the connection exists */ + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN connection not found for the handle %d", handle); + return PAN_FAILURE; + } + + result = BNEP_SetProtocolFilters(pcb->handle, num_filters, p_start_array, + p_end_array); + if (result != BNEP_SUCCESS) { + PAN_TRACE_ERROR("PAN failed to set protocol filters for handle %d", handle); + return result; + } + + PAN_TRACE_API("PAN successfully sent protocol filters for handle %d", handle); + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_SetMulticastFilters + * + * Description This function is used to set multicast filters on the peer + * + * Parameters: handle - handle for the connection + * num_filters - number of multicast filter ranges + * start - array of starting multicast filter addresses + * end - array of ending multicast filter addresses + * + * + * Returns PAN_SUCCESS if multicast filters are set successfully + * PAN_FAILURE if connection not found or error in setting + * + ******************************************************************************/ +tPAN_RESULT PAN_SetMulticastFilters(UINT16 handle, + UINT16 num_mcast_filters, + UINT8 *p_start_array, + UINT8 *p_end_array) +{ + tPAN_CONN *pcb; + tPAN_RESULT result; + + /* Check if the connection exists */ + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN connection not found for the handle %d", handle); + return PAN_FAILURE; + } + + result = BNEP_SetMulticastFilters(pcb->handle, num_mcast_filters, + p_start_array, p_end_array); + if (result != BNEP_SUCCESS) { + PAN_TRACE_ERROR("PAN failed to set multicast filters for handle %d", + handle); + return result; + } + + PAN_TRACE_API("PAN successfully sent multicast filters for handle %d", + handle); + return PAN_SUCCESS; +} + +/******************************************************************************* + * + * Function PAN_SetTraceLevel + * + * Description This function sets the trace level for PAN. If called with + * a value of 0xFF, it simply reads the current trace level. + * + * Returns the new (current) trace level + * + ******************************************************************************/ +UINT8 PAN_SetTraceLevel(UINT8 new_level) +{ + if (new_level != 0xFF) { + pan_cb.trace_level = new_level; + } else { + pan_dump_status(); + } + + return (pan_cb.trace_level); +} + +/******************************************************************************* + * + * Function PAN_Init + * + * Description This function initializes the PAN module variables + * + * Parameters: none + * + * Returns none + * + ******************************************************************************/ +void PAN_Init(void) +{ + memset(&pan_cb, 0, sizeof(tPAN_CB)); + +#if defined(PAN_INITIAL_TRACE_LEVEL) + pan_cb.trace_level = PAN_INITIAL_TRACE_LEVEL; +#else + pan_cb.trace_level = BT_TRACE_LEVEL_NONE; /* No traces */ +#endif +} + +#endif /* (PAN_INCLUDED == TRUE) */ diff --git a/components/bt/host/bluedroid/stack/pan/pan_main.c b/components/bt/host/bluedroid/stack/pan/pan_main.c new file mode 100644 index 00000000000..2ecb310f48b --- /dev/null +++ b/components/bt/host/bluedroid/stack/pan/pan_main.c @@ -0,0 +1,724 @@ +/****************************************************************************** + * + * Copyright (C) 1999-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains main functions to support PAN profile + * commands and events. + * + ******************************************************************************/ + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include +#include "osi/allocator.h" +#include "stack/bnep_api.h" +#include "bt_common.h" +#include "stack/bt_types.h" +#include "stack/hcidefs.h" +#include "stack/l2c_api.h" +#include "stack/pan_api.h" +#include "pan_int.h" +#include "stack/sdp_api.h" +#include "stack/sdpdefs.h" + +tPAN_CB pan_cb; + +#define UUID_CONSTANT_PART 12 +UINT8 constant_pan_uuid[UUID_CONSTANT_PART] = { + 0, 0, 0x10, 0, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb +}; + +/******************************************************************************* + * + * Function pan_register_with_bnep + * + * Description This function registers PAN profile with BNEP + * + * Parameters: none + * + * Returns none + * + ******************************************************************************/ +void pan_register_with_bnep(void) +{ + tBNEP_REGISTER reg_info; + + memset(®_info, 0, sizeof(tBNEP_REGISTER)); + + reg_info.p_conn_ind_cb = pan_conn_ind_cb; + reg_info.p_conn_state_cb = pan_connect_state_cb; + reg_info.p_data_buf_cb = pan_data_buf_ind_cb; + reg_info.p_data_ind_cb = NULL; + reg_info.p_tx_data_flow_cb = pan_tx_data_flow_cb; + reg_info.p_filter_ind_cb = pan_proto_filt_ind_cb; + reg_info.p_mfilter_ind_cb = pan_mcast_filt_ind_cb; + + BNEP_Register(®_info); +} + +/******************************************************************************* + * + * Function pan_conn_ind_cb + * + * Description This function is registered with BNEP as connection + * indication callback. BNEP will call this when there is + * connection request from the peer. PAN should call + * BNEP_ConnectResp to indicate whether to accept the + * connection or reject + * + * Parameters: handle - handle for the connection + * p_bda - BD Addr of the peer requesting the connection + * remote_uuid - UUID of the source role (peer device role) + * local_uuid - UUID of the destination role (local device + * role) + * is_role_change - Flag to indicate that it is a role change + * + * Returns none + * + ******************************************************************************/ +void pan_conn_ind_cb(UINT16 handle, BD_ADDR p_bda, + tBT_UUID *remote_uuid, tBT_UUID *local_uuid, + BOOLEAN is_role_change) +{ + tPAN_CONN *pcb; + UINT8 req_role; + BOOLEAN wrong_uuid; + + /* + ** If we are in GN or NAP role and have one or more + ** active connections and the received connection is + ** for user role reject it. + ** If we are in user role with one connection active + ** reject the connection. + ** Allocate PCB and store the parameters + ** Make bridge request to the host system if connection + ** is for NAP + */ + wrong_uuid = FALSE; + if (remote_uuid->len == 16) { + /* + ** If the UUID is 16 bytes first two bytes should be zeros + ** and last 12 bytes should match the spec defined constant value + */ + if (memcmp(constant_pan_uuid, remote_uuid->uu.uuid128 + 4, + UUID_CONSTANT_PART)) { + wrong_uuid = TRUE; + } + + if (remote_uuid->uu.uuid128[0] || remote_uuid->uu.uuid128[1]) { + wrong_uuid = TRUE; + } + + /* Extract the 16 bit equivalent of the UUID */ + remote_uuid->uu.uuid16 = (UINT16)((remote_uuid->uu.uuid128[2] << 8) | + remote_uuid->uu.uuid128[3]); + remote_uuid->len = 2; + } + if (remote_uuid->len == 4) { + /* First two bytes should be zeros */ + if (remote_uuid->uu.uuid32 & 0xFFFF0000) { + wrong_uuid = true; + } + + remote_uuid->uu.uuid16 = (UINT16)remote_uuid->uu.uuid32; + remote_uuid->len = 2; + } + + if (wrong_uuid) { + PAN_TRACE_ERROR("PAN Connection failed because of wrong remote UUID "); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID); + return; + } + + wrong_uuid = FALSE; + if (local_uuid->len == 16) { + /* + ** If the UUID is 16 bytes first two bytes should be zeros + ** and last 12 bytes should match the spec defined constant value + */ + if (memcmp(constant_pan_uuid, local_uuid->uu.uuid128 + 4, + UUID_CONSTANT_PART)) { + wrong_uuid = TRUE; + } + + if (local_uuid->uu.uuid128[0] || local_uuid->uu.uuid128[1]) { + wrong_uuid = TRUE; + } + + /* Extract the 16 bit equivalent of the UUID */ + local_uuid->uu.uuid16 = (UINT16)((local_uuid->uu.uuid128[2] << 8) | + local_uuid->uu.uuid128[3]); + local_uuid->len = 2; + } + if (local_uuid->len == 4) { + /* First two bytes should be zeros */ + if (local_uuid->uu.uuid32 & 0xFFFF0000) { + wrong_uuid = true; + } + + local_uuid->uu.uuid16 = (UINT16)local_uuid->uu.uuid32; + local_uuid->len = 2; + } + + if (wrong_uuid) { + PAN_TRACE_ERROR("PAN Connection failed because of wrong local UUID "); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); + return; + } + + PAN_TRACE_EVENT( + "pan_conn_ind_cb - for handle %d, current role %d, dst uuid 0x%x, src " + "uuid 0x%x, role change %s", + handle, pan_cb.role, local_uuid->uu.uuid16, remote_uuid->uu.uuid16, + is_role_change ? "YES" : "NO"); + /* The acceptable UUID size is only 2 */ + if (remote_uuid->len != 2) { + PAN_TRACE_ERROR("PAN Connection failed because of wrong UUID size %d", + remote_uuid->len); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_UUID_SIZE); + return; + } + + /* Check if the source UUID is a valid one */ + if (remote_uuid->uu.uuid16 != UUID_SERVCLASS_PANU && + remote_uuid->uu.uuid16 != UUID_SERVCLASS_NAP && + remote_uuid->uu.uuid16 != UUID_SERVCLASS_GN) { + PAN_TRACE_ERROR("Src UUID 0x%x is not valid", remote_uuid->uu.uuid16); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID); + return; + } + + /* Check if the destination UUID is a valid one */ + if (local_uuid->uu.uuid16 != UUID_SERVCLASS_PANU && + local_uuid->uu.uuid16 != UUID_SERVCLASS_NAP && + local_uuid->uu.uuid16 != UUID_SERVCLASS_GN) { + PAN_TRACE_ERROR("Dst UUID 0x%x is not valid", local_uuid->uu.uuid16); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); + return; + } + + /* Check if currently we support the destination role requested */ + if (((!(pan_cb.role & PAN_ROLE_CLIENT)) && + local_uuid->uu.uuid16 == UUID_SERVCLASS_PANU) || + ((!(pan_cb.role & PAN_ROLE_GN_SERVER)) && + local_uuid->uu.uuid16 == UUID_SERVCLASS_GN) || + ((!(pan_cb.role & PAN_ROLE_NAP_SERVER)) && + local_uuid->uu.uuid16 == UUID_SERVCLASS_NAP)) { + PAN_TRACE_ERROR( + "PAN Connection failed because of unsupported destination UUID 0x%x", + local_uuid->uu.uuid16); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); + return; + } + + /* Requested destination role is */ + if (local_uuid->uu.uuid16 == UUID_SERVCLASS_PANU) { + req_role = PAN_ROLE_CLIENT; + } else if (local_uuid->uu.uuid16 == UUID_SERVCLASS_GN) { + req_role = PAN_ROLE_GN_SERVER; + } else { + req_role = PAN_ROLE_NAP_SERVER; + } + + /* If the connection indication is for the existing connection + ** Check if the new destination role is acceptable + */ + pcb = pan_get_pcb_by_handle(handle); + if (pcb) { + if (pan_cb.num_conns > 1 && local_uuid->uu.uuid16 == UUID_SERVCLASS_PANU) { + /* There are connections other than this one + ** so we can't accept PANU role. Reject + */ + PAN_TRACE_ERROR( + "Dst UUID should be either GN or NAP only because there are other " + "connections"); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); + return; + } + + /* If it is already in connected state check for bridging status */ + if (pcb->con_state == PAN_STATE_CONNECTED) { + PAN_TRACE_EVENT("PAN Role changing New Src 0x%x Dst 0x%x", + remote_uuid->uu.uuid16, local_uuid->uu.uuid16); + + pcb->prv_src_uuid = pcb->src_uuid; + pcb->prv_dst_uuid = pcb->dst_uuid; + + if (pcb->src_uuid == UUID_SERVCLASS_NAP && + local_uuid->uu.uuid16 != UUID_SERVCLASS_NAP) { + /* Remove bridging */ + if (pan_cb.pan_bridge_req_cb) { + (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, FALSE); + } + } + } + /* Set the latest active PAN role */ + pan_cb.active_role = req_role; + pcb->src_uuid = local_uuid->uu.uuid16; + pcb->dst_uuid = remote_uuid->uu.uuid16; + BNEP_ConnectResp(handle, BNEP_SUCCESS); + return; + } else { + /* If this a new connection and destination is PANU role and + ** we already have a connection then reject the request. + ** If we have a connection in PANU role then reject it + */ + if (pan_cb.num_conns && (local_uuid->uu.uuid16 == UUID_SERVCLASS_PANU || + pan_cb.active_role == PAN_ROLE_CLIENT)) { + PAN_TRACE_ERROR("PAN already have a connection and can't be user"); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); + return; + } + } + + /* This is a new connection */ + PAN_TRACE_DEBUG("New connection indication for handle %d", handle); + pcb = pan_allocate_pcb(p_bda, handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN no control block for new connection"); + BNEP_ConnectResp(handle, BNEP_CONN_FAILED); + return; + } + + PAN_TRACE_EVENT("PAN connection destination UUID is 0x%x", + local_uuid->uu.uuid16); + /* Set the latest active PAN role */ + pan_cb.active_role = req_role; + pcb->src_uuid = local_uuid->uu.uuid16; + pcb->dst_uuid = remote_uuid->uu.uuid16; + pcb->con_state = PAN_STATE_CONN_START; + pan_cb.num_conns++; + + BNEP_ConnectResp(handle, BNEP_SUCCESS); + return; +} + +/******************************************************************************* + * + * Function pan_connect_state_cb + * + * Description This function is registered with BNEP as connection state + * change callback. BNEP will call this when the connection + * is established successfully or terminated + * + * Parameters: handle - handle for the connection given in the connection + * indication callback + * rem_bda - remote device bd addr + * result - indicates whether the connection is up or down + * BNEP_SUCCESS if the connection is up all other + * values indicate appropriate errors. + * is_role_change - flag to indicate that it is a role change + * + * Returns none + * + ******************************************************************************/ +void pan_connect_state_cb(UINT16 handle, BD_ADDR rem_bda, + tBNEP_RESULT result, BOOLEAN is_role_change) +{ + tPAN_CONN *pcb; + UINT8 peer_role; + + PAN_TRACE_EVENT("pan_connect_state_cb - for handle %d, result %d", handle, + result); + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN State change indication for wrong handle %d", handle); + return; + } + + /* If the connection is getting terminated remove bridging */ + if (result != BNEP_SUCCESS) { + /* Inform the application that connection is down */ + if (pan_cb.pan_conn_state_cb) + (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, result, + is_role_change, PAN_ROLE_INACTIVE, + PAN_ROLE_INACTIVE); + + /* Check if this failure is for role change only */ + if (pcb->con_state != PAN_STATE_CONNECTED && + (pcb->con_flags & PAN_FLAGS_CONN_COMPLETED)) { + /* restore the original values */ + PAN_TRACE_EVENT("restoring the connection state to active"); + pcb->con_state = PAN_STATE_CONNECTED; + pcb->con_flags &= (~PAN_FLAGS_CONN_COMPLETED); + + pcb->src_uuid = pcb->prv_src_uuid; + pcb->dst_uuid = pcb->prv_dst_uuid; + pan_cb.active_role = pan_cb.prv_active_role; + + if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) { + (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, TRUE); + } + + return; + } + + if (pcb->con_state == PAN_STATE_CONNECTED) { + /* If the connections destination role is NAP remove bridging */ + if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) { + (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, FALSE); + } + } + + pan_cb.num_conns--; + pan_release_pcb(pcb); + return; + } + + /* Requested destination role is */ + if (pcb->src_uuid == UUID_SERVCLASS_PANU) { + pan_cb.active_role = PAN_ROLE_CLIENT; + } else if (pcb->src_uuid == UUID_SERVCLASS_GN) { + pan_cb.active_role = PAN_ROLE_GN_SERVER; + } else { + pan_cb.active_role = PAN_ROLE_NAP_SERVER; + } + + if (pcb->dst_uuid == UUID_SERVCLASS_PANU) { + peer_role = PAN_ROLE_CLIENT; + } else if (pcb->dst_uuid == UUID_SERVCLASS_GN) { + peer_role = PAN_ROLE_GN_SERVER; + } else { + peer_role = PAN_ROLE_NAP_SERVER; + } + + pcb->con_state = PAN_STATE_CONNECTED; + + /* Inform the application that connection is down */ + if (pan_cb.pan_conn_state_cb) + (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, PAN_SUCCESS, + is_role_change, pan_cb.active_role, peer_role); + + /* Create bridge if the destination role is NAP */ + if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) { + PAN_TRACE_EVENT("PAN requesting for bridge"); + (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, TRUE); + } +} + +/******************************************************************************* + * + * Function pan_data_ind_cb + * + * Description This function is registered with BNEP as data indication + * callback. BNEP will call this when the peer sends any data + * on this connection + * + * Parameters: handle - handle for the connection + * src - source BD Addr + * dst - destination BD Addr + * protocol - Network protocol of the Eth packet + * p_data - pointer to the data + * len - length of the data + * fw_ext_present - to indicate whether the data contains any + * extension headers before the payload + * + * Returns none + * + ******************************************************************************/ +void pan_data_ind_cb(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, UINT8 *p_data, + UINT16 len, BOOLEAN ext) +{ + tPAN_CONN *pcb; + UINT16 i; + BOOLEAN forward; + + /* + ** Check the connection status + ** If the destination address is MAC broadcast send on all links + ** except on the one received + ** If the destination uuid is for NAP send to host system also + ** If the destination address is one of the devices connected + ** send the packet to over that link + ** If the destination address is unknown and destination uuid is NAP + ** send it to the host system + */ + + PAN_TRACE_EVENT("pan_data_ind_cb - for handle %d", handle); + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN Data indication for wrong handle %d", handle); + return; + } + + if (pcb->con_state != PAN_STATE_CONNECTED) { + PAN_TRACE_ERROR("PAN Data indication in wrong state %d for handle %d", + pcb->con_state, handle); + return; + } + + /* Check if it is broadcast packet */ + if (dst[0] & 0x01) { + PAN_TRACE_DEBUG("PAN received broadcast packet on handle %d, src uuid 0x%x", + handle, pcb->src_uuid); + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && + pan_cb.pcb[i].handle != handle && + pcb->src_uuid == pan_cb.pcb[i].src_uuid) { + BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, ext); + } + } + + if (pan_cb.pan_data_ind_cb) + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, + ext, TRUE); + + return; + } + + /* Check if it is for any other PAN connection */ + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && + pcb->src_uuid == pan_cb.pcb[i].src_uuid) { + if (!bdcmp(pan_cb.pcb[i].rem_bda, dst)) { + BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, ext); + return; + } + } + } + + if (pcb->src_uuid == UUID_SERVCLASS_NAP) { + forward = TRUE; + } else { + forward = FALSE; + } + + /* Send it over the LAN or give it to host software */ + if (pan_cb.pan_data_ind_cb) + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, ext, + forward); + + return; +} + +/******************************************************************************* + * + * Function pan_data_buf_ind_cb + * + * Description This function is registered with BNEP as data buffer + * indication callback. BNEP will call this when the peer sends + * any data on this connection. PAN is responsible to release + * the buffer + * + * Parameters: handle - handle for the connection + * src - source BD Addr + * dst - destination BD Addr + * protocol - Network protocol of the Eth packet + * p_buf - pointer to the data buffer + * ext - to indicate whether the data contains any + * extension headers before the payload + * + * Returns none + * + ******************************************************************************/ +void pan_data_buf_ind_cb(UINT16 handle, BD_ADDR src, + BD_ADDR dst, UINT16 protocol, + BT_HDR *p_buf, BOOLEAN ext) +{ + tPAN_CONN *pcb, *dst_pcb; + tBNEP_RESULT result; + UINT16 i, len; + UINT8 *p_data; + BOOLEAN forward = FALSE; + + /* Check if the connection is in right state */ + pcb = pan_get_pcb_by_handle(handle); + if (!pcb) { + PAN_TRACE_ERROR("PAN Data buffer indication for wrong handle %d", handle); + osi_free(p_buf); + return; + } + + if (pcb->con_state != PAN_STATE_CONNECTED) { + PAN_TRACE_ERROR("PAN Data indication in wrong state %d for handle %d", + pcb->con_state, handle); + osi_free(p_buf); + return; + } + + p_data = (UINT8 *)(p_buf + 1) + p_buf->offset; + len = p_buf->len; + + PAN_TRACE_EVENT( + "pan_data_buf_ind_cb - for handle %d, protocol 0x%x, length %d, ext %d", + handle, protocol, len, ext); + + if (pcb->src_uuid == UUID_SERVCLASS_NAP) { + forward = TRUE; + } else { + forward = FALSE; + } + + /* Check if it is broadcast or multicast packet */ + if (pcb->src_uuid != UUID_SERVCLASS_PANU) { + if (dst[0] & 0x01) { + PAN_TRACE_DEBUG( + "PAN received broadcast packet on handle %d, src uuid 0x%x", handle, + pcb->src_uuid); + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && + pan_cb.pcb[i].handle != handle && + pcb->src_uuid == pan_cb.pcb[i].src_uuid) { + BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, + ext); + } + } + + if (pan_cb.pan_data_buf_ind_cb) + (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, + ext, forward); + else if (pan_cb.pan_data_ind_cb) { + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, + ext, forward); + osi_free(p_buf); + } else { + osi_free(p_buf); + } + + return; + } + + /* Check if it is for any other PAN connection */ + dst_pcb = pan_get_pcb_by_addr(dst); + if (dst_pcb) { + PAN_TRACE_EVENT( + "%s - destination PANU found on handle %d and sending data, len: %d", + __func__, dst_pcb->handle, len); + + result = + BNEP_Write(dst_pcb->handle, dst, p_data, len, protocol, src, ext); + if (result != BNEP_SUCCESS && result != BNEP_IGNORE_CMD) + PAN_TRACE_ERROR("Failed to write data for PAN connection handle %d", + dst_pcb->handle); + osi_free(p_buf); + return; + } + } + + /* Send it over the LAN or give it to host software */ + if (pan_cb.pan_data_buf_ind_cb) + (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, ext, + forward); + else if (pan_cb.pan_data_ind_cb) { + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, ext, + forward); + osi_free(p_buf); + } else { + osi_free(p_buf); + } + + return; +} + +/******************************************************************************* + * + * Function pan_proto_filt_ind_cb + * + * Description This function is registered with BNEP to receive tx data + * flow status + * + * Parameters: handle - handle for the connection + * event - flow status + * + * Returns none + * + ******************************************************************************/ +void pan_tx_data_flow_cb(UINT16 handle, tBNEP_RESULT event) +{ + if (pan_cb.pan_tx_data_flow_cb) { + (*pan_cb.pan_tx_data_flow_cb)(handle, event); + } + + return; +} + +/******************************************************************************* + * + * Function pan_proto_filt_ind_cb + * + * Description This function is registered with BNEP as proto filter + * indication callback. BNEP will call this when the peer sends + * any protocol filter set for the connection or to indicate + * the result of the protocol filter set by the local device + * + * Parameters: handle - handle for the connection + * indication - true if this is indication + * false if it is called to give the result of + * local device protocol filter set + * result - This gives the result of the filter set + * operation + * num_filters - number of filters set by the peer device + * p_filters - pointer to the filters set by the peer device + * + * Returns none + * + ******************************************************************************/ +void pan_proto_filt_ind_cb(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_filters, + UINT8 *p_filters) +{ + PAN_TRACE_EVENT( + "pan_proto_filt_ind_cb - called for handle %d with ind %d, result %d, " + "num %d", + handle, indication, result, num_filters); + + if (pan_cb.pan_pfilt_ind_cb) + (*pan_cb.pan_pfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, + num_filters, p_filters); +} + +/******************************************************************************* + * + * Function pan_mcast_filt_ind_cb + * + * Description This function is registered with BNEP as mcast filter + * indication callback. BNEP will call this when the peer sends + * any multicast filter set for the connection or to indicate + * the result of the multicast filter set by the local device + * + * Parameters: handle - handle for the connection + * indication - true if this is indication + * false if it is called to give the result of + * local device multicast filter set + * result - This gives the result of the filter set + * operation + * num_filters - number of filters set by the peer device + * p_filters - pointer to the filters set by the peer device + * + * Returns none + * + ******************************************************************************/ +void pan_mcast_filt_ind_cb(UINT16 handle, BOOLEAN indication, + tBNEP_RESULT result, UINT16 num_filters, + UINT8 *p_filters) +{ + PAN_TRACE_EVENT( + "pan_mcast_filt_ind_cb - called for handle %d with ind %d, result %d, " + "num %d", + handle, indication, result, num_filters); + + if (pan_cb.pan_mfilt_ind_cb) + (*pan_cb.pan_mfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, + num_filters, p_filters); +} + +#endif /* (PAN_INCLUDED == TRUE) */ diff --git a/components/bt/host/bluedroid/stack/pan/pan_utils.c b/components/bt/host/bluedroid/stack/pan/pan_utils.c new file mode 100644 index 00000000000..b3645eee545 --- /dev/null +++ b/components/bt/host/bluedroid/stack/pan/pan_utils.c @@ -0,0 +1,335 @@ +/****************************************************************************** + * + * Copyright (C) 1999-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/***************************************************************************** + * + * This file contains main functions to support PAN profile + * commands and events. + * + *****************************************************************************/ + +#include "common/bt_target.h" + +#if (PAN_INCLUDED == TRUE) + +#include +#include "stack/bnep_api.h" +#include "bt_common.h" +#include "stack/btm_api.h" +#include "stack/hcidefs.h" +#include "stack/l2c_api.h" +#include "stack/pan_api.h" +#include "pan_int.h" +#include "stack/sdp_api.h" +#include "stack/sdpdefs.h" + +static const UINT8 pan_proto_elem_data[] = { + 0x35, 0x18, /* data element sequence of length 0x18 bytes */ + 0x35, 0x06, /* data element sequence for L2CAP descriptor */ + 0x19, 0x01, 0x00, /* UUID for L2CAP - 0x0100 */ + 0x09, 0x00, 0x0F, /* PSM for BNEP - 0x000F */ + 0x35, 0x0E, /* data element sequence for BNEP descriptor */ + 0x19, 0x00, 0x0F, /* UUID for BNEP - 0x000F */ + 0x09, 0x01, + 0x00, /* BNEP specific parameter 0 -- Version of BNEP = version 1 = 0x0001 + */ + 0x35, + 0x06, /* BNEP specific parameter 1 -- Supported network packet type list */ + 0x09, 0x08, 0x00, /* network packet type IPv4 = 0x0800 */ + 0x09, 0x08, 0x06 /* network packet type ARP = 0x0806 */ +}; + +/******************************************************************************* + * + * Function pan_register_with_sdp + * + * Description + * + * Returns + * + ******************************************************************************/ +UINT32 pan_register_with_sdp(UINT16 uuid, UINT8 sec_mask, + const char *p_name, const char *p_desc) +{ + UINT32 sdp_handle; + UINT16 browse_list = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; + UINT16 security = 0; + UINT32 proto_len = (UINT32)pan_proto_elem_data[1]; + + /* Create a record */ + sdp_handle = SDP_CreateRecord(); + + if (sdp_handle == 0) { + PAN_TRACE_ERROR("PAN_SetRole - could not create SDP record"); + return 0; + } + + /* Service Class ID List */ + SDP_AddServiceClassIdList(sdp_handle, 1, &uuid); + + /* Add protocol element sequence from the constant string */ + SDP_AddAttribute(sdp_handle, ATTR_ID_PROTOCOL_DESC_LIST, + DATA_ELE_SEQ_DESC_TYPE, proto_len, + (UINT8 *)(pan_proto_elem_data + 2)); + + /* Language base */ + SDP_AddLanguageBaseAttrIDList(sdp_handle, LANG_ID_CODE_ENGLISH, + LANG_ID_CHAR_ENCODE_UTF8, LANGUAGE_BASE_ID); + + /* Profile descriptor list */ + SDP_AddProfileDescriptorList(sdp_handle, uuid, PAN_PROFILE_VERSION); + + /* Service Name */ + SDP_AddAttribute(sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (UINT32)(strlen(p_name) + 1), (UINT8 *)p_name); + + /* Service description */ + SDP_AddAttribute(sdp_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, + (UINT32)(strlen(p_desc) + 1), (UINT8 *)p_desc); + + /* Security description */ + if (sec_mask) { + UINT16_TO_BE_FIELD(&security, 0x0001); + } + SDP_AddAttribute(sdp_handle, ATTR_ID_SECURITY_DESCRIPTION, UINT_DESC_TYPE, 2, + (UINT8 *)&security); + +#if (PAN_SUPPORTS_ROLE_NAP == TRUE) + if (uuid == UUID_SERVCLASS_NAP) { + UINT16 NetAccessType = 0x0005; /* Ethernet */ + UINT32 NetAccessRate = 0x0001312D0; /* 10Mb/sec */ + UINT8 array[10], *p; + + /* Net access type. */ + p = array; + UINT16_TO_BE_STREAM(p, NetAccessType); + SDP_AddAttribute(sdp_handle, ATTR_ID_NET_ACCESS_TYPE, UINT_DESC_TYPE, 2, + array); + + /* Net access rate. */ + p = array; + UINT32_TO_BE_STREAM(p, NetAccessRate); + SDP_AddAttribute(sdp_handle, ATTR_ID_MAX_NET_ACCESS_RATE, UINT_DESC_TYPE, 4, + array); + + /* Register with Security Manager for the specific security level */ + if ((!BTM_SetSecurityLevel(TRUE, p_name, BTM_SEC_SERVICE_BNEP_NAP, sec_mask, + BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_NAP)) || + (!BTM_SetSecurityLevel(FALSE, p_name, BTM_SEC_SERVICE_BNEP_NAP, + sec_mask, BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_NAP))) { + PAN_TRACE_ERROR("PAN Security Registration failed for NAP\n"); + } + } +#endif +#if (PAN_SUPPORTS_ROLE_GN == TRUE) + if (uuid == UUID_SERVCLASS_GN) { + if ((!BTM_SetSecurityLevel(TRUE, p_name, BTM_SEC_SERVICE_BNEP_GN, sec_mask, + BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_GN)) || + (!BTM_SetSecurityLevel(FALSE, p_name, BTM_SEC_SERVICE_BNEP_GN, sec_mask, + BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_GN))) { + PAN_TRACE_ERROR("PAN Security Registration failed for GN"); + } + } +#endif +#if (PAN_SUPPORTS_ROLE_PANU == TRUE) + if (uuid == UUID_SERVCLASS_PANU) { + if ((!BTM_SetSecurityLevel(TRUE, p_name, BTM_SEC_SERVICE_BNEP_PANU, + sec_mask, BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_PANU)) || + (!BTM_SetSecurityLevel(FALSE, p_name, BTM_SEC_SERVICE_BNEP_PANU, + sec_mask, BT_PSM_BNEP, BTM_SEC_PROTO_BNEP, + UUID_SERVCLASS_PANU))) { + PAN_TRACE_ERROR("PAN Security Registration failed for PANU"); + } + } +#endif + + /* Make the service browsable */ + SDP_AddUuidSequence(sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse_list); + + return sdp_handle; +} + +/******************************************************************************* + * + * Function pan_allocate_pcb + * + * Description + * + * Returns + * + ******************************************************************************/ +tPAN_CONN *pan_allocate_pcb(BD_ADDR p_bda, UINT16 handle) +{ + UINT16 i; + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && + pan_cb.pcb[i].handle == handle) { + return NULL; + } + } + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && + !bdcmp(pan_cb.pcb[i].rem_bda, p_bda)) { + return NULL; + } + } + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_IDLE) { + memset(&(pan_cb.pcb[i]), 0, sizeof(tPAN_CONN)); + bdcpy(pan_cb.pcb[i].rem_bda, p_bda); + pan_cb.pcb[i].handle = handle; + return &(pan_cb.pcb[i]); + } + } + return NULL; +} + +/******************************************************************************* + * + * Function pan_get_pcb_by_handle + * + * Description + * + * Returns + * + ******************************************************************************/ +tPAN_CONN *pan_get_pcb_by_handle(UINT16 handle) +{ + UINT16 i; + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && + pan_cb.pcb[i].handle == handle) { + return &(pan_cb.pcb[i]); + } + } + + return NULL; +} + +/******************************************************************************* + * + * Function pan_get_pcb_by_addr + * + * Description + * + * Returns + * + ******************************************************************************/ +tPAN_CONN *pan_get_pcb_by_addr(BD_ADDR p_bda) +{ + UINT16 i; + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state == PAN_STATE_IDLE) { + continue; + } + + if (!bdcmp(pan_cb.pcb[i].rem_bda, p_bda)) { + return &(pan_cb.pcb[i]); + } + + /* + if (pan_cb.pcb[i].mfilter_present && + p_bda == pan_cb.pcb[i].multi_cast_bridge) + return &(pan_cb.pcb[i]); + */ + } + + return NULL; +} + +/******************************************************************************* + * + * Function pan_close_all_connections + * + * Description + * + * Returns void + * + ******************************************************************************/ +void pan_close_all_connections(void) +{ + UINT16 i; + + for (i = 0; i < MAX_PAN_CONNS; i++) { + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE) { + BNEP_Disconnect(pan_cb.pcb[i].handle); + pan_cb.pcb[i].con_state = PAN_STATE_IDLE; + } + } + + pan_cb.active_role = PAN_ROLE_INACTIVE; + pan_cb.num_conns = 0; + return; +} + +/******************************************************************************* + * + * Function pan_release_pcb + * + * Description This function releases a PCB. + * + * Returns void + * + ******************************************************************************/ +void pan_release_pcb(tPAN_CONN *p_pcb) +{ + /* Drop any response pointer we may be holding */ + memset(p_pcb, 0, sizeof(tPAN_CONN)); + p_pcb->con_state = PAN_STATE_IDLE; +} + +/******************************************************************************* + * + * Function pan_dump_status + * + * Description This function dumps the pan control block and connection + * blocks information + * + * Returns none + * + ******************************************************************************/ +void pan_dump_status(void) +{ +#if (PAN_SUPPORTS_DEBUG_DUMP == TRUE) + UINT16 i; + tPAN_CONN *p_pcb; + + PAN_TRACE_DEBUG("PAN role %x, active role %d, num_conns %d", pan_cb.role, + pan_cb.active_role, pan_cb.num_conns); + + for (i = 0, p_pcb = pan_cb.pcb; i < MAX_PAN_CONNS; i++, p_pcb++) { + PAN_TRACE_DEBUG( + "pcb[%d] state:%d handle:%d src:0x%x rem_bda:%02x:%02x:%02x:%02x:%02x:%02x", + i, p_pcb->con_state, p_pcb->handle, p_pcb->src_uuid, + p_pcb->rem_bda[0], p_pcb->rem_bda[1], p_pcb->rem_bda[2], + p_pcb->rem_bda[3], p_pcb->rem_bda[4], p_pcb->rem_bda[5]); + } +#endif +} + +#endif /* (PAN_INCLUDED == TRUE) */ diff --git a/docs/doxygen/Doxyfile b/docs/doxygen/Doxyfile index 29b16cb209b..05fd118669d 100644 --- a/docs/doxygen/Doxyfile +++ b/docs/doxygen/Doxyfile @@ -99,6 +99,7 @@ INPUT = \ $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_hidd_api.h \ $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_hidh_api.h \ $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_l2cap_bt_api.h \ + $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_pan_api.h \ $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_sdp_api.h \ $(PROJECT_PATH)/components/bt/host/bluedroid/api/include/api/esp_spp_api.h \ $(PROJECT_PATH)/components/bt/host/nimble/esp-hci/include/esp_nimble_hci.h \ diff --git a/tools/ci/check_copyright_ignore.txt b/tools/ci/check_copyright_ignore.txt index 2be5c426d5b..3f838f4cfd0 100644 --- a/tools/ci/check_copyright_ignore.txt +++ b/tools/ci/check_copyright_ignore.txt @@ -111,6 +111,9 @@ components/bt/host/bluedroid/bta/include/bta/bta_hh_api.h components/bt/host/bluedroid/bta/include/bta/bta_hh_co.h components/bt/host/bluedroid/bta/include/bta/bta_jv_api.h components/bt/host/bluedroid/bta/include/bta/bta_jv_co.h +components/bt/host/bluedroid/bta/include/bta/bta_pan_api.h +components/bt/host/bluedroid/bta/include/bta/bta_pan_ci.h +components/bt/host/bluedroid/bta/include/bta/bta_pan_co.h components/bt/host/bluedroid/bta/include/bta/bta_sdp_api.h components/bt/host/bluedroid/bta/include/bta/bta_sys.h components/bt/host/bluedroid/bta/include/bta/utl.h @@ -119,6 +122,11 @@ components/bt/host/bluedroid/bta/jv/bta_jv_api.c components/bt/host/bluedroid/bta/jv/bta_jv_cfg.c components/bt/host/bluedroid/bta/jv/bta_jv_main.c components/bt/host/bluedroid/bta/jv/include/bta_jv_int.h +components/bt/host/bluedroid/bta/pan/bta_pan_act.c +components/bt/host/bluedroid/bta/pan/bta_pan_api.c +components/bt/host/bluedroid/bta/pan/bta_pan_ci.c +components/bt/host/bluedroid/bta/pan/bta_pan_int.h +components/bt/host/bluedroid/bta/pan/bta_pan_main.c components/bt/host/bluedroid/bta/sdp/bta_sdp.c components/bt/host/bluedroid/bta/sdp/bta_sdp_act.c components/bt/host/bluedroid/bta/sdp/bta_sdp_api.c @@ -143,6 +151,7 @@ components/bt/host/bluedroid/btc/profile/std/include/btc_hd.h components/bt/host/bluedroid/btc/profile/std/include/btc_hh.h components/bt/host/bluedroid/btc/profile/std/include/dis_api.h components/bt/host/bluedroid/btc/profile/std/include/srvc_api.h +components/bt/host/bluedroid/btc/profile/std/pan/bta_pan_co.c components/bt/host/bluedroid/common/include/common/bt_target.h components/bt/host/bluedroid/common/include/common/bt_trace.h components/bt/host/bluedroid/common/include/common/bt_vendor_lib.h @@ -246,6 +255,10 @@ components/bt/host/bluedroid/stack/avrc/avrc_pars_tg.c components/bt/host/bluedroid/stack/avrc/avrc_sdp.c components/bt/host/bluedroid/stack/avrc/avrc_utils.c components/bt/host/bluedroid/stack/avrc/include/avrc_int.h +components/bt/host/bluedroid/stack/bnep/bnep_api.c +components/bt/host/bluedroid/stack/bnep/bnep_main.c +components/bt/host/bluedroid/stack/bnep/bnep_utils.c +components/bt/host/bluedroid/stack/bnep/include/bnep_int.h components/bt/host/bluedroid/stack/btm/btm_acl.c components/bt/host/bluedroid/stack/btm/btm_ble.c components/bt/host/bluedroid/stack/btm/btm_ble_5_gap.c @@ -299,6 +312,7 @@ components/bt/host/bluedroid/stack/include/stack/avdt_api.h components/bt/host/bluedroid/stack/include/stack/avdtc_api.h components/bt/host/bluedroid/stack/include/stack/avrc_api.h components/bt/host/bluedroid/stack/include/stack/avrc_defs.h +components/bt/host/bluedroid/stack/include/stack/bnep_api.h components/bt/host/bluedroid/stack/include/stack/bt_types.h components/bt/host/bluedroid/stack/include/stack/btm_api.h components/bt/host/bluedroid/stack/include/stack/btm_ble_api.h @@ -315,6 +329,7 @@ components/bt/host/bluedroid/stack/include/stack/hidh_api.h components/bt/host/bluedroid/stack/include/stack/l2c_api.h components/bt/host/bluedroid/stack/include/stack/l2cap_client.h components/bt/host/bluedroid/stack/include/stack/l2cdefs.h +components/bt/host/bluedroid/stack/include/stack/pan_api.h components/bt/host/bluedroid/stack/include/stack/port_api.h components/bt/host/bluedroid/stack/include/stack/port_ext.h components/bt/host/bluedroid/stack/include/stack/profiles_api.h @@ -332,6 +347,10 @@ components/bt/host/bluedroid/stack/l2cap/l2c_main.c components/bt/host/bluedroid/stack/l2cap/l2c_ucd.c components/bt/host/bluedroid/stack/l2cap/l2c_utils.c components/bt/host/bluedroid/stack/l2cap/l2cap_client.c +components/bt/host/bluedroid/stack/pan/include/pan_int.h +components/bt/host/bluedroid/stack/pan/pan_api.c +components/bt/host/bluedroid/stack/pan/pan_main.c +components/bt/host/bluedroid/stack/pan/pan_utils.c components/bt/host/bluedroid/stack/rfcomm/include/port_int.h components/bt/host/bluedroid/stack/rfcomm/include/rfc_int.h components/bt/host/bluedroid/stack/rfcomm/port_api.c From 51eacff67810576c87af4efab14c8111a155f763 Mon Sep 17 00:00:00 2001 From: linruihao Date: Wed, 15 Jul 2026 15:32:00 +0800 Subject: [PATCH 2/2] feat(example): add Classic Bluetooth PAN profile examples --- docs/conf_common.py | 1 + .../en/api-reference/bluetooth/classic_bt.rst | 6 + docs/en/api-reference/bluetooth/esp_pan.rst | 23 + .../api-reference/bluetooth/classic_bt.rst | 6 + .../zh_CN/api-reference/bluetooth/esp_pan.rst | 23 + .../classic_bt/bt_pan_gn/CMakeLists.txt | 7 + .../bluedroid/classic_bt/bt_pan_gn/README.md | 61 +++ .../classic_bt/bt_pan_gn/main/CMakeLists.txt | 3 + .../bt_pan_gn/main/Kconfig.projbuild | 9 + .../bt_pan_gn/main/idf_component.yml | 3 + .../classic_bt/bt_pan_gn/main/main.c | 213 +++++++++ .../classic_bt/bt_pan_gn/main/pan_netif.c | 336 +++++++++++++ .../classic_bt/bt_pan_gn/main/pan_netif.h | 27 ++ .../classic_bt/bt_pan_gn/sdkconfig.defaults | 7 + .../classic_bt/bt_pan_nap/CMakeLists.txt | 7 + .../bluedroid/classic_bt/bt_pan_nap/README.md | 71 +++ .../classic_bt/bt_pan_nap/main/CMakeLists.txt | 3 + .../bt_pan_nap/main/Kconfig.projbuild | 24 + .../bt_pan_nap/main/idf_component.yml | 3 + .../classic_bt/bt_pan_nap/main/main.c | 306 ++++++++++++ .../classic_bt/bt_pan_nap/main/pan_netif.c | 440 ++++++++++++++++++ .../classic_bt/bt_pan_nap/main/pan_netif.h | 29 ++ .../classic_bt/bt_pan_nap/sdkconfig.defaults | 14 + .../classic_bt/bt_pan_panu/CMakeLists.txt | 7 + .../classic_bt/bt_pan_panu/README.md | 81 ++++ .../bt_pan_panu/main/CMakeLists.txt | 3 + .../bt_pan_panu/main/Kconfig.projbuild | 26 ++ .../bt_pan_panu/main/idf_component.yml | 3 + .../classic_bt/bt_pan_panu/main/main.c | 325 +++++++++++++ .../classic_bt/bt_pan_panu/main/pan_netif.c | 284 +++++++++++ .../classic_bt/bt_pan_panu/main/pan_netif.h | 19 + .../classic_bt/bt_pan_panu/sdkconfig.defaults | 8 + 32 files changed, 2378 insertions(+) create mode 100644 docs/en/api-reference/bluetooth/esp_pan.rst create mode 100644 docs/zh_CN/api-reference/bluetooth/esp_pan.rst create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/README.md create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/Kconfig.projbuild create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/idf_component.yml create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/main.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.h create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/sdkconfig.defaults create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/README.md create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/Kconfig.projbuild create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/idf_component.yml create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/main.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.h create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/sdkconfig.defaults create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/README.md create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/CMakeLists.txt create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/Kconfig.projbuild create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/idf_component.yml create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/main.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.c create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.h create mode 100644 examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/sdkconfig.defaults diff --git a/docs/conf_common.py b/docs/conf_common.py index f70ba92ecc2..57588afe0dc 100644 --- a/docs/conf_common.py +++ b/docs/conf_common.py @@ -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', diff --git a/docs/en/api-reference/bluetooth/classic_bt.rst b/docs/en/api-reference/bluetooth/classic_bt.rst index 34163d245b9..f0533dc58ad 100644 --- a/docs/en/api-reference/bluetooth/classic_bt.rst +++ b/docs/en/api-reference/bluetooth/classic_bt.rst @@ -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 `: Implements peripheral roles such as keyboard, mouse, or game controller - :doc:`Bluetooth HID Host `: Implements the host role for connecting to remote HID devices +**Personal Area Networking (PAN)** + +- :doc:`Bluetooth 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 Bluetooth HID Device Bluetooth HID Host + Bluetooth PAN diff --git a/docs/en/api-reference/bluetooth/esp_pan.rst b/docs/en/api-reference/bluetooth/esp_pan.rst new file mode 100644 index 00000000000..e935f87ae2a --- /dev/null +++ b/docs/en/api-reference/bluetooth/esp_pan.rst @@ -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 diff --git a/docs/zh_CN/api-reference/bluetooth/classic_bt.rst b/docs/zh_CN/api-reference/bluetooth/classic_bt.rst index 4aaaffdbef3..8bbdbeaecaa 100644 --- a/docs/zh_CN/api-reference/bluetooth/classic_bt.rst +++ b/docs/zh_CN/api-reference/bluetooth/classic_bt.rst @@ -13,6 +13,7 @@ - 媒体播放控制 (**AVRCP**) - 免提通话支持 (**HFP**) - 输入设备连接 (**HID** 主机和外设角色) +- 个人区域网络 (**PAN**) ---- @@ -59,6 +60,10 @@ - :doc:`Bluetooth HID Device `:实现外设角色,如键盘、鼠标或游戏手柄 - :doc:`Bluetooth HID Host `:实现主机角色,用于连接远程 HID 外设 +**个人区域网络 (PAN)** + +- :doc:`Bluetooth PAN `:基于 BNEP 的组网,支持 PANU、NAP 和 GN 角色 + 每个部分通常包含 **概述**、**应用示例** 和 **API 参考**,涵盖用途、主要功能、示例用法及详细 API 文档。 @@ -77,3 +82,4 @@ Bluetooth HFP AG Bluetooth HID Device Bluetooth HID Host + Bluetooth PAN diff --git a/docs/zh_CN/api-reference/bluetooth/esp_pan.rst b/docs/zh_CN/api-reference/bluetooth/esp_pan.rst new file mode 100644 index 00000000000..b4f8a8dd11d --- /dev/null +++ b/docs/zh_CN/api-reference/bluetooth/esp_pan.rst @@ -0,0 +1,23 @@ +蓝牙\ :sup:`®` PAN API +====================== + +:link_to_translation:`en:[English]` + +概述 +---- + +PAN(Personal Area Networking,个人区域网络)通过 BNEP(Bluetooth 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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/CMakeLists.txt new file mode 100644 index 00000000000..dc9ffb07f4c --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/CMakeLists.txt @@ -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) diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/README.md b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/README.md new file mode 100644 index 00000000000..b689c43dd86 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/README.md @@ -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. diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/CMakeLists.txt new file mode 100644 index 00000000000..25c13b304cc --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/CMakeLists.txt @@ -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 ".") diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/Kconfig.projbuild b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/Kconfig.projbuild new file mode 100644 index 00000000000..6a783b157cc --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/Kconfig.projbuild @@ -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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/idf_component.yml b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/idf_component.yml new file mode 100644 index 00000000000..6d958cec7ed --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/idf_component.yml @@ -0,0 +1,3 @@ +dependencies: + bt_app_core_utils: + path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/main.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/main.c new file mode 100644 index 00000000000..894f8f778ea --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/main.c @@ -0,0 +1,213 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include + +#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); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.c new file mode 100644 index 00000000000..d772610cc8a --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.c @@ -0,0 +1,336 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include + +#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); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.h b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.h new file mode 100644 index 00000000000..5ccd4bf9d30 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/main/pan_netif.h @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#pragma once + +#include +#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); diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/sdkconfig.defaults b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/sdkconfig.defaults new file mode 100644 index 00000000000..c8ec3bdacfc --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_gn/sdkconfig.defaults @@ -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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/CMakeLists.txt new file mode 100644 index 00000000000..0ff961827d1 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/CMakeLists.txt @@ -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) diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/README.md b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/README.md new file mode 100644 index 00000000000..02cca3c6c80 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/README.md @@ -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`. diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/CMakeLists.txt new file mode 100644 index 00000000000..db1a278c74b --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/CMakeLists.txt @@ -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 ".") diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/Kconfig.projbuild b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/Kconfig.projbuild new file mode 100644 index 00000000000..75e4494061a --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/Kconfig.projbuild @@ -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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/idf_component.yml b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/idf_component.yml new file mode 100644 index 00000000000..6d958cec7ed --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/idf_component.yml @@ -0,0 +1,3 @@ +dependencies: + bt_app_core_utils: + path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/main.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/main.c new file mode 100644 index 00000000000..4d86428d9b2 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/main.c @@ -0,0 +1,306 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include +#include +#include + +#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"); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.c new file mode 100644 index 00000000000..b93ec01d42f --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.c @@ -0,0 +1,440 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include +#include + +#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); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.h b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.h new file mode 100644 index 00000000000..ac5a6b05395 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/main/pan_netif.h @@ -0,0 +1,29 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#pragma once + +#include +#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); diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/sdkconfig.defaults b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/sdkconfig.defaults new file mode 100644 index 00000000000..8f6c51cd15d --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_nap/sdkconfig.defaults @@ -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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/CMakeLists.txt new file mode 100644 index 00000000000..8bce9414555 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/CMakeLists.txt @@ -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) diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/README.md b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/README.md new file mode 100644 index 00000000000..9ebb2791ce6 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/README.md @@ -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 | diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/CMakeLists.txt b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/CMakeLists.txt new file mode 100644 index 00000000000..25c13b304cc --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/CMakeLists.txt @@ -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 ".") diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/Kconfig.projbuild b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/Kconfig.projbuild new file mode 100644 index 00000000000..483e7f0c109 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/Kconfig.projbuild @@ -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 diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/idf_component.yml b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/idf_component.yml new file mode 100644 index 00000000000..6d958cec7ed --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/idf_component.yml @@ -0,0 +1,3 @@ +dependencies: + bt_app_core_utils: + path: ${IDF_PATH}/examples/bluetooth/bluedroid/classic_bt/common/bt_app_core_utils diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/main.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/main.c new file mode 100644 index 00000000000..b2590f3c978 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/main.c @@ -0,0 +1,325 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include +#include +#include + +#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); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.c b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.c new file mode 100644 index 00000000000..583e6830219 --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.c @@ -0,0 +1,284 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include +#include + +#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); +} diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.h b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.h new file mode 100644 index 00000000000..7ee2e98d5dd --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/main/pan_netif.h @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#pragma once + +#include +#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); diff --git a/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/sdkconfig.defaults b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/sdkconfig.defaults new file mode 100644 index 00000000000..302c4311c5c --- /dev/null +++ b/examples/bluetooth/bluedroid/classic_bt/bt_pan_panu/sdkconfig.defaults @@ -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