Compare commits

..

12 Commits

Author SHA1 Message Date
jh.chun 9f252c7bef BLE 연결 해제 헬퍼 함수 및 에러별 분기 처리 2026-04-21 16:54:51 +09:00
jh.chun be1ca58bd6 버전 업데이트 2026-04-21 16:52:21 +09:00
jh.chun e20e8f5665 전원 버튼 타이머 조건 변경 2026-04-21 16:51:54 +09:00
jh.chun 2bff259fa3 코드 정리 2026-04-21 14:59:47 +09:00
jh.chun c72349cf13 NUS characteristic: MITM 인증 완료된 연결만 접근 가능하도록 수정
- SEC_OPEN -> SEC_MITM
- 기존에는 SoftDevice 레벨에서 인증 전 write를 차단하지 않음
2026-04-21 14:08:57 +09:00
jh.chun a0aa180ef1 DFU characteristic: MITM 인증 완료된 연결만 접근 가능하도록 수정
- SEC_OPEN -> SEC_MITM
- 기존에는 페어링 완료 전에도 DFU characteristic write 가능, BLE SMP 타임아웃(30초) 전에 wirte하면 부트로더로 재부팅되어 인증 없이 DFU 모드 진입 가능했음
2026-04-21 14:08:02 +09:00
jh.chun e9eb89f203 DFU 진입 시 주변 장치 및 타이머 정리 추가
- PREPARE 이벤트 시 타이머(메인, 배터리/온도) 중지 및 비동기 측정 중단 및 상태 리셋, Piezo 전원 차단
- 정리하지 않는 경우 Piezo TX 비정상 신호 출력/Flash 데이터 깨질 가능성 존재
2026-04-21 10:51:02 +09:00
jh.chun 790e3a1b82 미사용 변수 삭제 2026-04-21 09:56:24 +09:00
jh.chun 50a8e68cf4 BLE 인증 전 NUS 명령 실행 방지
- GAP 연결 시 PROD 모드에서 ble_connection_st 조기 활성화 제거(보안 인증 후 활성화)
- nus_data_handler()에 인증 상태 검증 가드 추가(ble_connection_st가 0인 경우 받지 않고 즉시 리턴)
2026-04-21 09:41:12 +09:00
jh.chun 1fa0d8b30b FW 버전 업데이트 2026-04-20 14:23:19 +09:00
jh.chun 36cd84e49c 테스트용 함수 삭제 2026-04-20 14:22:55 +09:00
jh.chun 163593c0cd 코드 정리 2026-04-20 14:22:43 +09:00
11 changed files with 140 additions and 165 deletions
@@ -216,9 +216,9 @@ uint32_t ble_dfu_buttonless_char_add(ble_dfu_buttonless_t * p_dfu)
add_char_params.is_var_len = true;
add_char_params.max_len = BLE_GATT_ATT_MTU_DEFAULT;
add_char_params.cccd_write_access = SEC_OPEN;
add_char_params.write_access = SEC_OPEN;
add_char_params.read_access = SEC_OPEN;
add_char_params.cccd_write_access = SEC_MITM;
add_char_params.write_access = SEC_MITM;
add_char_params.read_access = SEC_MITM;
return characteristic_add(p_dfu->service_handle, &add_char_params, &p_dfu->control_point_char);
}
@@ -283,8 +283,8 @@ uint32_t ble_nus_init(ble_nus_t * p_nus, ble_nus_init_t const * p_nus_init)
add_char_params.char_props.write = 1;
add_char_params.char_props.write_wo_resp = 1;
add_char_params.read_access = SEC_OPEN;
add_char_params.write_access = SEC_OPEN;
add_char_params.read_access = SEC_MITM;
add_char_params.write_access = SEC_MITM;
err_code = characteristic_add(p_nus->service_handle, &add_char_params, &p_nus->rx_handles);
if (err_code != NRF_SUCCESS)
@@ -302,9 +302,9 @@ uint32_t ble_nus_init(ble_nus_t * p_nus, ble_nus_init_t const * p_nus_init)
add_char_params.is_var_len = true;
add_char_params.char_props.notify = 1;
add_char_params.read_access = SEC_OPEN;
add_char_params.write_access = SEC_OPEN;
add_char_params.cccd_write_access = SEC_OPEN;
add_char_params.read_access = SEC_MITM;
add_char_params.write_access = SEC_MITM;
add_char_params.cccd_write_access = SEC_MITM;
return characteristic_add(p_nus->service_handle, &add_char_params, &p_nus->tx_handles);
/**@snippet [Adding proprietary characteristic to the SoftDevice] */
@@ -143,13 +143,10 @@ static void fds_evt_handler( fds_evt_t const *p_evt )
break;
case FDS_EVT_WRITE:
{
fds_flag_write = false;
}
break;
case FDS_EVT_UPDATE:
{
fds_flag_write = false;
if (go_device_power_off == true)
@@ -165,7 +162,6 @@ static void fds_evt_handler( fds_evt_t const *p_evt )
DBG_PRINTF("Off FDS_EVENT\r\n");
NVIC_SystemReset();
}
}
break;
case FDS_EVT_DEL_RECORD:
@@ -39,10 +39,12 @@ static void twi_uninitialize(void)
}
/* Initialise the TWI peripheral (SCL/SDA pins, 400 kHz, blocking mode). */
static void twi_initialize(void){
static void twi_initialize(void)
{
ret_code_t err_code;
const nrfx_twi_config_t twi_config = {
const nrfx_twi_config_t twi_config =
{
.scl = ICM42670_I2C_SCL_PIN,
.sda = ICM42670_I2C_SDA_PIN,
.frequency = NRF_TWI_FREQ_400K,
@@ -115,8 +115,6 @@
#include "dr_piezo.h" /* Piezo ultrasound driver */
#include "led_control.h" /* LED direct control driver */
/*==============================================================================
* Build Configuration
*============================================================================*/
@@ -157,7 +155,6 @@
#define POWER_ON_DELAY 5 /* Power button polling interval (5ms) */
#define POWER_OFF_DELAY 3000 /* Power-off delay: 3s after LED indication */
#define POWER_RESET_DELAY 2000 /* Reset delay: 2s */
#define LED_NUM 24 /* LED pin number */
/*==============================================================================
* BLE Instances (statically allocated via SoftDevice macros)
@@ -193,14 +190,11 @@ static uint8_t c_addr[6] = {0}; /* Connected peer BLE a
static char * roles_str[] = {"INVALID_ROLE", "CENTRAL", "PERIPHERAL"};
/*==============================================================================
* Global Variables
* IEC 62304 §5.5.3: all global buffers zero-initialized for deterministic startup
*============================================================================*/
volatile uint8_t Sj_type; /* Command type identifier */
bool power_off_duble_prohibit = false; /* Power-off double prevention flag */
volatile bool power_state = false; /* Power state tracking */
/*==============================================================================
* Extern Variables and Functions
*============================================================================*/
/* -- External module flags (defined in main_timer/power_control) -- */
extern bool go_device_power_off; /* Power-off request flag */
extern bool go_sleep_mode_enter; /* Sleep mode entry request flag */
@@ -212,6 +206,14 @@ extern bool info4; /* Device info transmission complete flag
extern uint8_t add_cycle; /* Additional measurement cycle counter */
extern bool motion_raw_data_enabled; /* Motion raw data streaming enabled */
/* -- External module functions (used in DFU prepare / disconnect cleanup) -- */
extern void maa_async_abort(void);
extern bool maa_async_on_tx_ready(void);
extern bool maa_async_is_busy(void);
extern void dr_piezo_power_off(void);
extern void battery_timer_stop(void);
extern void main_timer_stop(void);
uint16_t cnt_s; /* Power button polling counter (5ms units, 150=0.75s) */
char ble_tx_buffer[BLE_NUS_MAX_DATA_LEN] = {0}; /* BLE text transmission buffer */
uint8_t ble_bin_buffer[BLE_NUS_MAX_DATA_LEN] = {0}; /* BLE binary response buffer */
@@ -485,6 +487,10 @@ static void ble_dfu_evt_handler(ble_dfu_buttonless_evt_type_t event)
{
case BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE:
DBG_PRINTF("[DFU] Prepare\r\n");
maa_async_abort();
dr_piezo_power_off();
battery_timer_stop();
main_timer_stop();
break;
case BLE_DFU_EVT_BOOTLOADER_ENTER:
DBG_PRINTF("[DFU] Enter\r\n");
@@ -494,7 +500,6 @@ static void ble_dfu_evt_handler(ble_dfu_buttonless_evt_type_t event)
break;
case BLE_DFU_EVT_RESPONSE_SEND_ERROR:
DBG_PRINTF("[DFU] Error\r\n");
APP_ERROR_CHECK(false);
break;
default:
break;
@@ -553,10 +558,6 @@ static void nrf_qwr_error_handler(uint32_t nrf_error)
APP_ERROR_HANDLER(nrf_error);
}
/* Async MAA TX complete handler (forward declarations) */
extern bool maa_async_on_tx_ready(void);
extern bool maa_async_is_busy(void);
extern void maa_async_abort(void);
/* 2026-03-17: Prevent blocking in BLE callback -- buffer command for main loop processing */
static volatile uint8_t pending_cmd_buf[BLE_NUS_MAX_DATA_LEN] = {0};
@@ -573,6 +574,11 @@ static void nus_data_handler(ble_nus_evt_t * p_evt)
{
if (p_evt->type == BLE_NUS_EVT_RX_DATA)
{
if (!ble_connection_st)
{
return; /* Reject command before security is established */
}
cmd_type_t = CMD_BLE;
ble_got_new_data = true;
@@ -1048,11 +1054,14 @@ static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
break;
case BLE_GAP_EVT_CONNECTED:
DBG_PRINTF("[BLE] Connected\r\n");
DBG_PRINTF("[BLE] GAP Connected\r\n");
#if FEATURE_SECURE_CONNECTION
if (BLE_DEV_MODE)
{
ble_connection_st = 1;
battery_timer_start();
}
#endif
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
@@ -1624,7 +1633,7 @@ static void main_s(void * p_context)
go_device_power_off = true;
main_timer_start();
}
else if (cnt_s > 250 || (m_reset_status == 2)) /* 250 x 5ms = 1.25s + α */
else if (cnt_s >= 250 || (m_reset_status == 2)) /* 250 x 5ms = 1.25s + α */
{
DBG_PRINTF("[BTN] Boot (cnt=%d)\r\n", cnt_s);
device_reset = false;
@@ -31,8 +31,14 @@
* Firmware Version Update History
* - VBTFW0101 : Merged reb+red packets (single packet per channel), 260330 jhChun
* - VBTFW0102 : Added LED state command (msl) and re-pairing support, 260331 jhChun
* - VBTFW0103 260416 jhChun
* : Stabilized ADC measurement by clearing buffers before sampling.
* : Improved low-battery detection and automatic power-off handling.
* : Updated BLE security, bonding, and advertising timeout behavior.
* : Cleaned up command parsing and removed unused project files.
* - VBTFW0111 260421 jhChun
------------------------------------------------------------------------- */
#define FIRMWARE_VERSION "VBTFW0102"
#define FIRMWARE_VERSION "VBTFW0111"
/*==============================================================================
* Data Length Constants
@@ -71,11 +71,25 @@ extern void dr_piezo_power_off(void);
/*==============================================================================
* PRIVATE DEFINES
*============================================================================*/
/* Extract pin number from NRF_GPIO_PIN_MAP (lower 5 bits) */
#define DR_PIN_NUM(pin) ((pin) & 0x1F)
#define DR_PIN_PORT(pin) (((pin) >> 5) & 0x01)
/* BLE packet constants */
#define BLE_MTU_SIZE 244 /* ATT MTU 247 - 3 (ATT header) = 244 */
#define BLE_REB_HEADER_LEN 6 /* "reb:" tag(4) + num_samples(2) */
#define BLE_RED_HEADER_LEN 6 /* "red:" tag(4) + pkt_idx(2) */
#define BLE_RDB_HEADER_LEN 8 /* "rdb:" tag(4) + num_samples(2) + compressed_size(2) */
#define BLE_REB_DATA_LEN (BLE_MTU_SIZE - BLE_REB_HEADER_LEN) /* 238 bytes = 119 samples */
#define BLE_RED_DATA_LEN (BLE_MTU_SIZE - BLE_RED_HEADER_LEN) /* 238 bytes = 119 samples */
#define BLE_PACKET_DELAY_MS 100 /* Inter-packet delay - allow BLE TX buffer to drain */
/* Piezo MUX pins (8ch) */
#define DR_PIEZO_EN_MUXA NRF_GPIO_PIN_MAP(0, 21) /**< MUXA Enable */
#define DR_PIEZO_EN_MUXB NRF_GPIO_PIN_MAP(0, 23) /**< MUXB Enable */
#define DR_PIEZO_MUX_SEL1 NRF_GPIO_PIN_MAP(0, 28) /**< MUX Select 1 */
#define DR_PIEZO_MUX_SEL0 NRF_GPIO_PIN_MAP(1, 10) /**< MUX Select 0 */
/*==============================================================================
* PRIVATE VARIABLES
*============================================================================*/
@@ -133,8 +147,6 @@ dr_adc_err_t dr_adc_init(void)
{
nrfx_err_t err;
ADC_LOG("ADC121S051 init (HW SPI, SPIM3)...");
nrfx_spim_config_t config = NRFX_SPIM_DEFAULT_CONFIG;
config.sck_pin = DR_ADC_PIN_SCLK; /* P0.14 */
config.mosi_pin = NRFX_SPIM_PIN_NOT_USED;/* not used (read-only ADC) */
@@ -146,7 +158,7 @@ dr_adc_err_t dr_adc_init(void)
config.ss_active_high = false; /* CS active LOW */
err = nrfx_spim_init(&m_spim, &config, NULL, NULL);
ADC_LOG("SPIM3 init result: 0x%08X (%s)", err, (err == NRFX_SUCCESS) ? "OK" : "FAIL");
if (err != NRFX_SUCCESS)
{
return DR_ADC_ERR_NOT_INIT;
@@ -160,8 +172,6 @@ dr_adc_err_t dr_adc_init(void)
m_initialized = true;
ADC_LOG("ADC121S051 ready (VREF=%dmV, HW SPI)", m_vref_mv);
return DR_ADC_OK;
}
@@ -173,10 +183,7 @@ void dr_adc_uninit(void)
}
nrfx_spim_uninit(&m_spim);
m_initialized = false;
ADC_LOG("ADC121S051 uninitialized");
}
bool dr_adc_is_initialized(void)
@@ -350,8 +357,7 @@ dr_adc_err_t dr_adc_measure_echo(dr_adc_echo_t *echo, const dr_adc_echo_config_t
return dr_adc_analyze_echo(m_echo_buffer, cfg.num_samples, echo, cfg.threshold_raw);
}
dr_adc_err_t dr_adc_burst_and_capture(uint8_t cycles, uint16_t delay_us,
uint16_t num_samples, dr_adc_echo_t *echo)
dr_adc_err_t dr_adc_burst_and_capture(uint8_t cycles, uint16_t delay_us, uint16_t num_samples, dr_adc_echo_t *echo)
{
(void)cycles; /* Not used - ADC test only */
@@ -407,8 +413,7 @@ const uint16_t* dr_adc_get_echo_buffer(void)
return m_echo_buffer;
}
dr_adc_err_t dr_adc_analyze_echo(const uint16_t *buffer, uint16_t num_samples,
dr_adc_echo_t *echo, uint16_t threshold)
dr_adc_err_t dr_adc_analyze_echo(const uint16_t *buffer, uint16_t num_samples, dr_adc_echo_t *echo, uint16_t threshold)
{
if (buffer == NULL || echo == NULL)
{
@@ -522,57 +527,6 @@ uint32_t dr_adc_get_vref(void)
return m_vref_mv;
}
/*==============================================================================
* PUBLIC FUNCTIONS - DEBUG
*============================================================================*/
bool dr_adc_test(void)
{
if (!m_initialized)
{
ADC_LOG("Test FAIL: not initialized");
return false;
}
uint16_t raw;
dr_adc_err_t err = dr_adc_read_raw(&raw);
if (err != DR_ADC_OK)
{
ADC_LOG("Test FAIL: read error %d", err);
return false;
}
if (raw > DR_ADC_MAX_VALUE)
{
ADC_LOG("Test FAIL: invalid value %d", raw);
return false;
}
ADC_LOG("Test PASS: raw=%d (%dmV)", raw, dr_adc_raw_to_mv(raw));
return true;
}
void dr_adc_print_buffer(const uint16_t *buffer, uint16_t num_samples)
{
#ifdef DEBUG_ADC
if (buffer == NULL || num_samples == 0)
{
return;
}
ADC_LOG("Echo buffer (%d samples):", num_samples);
for (uint16_t i = 0; i < num_samples; i++)
{
ADC_LOG("[%3d] %4d (%4dmV)", i, buffer[i], dr_adc_raw_to_mv(buffer[i]));
}
#else
(void)buffer;
(void)num_samples;
#endif
}
/*==============================================================================
* BLE TRANSMISSION
*============================================================================*/
@@ -591,26 +545,11 @@ extern void dr_sd_delay_ms(uint32_t ms);
/* External piezo burst function */
extern void dr_piezo_burst_sw(uint8_t cycles);
/* BLE packet constants */
#define BLE_MTU_SIZE 244 /* ATT MTU 247 - 3 (ATT header) = 244 */
#define BLE_REB_HEADER_LEN 6 /* "reb:" tag(4) + num_samples(2) */
#define BLE_RED_HEADER_LEN 6 /* "red:" tag(4) + pkt_idx(2) */
#define BLE_REB_DATA_LEN (BLE_MTU_SIZE - BLE_REB_HEADER_LEN) /* 238 bytes = 119 samples */
#define BLE_RED_DATA_LEN (BLE_MTU_SIZE - BLE_RED_HEADER_LEN) /* 238 bytes = 119 samples */
#define BLE_PACKET_DELAY_MS 100 /* Inter-packet delay - allow BLE TX buffer to drain */
/*==============================================================================
* PIEZO CHANNEL SELECTION
*============================================================================*/
/* Piezo MUX pins (8ch) */
#define DR_PIEZO_EN_MUXA NRF_GPIO_PIN_MAP(0, 21) /**< MUXA Enable */
#define DR_PIEZO_EN_MUXB NRF_GPIO_PIN_MAP(0, 23) /**< MUXB Enable */
#define DR_PIEZO_MUX_SEL1 NRF_GPIO_PIN_MAP(0, 28) /**< MUX Select 1 */
#define DR_PIEZO_MUX_SEL0 NRF_GPIO_PIN_MAP(1, 10) /**< MUX Select 0 */
/*
* Channel mapping (8ch) jhChun 26.01.29
* Channel mapping (8ch)
* | EN MUXA | EN MUXB | SEL 0 | SEL 1
* ----------------------------------------------
@@ -1124,7 +1063,6 @@ dr_adc_err_t dr_adc_transmit_channel_delta(const dr_maa_channel_t *ch_data, uint
ble_buffer[6] = (uint8_t)(compressed_size >> 8);
ble_buffer[7] = (uint8_t)(compressed_size & 0xFF);
#define BLE_RDB_HEADER_LEN 8 /* rdb: tag(4) + num_samples(2) + compressed_size(2) */
uint16_t rdb_data_cap = BLE_MTU_SIZE - BLE_RDB_HEADER_LEN; /* 236 bytes */
uint16_t dst_idx = BLE_RDB_HEADER_LEN;
@@ -263,19 +263,6 @@ uint32_t dr_adc_get_vref(void);
* DEBUG FUNCTIONS
*============================================================================*/
/**
* @brief Test ADC communication
* @return true if OK
*/
bool dr_adc_test(void);
/**
* @brief Print echo buffer to debug output
* @param buffer Sample buffer
* @param num_samples Number of samples
*/
void dr_adc_print_buffer(const uint16_t *buffer, uint16_t num_samples);
/*==============================================================================
* POWER CONTROL
*============================================================================*/
@@ -99,8 +99,8 @@ extern bool motion_data_once;
*============================================================================*/
void safety_check_complete(float temp_c)
{
DBG_PRINTF("[SAFETY] Batt=%d mV, Temp=%d.%d C\r\n",
(int)safety_batt_mv, (int)temp_c, ((int)(temp_c * 10)) % 10);
//DBG_PRINTF("[SAFETY] Batt=%d mV, Temp=%d.%d C\r\n",
// (int)safety_batt_mv, (int)temp_c, ((int)(temp_c * 10)) % 10);
/* Battery check */
if (safety_batt_mv <= LOW_BATTERY_VOLTAGE)
@@ -74,7 +74,8 @@ int device_sleep_mode(void)
*
* @return 0 (always succeeds)
*/
int device_activated(void){
int device_activated(void)
{
int rc = 0;
p_order = 0; /* State machine start step (Step 0: I2C init) */
lock_check =true; /* Lock: power sequence in progress */
@@ -117,10 +118,13 @@ void power_loop(void *p_context)
/* Advance to next step or finish */
/* Advance to next step or finish sequence */
if (p_order < 2) {
if (p_order < 2)
{
p_order++; /* Move to next step */
power_timer_start(); /* Execute next step after 20ms */
} else {
}
else
{
/* Power sequence fully complete */
DBG_PRINTF("[PWR] Device Activated OK!\r\n");
}
@@ -135,7 +139,8 @@ void power_loop(void *p_context)
*
* @return 0 (always succeeds)
*/
int device_reactivated(void){
int device_reactivated(void)
{
int rc = 0;
sw_i2c_init_once(); /* Re-initialize I2C bus */
nrf_delay_ms(10); /* Stabilization delay */
@@ -20,6 +20,22 @@ static struct {
bool bonds_delete_pending;
} m_state = {0};
static const char * sec_error_name(pm_sec_error_code_t error)
{
switch (error) {
case PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING:
return "PIN_OR_KEY_MISSING";
case PM_CONN_SEC_ERROR_MIC_FAILURE:
return "MIC_FAILURE";
case PM_CONN_SEC_ERROR_DISCONNECT:
return "DISCONNECT";
case PM_CONN_SEC_ERROR_SMP_TIMEOUT:
return "SMP_TIMEOUT";
default:
return "UNKNOWN";
}
}
/**
* @brief Initialize BLE security
*/
@@ -102,8 +118,9 @@ void ble_security_quick_pm_handler(pm_evt_t const *p_evt)
// DEV mode: do not forward security failure events to SDK handler (prevent disconnect)
if (m_state.dev_mode && p_evt->evt_id == PM_EVT_CONN_SEC_FAILED) {
DBG_PRINTF("Security failed: error=%d\r\n",
p_evt->params.conn_sec_failed.error);
DBG_PRINTF("Security failed: error=%d (%s)\r\n",
p_evt->params.conn_sec_failed.error,
sec_error_name(p_evt->params.conn_sec_failed.error));
DBG_PRINTF("DEV: Ignoring sec failure, keeping connection\r\n");
return;
}
@@ -129,8 +146,9 @@ void ble_security_quick_pm_handler(pm_evt_t const *p_evt)
break;
case PM_EVT_CONN_SEC_FAILED:
DBG_PRINTF("Security failed: error=%d\r\n",
p_evt->params.conn_sec_failed.error);
DBG_PRINTF("Security failed: error=%d (%s)\r\n",
p_evt->params.conn_sec_failed.error,
sec_error_name(p_evt->params.conn_sec_failed.error));
if (m_state.dev_mode) {
// DEV mode: ignore security failure, keep connection
@@ -138,6 +156,20 @@ void ble_security_quick_pm_handler(pm_evt_t const *p_evt)
break;
}
if (p_evt->params.conn_sec_failed.error == PM_CONN_SEC_ERROR_DISCONNECT) {
// The peer/link already disconnected before security finished.
// There is no live connection to repair; BLE_GAP_EVT_DISCONNECTED
// will restart advertising.
DBG_PRINTF("Security ended by disconnect; waiting for reconnect\r\n");
break;
}
if (p_evt->params.conn_sec_failed.error == PM_CONN_SEC_ERROR_SMP_TIMEOUT) {
// The SDK cannot start another SMP procedure on this link.
pm_handler_disconnect_on_sec_failure(p_evt);
break;
}
if (p_evt->params.conn_sec_failed.error == PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING) {
// Key missing: attempt re-pairing, fall back to disconnect on failure
err_code = pm_conn_secure(p_evt->conn_handle, true);