/*******************************************************************************
 * @file    spi2_bus.h
 * @brief   Shared SPI2 Bus Manager for ADA2200 and W25Q32RV Flash
 * @author  Charles KWON <charleskwon@medithings.co.kr>
 * @date    2025-02-03
 *
 * @details Both ADA2200 (Lock-in Amp) and W25Q32RV (Flash) share SPI2 bus.
 *          This module manages bus initialization and provides access.
 *          Device selection is done via individual CS pins:
 *          - ADA2200:  CS = P0.13
 *          - W25Q32RV: CS = P0.24
 ******************************************************************************/

#ifndef SPI2_BUS_H
#define SPI2_BUS_H

#include "nrf_drv_spi.h"
#include "sdk_errors.h"
#include <stdbool.h>

/*==============================================================================
 * SPI2 BUS CONFIGURATION
 *============================================================================*/

#define SPI2_BUS_INSTANCE       2

/* Shared SPI pins */
#define SPI2_SCK_PIN            14  /* P0.14 */
#define SPI2_MISO_PIN           15  /* P0.15 */
#define SPI2_MOSI_PIN           16  /* P0.16 */

/* Device CS pins (active low) */
#define SPI2_CS_ADA2200         13  /* P0.13 - Lock-in Amplifier */
#define SPI2_CS_FLASH           24  /* P0.24 - W25Q32RV Flash */

/*==============================================================================
 * PUBLIC FUNCTIONS
 *============================================================================*/

/**
 * @brief Initialize SPI2 bus (call once at startup)
 * @return NRF_SUCCESS or error code
 */
ret_code_t spi2_bus_init(void);

/**
 * @brief Uninitialize SPI2 bus
 */
void spi2_bus_uninit(void);

/**
 * @brief Check if SPI2 bus is initialized
 * @return true if initialized
 */
bool spi2_bus_is_initialized(void);

/**
 * @brief Get SPI2 bus instance for transfers
 * @return Pointer to SPI instance (NULL if not initialized)
 */
const nrf_drv_spi_t* spi2_bus_get_instance(void);

/**
 * @brief Perform SPI transfer (blocking mode)
 * @note Caller must manage CS pin manually
 */
ret_code_t spi2_bus_transfer(const uint8_t *tx_buf, uint8_t tx_len,
                              uint8_t *rx_buf, uint8_t rx_len);

#endif /* SPI2_BUS_H */
