/*******************************************************************************
 * @file	main.h
 * @author	CandyPops Co.
 * @version	V1.0.0
 * @date	2022-09-05
 * @brief   VesiScan BASIC main header file
 *
 * [System Overview]
 * VesiScan BASIC is an nRF52840-based BLE bladder monitoring patch device.
 * This header defines enums, function declarations, and global variables used system-wide.
 *
 * [Communication]
 * - BLE NUS (Nordic UART Service): binary protocol with smartphone app
 * - Physical UART (1Mbps): debug and factory testing
 *
 * [Data Transmission Flow]
 * 1. Receive command from app/UART -> received_command_process()
 * 2. Collect sensor data (battery, temperature, IMU, pressure)
 * 3. Build binary packets via format_data() family
 * 4. Transmit over BLE with CRC16 appended via dr_binary_tx_safe()
 ******************************************************************************/

#ifndef MAIN_H__
#define MAIN_H__

/* -------------------------------------------------------------------------
* Firmware Identification Code
*   - VBTFW0100 = Development (test) build Ver 1.00
*   - VB0FW0100 = Production build Ver 1.00
*
* 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 260422 jhChun : Updated firmware version for test.
*   - VBTFW0112 260428 jhChun : Added extra CH0 settling delay after MUX selection for maa capture.
*   - VBTFW0113 260430 jhChun : Changed piezo MUX settling delay after channel selection from busy-wait to TIMER4-based wait.
*   - VBTFW0114 260430 jhChun : Added delay time between averaged bursts to reduce residual echo carry-over.
*   - VBTFW0115 260518 jhChun
*      : Added mtb? command (reb:+raa:+rim:, 6ch piezo + ICM42670 FIFO at 50 Hz).
*      : rim: packet format and FIFO sample cap/filter options (app_raw).
*   - VBTFW0116 260522 jhChun : Expanded BLE TX pending slots from 1 → 8 to reduce ADC data packet loss when the TX queue is full
*   - VBTFW0117 260527 jhChun : Prevent battery/temperature safety checks from powering off piezo during MAA capture, and lock BLE PHY to 1M.
*   - VBTFW0118 260601 jhChun
*      : Added channel information(2B) to the ADC raw data response packet (reb:).
*      : Replaced TMP235 temperature with IMU register direct-read temperature in the rbb: response.
*   - VBTFW0119 260615 jhChun
*      : Replaced all TMP235 temperature paths with IMU register direct-read temperature and removed legacy TMP235 build references.
*      : Unify both IMU direct-read and FIFO outputs as raw data in datasheet axis convention.
*   - VBTFW0120 260615 jhChun : Add EMC mitigation logic for BLE link stability: extended supervision timeout and dynamic TX power control based on RSSI, RSSI silence, HVN latency, and TX queue congestion.
------------------------------------------------------------------------- */
#define FIRMWARE_VERSION                "VBTFW0120"

/*==============================================================================
 * Data Length Constants
 *============================================================================*/
#define SERIAL_NO_LENGTH                12      /* Serial number length (e.g. "VB026030000") */
#define HW_NO_LENGTH                    12      /* Hardware number (version) length */
#define PASSKEY_LENGTH                  6       /* BLE pairing passkey length (6 digits) */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include "boards.h"

/*==============================================================================
 * Enum Definitions
 *============================================================================*/

/* Device ON/OFF control enum (EEPROM, power, etc.) */
typedef enum
{
    OFF	= 0,        /* Off */
    ON	= 1         /* On */
}on_off_cont_t;

/* Command source identifier (BLE or UART) */
typedef enum
{
    CMD_BLE		= 0,    /* Command received via BLE NUS */
    CMD_UART	= 1     /* Command received via physical UART */
}which_cmd_t;

/* Chamber auto-test mode (when FEATURE_CHAMBER_AUTO_TEST enabled) */
#if FEATURE_CHAMBER_AUTO_TEST
typedef enum
{
	SIMPLE_AUTO_MODE 	= 0,    /* Simple auto mode */
    HALF_AUTO_MODE		= 1,    /* Semi-auto mode */
    FULL_AUTO_MODE		= 2,    /* Full auto mode */
    NONE_AUTO_MODE		= 3     /* No auto mode */
}auto_meas_mode_t;
#endif

/* BLE connection state */
typedef enum
{
    BLE_DISCONNECTED_ST 	= 0,    /* BLE disconnected */
    BLE_CONNECTED_ST		= 1     /* BLE connected */
}ble_status_t;

/*==============================================================================
 * Function Declarations
 *============================================================================*/

#if FEATURE_SECURE_CONNECTION
/* Start BLE advertising (if erase_bonds=true, delete bond info first) */
static void advertising_start(bool erase_bonds);
#endif

/* Enter sleep mode: show LED, then power off after POWER_OFF_DELAY (3s) */
void sleep_mode_enter(void);

/* Power-off timer callback: physically cut power after POWER_OFF_DELAY */
static void t_power_off_timeout_handler(void * p_context);

/* Device power off: show LED, then delayed power cut via timer */
void device_power_off(void);

/* Power control handler: physical power ON/OFF via POWER_HOLD pin */
static void power_control_handler(on_off_cont_t device_power_st);

/* Power button state machine (timer callback, 5ms interval):
 * - Short press (<1.5s): power OFF
 * - Medium press (1.5s~10s): start boot sequence
 * - Long press (>10s): factory reset (passkey reset + power OFF) */
static void main_s(void * p_context);

/* Peer Manager timer callback: force BLE disconnect if reset_status==5 */
static void PM_s(void * p_context);

//static void main_re(void * p_context);

/* Main routine handler (legacy, currently unused) */
static void main_routine_handler(void * p_context);

/*------------------------------------------------------------------------------
 * Data Transmission Functions
 *----------------------------------------------------------------------------*/

/* Send ASCII text over BLE (up to '\r', CRC16 appended automatically) */
void data_tx_handler(char const *p_data_to_send);

/* Safe binary data BLE transmission (CRC16 appended, with retry logic)
 * @param ble_bin_buff  Binary buffer to transmit
 * @param length        Data length in uint16_t words (actual bytes = length x 2) */
uint32_t dr_binary_tx_safe(uint8_t const *ble_bin_buff, uint16_t length);

/* SoftDevice-compatible delay (nrf_delay_ms wrapper) */
void dr_sd_delay_ms(uint32_t ms);

/*------------------------------------------------------------------------------
 * Binary Packet Format Functions
 * Packet structure: [4-byte tag][data][2-byte CRC16]
 *----------------------------------------------------------------------------*/

/* Format single uint16_t value: [tag 4B][value 2B] */
void single_format_data(uint8_t *buffer, const char *tag, const uint16_t value) ;

/* Format uint16_t array: [tag 4B][data0 2B][data1 2B]... */
void format_data(uint8_t *buffer, const char *tag, const uint16_t *data_array, size_t length);

/* Format uint8_t byte array: [tag 4B][byte0][byte1]... */
void format_data_byte(uint8_t *buffer, const char *tag, const uint8_t *data_array, size_t length);

/* Format ASCII string: [tag 4B][char0][char1]... */
void ascii_format_data(uint8_t *buffer, const char *tag, const char *data_ascii, size_t length);

/*==============================================================================
 * Global Variables (extern)
 *============================================================================*/
extern volatile bool data_tx_in_progress;   /* BLE TX in progress flag */
extern volatile bool ble_connection_st;     /* BLE connection state (0=disconnected, 1=connected) */

/* 2026-03-17: Global variables moved from cmd_parse.c to main.c */
extern char SERIAL_NO[SERIAL_NO_LENGTH];           /* Serial number */
extern char HW_NO[HW_NO_LENGTH];                   /* Hardware number */
extern char m_static_passkey[PASSKEY_LENGTH];       /* BLE static passkey */
extern bool bond_data_delete;                       /* Bond data delete request flag */
extern uint32_t m_life_cycle;                       /* Device life cycle counter */
extern uint8_t resetCount;                          /* Communication timeout counter */
extern bool info4;                                  /* Measurement with extra info flag */
extern uint8_t m_reset_status;                      /* Reset status code */

extern uint8_t ble_bin_buffer[];                    /* BLE binary response buffer */

/* Send error response */
void param_error(const char *cmd);

#endif //MAIN_H__

