#include <rtthread.h>
#include <stdarg.h>
#include <rthw.h>
#include "storage.h"
#include "bsp_misc.h"
#include "i2c.h"

void storage_dbg(const char *tag, const char *fmt, ...);

at24cx_dev_t at24c02_device = {
    .dev_addr    = 0xA0,
    .write_bytes = bsp_i2c_write_bytes,
    .read_bytes  = bsp_i2c_read_bytes,
    .log         = storage_dbg,
};

void storage_dbg(const char *tag, const char *fmt, ...)
{
    // RT-Thread系统下的存储模块日志函数
    va_list args;
    char    buffer[256];

    va_start(args, fmt);

    // 先格式化到缓冲区
    int len = rt_vsnprintf(buffer, sizeof(buffer), fmt, args);
    va_end(args);

    // 输出标签
    rt_hw_console_output("[");
    rt_hw_console_output(tag);
    rt_hw_console_output("] ");

    // 输出格式化后的内容
    if (len > 0)
    {
        rt_hw_console_output(buffer);
    }

    // 添加换行符
    rt_hw_console_output("\n");
}

uint8_t data_buf[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
uint8_t read_buf[8] = {0};

void storage_test(void)
{
    if (at24cx_write(&at24c02_device, 0xa, data_buf, 8) != 0)
    {
        rt_kprintf("Failed to write data to EEPROM\r\n");
    }
    rt_thread_delay(1000);  // Delay for 1 second
    bsp_system_led_toggle(); // Toggle the system LEDs
    //rt_kprintf("[%d] System LED toggled\n", rt_tick_get()); // Print message to console
    if (at24cx_read(&at24c02_device, 0x0a, read_buf, 8) != 0)
    {
        rt_kprintf("Failed to read data from EEPROM\r\n");
    }
    else
    {
        rt_kprintf("Read data from EEPROM: ");
        for (int i = 0; i < 8; i++)
        {
            rt_kprintf("%02X ", read_buf[i]);
        }
        rt_kprintf("\r\n");
    }
    rt_thread_mdelay(10);
}

int storage_init(void)
{
    MX_I2C2_Init();
    return 0;
}
