/*
 * @Description: 
 * @Version: 2.0
 * @Author: Seven
 * @Date: 2023-09-21 10:16:46
 * @LastEditors: Seven
 * @LastEditTime: 2024-04-17 16:42:43
 */
#ifndef BSP_H__
#define BSP_H__
#include "board.h"

#define DFU_APP_LOGIC_ADDRESS 0x800e7000 //fpga start address

extern uint32_t apb_clken;
extern uint32_t misc_ctrl;

#define SOFTWARE_VERSION_BOOT  0X02021004

/*
BKP_DR0：RTC时间是否初始化
BKP_DR1：升级标志
BKP_DR2：升级固件类型
BKP_DR3：升级状态
*/
enum BKP_t {
	BKP_DR0,
    BKP_DR1,
    BKP_DR2,
    BKP_DR3,
    BKP_DR4,
    BKP_DR5,
    BKP_DR6,
    BKP_DR7,
};
#define BKP_UPDATE_FLAG			BKP_DR1		//升级标志
#define BKP_UPDATE_STATE		BKP_DR2		//升级状态
#define BKP_UPDATE_FIRM_TYPE	BKP_DR3		//升级固件类型
#define BKP_UPDATE_TASK_NO		BKP_DR4		//升级任务号

//升级标记
#define UPDATA_FLAG  0x81	//升级
#define BACKOFF_FLAG 0x82	//回退
#define BACKOFF_OVER 0x83	//回退完成
#define UPDATE_ERR	 0x84	//升级失败


#define DEVICE_PUBLIC_INFO_ADDR     0x00        //公共信息存储地址
#define DEVICE_VERSION_INFO_ADDR    0x100       //软件版本存储地址
#define DEVICE_RESET_ADDR			0x140		//复位次数存储
#define FRAM_MQTT_MSG				0x200		//mqtt信息存储地址

#define EEPROM_FIRST_FLAG   0x5AA5  //是否第一次读eeprom标记

//公共信息
typedef struct _device_public_info_t
{
	uint16_t eeprom_first_flag;					//是否第一次上电
	uint8_t	eeprom_ver;							//eeprom版本
	uint8_t config_flag;						//是否配置的标记
	uint32_t device_sn;            				//设备sn
	uint16_t device_type;          				//设备类型
	uint16_t manufactures;         				//产品制造商
	uint16_t batch_number;         				//批次号
	uint32_t production_data;      				//出厂日期
	uint8_t  pcb_ver;              				//PCB版本
}__attribute__((packed)) device_public_info_t;

//单片机信息
typedef struct _device_mcu_info_t
{
	uint32_t bootloader_ver;					//bootloader版本
	uint32_t pt_ver;							//产测版本
	uint32_t app1_ver;							//app1版本
	uint32_t app2_ver;							//app2版本
	uint32_t app3_ver;							//app3版本
    uint32_t fpga_ver;                          //fpga版本
}__attribute__((packed)) device_mcu_info_t;

// /* mqtt IP地址 端口号*/
// typedef struct _MQTT_IP_PORT_{
//     uint8_t flag;                               //是否写入过标记
//     char port[8];                               //端口号
//     char ip[32];                                //IP地址
//     char admin[16];                             //用户名
//     char password[24];                          //密码
// }__attribute__((packed)) MqttIdPort;

extern device_public_info_t device_public_info;
extern device_mcu_info_t device_mcu_info;
// extern MqttIdPort mqttidport;

extern uint32_t Reset_cnt;

extern uint8_t updata_flag;

void bsp_init(void);
void IWDG_Config(void);
void IWDG_feed(void);
void eeprom_init_handle(void);
void eeprom_info_update(void);
uint16_t set_flag_not(uint16_t data);
uint8_t flag_not_cmp(uint16_t data);
uint32_t crc_block_data_calculate(uint32_t *buf, uint32_t len);
void updatee_process(void);
void update_handle(void);
void backoff_handle(void);
void run_app(void);
uint8_t app_check(uint32_t addr, uint32_t len, uint32_t *checkdata);


void update_test(void);
void clear_update_status(void);
#endif // !
