/*
 * AD5940 library ↔ ESP32-S3 bridge.
 * Implements the platform functions the ad5940 library expects to find at link time.
 */
#include "ad5940.h"
#include "ad5941_port.h"
#include "esp_rom_sys.h"

static volatile uint8_t int_flag;

static void IRAM_ATTR gp0_isr(void *arg)
{
    int_flag = 1;
}

/* ---- SPI ---- */

void AD5940_ReadWriteNBytes(unsigned char *pSendBuffer, unsigned char *pRecvBuff, unsigned long length)
{
    ad5941_port_spi_rw(pSendBuffer, pRecvBuff, length);
}

/* ---- CS ---- */

void AD5940_CsClr(void) { gpio_set_level(AD5940_CS_PIN, 0); }
void AD5940_CsSet(void) { gpio_set_level(AD5940_CS_PIN, 1); }

/* ---- Reset ---- */

void AD5940_RstSet(void) { gpio_set_level(AD5940_RST_PIN, 1); }
void AD5940_RstClr(void) { gpio_set_level(AD5940_RST_PIN, 0); }

/* ---- Timing ---- */

void AD5940_Delay10us(uint32_t time)
{
    if (time < 100)
        esp_rom_delay_us(time * 10);
    else
        vTaskDelay(pdMS_TO_TICKS(time / 100));
}

/* ---- Interrupt ---- */

uint32_t AD5940_GetMCUIntFlag(void)  { return int_flag; }

uint32_t AD5940_ClrMCUIntFlag(void)
{
    int_flag = 0;
    return 1;
}

/* ---- Resource init (called by AD5940_MCUResourceInit) ---- */

uint32_t AD5940_MCUResourceInit(void *pCfg)
{
    ad5941_port_init_spi();
    ad5941_port_init_gpio();

    AD5940_CsSet();
    AD5940_RstSet();

    gpio_install_isr_service(0);
    gpio_isr_handler_add(AD5940_GP0INT_PIN, gp0_isr, NULL);

    return 0;
}
