#include "main.h"
#include "mcp41x.h"

static uint32_t pot_value[MCP41X_RES_MAX] = {10000, 50000, 100000};

static void mcp41x_transmit(mcp41x_handle_t *hpot, uint8_t *data)
{
    hpot->hcs->cs_on(hpot->hcs);
    HAL_SPI_Transmit(hpot->hspi, data, 2, HAL_MAX_DELAY);
    hpot->hcs->cs_off(hpot->hcs);
}

void mcp41x_init(mcp41x_handle_t *hpot, SPI_HandleTypeDef *hspi, cs_handle_t *hcs, mcp41x_res_t res)
{
    hpot->hspi = hspi;
    hpot->hcs = hcs;
    hpot->max_res = res;
    hpot->dir = MCP41X_ATOB;

    hpot->hcs->cs_off(hcs);
}

void mcp41x_setValue(mcp41x_handle_t *hpot, uint8_t value)
{
    if (hpot->dir == MCP41X_BTOA)
    {
        value = 255 - value;
    }

    hpot->value = value;
    uint8_t data[2] = {MCP41X_WRITE0, value};
    mcp41x_transmit(hpot, data);
}

void mcp41x_setVolume(mcp41x_handle_t *hpot, uint8_t volume)
{
    if (volume > 100)
    {
        volume = 100;
    }
    uint32_t value = volume * 255U / 100U;
    mcp41x_setValue(hpot, value);
}

uint8_t mcp41x_getVolume(mcp41x_handle_t *hpot)
{
    return hpot->value * 100U / 255U;
}

void mcp41x_setResistance(mcp41x_handle_t *hpot, uint32_t resistance)
{
    if (resistance > pot_value[hpot->max_res])
    {
        resistance = pot_value[hpot->max_res];
    }

    uint32_t value = resistance * 255U / pot_value[hpot->max_res];
    mcp41x_setValue(hpot, value);
}

uint32_t mcp41x_getResistance(mcp41x_handle_t *hpot)
{
    return hpot->value * pot_value[hpot->max_res] / 255;
}

void mcp41x_setWiperDir(mcp41x_handle_t *hpot, mcp41x_dir_t dir)
{
    hpot->dir = dir;
}

void mcp41x_sleep(mcp41x_handle_t *hpot)
{
    uint8_t data[2] = {MCP41X_SLEEP, 0};
    mcp41x_transmit(hpot, data);
}