apply latest local changes

This commit is contained in:
jhChun
2026-03-23 16:22:25 +09:00
parent 310ca152cf
commit 1cf688a296
16 changed files with 252 additions and 395 deletions

View File

@@ -365,6 +365,7 @@ dr_adc_err_t dr_adc_analyze_echo(const uint16_t *buffer, uint16_t num_samples,
/* Convert to voltage and time */
echo->peak_mv = dr_adc_raw_to_mv(echo->peak_raw);
/* peak_time_us: sample_index * 0.116us (8.6MHz sample rate) */
echo->peak_time_us = (uint32_t)((float)echo->peak_index * DR_ADC_SAMPLE_INTERVAL_US);
echo->num_samples = num_samples;
@@ -505,6 +506,9 @@ void dr_adc_print_buffer(const uint16_t *buffer, uint16_t num_samples)
extern void dr_binary_tx_safe(uint8_t const *ble_bin_buff, uint16_t length);
extern void dr_sd_delay_ms(uint32_t ms);
/* Platform interface (log function) */
#include "parser.h"
/*==============================================================================
* INTEGRATED BURST + CAPTURE + TRANSMIT
*============================================================================*/
@@ -649,7 +653,7 @@ dr_adc_err_t dr_adc_burst_capture_transmit(uint8_t freq_option, uint16_t delay_u
dr_adc_err_t err = dr_adc_capture_echo(m_echo_buffer, num_samples);
if (err != DR_ADC_OK) return err;
ADC_LOG("mec: single measurement (no averaging)");
//ADC_LOG("mec: single measurement (no averaging)");
}
else {
/*=== MULTIPLE MEASUREMENTS (with averaging) ===*/
@@ -795,7 +799,7 @@ dr_adc_err_t dr_adc_burst_capture_transmit(uint8_t freq_option, uint16_t delay_u
/*==============================================================================
* 4-CHANNEL CAPTURE FUNCTIONS (maa? command support)
* CHANNEL CAPTURE FUNCTIONS (maa? command support)
*============================================================================*/
dr_adc_err_t dr_adc_capture_channel_only(uint8_t freq_option, uint16_t delay_us,
@@ -816,31 +820,28 @@ dr_adc_err_t dr_adc_capture_channel_only(uint8_t freq_option, uint16_t delay_us,
static uint32_t accum_buffer[MAA_SAMPLES_MAX];
memset(accum_buffer, 0, num_samples * sizeof(uint32_t));
if (!m_initialized) {
if (!m_initialized)
{
dr_adc_err_t init_err = dr_adc_init();
if (init_err != DR_ADC_OK) return init_err;
}
nrf_delay_us(100);
/* Select piezo channel */
//nrf_delay_us(100);
/* 채널 선택(MUX) : 1.3ms */
dr_piezo_select_channel(piezo_ch);
/* Capture with averaging */
for (uint16_t avg_iter = 0; avg_iter < averaging; avg_iter++) {
if (avg_iter > 0) {
//nrf_delay_us(500); /* Echo decay time */
}
//dr_piezo_select_channel(piezo_ch);
/* Execute piezo burst */
/* 채널당 반복 측정 횟수만큼 */
for (uint16_t avg_iter = 0; avg_iter < averaging; avg_iter++)
{
/* TX 펄스 출력(Burst) */
switch (freq_option) {
case 0:
default:
dr_piezo_burst_sw_18mhz(cycles);
break;
case 1:
dr_piezo_burst_sw(cycles);
dr_piezo_burst_sw(cycles); /* 2.1MHz */
break;
case 2:
dr_piezo_burst_sw_20mhz(cycles);
@@ -850,24 +851,30 @@ dr_adc_err_t dr_adc_capture_channel_only(uint8_t freq_option, uint16_t delay_us,
break;
}
if (delay_us > 0) {
/* TX 펄스 출력 후 ADC 시작 시까지 대기 시간 */
if (delay_us > 0)
{
nrf_delay_us(delay_us);
}
/* Capture to internal buffer */
/* 측정 ADC 샘플 수만큼 캡처 */
dr_adc_err_t err = dr_adc_capture_echo(m_echo_buffer, num_samples);
if (err != DR_ADC_OK) return err;
/* Accumulate */
for (uint16_t i = 0; i < num_samples; i++) {
for (uint16_t i = 0; i < num_samples; i++)
{
accum_buffer[i] += m_echo_buffer[i];
}
}
/* Calculate average and copy to output */
for (uint16_t i = 0; i < num_samples; i++) {
for (uint16_t i = 0; i < num_samples; i++)
{
out_channel->samples[i] = (uint16_t)(accum_buffer[i] / averaging);
}
out_channel->num_samples = num_samples;
/* Analyze echo data */
@@ -877,8 +884,8 @@ dr_adc_err_t dr_adc_capture_channel_only(uint8_t freq_option, uint16_t delay_us,
out_channel->peak_index = echo.peak_index;
out_channel->baseline_raw = echo.baseline_raw;
ADC_LOG("maa capture CH%u: peak=%u idx=%u baseline=%u",
piezo_ch, out_channel->peak_raw, out_channel->peak_index, out_channel->baseline_raw);
/* peak, index, baseline 확인용 로그 */
//if (g_plat.log) g_plat.log("CH%u: peak=%u index=%u baseline=%u\r\n", piezo_ch, out_channel->peak_raw, out_channel->peak_index, out_channel->baseline_raw);
return DR_ADC_OK;
}
@@ -1059,7 +1066,8 @@ dr_adc_err_t dr_adc_transmit_channel_delta(const dr_maa_channel_t *ch_data,
/* Data packets (rdd:) */
uint16_t src_idx = 0;
for (uint16_t pkt = 0; pkt < data_packets; pkt++) {
for (uint16_t pkt = 0; pkt < data_packets; pkt++)
{
ble_buffer[0] = 'r';
ble_buffer[1] = 'd';
ble_buffer[2] = 'd';
@@ -1069,13 +1077,15 @@ dr_adc_err_t dr_adc_transmit_channel_delta(const dr_maa_channel_t *ch_data,
uint16_t dst_idx = 6;
uint16_t bytes_this_pkt = 0;
while (src_idx < compressed_size && bytes_this_pkt < cont_pkt_data_cap) {
while (src_idx < compressed_size && bytes_this_pkt < cont_pkt_data_cap)
{
ble_buffer[dst_idx++] = delta_buffer[src_idx++];
bytes_this_pkt++;
}
/* Pad to word boundary if needed */
if (dst_idx & 1) {
if (dst_idx & 1)
{
ble_buffer[dst_idx++] = 0;
}
@@ -1117,8 +1127,6 @@ static dr_adc_err_t maa_async_capture_channel(uint8_t ch)
{
if (ch > (MAA_NUM_CHANNELS - 1)) return DR_ADC_ERR_INVALID_PARAM;
if (g_plat.log) g_plat.log("[maa] capturing CH%u\r\n", ch);
dr_adc_err_t err = dr_adc_capture_channel_only(
g_maa_ctx.freq_option,
g_maa_ctx.delay_us,
@@ -1129,21 +1137,6 @@ static dr_adc_err_t maa_async_capture_channel(uint8_t ch)
&g_maa_ctx.channels[ch]
);
/* 캡처 성공 시 원시 데이터 덤프 (10진수) */
if (err == DR_ADC_OK && g_plat.log)
{
dr_maa_channel_t *c = &g_maa_ctx.channels[ch];
g_plat.log("[maa] CH%u raw (%u samples):\r\n", ch, c->num_samples);
for (uint16_t i = 0; i < c->num_samples; i++)
{
g_plat.log("%u ", c->samples[i]);
if ((i + 1) % 16 == 0) g_plat.log("\r\n");
}
if (c->num_samples % 16 != 0) g_plat.log("\r\n");
}
return err;
}
@@ -1176,13 +1169,25 @@ static void maa_async_send_header(void)
buf[13] = (uint8_t)(ch->num_samples >> 8);
dr_binary_tx_safe(buf, 7); /* 14 bytes = 7 words */
/* 50ms BLE 대기 시간을 활용하여 raw 덤프 로그 (캡처 시간에 영향 없음)
if (g_plat.log)
{
if (g_maa_ctx.current_ch > 0) g_plat.log("\r\n");
g_plat.log("CH%u raw (%u samples):\r\n", g_maa_ctx.current_ch, ch->num_samples);
for (uint16_t i = 0; i < ch->num_samples; i++)
{
g_plat.log("%u ", ch->samples[i]);
if ((i + 1) % 16 == 0) g_plat.log("\r\n");
}
if (ch->num_samples % 16 != 0) g_plat.log("\r\n");
}*/
dr_sd_delay_ms(50); /* Allow BLE stack to process TX */
g_maa_ctx.current_pkt = 0;
g_maa_ctx.data_offset = 0;
g_maa_ctx.state = MAA_ASYNC_TX_DATA;
ADC_LOG("maa_async: CH%u reb: sent (pkts=%u)", g_maa_ctx.current_ch, g_maa_ctx.total_packets);
}
/**
@@ -1225,7 +1230,7 @@ static bool maa_async_send_data_packet(void)
g_maa_ctx.data_offset += chunk_size;
g_maa_ctx.current_pkt++;
ADC_LOG("maa_async: CH%u red:%u (%u/%u bytes)", g_maa_ctx.current_ch, pkt_idx, g_maa_ctx.data_offset, total_data_bytes);
//ADC_LOG("maa_async: CH%u red:%u (%u/%u bytes)", g_maa_ctx.current_ch, pkt_idx, g_maa_ctx.data_offset, total_data_bytes);
return (g_maa_ctx.data_offset < total_data_bytes);
}
@@ -1246,15 +1251,13 @@ static void maa_async_send_completion(uint16_t status)
dr_binary_tx_safe(buf, 3);
/* 자동으로 켰으면 완료 후 전원 OFF */
if (g_maa_ctx.auto_powered) {
if (g_plat.log) g_plat.log("[Cmd_maa] TX/RX Active -> Sleep\r\n");
dr_piezo_power_off();
g_maa_ctx.auto_powered = false;
}
//if (g_plat.log) g_plat.log("-------------------------------------------------------------------------------------\r\n");
/* 캡처 완료 → Piezo TX/RX 전원 OFF */
dr_piezo_power_off();
g_maa_ctx.state = MAA_ASYNC_IDLE;
ADC_LOG("maa_async: complete, status=0x%04X", status);
//ADC_LOG("maa_async: complete, status=0x%04X", status);
/* 완료 콜백 호출 (mbb? 등에서 센서 측정 체인 트리거용) */
if (g_maa_ctx.on_complete_cb)
@@ -1269,9 +1272,7 @@ static void maa_async_send_completion(uint16_t status)
* PUBLIC ASYNC API
*============================================================================*/
dr_adc_err_t maa_async_start(uint8_t freq_option, uint16_t delay_us,
uint16_t num_samples, uint8_t cycles,
uint16_t averaging, uint8_t *ble_buffer)
dr_adc_err_t maa_async_start(uint8_t freq_option, uint16_t delay_us, uint16_t num_samples, uint8_t cycles, uint16_t averaging, uint8_t *ble_buffer)
{
dr_adc_err_t err;
uint8_t ch;
@@ -1298,28 +1299,25 @@ dr_adc_err_t maa_async_start(uint8_t freq_option, uint16_t delay_us,
g_maa_ctx.data_offset = 0;
g_maa_ctx.on_complete_cb = NULL; /* 기본: 콜백 없음 (maa?) */
ADC_LOG("maa_async_start: freq=%u delay=%u samples=%u cycles=%u avg=%u",
freq_option, delay_us, num_samples, g_maa_ctx.cycles, g_maa_ctx.averaging);
/* 전채널 캡처: BLE 전송 없이 6채널 전부 캡처 완료 후 TX 시작 */
g_maa_ctx.state = MAA_ASYNC_CAPTURING;
for (ch = 0; ch < MAA_NUM_CHANNELS; ch++)
{
err = maa_async_capture_channel(ch);
if (err != DR_ADC_OK)
{
//ADC_LOG("maa_async_start: CH%u capture failed (%d)", ch, err);
if (g_plat.log) g_plat.log("[maa] maa_async_start: CH%u capture failed (%d)", ch, err);
maa_async_send_completion(0xFFF0 | ch);
return err;
}
}
//ADC_LOG("maa_async_start: all channels captured, starting TX");
if (g_plat.log) g_plat.log("[maa] maa_async_start: all channels captured, starting TX");
/* 캡처 완료 → 피에조 전원 OFF (BLE 전송 중 불필요) */
/* peak 로그와 raw 덤프 사이 구분 */
//if (g_plat.log) g_plat.log("\r\n");
/* 캡처 완료 → Piezo TX/RX 전원 OFF (BLE 전송 중 불필요) */
dr_piezo_power_off();
g_maa_ctx.auto_powered = false; /* 이미 껐으므로 완료 후 중복 OFF 방지 */
/* Send CH0 header - this will trigger TX_RDY for subsequent packets */
maa_async_send_header();
@@ -1398,11 +1396,6 @@ void maa_async_abort(void)
}
}
void maa_async_set_auto_power(bool on)
{
g_maa_ctx.auto_powered = on;
}
void maa_async_set_on_complete(void (*cb)(void))
{
g_maa_ctx.on_complete_cb = cb;

View File

@@ -454,7 +454,6 @@ typedef struct {
dr_maa_channel_t channels[MAA_NUM_CHANNELS]; /**< Captured data for each channel */
uint16_t total_packets; /**< Total packets for current channel */
uint16_t data_packets; /**< Data packets for current channel */
bool auto_powered; /**< true: 자동 전원 ON → 완료 후 OFF */
bool pre_capture_all; /**< true: 전채널 캡처 완료 후 일괄 전송 (mbb용) */
void (*on_complete_cb)(void); /**< 비동기 캡처 완료 후 호출될 콜백 (NULL이면 미사용) */
} maa_async_ctx_t;

View File

@@ -194,25 +194,27 @@ static bool dr_get_u16(const ParsedCmd *cmd, uint8_t word_index, uint16_t *out)
* out: 추출된 문자열 저장 버퍼 (max_len+1 이상 크기 필요)
* max_len: 최대 추출 길이 (바이트)
*/
static void dr_get_ascii(const ParsedCmd *cmd, uint8_t offset,
char *out, uint8_t max_len)
static void dr_get_ascii(const ParsedCmd *cmd, uint8_t offset, char *out, uint8_t max_len)
{
uint8_t i;
uint8_t remain;
/* 오프셋이 데이터 범위를 초과하면 빈 문자열 반환 */
if (offset >= cmd->data_len) {
if (offset >= cmd->data_len)
{
out[0] = '\0';
return;
}
/* 실제 복사 가능한 길이 계산 (남은 데이터 vs 최대 길이 중 작은 값) */
remain = (uint8_t)(cmd->data_len - offset);
if (remain > max_len) {
if (remain > max_len)
{
remain = max_len;
}
for (i = 0; i < remain; i++) {
for (i = 0; i < remain; i++)
{
out[i] = (char)cmd->data[offset + i];
}
out[remain] = '\0'; /* 널 종료 보장 */
@@ -259,7 +261,8 @@ static bool dr_crc16_check_packet(const uint8_t *packet, uint32_t packet_len)
uint16_t expected_crc;
uint32_t data_len;
if (packet_len < 2) {
if (packet_len < 2)
{
return false; /* 최소 CRC 2바이트도 없으면 실패 */
}
@@ -269,10 +272,6 @@ static bool dr_crc16_check_packet(const uint8_t *packet, uint32_t packet_len)
expected_crc = (uint16_t)packet[packet_len - 2]
| ((uint16_t)packet[packet_len - 1] << 8);
if (g_plat.log && g_log_enable) {
g_plat.log("CRC check: expected=0x%04X\n", expected_crc);
}
return dr_crc16_check(packet, data_len, expected_crc);
}
@@ -294,8 +293,10 @@ static bool dr_parse_cmd(const uint8_t *buffer, uint8_t length, ParsedCmd *out)
}
/* CRC 검증이 활성화된 경우 패킷 무결성 확인 */
if (g_plat.crc_check) {
if (!dr_crc16_check_packet(buffer, length)) {
if (g_plat.crc_check)
{
if (!dr_crc16_check_packet(buffer, length))
{
if (g_plat.log && g_log_enable) {
g_plat.log("CRC check FAILED!\n");
}
@@ -304,10 +305,6 @@ static bool dr_parse_cmd(const uint8_t *buffer, uint8_t length, ParsedCmd *out)
/* CRC 검증 성공 → CRC 2바이트를 제외한 실제 데이터 길이로 조정 */
length = (uint8_t)(length - 2);
if (g_plat.log && g_log_enable) {
g_plat.log("CRC check OK\n");
}
}
/* TAG 4바이트 복사 */
@@ -315,20 +312,17 @@ static bool dr_parse_cmd(const uint8_t *buffer, uint8_t length, ParsedCmd *out)
/* TAG 이후 데이터 길이 계산 (최대 DR_MAX_DATA까지) */
out->data_len = (length > 4) ? (uint8_t)(length - 4) : 0;
if (out->data_len > DR_MAX_DATA) {
if (out->data_len > DR_MAX_DATA)
{
out->data_len = DR_MAX_DATA;
}
/* TAG 뒤의 데이터 바이트를 ParsedCmd.data[]에 복사 */
for (i = 0; i < out->data_len; i++) {
for (i = 0; i < out->data_len; i++)
{
out->data[i] = buffer[4 + i];
}
if (g_plat.log && g_log_enable) {
g_plat.log("parse_cmd: TAG='%s', data_len=%u\n",
out->tag, out->data_len);
}
return true;
}
@@ -491,16 +485,12 @@ static int dr_cmd_dispatch(const ParsedCmd *cmd)
return 0;
}
if (g_plat.log && g_log_enable) {
g_plat.log("Run handler '%s'\n", cmd->tag);
}
/* 매칭된 핸들러 호출 */
return g_cmd_table[i].handler(cmd);
}
}
/* 테이블에 없는 미지의 TAG */
/* 테이블에 없는 TAG 수신 시 */
if (g_plat.log && g_log_enable) {
g_plat.log("Unknown TAG '%s'\n", cmd->tag);
}
@@ -522,8 +512,6 @@ int dr_cmd_parser(const uint8_t *buf, uint8_t len)
{
ParsedCmd cmd;
if (g_plat.log) g_plat.log("[PARSER] in len=%u crc=%u\r\n", len, g_plat.crc_check);
/* 패킷 파싱 (CRC 검증 포함) */
if (!dr_parse_cmd(buf, len, &cmd)) {
if (g_plat.log) g_plat.log("[PARSER] PARSE FAIL\r\n");
@@ -536,7 +524,8 @@ int dr_cmd_parser(const uint8_t *buf, uint8_t len)
return -1; /* CRC/파싱 실패 → 음수 반환으로 레거시 파서에 위임 */
}
if (g_plat.log) g_plat.log("[PARSER] tag=%s\r\n", cmd.tag);
/* 수신 명령어 종류 확인용 로그 */
//if (g_plat.log) g_plat.log("[PARSER] tag=%s\r\n", cmd.tag);
/* 파싱 성공 → 명령 테이블에서 핸들러를 찾아 실행 */
return dr_cmd_dispatch(&cmd);
@@ -551,9 +540,6 @@ int dr_cmd_parser(const uint8_t *buf, uint8_t len)
static int Cmd_msn(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_msn] Measure battery level\n");
}
battery_level_meas(); /* ADC로 배터리 전압 측정 → BLE 응답 전송 */
return 1;
}
@@ -564,9 +550,6 @@ static int Cmd_msn(const ParsedCmd *cmd)
static int Cmd_mso(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mso] TMP235 temperature measurement\n");
}
tmp235_voltage_level_meas();
return 1;
}
@@ -596,9 +579,6 @@ static int Cmd_msi(const ParsedCmd *cmd)
main_timer_start(); /* 타이머 콜백에서 IMU 데이터 읽기 + BLE 전송 */
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_msi] Motion sensor raw, once=%u\r\n", motion_data_once);
}
return 1;
}
@@ -636,7 +616,7 @@ static int Cmd_msr(const ParsedCmd *cmd)
{
uint16_t val = 0;
dr_get_u16(cmd, 0, &val);
if (g_plat.log) g_plat.log("[Cmd_msr] Bond delete + reset val=%u\r\n", val);
//if (g_plat.log) g_plat.log("[Cmd_msr] Bond delete + reset val=%u\r\n", val);
single_format_data(ble_bin_buffer, "rsr:", val);
dr_binary_tx_safe(ble_bin_buffer, 2);
@@ -656,13 +636,13 @@ static int Cmd_msr(const ParsedCmd *cmd)
/* mss? - 디바이스 소프트 리셋 (리부팅)
*
* msr?과 유사하지만 본딩 정보는 삭제하지 않음
* 리셋 상태 코드를 FDS에 저장하여 부팅 시 리셋 원인 확인 가능
* 리셋 상태 코드를 FDS에 저장하여 부팅 시 리셋 원인 확인 가능 =======> val 파라미터 확인
*/
static int Cmd_mss(const ParsedCmd *cmd)
{
uint16_t val = 0;
dr_get_u16(cmd, 0, &val);
if (g_plat.log) g_plat.log("[Cmd_mss] Device reset val=%u\r\n", val);
//if (g_plat.log) g_plat.log("[Cmd_mss] Device reset val=%u\r\n", val);
single_format_data(ble_bin_buffer, "rss:", val);
dr_binary_tx_safe(ble_bin_buffer, 2);
@@ -683,9 +663,6 @@ static int Cmd_mss(const ParsedCmd *cmd)
static int Cmd_mfv(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mfv] FW=%s\r\n", DR_DEVICE_VERSION);
}
ascii_format_data(ble_bin_buffer, "rfv:", DR_DEVICE_VERSION, 12);
dr_binary_tx_safe(ble_bin_buffer, 8); /* 4(TAG) + 12(버전) = 16바이트 = 8워드 */
return 1;
@@ -701,13 +678,10 @@ static int Cmd_mpa(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mpa] Piezo Activation\n");
}
dr_piezo_power_on(); /* 부팅 시 init 완료, 전원만 ON */
dr_piezo_system_init(); /* 내부에서 power_on + init 수행 */
if (g_plat.tx_bin) {
if (g_plat.tx_bin)
{
single_format_data(ble_bin_buffer, "rpa:", 1);
dr_binary_tx_safe(ble_bin_buffer, 3);
}
@@ -724,10 +698,6 @@ static int Cmd_mpb(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mpb] Piezo Deactivation\n");
}
dr_piezo_power_off(); /* 피에조 보드 전원 OFF */
if (g_plat.tx_bin) {
@@ -772,19 +742,9 @@ static int Cmd_mpc(const ParsedCmd *cmd)
/* 채널 범위 검증: 초과 시 0으로 리셋 */
if (piezo_ch >= MAA_NUM_CHANNELS) piezo_ch = 0;
if (g_plat.log && g_log_enable) {
const char *freq_str = (freq_option == 0) ? "1.8MHz" :
(freq_option == 1) ? "2.1MHz" :
(freq_option == 2) ? "2.0MHz" :
(freq_option == 3) ? "1.7MHz" :
(freq_option == 4) ? "2.2MHz" :
(freq_option == 9) ? "1.9MHz" : "unknown";
g_plat.log("[Cmd_mpc] cycles=%u, freq=%u (%s), piezo=%u\r\n",
cycles, freq_option, freq_str, piezo_ch);
}
/* 사이클 범위 검증: 3~7 유효 */
if (cycles < 3 || cycles > 7) {
if (cycles < 3 || cycles > 7)
{
dr_ble_return_1("rpc:", 2); /* 에러 응답: 범위 초과 */
return 1;
}
@@ -793,7 +753,8 @@ static int Cmd_mpc(const ParsedCmd *cmd)
dr_piezo_select_channel((uint8_t)piezo_ch);
/* 선택된 주파수로 버스트 펄스 발생 */
switch (freq_option) {
switch (freq_option)
{
case 0: dr_piezo_burst_sw_18mhz((uint8_t)cycles); break; /* 1.8MHz */
case 2: dr_piezo_burst_sw_20mhz((uint8_t)cycles); break; /* 2.0MHz */
case 3: dr_piezo_burst_sw_17mhz((uint8_t)cycles); break; /* 1.7MHz */
@@ -810,8 +771,6 @@ static int Cmd_mpc(const ParsedCmd *cmd)
}
/* 2026-03-17: mdc? 삭제 (12비트 압축 전송, mec?로 대체) */
/**
* @brief mec? - 피에조 버스트 + 에코 캡처 (16비트 원시 데이터, 무압축)
*
@@ -844,9 +803,10 @@ static int Cmd_mec(const ParsedCmd *cmd)
uint16_t piezo_ch = 0; /* 기본 채널 0 (유효: 0~7) */
/* 피에조 전원이 꺼져 있으면 켜기 */
if (!dr_piezo_is_power_on()) {
if (g_plat.log) g_plat.log("[Cmd_mec] TX/RX Sleep -> Active\r\n");
dr_piezo_system_init();
if (!dr_piezo_is_power_on())
{
//if (g_plat.log) g_plat.log("[Cmd_mec] TX/RX Sleep -> Active\r\n");
dr_piezo_power_on();
}
/* 6개 파라미터 순서대로 추출 (데이터 부족 시 기본값 유지) */
@@ -863,7 +823,8 @@ static int Cmd_mec(const ParsedCmd *cmd)
/* 피에조 채널 범위 검증 */
if (piezo_ch >= MAA_NUM_CHANNELS) piezo_ch = 0;
/*
if (g_plat.log && g_log_enable) {
const char *freq_str = (freq_option == 0) ? "1.8MHz" :
(freq_option == 1) ? "2.1MHz" :
@@ -871,9 +832,10 @@ static int Cmd_mec(const ParsedCmd *cmd)
(freq_option == 3) ? "1.7MHz" :
(freq_option == 4) ? "2.2MHz" :
(freq_option == 9) ? "1.9MHz" : "unknown";
g_plat.log("[Cmd_mec] freq=%u (%s), delay=%uus, samples=%u, cycles=%u, avg=%u, piezo=%u\r\n",
g_plat.log("[Parameter] freq=%u (%s), delay=%uus, samples=%u, cycles=%u, avg=%u, piezo=%u\r\n",
freq_option, freq_str, delay_us, num_samples, cycles, averaging, piezo_ch);
}
*/
/* 통합 버스트+캡처+전송 함수 호출 */
dr_adc_err_t err = dr_adc_burst_capture_transmit(
@@ -885,10 +847,10 @@ static int Cmd_mec(const ParsedCmd *cmd)
dr_ble_return_2("rer:", 0xEE00 | (uint16_t)err, num_samples);
}
/* raw 데이터 덤프
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mec] result=%d\r\n", err);
/* raw 데이터 덤프 */
const uint16_t *buf = dr_adc_get_echo_buffer();
g_plat.log("[mec] CH%u raw (%u samples):\r\n", piezo_ch, num_samples);
for (uint16_t i = 0; i < num_samples; i++) {
@@ -896,10 +858,9 @@ static int Cmd_mec(const ParsedCmd *cmd)
if ((i + 1) % 16 == 0) g_plat.log("\r\n");
}
if (num_samples % 16 != 0) g_plat.log("\r\n");
}
}*/
/* 측정 완료 후 무조건 전원 OFF */
if (g_plat.log) g_plat.log("[Cmd_mec] TX/RX Active -> Sleep\r\n");
/* 측정 완료 후 Piezo TX/RX Sleep */
dr_piezo_power_off();
return 1;
@@ -988,48 +949,24 @@ static int Cmd_maa(const ParsedCmd *cmd)
{
dr_adc_err_t err;
/* 파라미터 5개 수신 시 FDS에 저장 — 디버그 중 비활성화
if (cmd->data_len >= 10) {
uint16_t freq, cycles, averaging, delay_us, num_samples;
dr_get_u16(cmd, 0, &freq);
dr_get_u16(cmd, 1, &cycles);
dr_get_u16(cmd, 2, &averaging);
dr_get_u16(cmd, 3, &delay_us);
dr_get_u16(cmd, 4, &num_samples);
m_config.piezo_freq_option = (uint8_t)freq;
m_config.piezo_cycles = (uint8_t)cycles;
m_config.piezo_averaging = averaging;
m_config.piezo_delay_us = delay_us;
m_config.piezo_num_samples = num_samples;
config_save();
if (g_plat.log) g_plat.log("[Cmd_maa] params updated: freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n",
m_config.piezo_freq_option, m_config.piezo_cycles,
m_config.piezo_averaging, m_config.piezo_delay_us,
m_config.piezo_num_samples);
}
*/
/* 이전 캡처가 진행 중인지 확인 (비동기이므로 중복 실행 방지) */
if (maa_async_is_busy()) {
if (maa_async_is_busy())
{
dr_ble_return_1("raa:", 0xFFFE); /* 처리 중(Busy) 에러 */
return 1;
}
/* 피에조 전원: OFF일 경우 ON → 완료 후 OFF */
/* Piezo TX/RX 전원: OFF일 경우 ON → maa_async_start()에서 캡처 완료 후 OFF */
if (!dr_piezo_is_power_on())
{
if (g_plat.log) g_plat.log("[Cmd_maa] TX/RX Sleep -> Active\r\n");
dr_piezo_system_init();
//if (g_plat.log) g_plat.log("[Cmd_maa] TX/RX Sleep -> Active\r\n");
dr_piezo_power_on();
}
/*=======================================================================
* 비동기 6채널 캡처 시작
* - maa_async_start(): CH0 캡처 실행 + 첫 헤더 패킷 전송
* - 이후 패킷은 BLE_NUS_EVT_TX_RDY 콜백에서 자동 전송
* - 블로킹 딜레이 없음 → SoftDevice 이벤트 정상 처리 가능
* - auto_powered=true면 완료 후 자동 전원 OFF
*=======================================================================*/
err = maa_async_start(
m_config.piezo_freq_option,
@@ -1040,7 +977,8 @@ static int Cmd_maa(const ParsedCmd *cmd)
ble_bin_buffer
);
if (err != DR_ADC_OK) {
if (err != DR_ADC_OK)
{
/* 시작 실패 → 에러 응답 전송 (앱 타임아웃 방지) */
if (g_plat.log) g_plat.log("[Cmd_maa] start failed err=%d\r\n", err);
single_format_data(ble_bin_buffer, "raa:", (uint16_t)(0xFF00 | err));
@@ -1049,12 +987,6 @@ static int Cmd_maa(const ParsedCmd *cmd)
return 1;
}
/* 측정 완료 시 무조건 전원 OFF */
//maa_async_set_auto_power(true);
//dr_piezo_power_off();
/* 즉시 반환 → 비동기 전송 진행 중 */
/* 전체 완료 시 상태 머신이 "raa:" 응답 + 자동 power off 처리 */
return 1;
}
@@ -1066,28 +998,25 @@ static int Cmd_maa(const ParsedCmd *cmd)
* info4 모드로 센서값을 전역 변수에 저장한 뒤, rbb: 패킷으로 일괄 전송
* SAADC 측정은 비동기(콜백)이므로 dr_sd_delay_ms()로 완료 대기
*
* 순서: 배터리 → IMU → (피에조 ON) → 온도
* 순서: 배터리 → IMU → (Piezo TX/RX ON) → 온도
* 응답: rbb: [배터리mV(2)] [IMU 6축(12)] [온도°Cx100(2)] = 20바이트
*/
static void all_sensors(void)
{
if (g_plat.log) g_plat.log("[Cmd_mbb] measuring sensors\r\n");
info4 = true; /* 센서값을 전역 변수에 저장 (BLE 전송 안 함) */
/* 1) 배터리 전압 측정 → info_batt에 저장 */
/* 1. 배터리 전압 측정 → info_batt에 저장 */
battery_level_meas();
dr_sd_delay_ms(1); /* SAADC 콜백 완료 대기 */
/* 2) IMU 6축 단발 읽기 → info_imu[6]에 저장 */
/* 2. IMU 6축 단발 읽기 → info_imu[6]에 저장 */
hw_i2c_init_once();
imu_read_direct();
/* 3) 온도 측정 → info_temp에 저장 (TMP235는 피에조 전원 필요) */
/* 3. 온도 측정 → info_temp에 저장 (TMP235는 Piezo TX/RX 전원 필요) */
if (!dr_piezo_is_power_on())
{
if (g_plat.log) g_plat.log("[Cmd_mbb] TX/RX Sleep -> Active for TEMP\r\n");
dr_piezo_system_init();
dr_piezo_power_on();
}
tmp235_voltage_level_meas();
@@ -1111,10 +1040,11 @@ static void all_sensors(void)
buf[18] = (uint8_t)(info_temp & 0xFF);
buf[19] = (uint8_t)(info_temp >> 8);
if (g_plat.log) g_plat.log("[Cmd_mbb] rbb: TX before send, in_progress=%d\r\n", (int)data_tx_in_progress);
dr_binary_tx_safe(buf, 10); /* 20바이트 = 10워드 */
if (g_plat.log) g_plat.log("[Cmd_mbb] rbb: sent (batt=%u temp=%u)\r\n", info_batt, info_temp);
/* 배터리, IMU, 온도 확인용 로그 */
//if (g_plat.log) g_plat.log("-------------------------------------------------------------------------------------\r\n[Battery] %u\r\n[IMU] %d,%d,%d,%d,%d,%d\r\n[Temperature] %u\r\n\r\n", info_batt, (int16_t)info_imu[0], (int16_t)info_imu[1], (int16_t)info_imu[2],
//(int16_t)info_imu[3], (int16_t)info_imu[4], (int16_t)info_imu[5], info_temp);
}
@@ -1123,8 +1053,6 @@ static void all_sensors(void)
*
* 센서 측정(rbb:) → 6채널 비동기 캡처(reb:/red:/raa:) → TX/RX OFF
*
* 파라미터: mode (uint16, word 0) - 현재 mode=0만 지원
*
* 응답 흐름:
* 1) 센서 측정: rbb: [배터리(2) + IMU 6축(12) + 온도(2)]
* 2) 각 채널(CH0~CH5): reb: [헤더] → red: [데이터...]
@@ -1135,30 +1063,7 @@ static int Cmd_mbb(const ParsedCmd *cmd)
{
dr_adc_err_t err;
if (g_plat.log) g_plat.log("[Cmd_mbb] params updated: freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n",
m_config.piezo_freq_option, m_config.piezo_cycles,
m_config.piezo_averaging, m_config.piezo_delay_us,
m_config.piezo_num_samples);
// 파라미터 5개 수신 시 FDS에 저장 — 디버그 중 비활성화
/*
if (cmd->data_len >= 10) {
uint16_t freq, cycles, averaging, delay_us, num_samples;
dr_get_u16(cmd, 0, &freq);
dr_get_u16(cmd, 1, &cycles);
dr_get_u16(cmd, 2, &averaging);
dr_get_u16(cmd, 3, &delay_us);
dr_get_u16(cmd, 4, &num_samples);
m_config.piezo_freq_option = (uint8_t)freq;
m_config.piezo_cycles = (uint8_t)cycles;
m_config.piezo_averaging = averaging;
m_config.piezo_delay_us = delay_us;
m_config.piezo_num_samples = num_samples;
config_save();
}*/
all_sensors();
all_sensors(); /* 배터리, IMU, 온도 센서 먼저 측정 */
if (maa_async_is_busy())
{
@@ -1166,22 +1071,16 @@ static int Cmd_mbb(const ParsedCmd *cmd)
return 1;
}
/* 피에조 전원: OFF일 경우 ON */
if (!dr_piezo_is_power_on())
{
if (g_plat.log) g_plat.log("[Cmd_mbb] TX/RX Sleep -> Active\r\n");
dr_piezo_system_init();
}
if (g_plat.log) g_plat.log("[Cmd_mbb] freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n",
/* 측정 파라미터 확인용 로그
if (g_plat.log) g_plat.log("[Parameter] freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n\r\n",
m_config.piezo_freq_option, m_config.piezo_cycles,
m_config.piezo_averaging, m_config.piezo_delay_us,
m_config.piezo_num_samples);
m_config.piezo_num_samples);*/
/* 전채널 선캡처 모드: 모든 채널 캡처 완료 후 BLE 전송 */
/* 전채널 선캡처 모드: 모든 채널 캡처 완료 후 BLE 전송하도록 */
maa_async_set_pre_capture_all(true);
/* 비동기 6채널 캡처 시작 (m_config 파라미터 사용) */
/* 비동기 6채널 캡처 시작 (FDS m_config 파라미터 사용) */
err = maa_async_start(
m_config.piezo_freq_option,
m_config.piezo_delay_us,
@@ -1222,11 +1121,6 @@ static int Cmd_mcf(const ParsedCmd *cmd)
buf[12] = (uint8_t)(m_config.piezo_num_samples & 0xFF); buf[13] = (uint8_t)(m_config.piezo_num_samples >> 8);
dr_binary_tx_safe(buf, 7); /* 14바이트 = 7워드 */
if (g_plat.log) g_plat.log("[Cmd_mcf] freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n",
m_config.piezo_freq_option, m_config.piezo_cycles,
m_config.piezo_averaging, m_config.piezo_delay_us,
m_config.piezo_num_samples);
return 1;
}
@@ -1239,7 +1133,8 @@ static int Cmd_mcf(const ParsedCmd *cmd)
*/
static int Cmd_mcs(const ParsedCmd *cmd)
{
if (cmd->data_len < 10) {
if (cmd->data_len < 10)
{
if (g_plat.log) g_plat.log("[Cmd_mcs] missing params (data_len=%u)\r\n", cmd->data_len);
dr_ble_return_1("rcs:", 0xFFFF);
return 1;
@@ -1259,10 +1154,12 @@ static int Cmd_mcs(const ParsedCmd *cmd)
m_config.piezo_num_samples = num_samples;
config_save();
/*
if (g_plat.log) g_plat.log("[Cmd_mcs] saved: freq=%u cyc=%u avg=%u delay=%u samples=%u\r\n",
m_config.piezo_freq_option, m_config.piezo_cycles,
m_config.piezo_averaging, m_config.piezo_delay_us,
m_config.piezo_num_samples);
*/
uint8_t *buf = ble_bin_buffer;
buf[0] = 'r'; buf[1] = 'c'; buf[2] = 's'; buf[3] = ':';
@@ -1294,7 +1191,8 @@ static int Cmd_mwh(const ParsedCmd *cmd)
char buf[13];
/* 최소 12바이트 데이터 필요 */
if (cmd->data_len < 12) {
if (cmd->data_len < 12)
{
dr_ble_return_1("rwh:", 0xFFFF); /* 데이터 부족 에러 */
return 1;
}
@@ -1303,11 +1201,7 @@ static int Cmd_mwh(const ParsedCmd *cmd)
dr_get_ascii(cmd, 0, buf, 12);
memcpy(HW_NO, buf, 12);
memcpy(m_config.hw_no, buf, 12);
config_save(); /* FDS(Flash)에 영구 저장 */
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mwh] HW=%.12s saved to FDS\r\n", m_config.hw_no);
}
config_save(); /* FDS(Flash Memory)에 저장 */
ascii_format_data(ble_bin_buffer, "rwh:", buf, 12);
dr_binary_tx_safe(ble_bin_buffer, 8);
@@ -1331,11 +1225,7 @@ static int Cmd_mws(const ParsedCmd *cmd)
dr_get_ascii(cmd, 0, buf, 12);
memcpy(SERIAL_NO, buf, 12);
memcpy(m_config.serial_no, buf, 12);
config_save();
if (g_plat.log && g_log_enable) {
g_plat.log("[Cmd_mws] S/N=%.12s saved to FDS\r\n", m_config.serial_no);
}
config_save(); /* FDS(Flash Memory)에 저장 */
ascii_format_data(ble_bin_buffer, "rws:", buf, 12);
dr_binary_tx_safe(ble_bin_buffer, 8);
@@ -1379,9 +1269,7 @@ static int Cmd_mpz(const ParsedCmd *cmd)
memcpy(m_static_passkey, passkey, 6);
memcpy(m_config.static_passkey, m_static_passkey, 6);
config_save();
if (g_plat.log) g_plat.log("[mpz] Passkey saved: %.6s\r\n", m_static_passkey);
config_save(); /* FDS(Flash Memory)에 저장 */
ascii_format_data(ble_bin_buffer, "rpz:", passkey, 6);
dr_binary_tx_safe(ble_bin_buffer, 5);
@@ -1397,8 +1285,6 @@ static int Cmd_mqz(const ParsedCmd *cmd)
(void)cmd;
memcpy(m_static_passkey, m_config.static_passkey, 6);
if (g_plat.log) g_plat.log("[mqz] Passkey read: %.6s\r\n", m_static_passkey);
ascii_format_data(ble_bin_buffer, "rqz:", m_static_passkey, 6);
dr_binary_tx_safe(ble_bin_buffer, 5);
return 1;
@@ -1420,13 +1306,10 @@ static int Cmd_msp(const ParsedCmd *cmd)
{
(void)cmd;
if (g_plat.log) g_plat.log("[MSP] enter\r\n");
hw_i2c_init_once(); /* I2C 버스 초기화 (최초 1회) */
/* IMU 레지스터 직접 읽기 - 타이머, DRDY 인터럽트, 콜백 없이 동기 실행 */
int rc = imu_read_direct();
if (g_plat.log) g_plat.log("[MSP] rc=%d\r\n", rc);
return 1;
}