#include "main.h"
#include "spi.h"
#include "w25qxx.h"
#include "iwdg.h"

/**
  *  W25Q128 代表128Mb，实际 128/8 = 16 MB
  */

/*
引脚配置:
				SPI1_CS    PB12
				SPI1_SCK   PB13
				SPI1_MISO  PB14
				SPI1_MOSI  PB15
*/
/**
  * @brief spi 读一个字节
  * @param None
  * @retval None
  */
	
uint32_t W25_Tempaddress = W25Q128_TEMP_DATA_BASE_ADDR; // 当前写入地址
volatile uint8_t flash_print_busy = 0;
uint8_t flash_print_buffer[W25Q128_PAGE_SIZE] = {0};;
uint32_t flash_print_page = 0;
uint32_t flash_print_end_page  = 0;
uint8_t sector_erased_flag[W25Q128_SECTOR_COUNT] = {0}; // 记录哪些扇区被擦除过


static uint8_t spi_flash_read_byte(void)
{
    uint8_t t_data, r_data;

    if(HAL_SPI_TransmitReceive(&hspi2, &t_data, &r_data, 1, 0xFFFFFF) != HAL_OK)
    {
        r_data = 0xff;
    }
    return r_data;
}
/**
  * @brief spi 写一个字节
  * @param byte 写入的字节
  * @retval 写状态 0成功 1失败
  */
static uint8_t spi_flash_send_byte(uint8_t byte)
{
    uint8_t r_data;

    if(HAL_SPI_TransmitReceive(&hspi2, &byte, &r_data, 1, 0xFFFFFF) != HAL_OK)
    {
        return 1;
    }
    return 0;
}

/**
  * @brief FLASH 写使能
  * @param None
  * @retval None
  */
static void spi_flash_write_enable(void)
{
    SPI_FLASH_CS_LOW();/* 通讯开始：CS低 */
    spi_flash_send_byte(W25X_WriteEnable); /* 发送写使能命令*/
    SPI_FLASH_CS_HIGH();/*通讯结束：CS高 */
}
/**
  * @brief FLASH 等待写结束
  * @param None
  * @retval None
  */
void spi_flash_wait_for_write_end(void)
{
    uint8_t state = 0;

    SPI_FLASH_CS_LOW();/* 选择 FLASH: CS 低 */

    spi_flash_send_byte(W25X_ReadStatusReg); /* 发送 读状态寄存器 命令 */
/* 若FLASH忙碌，则等待 */
    do
    {/* 读取FLASH芯片的状态寄存器 */
        state = spi_flash_read_byte();
    }
    while((state & 0x01) == SET);/* 正在写入标志 */

    SPI_FLASH_CS_HIGH(); /* 停止信号  FLASH: CS 高 */
}
/**
  * @brief FLASH 读ID
  * @param None
  * @retval None
  */
uint32_t spi_flash_read_ID(void)
{
    uint32_t temp, temp0, temp1, temp2;

    SPI_FLASH_CS_LOW();/* 开始通讯：CS低电平 */
    spi_flash_send_byte(W25X_JedecDeviceID);/* 发送JEDEC指令，读取ID */

    temp0 = spi_flash_read_byte();
    temp1 = spi_flash_read_byte();
    temp2 = spi_flash_read_byte();

    SPI_FLASH_CS_HIGH();/* 停止通讯：CS高电平 */

    temp = (temp0 << 16) | (temp1 << 8) | temp2;

    return temp;
}
/**
  * @brief 读FLASH
  * @param addr 读flash的起始地址
  * @param pdata 读到的数据存放起始地址
  * pdata size 读数据大小
  * @retval None
  */
void spi_flash_read(uint32_t addr,uint8_t *pdata, uint16_t size)
{
    SPI_FLASH_CS_LOW();

    spi_flash_send_byte(W25X_ReadData);

    spi_flash_send_byte((addr & 0xFF0000) >> 16);
    spi_flash_send_byte((addr & 0xFF00) >> 8);
    spi_flash_send_byte(addr  & 0xFF);

    while (size--)
    {
        *pdata = spi_flash_read_byte();
				
        pdata++;
    }

    SPI_FLASH_CS_HIGH();
}
/**
  * @brief 按页写FLASH
  * @param addr 写入flash的起始地址
  * @param pdata 写入数据的起始地址
  * pdata size 写数据大小
  * @retval None
  */
void spi_flash_page_write(uint32_t addr, uint8_t *pdata, uint16_t size)
{
    uint16_t i;

    spi_flash_write_enable();/* 发送FLASH写使能命令 */

    SPI_FLASH_CS_LOW();/* 选择FLASH: CS低电平 */

    spi_flash_send_byte(W25X_PageProgram);/* 写送写指令*/
    spi_flash_send_byte((uint8_t)((addr)>>16));
    spi_flash_send_byte((uint8_t)((addr)>>8));
    spi_flash_send_byte((uint8_t)addr);

    for(i = 0; i < size; i++)
    {
        spi_flash_send_byte(pdata[i]);
    }

    SPI_FLASH_CS_HIGH();/* 停止信号 FLASH: CS 高电平 */
    spi_flash_wait_for_write_end();/* 等待写入完毕*/
}
/**
  * @brief 写FLASH
  * @param addr 写入flash的起始地址
  * @param pdata 写入数据的起始地址
  * pdata size 写数据大小
  * @retval None
  */
void spi_flash_write(uint32_t addr, uint8_t *pdata, uint32_t size)
{
    uint32_t page_remain;

    page_remain = 256 - addr%256;

    if(size <= page_remain)
    {
        page_remain = size;
    }
    while(1)
    {
				// 确保写入之前发送 Write Enable 命令
        spi_flash_write_enable();
			
        spi_flash_page_write(addr, pdata, page_remain);

        if(size == page_remain)
            break;
        else
        {
            pdata += page_remain;
            addr += page_remain;

            size -= page_remain;
            if(size > 256)
                page_remain = 256;
            else
                page_remain = size;
        }
    }
}
/**
  * @brief 擦除FLASH扇区
  * @param sector_addr 扇区的起始地址
  * @retval None
  */
void spi_flash_sector_erase(uint32_t sector_addr)
{
    spi_flash_write_enable();/* 发送FLASH写使能命令 */
    spi_flash_wait_for_write_end();
		/* 擦除扇区 */
    
    SPI_FLASH_CS_LOW();/* 选择FLASH: CS低电平 */
    spi_flash_send_byte(W25X_SectorErase);/* 发送扇区擦除指令*/
    spi_flash_send_byte((sector_addr & 0xFF0000) >> 16);/*发送擦除扇区地址的高位*/
    spi_flash_send_byte((sector_addr & 0xFF00) >> 8);/* 发送擦除扇区地址的中位 */
    spi_flash_send_byte(sector_addr & 0xFF); /* 发送擦除扇区地址的低位 */
		/* 停止信号 FLASH: CS 高电平 */
    SPI_FLASH_CS_HIGH();
		/* 等待擦除完毕*/
    spi_flash_wait_for_write_end();
}

/**
  * @brief 擦除FLASH块
  * @param None
  * @retval None
  */
void spi_flash_block_erase(void)
{
    spi_flash_write_enable();

    SPI_FLASH_CS_LOW();
    spi_flash_send_byte(W25X_ChipErase);
    SPI_FLASH_CS_HIGH();

    spi_flash_wait_for_write_end();
}

/*进入深度掉电模式*/
void spi_flash_enter_deep_power_down(void)
{
    SPI_FLASH_CS_LOW(); // 选择FLASH: CS低电平
    spi_flash_send_byte(W25X_PowerDown); // 发送深度掉电模式指令0xB9
    SPI_FLASH_CS_HIGH(); // 停止信号 FLASH: CS 高电平
}
/*退出深度掉电模式*/
void spi_flash_release_from_deep_power_down(void)
{
    SPI_FLASH_CS_LOW(); // 选择FLASH: CS低电平
    spi_flash_send_byte(W25X_ReleasePowerDown); // 发送退出深度掉电模式指令0XAB
    SPI_FLASH_CS_HIGH(); // 停止信号 FLASH: CS 高电平

    // 释放后需等待一段时间，确保W25Q16完全唤醒
    HAL_Delay(1); // 延时1ms，确保Flash已完全唤醒
}

/*将温度压力数据循环写入flash*/

void flash_write_tempprecoh2_data(uint8_t* data, uint32_t length)
{
    // 写满了，从头循环并清除记录
    if ((W25_Tempaddress + length) >= W25Q128_TEMP_DATA_MAX_ADDR) 
    {
        W25_Tempaddress = W25Q128_TEMP_DATA_BASE_ADDR;

        // 擦除全部相关区域扇区
        for (uint32_t sector = 0; sector < W25Q128_SECTOR_COUNT; sector++) 
        {
            spi_flash_sector_erase(sector * W25Q128_SECTOR_SIZE);
            spi_flash_wait_for_write_end();
            sector_erased_flag[sector] = 1;  // 标记已擦除
        }
    }

    // 计算本次写入涉及的扇区
    uint32_t start_sector = W25_Tempaddress / W25Q128_SECTOR_SIZE;
    uint32_t end_sector = (W25_Tempaddress + length - 1) / W25Q128_SECTOR_SIZE;

    // 擦除未擦除的扇区
    for (uint32_t sector = start_sector; sector <= end_sector; sector++) 
    {
        if (sector_erased_flag[sector] == 0)
        {
            spi_flash_sector_erase(sector * W25Q128_SECTOR_SIZE);
            spi_flash_wait_for_write_end();
            sector_erased_flag[sector] = 1; // 标记为已擦除
        }
    }

    // 写入数据
    spi_flash_write(W25_Tempaddress, data, length);
    spi_flash_wait_for_write_end();

    // 更新写入指针
    W25_Tempaddress += length;
}


/*读取flash*/
void flash_dma_print_all_pages_start(void)
{
    if (flash_print_busy) return;

    flash_print_page = FLASH_PRINT_START_PAGE;
    flash_print_end_page = FLASH_PRINT_END_PAGE;
    flash_print_busy = 1;
    flash_dma_print_next_page();
}


void flash_dma_print_next_page(void)
{
    if (flash_print_page > flash_print_end_page)
    {
        printf("\r\n[PRINT] Pages %lu to %lu printed\r\n", 
							(unsigned long)FLASH_PRINT_START_PAGE, 
							(unsigned long)FLASH_PRINT_END_PAGE);
        flash_print_busy = 0;
        return;
    }

    uint32_t addr = flash_print_page * W25Q128_PAGE_SIZE;

    spi_flash_read(addr, flash_print_buffer, W25Q128_PAGE_SIZE);

    // 打印页号
    printf("\r\n[Page %lu - 0x%08lX]:\r\n", 
					(unsigned long)flash_print_page, 
					(unsigned long)addr);

    // 发送当前页数据
		// 每16字节打印一行
    for (uint32_t i = 0; i < W25Q128_PAGE_SIZE; i++)
    {
        printf("%02X ", flash_print_buffer[i]);
        if ((i + 1) % 16 == 0) 
						printf("\r\n");
    }

    flash_print_page++;  // 提前准备下一页
		flash_dma_print_next_page();
}

/**
 * @brief 同步打印 Flash 中某一页到另一页的数据（每页256字节，按16字节一行打印）
 * 
 * @param start 起始页号（包含）
 * @param end   结束页号（包含）
 */
void print_flash_pages(uint32_t start, uint32_t end)
{
    for (uint32_t page = start; page <= end; page++)
    {
        uint32_t addr = page * W25Q128_PAGE_SIZE;

        spi_flash_read(addr, flash_print_buffer, W25Q128_PAGE_SIZE);

        printf("\r\n[Page %lu - 0x%08lX]:\r\n", (unsigned long)page, (unsigned long)addr);

        for (uint32_t i = 0; i < W25Q128_PAGE_SIZE; i++)
        {
            printf("%02X ", flash_print_buffer[i]);
            if ((i + 1) % 16 == 0)
                printf("\r\n");
        }
    }

    printf("\r\n[PRINT] Pages %lu to %lu printed\r\n", (unsigned long)start, (unsigned long)end);
}

/**
  * @brief 清空flash中用于保存温度/压力等数据的区域
  * @param None
  * @retval None
  */
void flash_clear_all_data(void)
{
		spi_flash_write_enable();  // 发送写使能指令

    spi_flash_send_byte(0xC7); // 或者用 0x60，也是 Chip Erase 指令
	
    // 等待擦除完成
    spi_flash_wait_for_write_end();

    // 擦除完成后，写入指针归零
    W25_Tempaddress = 0;
    memset(sector_erased_flag, 0, sizeof(sector_erased_flag));  

		printf("W25FLASH complete emptied\r\n");

}

