#include "ad5941_port.h"

static const char *TAG = "ad5941-port";
static spi_device_handle_t spi;

void ad5941_port_init_spi(void)
{
    if (spi) return;

    spi_bus_config_t bus = {
        .mosi_io_num = PIN_NUM_MOSI,
        .miso_io_num = PIN_NUM_MISO,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = SOC_SPI_MAXIMUM_BUFFER_SIZE,
    };

    spi_device_interface_config_t dev = {
        .clock_source = SPI_CLK_SRC_DEFAULT,
        .queue_size = 1,
        .mode = 0,
        .clock_speed_hz = SPI_MASTER_FREQ_16M,
        .spics_io_num = -1,    /* CS managed manually */
    };

    ESP_ERROR_CHECK(spi_bus_initialize(AD594x_HOST, &bus, SPI_DMA_CH_AUTO));
    ESP_ERROR_CHECK(spi_bus_add_device(AD594x_HOST, &dev, &spi));
    ESP_LOGI(TAG, "SPI%d initialised", AD594x_HOST + 1);
}

void ad5941_port_init_gpio(void)
{
    gpio_reset_pin(AD5940_CS_PIN);
    gpio_set_direction(AD5940_CS_PIN, GPIO_MODE_OUTPUT);
    gpio_set_level(AD5940_CS_PIN, 1);

    gpio_reset_pin(AD5940_RST_PIN);
    gpio_set_direction(AD5940_RST_PIN, GPIO_MODE_OUTPUT);
    gpio_set_level(AD5940_RST_PIN, 1);

    gpio_reset_pin(AD5940_GP0INT_PIN);
    gpio_set_direction(AD5940_GP0INT_PIN, GPIO_MODE_INPUT);
    gpio_set_pull_mode(AD5940_GP0INT_PIN, GPIO_PULLUP_ONLY);
    gpio_set_intr_type(AD5940_GP0INT_PIN, GPIO_INTR_NEGEDGE);
}

void ad5941_port_spi_rw(uint8_t *tx, uint8_t *rx, unsigned long len)
{
    if (!len) return;

    spi_transaction_t t = {
        .length = len * 8,
        .tx_buffer = tx,
        .rx_buffer = rx,
    };
    ESP_ERROR_CHECK(spi_device_polling_transmit(spi, &t));
}
