#ifndef __SPI_FLASH_H
#define	__SPI_FLASH_H

#include "bsp.h"

#define	LOG_SAV_FLAG										(0xAA5555AA)
#define	LOG_INFO_SAV_FLAG								(0xA55A)

#define	SpiFlashClrNss()								SPI_NSS_CLR()
#define	SpiFlashSetNss()								SPI_NSS_SET()

#define SPIFLASH_CMD_WRITE							0x02  /* Write to Memory instruction */
#define SPIFLASH_CMD_WRSR								0x01  /* Write Status Register instruction */
#define SPIFLASH_CMD_WREN								0x06  /* Write enable instruction */
#define SPIFLASH_CMD_READ								0x03  /* Read from Memory instruction */
#define SPIFLASH_CMD_RDSR								0x05  /* Read Status Register instruction  */
#define SPIFLASH_CMD_RDID								0x9F  /* Read identification */
#define SPIFLASH_CMD_SE									0x20  /* 4KSector Erase instruction */
#define SPIFLASH_CMD_BE									0xC7  /* Bulk Erase instruction */
#define SPIFLASH_WIP_FLAG								0x01  /* Write In Progress (WIP) flag */
#define SPIFLASH_DUMMY_BYTE							0xA5
#define SPIFLASH_PAGESIZE								0x100
#define	SPIFLASH_SECTORSIZE							4096
#define SPIFLASH_M25P128_ID							0x202018
#define SPIFLASH_M25P64_ID							0x202017

void SpiFlashEraseChip(void);
void SpiFlashEraseSector(uint32_t SectorAddr);
void SpiFlashWriteAnyLengthData(uint8_t* wData, uint32_t wAddr, uint16_t wLen);
void SpiFlashReadAnyLengthData(uint8_t* rData, uint32_t rAddr, uint16_t rLen);
uint32_t SpiFlashReadId(void);

/* USER CODE BEGIN */
#define	SPIFLASH_SIZE										16777216
#define	SPIFLASH_SECTOR_NUM							4096

#define	GATEWEY_PARA_SAV_ADDR										0x00
#define	GATEWEY_PARA_SAV_SECTOR									0x00

#define	LOG_INFO_START_SECTOR										0x02
#define	LOG_SAV_START_SECTOR										0x03

//#if (LORA_MODULE == WH_LR36_L)
//#define	LOG_SAV_SIZE														78
//#define	LOG_SAV_NUM_SECTOR											52			//每扇区存储数量
//#else
//#define	LOG_SAV_SIZE														78  //150
//#define	LOG_SAV_NUM_SECTOR											52  //27			//每扇区存储数量
//#endif

#define	LOG_SAV_SIZE_MAX													256
#define	LOG_SAV_NUM_MAX													((SPIFLASH_SECTOR_NUM - LOG_SAV_START_SECTOR) * LOG_SAV_NUM_SECTOR)

typedef struct {
	uint32_t LogSavFlag;		//日志存储标志
	uint32_t LogIdx;				//日志序号
	uint32_t LogEndAddr;		//日志结束地址
	uint32_t TimeStamp;			//存储时间
}LogHeader_t, *LogHeader;

void SavMMC5983Calib(uint8_t *wData, uint32_t wLen);
void ReadMMC5983Calib(uint8_t *rData, uint32_t rLen);

void LogInit(void);
uint32_t ReadLogNum(void);
uint32_t ReadLastLogEndAddr(void);
uint32_t ReadFirstLogStartAddr(void);
void SavLogNum(uint32_t LogNum);
void AddLog(uint8_t *wData, uint32_t wLen);
int ReadLog(LogHeader Header, uint8_t **wData, uint32_t LogIdx);
int ReadPara(uint8_t *Para, uint32_t ParaLen);
int WritePara(uint8_t *Para, uint32_t ParaLen);

/* USER CODE END */
	
#endif
