/**
 * @file he24c64soh.c
 * @brief HE24C64SOH EEPROM驱动库实现文件（简化版）
 * @description 只包含读写字节功能，不包含初始化
 */

#include "he24c64soh.h"
#include "driverlib.h"
#include "device.h"

// ============================================================================
// 私有函数声明
// ============================================================================

static uint8_t HE24C64SOH_WaitForBusIdle(uint16_t timeout_ms);
// static void HE24C64SOH_SimpleDelay(uint32_t cycles);
// static uint8_t HE24C64SOH_PollForWriteComplete(void);
static uint8_t HE24C64SOH_WaitForTransfer(uint32_t base, uint16_t timeout);
static uint8_t HE24C64SOH_WaitForReceive(uint32_t base, uint16_t timeout);

// ============================================================================
// 公共函数实现
// ============================================================================

// /**
//  * @brief 多数据写入函数
//  */
// uint8_t HE24C64SOH_WriteByte(uint16_t address, uint8_t data)
// {
//     uint8_t status = HE24C64SOH_SUCCESS;
//     uint8_t tx_data[6];
    
//     // 1. 参数验证
//     if (!HE24C64SOH_CheckAddress(address)) {
//         return HE24C64SOH_ADDR_ERROR;
//     }
    
//     // 2. 等待总线空闲
//     status = HE24C64SOH_WaitForBusIdle(1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         return status;
//     }
    
//     // 3. 准备数据
//     tx_data[0] = HE24C64SOH_WRITE_ADDR;      // 设备地址 + 写
//     tx_data[1] = (address >> 8) & 0x1F;      // 地址高字节
//     tx_data[2] = address & 0xFF;             // 地址低字节
//     tx_data[3] = data;                       // 数据
//     tx_data[4] = 0X55;
//     tx_data[5] = 0X55;
    
//     // 4. 配置发送模式
//     I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_SEND_MODE);
//     I2C_setDataCount(HE24C64SOH_I2C_BASE, 5);  // 准备发送3个字节
    
//     volatile uint16_t j = 0;
//     for(; j < 1000; j++) 
//     {
//         asm(" NOP");
//     }
//     // 5. 发送START
//     I2C_sendStartCondition(HE24C64SOH_I2C_BASE);
//     // 检查XRDY和ACK
//     status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }
    
//     // 6. 发送所有数据（包含ARDY和ACK检查）
//     uint8_t i = 1;
//     for (; i < 6; i++) {
//         I2C_putData(HE24C64SOH_I2C_BASE, tx_data[i]);
        
//         status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//         if (status != HE24C64SOH_SUCCESS) {
//             I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//             return status;
//         }
//     }
    
//     // 7. 发送STOP条件
//     I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
    
//     // 8. 等待总线空闲
//     status = HE24C64SOH_WaitForBusIdle(1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         return status;
//     }
    
//     // 9. 轮询等待写入完成
//     status = HE24C64SOH_PollForWriteComplete();
    
//     return status;
// }
// 1. 参数验证（新增页边界检查）
// if (!HE24C64SOH_CheckAddress(address) || !HE24C64SOH_CheckAddress(address + data_len - 1)) {
//     return HE24C64SOH_ADDR_ERROR; // 地址越界检查（含起始/结束地址）
// }

// if (data_len == 0 || data_len &gt; 32) {
//     return HE24C64SOH_PARAM_ERROR; // 数据长度限制（最大32字节）
// }

// // 页边界检查：计算起始地址所在页的结束地址，判断是否跨页
// uint16_t page_start = address &amp; 0xFFE0; // 页起始地址（低5位清零）
// uint16_t page_end = page_start + 31;    // 页结束地址（页起始+31）
// if (address + data_len - 1 &gt; page_end) {
//     return HE24C64SOH_PAGE_ERROR; // 跨页错误（需新增此错误码）
// }





/**
 * @brief 任意字节写入函数（支持跨页）
 * @param address: 要写入的起始地址（16位）
 * @param data: 要写入的数据指针
 * @param data_len: 要写入的数据字节数
 * @return 写入状态
 */
uint8_t HE24C64SOH_WriteData(uint16_t address, const uint8_t *data, uint16_t data_len)
{
    uint8_t status = HE24C64SOH_SUCCESS;
    uint16_t bytes_written = 0;
    uint16_t bytes_to_write = 0;
    uint16_t current_address = address;
    const uint8_t *current_data_ptr = data;
    
    // 1. 参数验证
    if (data == NULL) {
        return HE24C64SOH_PARAM_ERROR;
    }
    
    if (data_len == 0) {
        return HE24C64SOH_SUCCESS;  // 无数据写入，直接返回成功
    }
    
    // 检查地址范围
    uint32_t end_address = (uint32_t)address + data_len - 1;
    if (address >= HE24C64SOH_TOTAL_SIZE || end_address >= HE24C64SOH_TOTAL_SIZE) 
    {
        return HE24C64SOH_ADDR_ERROR;
    }
    
    // 2. 计算起始页偏移
    // 计算从起始地址到当前页结束的字节数
    uint16_t page_offset = current_address % HE24C64SOH_PAGE_SIZE;  // 当前地址在页内的偏移
    uint16_t first_page_remaining = HE24C64SOH_PAGE_SIZE - page_offset;  // 当前页剩余空间
    
    // 3. 循环写入，直到所有数据写完
    while (bytes_written < data_len) 
    {
        // 计算本次要写入的字节数
        bytes_to_write = data_len - bytes_written;  // 剩余总字节数
        
        // 如果是第一页且有偏移，则写入不超过当前页剩余空间
        if (bytes_written == 0 && page_offset > 0) {
            if (bytes_to_write > first_page_remaining) 
            {
                bytes_to_write = first_page_remaining;
            }
        } 
        // 否则，如果是页对齐的地址，写入不超过一页
        else if (bytes_to_write > HE24C64SOH_PAGE_SIZE) 
        {
            bytes_to_write = HE24C64SOH_PAGE_SIZE;
        }
        
        // 调用页写入函数
        status = HE24C64SOH_PageWriteBytes(current_address, current_data_ptr, bytes_to_write);
        if (status != HE24C64SOH_SUCCESS) {
            return status;  // 写入失败，直接返回
        }
        
        // 更新写入进度
        bytes_written += bytes_to_write;
        current_address += bytes_to_write;
        current_data_ptr += bytes_to_write;
        
        // 写入完成后等待一小段时间（确保写入完成）
        // 这里可以添加一个小的延时，或者依赖页写入函数内部的轮询机制
        DEVICE_DELAY_US(5000);
        // HE24C64SOH_SimpleDelay(100000);
    }
    
    return HE24C64SOH_SUCCESS;
}

/**
 * @brief 页写入函数
 * @param address: 要写入的起始地址（16位）
 * @param data: 要写入的数据指针
 * @param data_len: 要写入的数据字节数（最大32字节）
 * @return 写入状态
 */
uint8_t HE24C64SOH_PageWriteBytes(uint16_t address, const uint8_t *data, uint8_t data_len)
{
    uint8_t status = HE24C64SOH_SUCCESS;
    uint8_t tx_data[34] = {0};  // 最大支持32字节写入
    uint8_t i = 0;

    HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0XD7FF;  // 清除stop和start位
    
    // 1. 参数验证
    if (data == NULL) {
        return HE24C64SOH_PARAM_ERROR;
    }
    
    if (data_len == 0 || data_len > 32) {
        return HE24C64SOH_PARAM_ERROR;
    }
    
    // 计算结束地址
    uint32_t end_address = (uint32_t)address + data_len - 1;
    
    // 检查地址范围
    if (address >= HE24C64SOH_TOTAL_SIZE || end_address >= HE24C64SOH_TOTAL_SIZE) {
        return HE24C64SOH_ADDR_ERROR;
    }
    
    // 检查是否跨页
    uint16_t start_page = address / HE24C64SOH_PAGE_SIZE;
    uint16_t end_page = end_address / HE24C64SOH_PAGE_SIZE;
    
    if (start_page != end_page) {
        return HE24C64SOH_PAGE_ERROR;
    }
    
    // 2. 等待总线空闲
    status = HE24C64SOH_WaitForBusIdle(1000);
    if (status != HE24C64SOH_SUCCESS) {
        return status;
    }
    
    // 3. 准备数据
    // 起始条件时硬件会自动发送设备地址，所以不需要在tx_data中包含设备地址
    tx_data[0] = (address >> 8) & 0x1F;  // 地址高字节
    tx_data[1] = address & 0xFF;         // 地址低字节
    
    // 拷贝用户数据
    for (i = 0; i < data_len; i++) {
        tx_data[2 + i] = data[i];
    }
    
    // 4. 配置发送模式
    I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_SEND_MODE);
    I2C_setDataCount(HE24C64SOH_I2C_BASE, data_len + 2);  // 地址字节数(2) + 数据字节数
    
    // 5. 发送START条件
    I2C_sendStartCondition(HE24C64SOH_I2C_BASE);

    // HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0XDFFF;  // 清除start位
    
    // 检查XRDY和ACK
    status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
    if (status != HE24C64SOH_SUCCESS) {
        I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
        return status;
    }
    // HE24C64SOH_SimpleDelay(1000);
    DEVICE_DELAY_US(100);
    
    // 6. 发送所有数据
    for (i = 0; i < data_len + 2; i++) {
        I2C_putData(HE24C64SOH_I2C_BASE, tx_data[i]);
        
        status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
        if (status != HE24C64SOH_SUCCESS) {
            I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
            return status;
        }
        
        // 在每次发送完一个字节、检查完成XRDY和ACK后增加延时110us
        // HE24C64SOH_SimpleDelay(1000);
        DEVICE_DELAY_US(100);
    }
    
    // 7. 发送STOP条件
    I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
    // for(i = 0; i < 10; i++)
    // {
    //     I2C_sendStopCondition(HE24C64SOH_I2C_BASE);

    //     if (!I2C_isBusBusy(HE24C64SOH_I2C_BASE)) 
    //     {
    //         break;
    //     }
    //     DEVICE_DELAY_US(10000);
    // }
    // HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0XF7FF;  // 清除stop位
    
    // 8. 等待总线空闲
    status = HE24C64SOH_WaitForBusIdle(1000);
    if (status != HE24C64SOH_SUCCESS) 
    {
        I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
        return status;
    }

    // 9. 轮询等待写入完成
    // status = HE24C64SOH_PollForWriteComplete();
    
    return status;
}

/**
 * @brief 多字节读取函数
 * @param address: 要读取的起始地址（16位）
 * @param data: 存储读取数据的指针
 * @param data_len: 要读取的数据字节数
 * @return 读取状态
 */
uint8_t HE24C64SOH_ReadBytes(uint16_t address, uint8_t *data, uint8_t data_len)
{
    uint8_t status = HE24C64SOH_SUCCESS;
    // uint8_t read_bytes_len = data_len;
    uint8_t rx_data[256] = {0};
    uint8_t i = 0;
    uint8_t actual_len = data_len;  // 实际要读取的字节数

    HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0XD7FF;  // 清除stop和start位
    
    // 1. 参数验证
    if (data_len == 0 ) 
    {
        return HE24C64SOH_PARAM_ERROR;
    }
    
    if (data == NULL) {
        return HE24C64SOH_PARAM_ERROR;
    }
    
    // 计算结束地址
    uint32_t end_address = (uint32_t)address + data_len - 1;
    
    // 检查地址范围
    if (address >= HE24C64SOH_TOTAL_SIZE || end_address >= HE24C64SOH_TOTAL_SIZE) {
        return HE24C64SOH_ADDR_ERROR;
    }
    
    // 2. 等待总线空闲
    status = HE24C64SOH_WaitForBusIdle(1000);
    if (status != HE24C64SOH_SUCCESS) {
        return status;
    }
    
    // 3. 准备要发送的地址字节
    uint8_t addr_high = (address >> 8) & 0x1F;  // 地址高字节
    uint8_t addr_low = address & 0xFF;          // 地址低字节
    
    // 4. 配置发送模式（发送内存地址）
    I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_SEND_MODE);
    
    // 当读取字节数为2时，按照n=3的逻辑执行
    if (data_len == 2) {
        actual_len = 3;  // 按照n=3处理
    }
    
    // 设置要发送的数据计数（2个地址字节）
    I2C_setDataCount(HE24C64SOH_I2C_BASE, 2);
    
    // 5. 发送START条件
    I2C_sendStartCondition(HE24C64SOH_I2C_BASE);
    
    // 检查XRDY和ACK
    status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
    if (status != HE24C64SOH_SUCCESS) {
        I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
        return status;
    }
    
    // 6. 发送地址高字节
    I2C_putData(HE24C64SOH_I2C_BASE, addr_high);
    status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
    if (status != HE24C64SOH_SUCCESS) {
        I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
        return status;
    }
    
    // 7. 发送地址低字节
    I2C_putData(HE24C64SOH_I2C_BASE, addr_low);
    status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
    if (status != HE24C64SOH_SUCCESS) {
        I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
        return status;
    }
    
    // 8. 重新配置为接收模式
    I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_RECEIVE_MODE);
    
    // 设置要接收的数据字节数
    I2C_setDataCount(HE24C64SOH_I2C_BASE, actual_len);
    
    // 9. 发送重复START条件
    I2C_sendStartCondition(HE24C64SOH_I2C_BASE);
    
    // 10. 读取数据
    for (i = 0; i < actual_len; i++) {
        // 等待接收完成
        status = HE24C64SOH_WaitForReceive(HE24C64SOH_I2C_BASE, 1000);
        if (status != HE24C64SOH_SUCCESS) {
            I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
            return status;
        }
        
        // 读取数据
        rx_data[i] = I2C_getData(HE24C64SOH_I2C_BASE);
        
        // 根据读取的字节数和当前位置设置ACK/NACK
        if (data_len >= 3) {
            // n >= 3的情况
            if (i < data_len - 2) {
                // 前n-2个字节读取完成后发送ACK
                HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0X7FFF;
            } else if (i == data_len - 2) {
                // 第n-1个字节读取完成后发送NACK
                HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) |= I2C_MDR_NACKMOD;
            }
            // 第n个字节读取完成后不操作
        } else if (data_len == 2) {
            // n=2的情况，按照n=3的逻辑执行
            if (i == 0) {
                // 第一个字节读取完成后发送ACK
                HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0X7FFF;
            } else if (i == 1) {
                // 第二个字节读取完成后发送NACK
                HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) |= I2C_MDR_NACKMOD;
            }
            // 第三个字节读取完成后不操作（但我们会丢弃这个字节）
        }
        // n=1的情况，硬件自动处理，不需要操作ACK/NACK
    }
    
    // 11. 拷贝读取到的数据到输出缓冲区
    for (i = 0; i < data_len; i++) {
        data[i] = rx_data[i];
    }
    
    // 12. 发送STOP条件
    I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
    
    // 13. 等待总线空闲
    status = HE24C64SOH_WaitForBusIdle(1000);
    if (status != HE24C64SOH_SUCCESS) {
        return status;
    }
    
    return HE24C64SOH_SUCCESS;
}




// /**
//  * @brief 从HE24C64SOH读取一个字节
//  * @param address 要读取的内存地址（13位，0x0000-0x1FFF）
//  * @param data 读取到的数据指针
//  * @return uint8_t 状态码
//  */
// uint8_t HE24C64SOH_ReadByte(uint16_t address, uint8_t* data)
// {
//     uint8_t status = HE24C64SOH_SUCCESS;
//     // uint16_t timeout = 0;
//     uint8_t tx_data[5];
//     tx_data[4] = 0;
    
//     // 1. 参数验证
//     if (!HE24C64SOH_CheckAddress(address)) {
//         return HE24C64SOH_ADDR_ERROR;
//     }
    
//     // 2. 等待总线空闲
//     status = HE24C64SOH_WaitForBusIdle(1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         return status;
//     }
    
//     // 3. 准备数据
//     tx_data[0] = (address >> 8) & 0x1F;      // 地址高字节
//     tx_data[1] = address & 0xFF;             // 地址低字节
    
//     // 4. 配置发送模式
//     I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_SEND_MODE);
//     I2C_setDataCount(HE24C64SOH_I2C_BASE, 3);  // 准备发送3个字节
    
//     // volatile uint16_t j = 0;
//     // for(j = 0; j < 1000; j++) 
//     // {
//     //     asm(" NOP");
//     // }
//     // 5. 发送START
//     I2C_sendStartCondition(HE24C64SOH_I2C_BASE);
//     // 检查XRDY和ACK
//     status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }
    
//     // 6. 发送所有数据（包含ARDY和ACK检查）
//     I2C_putData(HE24C64SOH_I2C_BASE, tx_data[0]);
//     status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }
//     // I2C_setTargetAddress(HE24C64SOH_I2C_BASE, HE24C64SOH_READ_ADDR);
//     I2C_putData(HE24C64SOH_I2C_BASE, tx_data[1]);
//     status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }

//     // 14. 重新配置为接收模式
//     I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_RECEIVE_MODE);
//     I2C_setDataCount(HE24C64SOH_I2C_BASE, 2);  // 准备接收2个字节
    
//     HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) |= I2C_MDR_RM;
//     // 5. 发送START
//     I2C_sendStartCondition(HE24C64SOH_I2C_BASE);

//     // 检查RRDY
//     status = HE24C64SOH_WaitForReceive(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) 
//     {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }

//     tx_data[2] = I2C_getData(HE24C64SOH_I2C_BASE);
//     HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) &= 0X7FFF;
//     status = HE24C64SOH_WaitForReceive(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) 
//     {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }

//     tx_data[3] = I2C_getData(HE24C64SOH_I2C_BASE);
//     HWREGH(HE24C64SOH_I2C_BASE + I2C_O_MDR) |= I2C_MDR_NACKMOD;
//     status = HE24C64SOH_WaitForReceive(HE24C64SOH_I2C_BASE, 1000);
//     if (status != HE24C64SOH_SUCCESS) 
//     {
//         I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//         return status;
//     }

//     tx_data[4] = I2C_getData(HE24C64SOH_I2C_BASE);

//     *data = tx_data[2];
    
//     // 18. 发送STOP条件
//     I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
    
//     // 19. 等待总线空闲
//     status = HE24C64SOH_WaitForBusIdle(1000);
//     if (status != HE24C64SOH_SUCCESS) {
//         return status;
//     }
    
//     return HE24C64SOH_SUCCESS;
// }

// ============================================================================
// 私有函数实现
// ============================================================================

/**
 * @brief 等待I2C总线空闲
 */
static uint8_t HE24C64SOH_WaitForBusIdle(uint16_t timeout_ms)
{
    uint16_t i;
    
    for (i = 0; i < timeout_ms; i++) {
        if (!I2C_isBusBusy(HE24C64SOH_I2C_BASE)) 
        {
            return HE24C64SOH_SUCCESS;
        }
        
        // HE24C64SOH_SimpleDelay(1000);
        DEVICE_DELAY_US(100);

        // ✅ 修复：检查是否有错误状态
        uint16_t status = I2C_getStatus(HE24C64SOH_I2C_BASE);
        if (status & (I2C_STS_NO_ACK | I2C_STS_ARB_LOST)) 
        {
            // 有错误，发送STOP清除
            I2C_setConfig(HE24C64SOH_I2C_BASE, I2C_CONTROLLER_SEND_MODE);
            I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
            // HE24C64SOH_SimpleDelay(10000);
            DEVICE_DELAY_US(1000);
        }
    }
    
    // ✅ 修复：超时后强制复位模块
    I2C_disableModule(HE24C64SOH_I2C_BASE);
    // HE24C64SOH_SimpleDelay(10000);
    DEVICE_DELAY_US(1000);
    I2C_enableModule(HE24C64SOH_I2C_BASE);
    // HE24C64SOH_SimpleDelay(10000);
    DEVICE_DELAY_US(1000);
    
    return HE24C64SOH_BUS_BUSY;
}

// /**
//  * @brief 简单延时函数, 110ns
//  */
// static void HE24C64SOH_SimpleDelay(uint32_t cycles)
// {
//     volatile uint32_t i;
//     for (i = 0; i < cycles; i++) {
//         asm(" NOP");
//     }
// }

// /**
//  * @brief 轮询检测EEPROM写入完成
//  * @return uint8_t 状态码
//  */
// static uint8_t HE24C64SOH_PollForWriteComplete(void)
// {
//     uint8_t status = HE24C64SOH_SUCCESS;
//     uint16_t poll_count = 0;
//     const uint16_t max_polls = 100;  // 约5ms超时
    
//     // 轮询循环
//     for (poll_count = 0; poll_count < max_polls; poll_count++) 
//     {
//         // 5. 发送START
//         I2C_sendStartCondition(HE24C64SOH_I2C_BASE);
//         status = HE24C64SOH_WaitForTransfer(HE24C64SOH_I2C_BASE, 1000);
//         if (status == HE24C64SOH_SUCCESS) 
//         {
//             I2C_sendStopCondition(HE24C64SOH_I2C_BASE);
//             return status;
//         }
            
//         // 短暂延时后重试
//         // HE24C64SOH_SimpleDelay(1000);
//         DEVICE_DELAY_US(100);
//         continue;
//     }
    
//     // 超时
//     return HE24C64SOH_TIMEOUT;
// }

/**
 * @brief 优化的等待函数：同时检查ARDY和ACK
 */
static uint8_t HE24C64SOH_WaitForReceive(uint32_t base, uint16_t timeout)
{
    volatile uint16_t i = 0;
    uint16_t status = 0;
    
    // 1. 等待RRDY（寄存器就绪）
    for (i = 0; i < timeout; i++) {
        status = HWREG(base + 0x02);  // 读取I2CSTR
        
        if (status & 0x0008)    // RRDY位为1
        {        
            return HE24C64SOH_SUCCESS;
        }
        
        // 短暂延时
        // HE24C64SOH_SimpleDelay(10);
        DEVICE_DELAY_US(1);
    }
    
    return HE24C64SOH_TIMEOUT;
}


/**
 * @brief 优化的等待函数：同时检查ARDY和ACK
 */
static uint8_t HE24C64SOH_WaitForTransfer(uint32_t base, uint16_t timeout)
{
    volatile uint16_t i = 0;
    uint16_t status = 0;
    
    // 1. 等待ARDY（寄存器就绪）
    for (i = 0; i < timeout; i++) {
        status = HWREG(base + 0x02);  // 读取I2CSTR
        
        if (status & 0x0010) {        // XRDY位为1
            // 2. 检查NACK
            if (status & 0x0002) {    // NACK位为1
                return HE24C64SOH_NACK_ERROR;
            }
            return HE24C64SOH_SUCCESS;
        }
        
        // 短暂延时
        // HE24C64SOH_SimpleDelay(10);
        DEVICE_DELAY_US(1);
    }
    
    return HE24C64SOH_TIMEOUT;
}


