/*
 * spi.cpp
 *
 *  Created on: Nov 16, 2015
 *      Author: Philipp Hinz
 */

#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "global.h"
#include "logger.h"

#include <inttypes.h>
#include <unistd.h>
#include "spi.h"

/**
 * Writes the data on the SPI bus and returns the reply
 * @param data byte to write to the bus
 * @return byte read from the bus
 */

uint8_t spi_readwrite(uint8_t data) {
	uint8_t tmp[1];
	tmp[0] = data;
	wiringPiSPIDataRW(SPI_CHANNEL, tmp, 1); // int wiringPiSPIDataRW (int channel, unsigned char *data, int len) ;
	if (verbose >= V_SPI)
		logger(V_SPI, "SPI Write %x Read %x\n", data, tmp[0]);
	return tmp[0];
}

/**
 * Initializes the SPI bus
 */

void spi_init(void) {
	if (wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED) < 0) { //int wiringPiSPISetup (int channel, int speed) ;
		logger_error("Unable to setup SPI on channel %d: %s\n", SPI_CHANNEL,
				strerror(errno));
		return;
	}
}

/**
 * Initializes the shift register
 */

void shift_init(void) {
	pinMode(SHIFT_G, OUTPUT);
	pinMode(SHIFT_RCK, OUTPUT);
	pinMode(SHIFT_SCLR, OUTPUT);
	digitalWrite(SHIFT_G, HIGH);
	digitalWrite(SHIFT_RCK, HIGH);
	digitalWrite(SHIFT_SCLR, LOW);
	usleep(10);
	digitalWrite(SHIFT_G, LOW);
	digitalWrite(SHIFT_RCK, LOW);
	digitalWrite(SHIFT_SCLR, HIGH);
}

/**
 * Sends a byte to the shift register
 * @param data Data byte
 */

void shift_data(uint8_t data) {
	spi_readwrite(data);
	digitalWrite(SHIFT_RCK, HIGH);
	usleep(10);
	digitalWrite(SHIFT_RCK, LOW);
}

