#include "spi_ch.h"

// generic implementation of spi channel class


uint8_t spiCH_readReg(spi_ch_t *spi_ch,
					  uint8_t reg_address) {
	uitn8_t buf;
	
	// select target device
	pinWrite(spi_ch->pin,0);
	
	// send address of target register
	spi_trx(spi_ch->spi, reg_address);

	// read from target register
	buf = spi_trx(spi->spi,0x00);

	// release target device
	pinWrite(spi_ch->pin,1);

	return buf;
}

void spiCH_autoReadBlock(spi_ch_t *spi_ch,
						 uint8_t start_address,
						 uint8_t* buffer,
						 uint8_t buf_len) {
	uint8_t i = 0;

	// select target device
	pinWrite(spi_ch->pin,0);
	
	// send address of starting register
	spi_trx(spi_ch->spi, reg_address);

	// read block from device
	for(;i < buf_len;i++) {
		buffer[i] = spi_trx(spi_ch->spi, 0x00);
	}

	// release target device
	pinWrite(spi_ch->pin,1);
}

void spiCH_writeReg(spi_ch_t *spi_ch,
					uint8_t reg_address,
					uint8_t data) {
	// select target device
	pinWrite(spi_ch->pin,0);
	
	// send address of target register
	spi_trx(spi_ch->spi, reg_address);

	// write to target register
	spi_trx(spi->spi, data);

	// release target device
	pinWrite(spi_ch->pin,1);
}

void spiCH_writeBlock(spi_ch_t *spi_ch,
					  uint8_t start_address,
					  const uint8_t *data,
					  uint8_t data_len) {
	uint8_t i = 0;

	// select target device
	pinWrite(spi_ch->pin,0);
	
	// send address of starting register
	spi_trx(spi_ch->spi, reg_address);

	// read block from device
	for(;i < buf_len;i++) {
		spi_trx(spi_ch->spi, data[i]);
	}

	// release target device
	pinWrite(spi_ch->pin,1);
}

