623 lines
16 KiB
C
623 lines
16 KiB
C
/*******************************************************************************
|
|
* @file ble_service.c
|
|
* @brief BLE NUS service module (Zephyr port)
|
|
*
|
|
* Original VesiScan-Basic BLE implementation ported to Zephyr/NCS:
|
|
* - NUS (Nordic UART Service) for data exchange
|
|
* - Advertising: 40ms interval, 3-min timeout
|
|
* - Connection: 30ms interval, 0 latency, 4s supervision timeout
|
|
* - TX power +8 dBm, 2M PHY preferred
|
|
* - Dev mode: no security / Production mode: bonding + passkey (TODO)
|
|
******************************************************************************/
|
|
#include <zephyr/kernel.h>
|
|
#include <zephyr/bluetooth/bluetooth.h>
|
|
#include <zephyr/bluetooth/hci.h>
|
|
#include <zephyr/bluetooth/conn.h>
|
|
#include <zephyr/bluetooth/uuid.h>
|
|
#include <zephyr/bluetooth/gatt.h>
|
|
#if IS_ENABLED(CONFIG_SETTINGS)
|
|
#include <zephyr/settings/settings.h>
|
|
#endif
|
|
#include <zephyr/mgmt/mcumgr/transport/smp_bt.h>
|
|
#include <bluetooth/services/nus.h>
|
|
#include <errno.h>
|
|
|
|
#include "ble_service.h"
|
|
#include "main.h"
|
|
#include "debug_print.h"
|
|
#include "led_control.h"
|
|
|
|
LOG_MODULE_REGISTER(ble_svc, LOG_LEVEL_INF);
|
|
|
|
/*==============================================================================
|
|
* Module variables
|
|
*============================================================================*/
|
|
static struct bt_conn *current_conn;
|
|
static ble_data_rx_cb_t rx_callback;
|
|
static bool dfu_advertising_mode;
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
#define BLE_REQUIRED_SECURITY_LEVEL BT_SECURITY_L4
|
|
static uint32_t pairing_passkey = BT_PASSKEY_RAND;
|
|
#endif
|
|
|
|
/*
|
|
* NUS 전송은 "보냈다" 호출만 한다고 바로 끝나는 게 아니다.
|
|
* 내부 TX 버퍼에 들어간 뒤 실제로 무선으로 나가고,
|
|
* Zephyr가 sent 콜백을 줄 때 비로소 한 건이 끝났다고 볼 수 있다.
|
|
*
|
|
* 그래서 아래 2개를 같이 쓴다.
|
|
* - mutex: 여러 곳에서 동시에 NUS 전송을 시작하지 못하게 막음
|
|
* - sem : "직전 전송이 정말 끝났는지" 기다리는 신호
|
|
*
|
|
* mbb?처럼 큰 패킷을 여러 개 연속으로 보내는 경우 이 보호가 없으면
|
|
* - 중간에 -ENOMEM이 뜨거나
|
|
* - 몇 개는 나가고 몇 개는 실패하거나
|
|
* - 앱 쪽에서 응답이 꼬여 보일 수 있다.
|
|
*/
|
|
static struct k_mutex nus_tx_lock;
|
|
static struct k_sem nus_tx_done_sem;
|
|
|
|
/* BLE API는 ISR/콜백에서 직접 호출하면 안전하지 않을 수 있으므로 k_work 사용 */
|
|
static struct k_work adv_restart_work;
|
|
static const bt_addr_le_t fixed_identity_addr = {
|
|
.type = BT_ADDR_LE_RANDOM,
|
|
.a = {
|
|
.val = { 0xF1, 0x8E, 0x81, 0xFA, 0x87, 0xC5 },
|
|
},
|
|
};
|
|
|
|
static const char *ble_addr_type_str(uint8_t type)
|
|
{
|
|
switch (type)
|
|
{
|
|
case BT_ADDR_LE_PUBLIC:
|
|
return "public";
|
|
case BT_ADDR_LE_RANDOM:
|
|
return "random";
|
|
case BT_ADDR_LE_PUBLIC_ID:
|
|
return "public-id";
|
|
case BT_ADDR_LE_RANDOM_ID:
|
|
return "random-id";
|
|
default:
|
|
return "unknown";
|
|
}
|
|
}
|
|
|
|
static void ble_log_local_identity(void)
|
|
{
|
|
bt_addr_le_t addr = {0};
|
|
size_t count = 1;
|
|
char addr_str[BT_ADDR_LE_STR_LEN];
|
|
|
|
bt_id_get(&addr, &count);
|
|
if (count == 0U)
|
|
{
|
|
DBG_ERR("[BLE] No local identity address\r\n");
|
|
return;
|
|
}
|
|
|
|
bt_addr_le_to_str(&addr, addr_str, sizeof(addr_str));
|
|
DBG_CORE("[BLE] Local identity: %s (%s)\r\n",
|
|
addr_str,
|
|
ble_addr_type_str(addr.type));
|
|
}
|
|
|
|
static int ble_configure_fixed_identity(void)
|
|
{
|
|
bt_addr_le_t addr = fixed_identity_addr;
|
|
char addr_str[BT_ADDR_LE_STR_LEN];
|
|
int id;
|
|
|
|
bt_addr_le_to_str(&addr, addr_str, sizeof(addr_str));
|
|
DBG_CORE("[BLE] Request fixed identity: %s\r\n", addr_str);
|
|
|
|
id = bt_id_create(&addr, NULL);
|
|
if (id < 0)
|
|
{
|
|
DBG_ERR("[BLE] bt_id_create failed (err %d)\r\n", id);
|
|
return id;
|
|
}
|
|
|
|
if (id != BT_ID_DEFAULT)
|
|
{
|
|
DBG_ERR("[BLE] Unexpected identity slot %d\r\n", id);
|
|
return -EINVAL;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
static bool ble_conn_is_secure(const struct bt_conn *conn)
|
|
{
|
|
return (conn != NULL) && (bt_conn_get_security(conn) >= BLE_REQUIRED_SECURITY_LEVEL);
|
|
}
|
|
|
|
static int ble_passkey_to_uint(const char *passkey, unsigned int *value)
|
|
{
|
|
unsigned int parsed = 0U;
|
|
|
|
if ((passkey == NULL) || (value == NULL))
|
|
{
|
|
return -EINVAL;
|
|
}
|
|
|
|
for (size_t i = 0; i < PASSKEY_LENGTH; i++)
|
|
{
|
|
if ((passkey[i] < '0') || (passkey[i] > '9'))
|
|
{
|
|
return -EINVAL;
|
|
}
|
|
|
|
parsed = (parsed * 10U) + (unsigned int)(passkey[i] - '0');
|
|
}
|
|
|
|
*value = parsed;
|
|
return 0;
|
|
}
|
|
|
|
static int ble_security_configure(void)
|
|
{
|
|
unsigned int passkey;
|
|
int err = ble_passkey_to_uint(m_static_passkey, &passkey);
|
|
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Invalid stored passkey, using default\r\n");
|
|
memset(m_static_passkey, 0, sizeof(m_static_passkey));
|
|
memcpy(m_static_passkey, DEFAULT_PASSKEY, PASSKEY_LENGTH);
|
|
|
|
err = ble_passkey_to_uint(m_static_passkey, &passkey);
|
|
if (err)
|
|
{
|
|
return err;
|
|
}
|
|
}
|
|
|
|
pairing_passkey = passkey;
|
|
DBG_CORE("[BLE] Fixed passkey configured\r\n");
|
|
return 0;
|
|
}
|
|
|
|
static void auth_pairing_confirm(struct bt_conn *conn)
|
|
{
|
|
int err = bt_conn_auth_pairing_confirm(conn);
|
|
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Pairing confirm failed err=%d\r\n", err);
|
|
return;
|
|
}
|
|
|
|
DBG_CORE("[BLE] Pairing confirmed\r\n");
|
|
}
|
|
|
|
static void auth_cancel(struct bt_conn *conn)
|
|
{
|
|
ARG_UNUSED(conn);
|
|
DBG_ERR("[BLE] Pairing cancelled\r\n");
|
|
}
|
|
|
|
#if IS_ENABLED(CONFIG_BT_APP_PASSKEY)
|
|
static uint32_t auth_app_passkey(struct bt_conn *conn)
|
|
{
|
|
unsigned int passkey;
|
|
|
|
ARG_UNUSED(conn);
|
|
|
|
if (ble_passkey_to_uint(m_static_passkey, &passkey) == 0)
|
|
{
|
|
return passkey;
|
|
}
|
|
|
|
DBG_ERR("[BLE] Invalid runtime passkey, using configured fallback\r\n");
|
|
return pairing_passkey;
|
|
}
|
|
#endif
|
|
|
|
static struct bt_conn_auth_cb auth_cb =
|
|
{
|
|
.pairing_confirm = auth_pairing_confirm,
|
|
.cancel = auth_cancel,
|
|
#if IS_ENABLED(CONFIG_BT_APP_PASSKEY)
|
|
.app_passkey = auth_app_passkey,
|
|
#endif
|
|
};
|
|
|
|
static void auth_pairing_complete(struct bt_conn *conn, bool bonded)
|
|
{
|
|
ARG_UNUSED(conn);
|
|
DBG_CORE("[BLE] Pairing complete bonded=%u\r\n", bonded ? 1U : 0U);
|
|
}
|
|
|
|
static void auth_pairing_failed(struct bt_conn *conn, enum bt_security_err reason)
|
|
{
|
|
DBG_ERR("[BLE] Pairing failed reason=%u\r\n", reason);
|
|
(void)bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
|
|
}
|
|
|
|
static struct bt_conn_auth_info_cb auth_info_cb =
|
|
{
|
|
.pairing_complete = auth_pairing_complete,
|
|
.pairing_failed = auth_pairing_failed,
|
|
};
|
|
|
|
static int ble_security_init(void)
|
|
{
|
|
int err = bt_conn_auth_cb_register(&auth_cb);
|
|
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] auth cb register failed err=%d\r\n", err);
|
|
return err;
|
|
}
|
|
|
|
err = bt_conn_auth_info_cb_register(&auth_info_cb);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] auth info cb register failed err=%d\r\n", err);
|
|
return err;
|
|
}
|
|
|
|
return ble_security_configure();
|
|
}
|
|
#endif
|
|
|
|
static void adv_restart_handler(struct k_work *work)
|
|
{
|
|
ARG_UNUSED(work);
|
|
ble_advertising_start();
|
|
led_set_state(LED_STATE_ADVERTISING);
|
|
}
|
|
|
|
/*==============================================================================
|
|
* Advertising data
|
|
*============================================================================*/
|
|
static const struct bt_data ad[] =
|
|
{
|
|
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
|
|
BT_DATA(BT_DATA_NAME_COMPLETE, SERIAL_NUMBER, sizeof(SERIAL_NUMBER) - 1),
|
|
};
|
|
|
|
static const struct bt_data sd[] =
|
|
{
|
|
/* 평상시 Web Bluetooth 앱이 찾을 수 있도록 NUS UUID 광고 */
|
|
BT_DATA_BYTES(BT_DATA_UUID128_SOME, BT_UUID_NUS_VAL),
|
|
};
|
|
|
|
static const struct bt_data sd_dfu[] =
|
|
{
|
|
/* DFU 진입 후 mcumgr 앱이 찾을 수 있도록 SMP UUID 광고 */
|
|
BT_DATA_BYTES(BT_DATA_UUID128_SOME, SMP_BT_SVC_UUID_VAL),
|
|
};
|
|
|
|
/*==============================================================================
|
|
* Connection callbacks
|
|
*============================================================================*/
|
|
static void connected(struct bt_conn *conn, uint8_t err)
|
|
{
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Connect failed (err %d) -> re-adv\r\n", err);
|
|
k_work_submit(&adv_restart_work);
|
|
return;
|
|
}
|
|
|
|
current_conn = bt_conn_ref(conn);
|
|
ble_connection_st = true;
|
|
|
|
/* 연결 정보 출력 */
|
|
char addr_str[BT_ADDR_LE_STR_LEN];
|
|
bt_addr_le_to_str(bt_conn_get_dst(conn), addr_str, sizeof(addr_str));
|
|
DBG_CORE("[BLE] Peer: %s\r\n", addr_str);
|
|
|
|
/* Connection parameters (30ms interval) */
|
|
struct bt_le_conn_param conn_param =
|
|
{
|
|
.interval_min = BLE_MIN_CONN_INTERVAL,
|
|
.interval_max = BLE_MAX_CONN_INTERVAL,
|
|
.latency = BLE_SLAVE_LATENCY,
|
|
.timeout = BLE_CONN_SUP_TIMEOUT,
|
|
};
|
|
bt_conn_le_param_update(conn, &conn_param);
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
err = bt_conn_set_security(conn, BLE_REQUIRED_SECURITY_LEVEL);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Security request failed err=%d\r\n", err);
|
|
(void)bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
|
|
return;
|
|
}
|
|
DBG_CORE("[BLE] Security requested level=%u\r\n", BLE_REQUIRED_SECURITY_LEVEL);
|
|
#endif
|
|
|
|
led_set_state(LED_STATE_OFF);
|
|
DBG_CORE("[BLE] Connected\r\n");
|
|
}
|
|
|
|
static void disconnected(struct bt_conn *conn, uint8_t reason)
|
|
{
|
|
if (current_conn)
|
|
{
|
|
bt_conn_unref(current_conn);
|
|
current_conn = NULL;
|
|
}
|
|
|
|
ble_connection_st = false;
|
|
DBG_CORE("[BLE] Disconnected (reason 0x%02x)\r\n", reason);
|
|
|
|
/* 워크큐에서 advertising 재시작 */
|
|
k_work_submit(&adv_restart_work);
|
|
}
|
|
|
|
static void le_param_updated(struct bt_conn *conn, uint16_t interval,
|
|
uint16_t latency, uint16_t timeout)
|
|
{
|
|
DBG_PRINTF("[BLE] Params: interval=%d latency=%d timeout=%d\r\n",
|
|
interval, latency, timeout);
|
|
}
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
static void security_changed(struct bt_conn *conn, bt_security_t level,
|
|
enum bt_security_err err)
|
|
{
|
|
ARG_UNUSED(conn);
|
|
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Security failed level=%u err=%u\r\n", level, err);
|
|
return;
|
|
}
|
|
|
|
DBG_CORE("[BLE] Security ready level=%u\r\n", level);
|
|
}
|
|
#endif
|
|
|
|
BT_CONN_CB_DEFINE(conn_callbacks) =
|
|
{
|
|
.connected = connected,
|
|
.disconnected = disconnected,
|
|
.le_param_updated = le_param_updated,
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
.security_changed = security_changed,
|
|
#endif
|
|
};
|
|
|
|
/*==============================================================================
|
|
* NUS callbacks
|
|
*============================================================================*/
|
|
static void nus_received(struct bt_conn *conn, const uint8_t *data, uint16_t len)
|
|
{
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
if (!ble_conn_is_secure(conn))
|
|
{
|
|
DBG_ERR("[NUS RX] blocked until BLE security is ready\r\n");
|
|
return;
|
|
}
|
|
#else
|
|
ARG_UNUSED(conn);
|
|
#endif
|
|
|
|
DBG_CORE("[NUS RX] len=%u\r\n", len);
|
|
if (rx_callback)
|
|
{
|
|
rx_callback(data, len);
|
|
}
|
|
}
|
|
|
|
static void nus_sent(struct bt_conn *conn)
|
|
{
|
|
ARG_UNUSED(conn);
|
|
/* 이 시점이 "직전 NUS 패킷 전송이 끝났다"는 완료 신호다. */
|
|
k_sem_give(&nus_tx_done_sem);
|
|
DBG_CORE("[NUS TX] complete\r\n");
|
|
}
|
|
|
|
static struct bt_nus_cb nus_cb =
|
|
{
|
|
.received = nus_received,
|
|
.sent = nus_sent,
|
|
};
|
|
|
|
/*==============================================================================
|
|
* Public functions
|
|
*============================================================================*/
|
|
int ble_service_init(ble_data_rx_cb_t rx_cb)
|
|
{
|
|
int err;
|
|
|
|
rx_callback = rx_cb;
|
|
k_mutex_init(&nus_tx_lock);
|
|
k_sem_init(&nus_tx_done_sem, 0, 1);
|
|
|
|
k_work_init(&adv_restart_work, adv_restart_handler);
|
|
|
|
err = ble_configure_fixed_identity();
|
|
if (err)
|
|
{
|
|
return err;
|
|
}
|
|
|
|
/* Enable BLE stack */
|
|
err = bt_enable(NULL);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] bt_enable failed (err %d)\r\n", err);
|
|
return err;
|
|
}
|
|
DBG_CORE("[BLE] Stack enabled\r\n");
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SETTINGS)
|
|
err = settings_load_subtree("bt");
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] BT settings load failed err=%d\r\n", err);
|
|
return err;
|
|
}
|
|
DBG_CORE("[BLE] BT settings loaded\r\n");
|
|
#endif
|
|
|
|
ble_log_local_identity();
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
err = ble_security_init();
|
|
if (err)
|
|
{
|
|
return err;
|
|
}
|
|
#endif
|
|
|
|
/* Initialize NUS */
|
|
err = bt_nus_init(&nus_cb);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] NUS init failed (err %d)\r\n", err);
|
|
return err;
|
|
}
|
|
DBG_CORE("[BLE] NUS initialized\r\n");
|
|
|
|
return 0;
|
|
}
|
|
|
|
int ble_advertising_start(void)
|
|
{
|
|
int err;
|
|
const struct bt_data *scan_data = dfu_advertising_mode ? sd_dfu : sd;
|
|
size_t scan_data_count = dfu_advertising_mode ? ARRAY_SIZE(sd_dfu) : ARRAY_SIZE(sd);
|
|
|
|
struct bt_le_adv_param adv_param = BT_LE_ADV_PARAM_INIT(
|
|
BT_LE_ADV_OPT_CONN,
|
|
APP_ADV_INTERVAL, /* min interval */
|
|
APP_ADV_INTERVAL + 16, /* max interval (slight window) */
|
|
NULL /* undirected */
|
|
);
|
|
|
|
err = bt_le_adv_start(&adv_param, ad, ARRAY_SIZE(ad), scan_data, scan_data_count);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Adv start failed (err %d)\r\n", err);
|
|
return err;
|
|
}
|
|
|
|
DBG_PRINTF("[BLE] Advertising started (%s)\r\n", dfu_advertising_mode ? "SMP" : "NUS");
|
|
return 0;
|
|
}
|
|
|
|
int ble_advertising_stop(void)
|
|
{
|
|
int err = bt_le_adv_stop();
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] Adv stop failed (err %d)\r\n", err);
|
|
return err;
|
|
}
|
|
|
|
DBG_PRINTF("[BLE] Advertising stopped\r\n");
|
|
return 0;
|
|
}
|
|
|
|
int ble_dfu_advertising_enable(void)
|
|
{
|
|
if (dfu_advertising_mode)
|
|
{
|
|
DBG_ERR("[BLE] DFU advertising already enabled\r\n");
|
|
return -EALREADY;
|
|
}
|
|
|
|
/* mdf? 응답 전송 후 현재 연결을 끊고 SMP UUID 광고로 재시작 */
|
|
dfu_advertising_mode = true;
|
|
DBG_PRINTF("[BLE] DFU advertising mode enabled\r\n");
|
|
|
|
if (current_conn)
|
|
{
|
|
int err = bt_conn_disconnect(current_conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
|
|
if (err)
|
|
{
|
|
DBG_ERR("[BLE] DFU disconnect failed err=%d\r\n", err);
|
|
return err;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
(void)ble_advertising_stop();
|
|
return ble_advertising_start();
|
|
}
|
|
|
|
bool ble_dfu_advertising_is_enabled(void)
|
|
{
|
|
return dfu_advertising_mode;
|
|
}
|
|
|
|
int ble_data_send(const uint8_t *data, uint16_t len)
|
|
{
|
|
int err;
|
|
|
|
if (!current_conn)
|
|
{
|
|
DBG_ERR("[NUS TX] not connected\r\n");
|
|
return -ENOTCONN;
|
|
}
|
|
|
|
#if IS_ENABLED(CONFIG_BT_SMP)
|
|
if (!ble_conn_is_secure(current_conn))
|
|
{
|
|
DBG_ERR("[NUS TX] blocked until BLE security is ready\r\n");
|
|
return -EACCES;
|
|
}
|
|
#endif
|
|
|
|
/*
|
|
* NUS는 한 번에 한 패킷씩 질서 있게 보내는 편이 안전하다.
|
|
* 특히 mbb?는 rbb + reb x6 + raa처럼 여러 응답을 연속 전송하므로
|
|
* 먼저 들어온 전송이 끝나기 전 다음 전송이 겹치지 않게 잠근다.
|
|
*/
|
|
k_mutex_lock(&nus_tx_lock, K_FOREVER);
|
|
|
|
/* 혹시 남아 있는 완료 신호가 있으면 비워서 "이번 전송 전용" 상태로 만든다. */
|
|
while (k_sem_take(&nus_tx_done_sem, K_NO_WAIT) == 0) {
|
|
}
|
|
|
|
DBG_CORE("[NUS TX] send len=%u\r\n", len);
|
|
for (int retry = 0; ; retry++)
|
|
{
|
|
err = bt_nus_send(current_conn, data, len);
|
|
if (err != -ENOMEM || retry >= 20) {
|
|
break;
|
|
}
|
|
|
|
/*
|
|
* -ENOMEM은 지금 당장 보낼 자리(TX 버퍼)가 없다는 뜻이다.
|
|
* 바로 포기하지 않고 짧게 쉬었다가 다시 시도한다.
|
|
*/
|
|
DBG_ERR("[NUS TX] busy, retry=%d\r\n", retry + 1);
|
|
k_msleep(5);
|
|
}
|
|
|
|
if (err)
|
|
{
|
|
DBG_ERR("[NUS TX] failed (err %d)\r\n", err);
|
|
k_mutex_unlock(&nus_tx_lock);
|
|
return err;
|
|
}
|
|
|
|
/*
|
|
* bt_nus_send()가 성공했다고 해서 공중으로 다 나간 것은 아니다.
|
|
* sent 콜백이 올 때까지 조금 기다려서 "다음 패킷을 보내도 되는 시점"을 맞춘다.
|
|
*/
|
|
err = k_sem_take(&nus_tx_done_sem, K_MSEC(1000));
|
|
if (err)
|
|
{
|
|
DBG_ERR("[NUS TX] completion timeout (err %d)\r\n", err);
|
|
}
|
|
|
|
k_mutex_unlock(&nus_tx_lock);
|
|
return err;
|
|
}
|
|
|
|
bool ble_is_connected(void)
|
|
{
|
|
return (current_conn != NULL);
|
|
}
|