#pragma once

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ----------------------------------------------------------------- */
#include <stdint.h>
#include <stdbool.h>

#include "device/sx1281_driver/sx1281.h"
/* USER INCLUDE BEGIN */

/* USER INCLUDE END */

/* Exported constants ------------------------------------------------------- */
/* Exported macro ----------------------------------------------------------- */
#define MR16_HEADER_LEN 2      // Header长度(TX_ID)
#define MR16_CRC_LEN 2         // CRC长度
#define MR16_DEFAULT_FIXED_LEN 113  // 默认用户数据长度(不含Header和CRC)

/* 失控保护安全帧模式: 用户数据前4字节为特殊序列 */
#define MR16_FAILSAFE_PATTERN_LEN 4
#define MR16_FAILSAFE_BYTE0 0xFF
#define MR16_FAILSAFE_BYTE1 0x00
#define MR16_FAILSAFE_BYTE2 0xFF
#define MR16_FAILSAFE_BYTE3 0x00
/* USER DEFINE BEGIN */

/* USER DEFINE END */

/* Exported types ----------------------------------------------------------- */

typedef enum {
  MR16_FORMAT_VARIABLE,  // 可变长度(UART空闲中断)
  MR16_FORMAT_FIXED,     // 固定长度
  MR16_FORMAT_NUM
}MR16_DataFormat_t;

typedef struct {
  uint16_t ch_l_x;
  uint16_t ch_l_y;
  uint16_t ch_r_x;
  uint16_t ch_r_y;
  bool sw[16];//二值按键
  bool threePosLever[8];//三值按键
  uint16_t res1;//保留位1
  uint16_t res2;//保留位2
  uint16_t res3;//保留位3
  uint16_t res4;//保留位4
}MR16_RCData_t;

typedef struct {
  uint8_t header1;
  uint8_t header2;
  union {
	MR16_RCData_t rc;
  }data;

  uint16_t crc;   
}MR16_Data_t;

typedef struct {
  SX1281_Params_t radioParams;
  MR16_DataFormat_t format;  // 数据格式: VARIABLE或FIXED
  uint16_t fixedLength;      // 固定长度模式下的用户纯数据长度(不含Header,不含CRC)
  uint16_t TX_ID;
  uint16_t RX_ID[3];//最多识别三台设备的信号
}MR16_Param_t;

typedef struct {
  float now;            /* 当前时间，单位秒 */
  uint64_t last_wakeup; /* 上次唤醒时间，单位微秒 */
  float dt;             /* 两次唤醒间隔时间，单位秒 */
  float lastUIupdata;
  float lastDbusSend;
  float lastDataReceived; /* 上次接收到有效数据的时间，用于失控保护 */
}MR16_Timer_t;

typedef struct {
  MR16_Param_t *param;
  MR16_Data_t *data;
  MR16_Timer_t timer;
  /*
  TX端数据流: 用户发[纯数据] → MR16添加Header+CRC → [发送]
  RX端数据流: [接收] → MR16验证CRC → 输出[Header+数据]给用户
  
  Buffer格式:
  [0]header1(TXID_highbyte)
  [1]header2(TXID_lowbyte)
  [2..N]data (用户纯数据)
  [N+1]crc_highbyte
  [N+2]crc_lowbyte
  */
  uint8_t txbuffer[127];

  uint32_t packetCount[3];
}MR16_t;

/* Exported functions prototypes -------------------------------------------- */
int8_t MR16_Init(MR16_t *mr16,MR16_Param_t *param);
int8_t MR16_Main(MR16_t *mr16);

/* RC Mode Functions */
int8_t MR16_PackTxBuffer(MR16_t *mr16, const uint8_t *userData, uint16_t userDataLen);

/* UI Functions */
int8_t MR16_UI_PowerON(void);
int8_t MR16_UI_Home(MR16_t *mr16);
int8_t MR16_UI_UpdateStatus(MR16_t *mr16);

/* USER FUNCTION BEGIN */

/* USER FUNCTION END */

#ifdef __cplusplus
}
#endif