/*
 * eeprom.h
 *
 *  Created on: Dec 7, 2025
 *      Author: user
 */

#ifndef __EEPROM_H
#define __EEPROM_H

#ifdef __cplusplus
extern "C" {
#endif

#include "stm32f1xx_hal.h"

/*
 * Simple EEPROM emulation for STM32F103C8T6 (medium density).
 * - Uses 2 Flash pages (1 kB each) at the end of Flash.
 * - Stores variables as 16-bit values identified by 16-bit "virtual addresses".
 *
 * You must define the list of virtual addresses in eeprom.c: EE_VirtAddrs[].
 */

typedef enum
{
    EE_STATUS_OK = 0,
    EE_STATUS_ERROR,
    EE_STATUS_NOT_FOUND,
    EE_STATUS_NO_SPACE
} EE_Status;

/* For compatibility with ST style uint16_t return codes */
#define EE_OK        ((uint16_t)EE_STATUS_OK)
#define EE_ERROR     ((uint16_t)EE_STATUS_ERROR)
#define EE_NOT_FOUND ((uint16_t)EE_STATUS_NOT_FOUND)
#define EE_NO_SPACE  ((uint16_t)EE_STATUS_NO_SPACE)

/* Flash parameters for STM32F103C8T6 */
#define EE_FLASH_BASE_ADDR     0x08000000U
#define EE_PAGE_SIZE           0x400U      /* 1 kB pages */

/*
 * Here we assume a 64 kB Flash device (STM32F103C8T6):
 * Flash range: 0x0800 0000 - 0x0800 FFFF
 * Pages: 0..63 (64 pages)
 * We use the last 2 pages for EEPROM:
 *  - Page 62: 0x0800 F800
 *  - Page 63: 0x0800 FC00
 */
#define EE_PAGE0_BASE          (EE_FLASH_BASE_ADDR + (62U * EE_PAGE_SIZE))
#define EE_PAGE1_BASE          (EE_FLASH_BASE_ADDR + (63U * EE_PAGE_SIZE))

/* Page status markers (stored in the first halfword of each page) */
#define EE_PAGE_STATUS_ERASED  0xFFFFU
#define EE_PAGE_STATUS_VALID   0xAAAAU
#define EE_PAGE_STATUS_RECEIVE 0x5555U

/*
 * Configure how many virtual variables you have.
 * Example: bytes, words, and array elements mapped to 16-bit variables.
 * Set EE_NUM_VIRTUAL_ADDR and define EE_VirtAddrs[] in eeprom.c.
 */
/* 32 virtual variables, sequential addresses */
#define EE_NUM_VIRTUAL_ADDR    32U
#define EEW_ADDR(i)            (uint16_t)(0x0001 + (i))   // i = 0..31

/* Virtual address table (defined in eeprom.c, can be customized) */
extern const uint16_t EE_VirtAddrs[EE_NUM_VIRTUAL_ADDR];

/* Public API – now using uint16_t like ST examples */
uint16_t EE_Init(void);
uint16_t EE_ReadVariable(uint16_t VirtAddress, uint16_t *Data);
uint16_t EE_WriteVariable(uint16_t VirtAddress, uint16_t Data);

/* Pseudo-array accessor EEW[idx] */
static inline uint16_t EEW_Read(uint8_t idx, uint16_t *value)
{
    return EE_ReadVariable(EEW_ADDR(idx), value);
}

static inline uint16_t EEW_Write(uint8_t idx, uint16_t value)
{
    return EE_WriteVariable(EEW_ADDR(idx), value);
}

#ifdef __cplusplus
}
#endif

#endif /* __EEPROM_H */
