#include <stdio.h>
#include <unistd.h>

#include "../hubolib.h"
#include "../hubocfg.h" // Required for changing default I2C device.

using namespace HuboLib;

/*
Compile and link: 
	g++ FanSpeed.cpp -L../ -lhubo -lpthread -lrt -o FanSpeed.out
Run:
	sudo ./FanSpeed.out
Purpose:
	Simple demo doing sending ON-OFF patterns to a digital output e.g. to control fan speed.
*/

#define FAN_CHANNEL 0
#define WAIT_TIME 	10000


int main(void)
{
	// If required - set the I2C device to work with. The Raspberry Pi uses "/dev/i2c-1" which is default, the Banana Pi uses "/dev/i2c-0"
	#ifdef BPI
	    g_I2CConfig.m_sI2CDevice = "/dev/i2c-0";
	#endif

	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}

	// Set background cycle time to 5ms in order to have the digital IO's being updated every 5ms.
	Set_Cycle_Time(5);
	
	// The pattern to use to update the FAN-CHANNEL IO pin.
//	int channelPattern [10] = {0, 0, 1, -1}; 		// 33% duty time
//	int channelPattern [10] = {0, 1, -1}; 			// 50% duty time
//	int channelPattern [10] = {0, 1, 1, -1}; 		// 66% duty time
	int channelPattern [10] = {0, 1, 1, 1, -1}; 	// 75% duty time
//	int channelPattern [10] = {1, -1}; 				// 100% duty time

	// This rover goes round and round.
	int patternRover = 0;
	
	// Cyclic update of the FAN_CHANNEL IO pin.
	while (1)
	{
		int value = channelPattern[patternRover++];
		if (value == -1)
		{
			patternRover = 0;
			continue;
		}
		
		// Set output to new value.
		Set_DO_Channel(FAN_CHANNEL, value);
	
		// Wait a while.
		usleep (WAIT_TIME);
	}
	
	// Free library resources (despite the fact we'll never get here).
	Uninitialize();
	
	return 0;
}
