/*
 * XS65_port.c
 *
 *  Created on: 2020Äê10ÔÂ30ÈÕ
 *      Author: nxa16228
 */


#include "bsp.h"
#include "XS65_port.h"

#define Lpspi_Ip_DeviceAttributes_SPI0_XS6500_BOARD_InitPeripherals (Lpspi_Ip_DeviceAttributes_SPI0_PCS3_XS65_Instance_0_BOARD_InitPeripherals)

bool SPI_Device1_UnselectAfter;

void SPI_Device1_Select(void){
	return;
}


void SPI_Device1_Unselect(void){
	return;
}

uint8_t SPI_Device1_RequestBus(void){
	return 1;
}

uint8_t SPI_Device1_ReleaseBus(void){
	return 1;
}

uint8_t SPI_Device1_TransferBlock(void* SendDataPtr, void* ReceiveDataPtr, uint32_t Length, bool UnselectAfterTransfer)
{
  uint8_t tmpStatus;

  (void)Length;
  (void)UnselectAfterTransfer;

  while(Lpspi_Ip_GetStatus(XS65_SPI_INST) == LPSPI_IP_BUSY);	//wait till the LPSPI for XS65 is not busy
  tmpStatus = Lpspi_Ip_SyncTransmit(&Lpspi_Ip_DeviceAttributes_SPI0_XS6500_BOARD_InitPeripherals, \
								  (uint8_t *)SendDataPtr, \
								  (uint8_t *)ReceiveDataPtr, \
								  (uint16_t)2, \
								  1000U);
  return tmpStatus;
}

/* use ADC injected conversion (PTE26_ADC2_P6) to sample the XS65_CSNS pin */
uint8_t XS65_ADC_GetCsnsValue(uint32_t adcInst, uint32_t adcChanIdx, uint16_t *pData){
	uint16_t tmpData;
	//wait if the ADC Injected conversion is occupied by other tasks
	while((Adc_Sar_Ip_GetStatusFlags(adcInst)&ADC_SAR_IP_STATUS_FLAG_INJECTED_STARTED) != 0);
	Adc_Sar_Ip_EnableChannel(adcInst, ADC_SAR_IP_CONV_CHAIN_INJECTED, adcChanIdx);
	Adc_Sar_Ip_StartConversion(adcInst, ADC_SAR_IP_CONV_CHAIN_INJECTED);
	//wait till injected conversion is completed, read result
	for(uint32_t cnt=0; cnt<1000; cnt++){
		tmpData = Adc_Sar_Ip_GetConvData(adcInst, adcChanIdx);
		if(tmpData>0)
			break;
	}
	*pData = tmpData;
	Adc_Sar_Ip_DisableChannel(adcInst, ADC_SAR_IP_CONV_CHAIN_INJECTED, adcChanIdx);
	if(tmpData>0)
		return E_OK;
	else
		return E_NOT_OK;
}

void XS65_RstPinHigh(void){
	//Siul2_Port_Ip_SetGPDO(0, XS65_RSTB_PIN_INST, 1);
	Siul2_Dio_Ip_WritePin(XS65_RST_PORT, XS65_RST_PIN, 1);
}

void XS65_RstPinLow(void){
	//Siul2_Port_Ip_SetGPDO(0, XS65_RSTB_PIN_INST, 0);
	Siul2_Dio_Ip_WritePin(XS65_RST_PORT, XS65_RST_PIN, 0);
}

void XS65_LimphomeDisable(void){
	//Siul2_Port_Ip_SetGPDO(0, XS65_LIMP_PIN_INST, 0);
	Siul2_Dio_Ip_WritePin(XS65_LIMP_PORT, XS65_LIMP_PIN, 0);
}

void XS65_LimphomeEnable(void){
	//Siul2_Port_Ip_SetGPDO(0, XS65_LIMP_PIN_INST, 1);
	Siul2_Dio_Ip_WritePin(XS65_LIMP_PORT, XS65_LIMP_PIN, 1);
}
