/*
 * LinuxBoardController.cpp
 *
 *  Created on: 22 Mar 2017
 *      Author: lenka
 */

#include <LinuxBoardController.h>

LinuxBoardController::LinuxBoardController() {


}

LinuxBoardController::~LinuxBoardController() {

}

/**
 * Set a user LED (on top of the board) on / off
 */
int LinuxBoardController::SetBoardLED(int led_no, int on) {
	char str[256];
	int fd;

	if (led_no < 0 || led_no > 3) {
		printf("only support 'user1' and 'user2' leds now!\n");
		return 0;
	}

	//-- set brightness
	sprintf(str, "/sys/class/leds/user%d/brightness", led_no);
	if ((fd = open(str, O_WRONLY)) < 0) {
		perror("open");
		return 0;
	}
	sprintf(str, "%d\n", 255 * on);
	if (write(fd, str, strlen(str)) != strlen(str)) {
		perror("set brightness");
		close(fd);
		return 0;
	}
	close(fd);
	return 1;
}

/**
 * Blink a user led (on top of the board
 */
int LinuxBoardController::BlinkBoardLED(int led_no, int delay_on, int delay_off) {
	char str[256];
	int fd;

	if (led_no < 0 || led_no > 3) {
		printf("only support 'user1' and 'user2' leds now!\n");
		return 0;
	}

	//-- set delay_on
	sprintf(str, "/sys/class/leds/user%d/delay_on", led_no);
	if ((fd = open(str, O_WRONLY)) < 0) {
		perror("open");
		return 0;
	}
	sprintf(str, "%d\n", delay_on);
	if (write(fd, str, strlen(str)) != strlen(str)) {
		perror("set delay_on");
		close(fd);
		return 0;
	}
	close(fd);

	//-- set delay_off
	sprintf(str, "/sys/class/leds/user%d/delay_off", led_no);
	if ((fd = open(str, O_WRONLY)) < 0) {
		perror("open");
		return 0;
	}
	sprintf(str, "%d\n", delay_off);
	if (write(fd, str, strlen(str)) != strlen(str)) {
		perror("set brightness");
		close(fd);
		return 0;
	}
	close(fd);

	return 1;
}

/**
 * Reset the board
 */
int LinuxBoardController::ResetDSPIC() {
	char str[256];
	int fd;

	//set brightness
	if ((fd = open("/sys/class/leds/dspic_reset/brightness", O_WRONLY)) < 0) {
		perror("open");
		return 0;
	}
	sprintf(str, "%d\n", 255);
	if (write(fd, str, strlen(str)) != strlen(str)) {
		perror("pull low");
		return 0;
	}
	sprintf(str, "%d\n", 0);
	if (write(fd, str, strlen(str)) != strlen(str)) {
		perror("pull high");
		return 0;
	}

	close(fd);
	return 1;
}
