#include "eeprom.h"
#include "main.h"
#include "config.h"
#include "elog.h"

extern int Eeprom_Port();
extern void Eeprom_Task();
extern int Config_Read_Eeprom( uint8_t numSeconds);
extern int Config_Write_Eeprom( );

osThreadId_t eeprom_taskHandle;
const osThreadAttr_t eeprom_task_attributes = {
.name = "eeprom_task",
.stack_size = 256,
.priority = (osPriority_t) osPriorityLow,
};

/*  1: 8bit  2: 16bit I2C_MEMADD_SIZE_8BIT  I2C_MEMADD_SIZE_16BIT */ 

enum  EEPROM_MODEL{ 
    AT24C01     =127,
    AT24C02     =255,
    AT24C04     =511,
    AT24C08     =1023,
    AT24C16     =2047,
    AT24C32     =4095,
    AT24C64     =8191,
    AT24C128    =16383,
    AT24C256    =32767, 
};

eeprom_t *eeprom;
extern I2C_HandleTypeDef hi2c1;
I2C_HandleTypeDef *Eeprom_I2C = &hi2c1;

extern struct config config;
extern int Config_Read_Eeprom( uint8_t numSeconds);

uint8_t eeprom_buf;

int Eeprom_Port()
{
    eeprom = Eeprom_init();
    Eeprom_SET_I2C( eeprom,  &hi2c1 );
    Eeprom_SET_Device_Model( eeprom, AT24C02 );
    Eeprom_SET_Device_Addr(   eeprom, 0xA0 );
    if ( eeprom->model < AT24C16 ) 
         Eeprom_SET_Mem_Addr_Type( eeprom,  I2C_MEMADD_SIZE_8BIT);  
    else
         Eeprom_SET_Mem_Addr_Type( eeprom, I2C_MEMADD_SIZE_16BIT);  
    eeprom->stat = HAL_I2C_STATE_READY;

  eeprom_taskHandle = osThreadNew(Eeprom_Task, NULL, &eeprom_task_attributes);
    // if (Config_Read_Eeprom( 8) == 0)
    // {
    //     HAL_GPIO_TogglePin(RED_GPIO_Port,RED_Pin);     
    //     // log_i( "ok>>>>>>>>");
    // }

    return 0;
}

void Eeprom_Task()
{
    for ( ; ; )
    {
        Eeprom_send( eeprom );
    }
}

int Config_Read_Eeprom( uint8_t numSeconds)
{
    eeprom->stat= HAL_I2C_STATE_BUSY;
    eeprom->time_base = osKernelGetTickCount();

    uint8_t aa = Eeprom_Read_Multi_Byte_IT( eeprom, 0, (uint8_t *)&config, sizeof(config) );
    // uint8_t aa = HAL_I2C_Mem_Read_IT( eeprom->i2c, eeprom->dev_addr, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&config, sizeof(config) );
    // uint8_t aa = HAL_I2C_Mem_Read_IT(eeprom->i2c, eeprom->dev_addr, 0, I2C_MEMADD_SIZE_8BIT, data, 1  );

    while(HAL_I2C_GetState(eeprom->i2c)!=HAL_I2C_STATE_READY ){
      if ((  osKernelGetTickCount() - eeprom->time_base) >numSeconds*1000)
      {      
        return -1;
      }
    }

    log_i("eeprom init ok.");

    if(config_check()==0){
        return 0;
    }
    config_reset();
    return 0;

}

/* config 内容写道eeprom ,一个一个依据时间限写入，启用任务*/
int Config_Write_Eeprom( )
{
    // Eeprom_Port_Init();
    Eeprom_Write_Multi_Byte_IT( eeprom, 0, (uint8_t *)&config, sizeof(config)  );
    for ( ; ; )
    {
        if (eeprom->size > 0)
            Eeprom_send_callback( eeprom );
        else
            return -1;
    }
    return 0;

}