#ifndef INC_HC_06_H_
#define INC_HC_06_H_

#include "main.h"
#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/* =========================
   User config
   ========================= */
#define HC06_SYNC 0xA5

/* =========================
   Frame type
   ========================= */
typedef struct {
    uint8_t  cmd;
    uint16_t w1;
    uint16_t w2;
    uint16_t w3;
} hc06_frame_t;

typedef enum {
	CMD_INIT_COMM = 0x01,
	CMD_READ_DFI = 0x02,
	CMD_WRITE_DFI = 0x03,
	CMD_DATA_REQUEST = 0x04,
	CMD_READ_DTC = 0x05,
	CMD_ERASE_DTC = 0x06,
	CMD_READ_AUDI_PIN = 0x07,
	CMD_WRITE_AUDI_PIN = 0x08,
	CMD_TOOL_COMM_STATUS = 0x09,

} hc_06_CMD;

typedef enum {
    REQ_FW_VERSION = 0x00,
    REQ_IDENT      = 0x01,
    REQ_STATUS     = 0x02,
    REQ_CONFIG     = 0x03,
    REQ_ERROR = 0x04,
    REQ_RESERVED   = 0x05,
} hc06_req_id_t;

typedef enum {
	HC06_STATUS_OK = 0x00,
	CONN_DEAD = 0x01,
	CONN_ALIVE = 0x02,
	CONN_HEAVY = 0x03,
	KLINE_ERROR = 0x04,
	HC06_STATUS_NOT_IMPLEMENTED = 0x10,
} hc06_status_t;

/* Latest received frame */
extern volatile uint8_t g_hc06_frame_ready;
extern hc06_frame_t g_hc06_frame;

/* =========================
   Public API
   ========================= */
void BT_KLINE_ERROR(void);

void BT_OnPSG5CommEstablished(void);

void BT_SendCommStatus(void);
// Call once after MX_USART2_UART_Init()
void HC06_Init(void);

// Optional: call once at boot to configure HC-06 (name, optional PIN)
void HC06_AT_BootSetup(void);

// Call from HAL_UART_RxCpltCallback()
void HC06_UART_RxByteCallback(UART_HandleTypeDef *huart);

// Call from HAL_UART_TxCpltCallback()
void HC06_UART_TxCpltCallback(UART_HandleTypeDef *huart);

// Call repeatedly in main loop
void HC06_Process(void);

// TX helpers
HAL_StatusTypeDef HC06_SendAscii(const char *s);
HAL_StatusTypeDef HC06_SendAsciiLn(const char *s);
HAL_StatusTypeDef HC06_SendFrame(uint8_t cmd, uint16_t w1, uint16_t w2, uint16_t w3);

// DFI scaling helpers (signed int16, factor 256/3)
int16_t HC06_DfiFloatToS16(float dfi);   // s16 = round(dfi * 256/3)
float   HC06_DfiS16ToFloat(int16_t s);   // dfi = s * 3/256

#ifdef __cplusplus
}
#endif

#endif /* INC_HC_06_H_ */
