#include "iso8200aq.h"
#include "spi.h"
#include "main.h"

/* Access the SPI2 handle generated by CubeMX */
extern SPI_HandleTypeDef hspi2;

/* Direct Software Control Macros for Chip Select on PB12 */
#define ISO_CS_LOW()   HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_RESET)
#define ISO_CS_HIGH()  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_SET)

/**
  * @brief  Write and read bytes simultaneously via SPI2 to the ISO8200AQ
  */
uint8_t Iso8200aq_Board_SpiWriteBytes(uint8_t *pByteToTransmit, uint8_t *pReceivedByte, uint8_t nbDevices)
{
    ISO_CS_LOW();

    // ISO8200AQ shifts data on a per-device basis (1 byte per chip)
    HAL_StatusTypeDef status = HAL_SPI_TransmitReceive(&hspi2, pByteToTransmit, pReceivedByte, nbDevices, 100);

    ISO_CS_HIGH();

    return (status == HAL_OK) ? 0 : 1;
}

/**
  * @brief  Provides a millisecond delay wrapper
  */
void Iso8200aq_Board_Delay(uint32_t delay)
{
    HAL_Delay(delay);
}

/**
  * @brief  Reads the current hardware status of the active diagnostic pins
  */
uint8_t Iso8200aq_Board_GetFaultPinState(uint8_t deviceId)
{
    // Make sure DI_FAULT pin was mapped inside your CubeMX setup
    return (HAL_GPIO_ReadPin(DI_FAULT_GPIO_Port, DI_FAULT_Pin) == GPIO_PIN_RESET) ? 0 : 1;
}

uint8_t Iso8200aq_Board_GetPGoodPinState(uint8_t deviceId)
{
    // Make sure DI_GOOD pin was mapped inside your CubeMX setup
    return (HAL_GPIO_ReadPin(DI_GOOD_GPIO_Port, DI_GOOD_Pin) == GPIO_PIN_RESET) ? 0 : 1;
}

/* Optional Stubs requested by the base driver specification */
void Iso8200aq_Board_GpioInit(uint8_t deviceId)       { ISO_CS_HIGH(); }
uint8_t Iso8200aq_Board_SpiInit(uint32_t spiFreq)     { return 0; }
void Iso8200aq_Board_OutEnable(uint8_t deviceId)     { HAL_GPIO_WritePin(DI_EN_GPIO_Port, DI_EN_Pin, GPIO_PIN_SET); }
void Iso8200aq_Board_OutDisable(uint8_t deviceId)    { HAL_GPIO_WritePin(DI_EN_GPIO_Port, DI_EN_Pin, GPIO_PIN_RESET); }
uint8_t Iso8200aq_Board_TimerInit(uint32_t pwmFreq, uint32_t guardFreq) { return 0; }
void Iso8200aq_Board_GuardTimerStart(void)            {}
void Iso8200aq_Board_GuardTimerStop(void)             {}
void Iso8200aq_Board_EnableIrq(void)                  {}
void Iso8200aq_Board_DisableIrq(void)                 {}


/**
  * @brief  Reads the current hardware status of the Output Enable pin
  */
uint8_t Iso8200aq_Board_GetOutPinState(uint8_t deviceId)
{
    // Checks if your output enable control line is physically HIGH or LOW
    return (HAL_GPIO_ReadPin(DI_EN_GPIO_Port, DI_EN_Pin) == GPIO_PIN_RESET) ? 0 : 1;
}
