#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++ DigitalInput5.cpp -L../ -lhubo -lpthread -lrt -o DigitalInput5.out
Run:
	sudo ./DigitalInput5.out
Purpose:
	Let's get notified whenever a digital input changes.
	The program will terminate when digital input 2 is lowered to ground.
*/

// This function is called whenever a digital input changes.
void DIChangedCallback (unsigned char changedInputs, unsigned char allInputs);

bool bTerminate = false;

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;
	}
	
	// After initialization the callback can be registered.
	Register_DIChangedCallback (DIChangedCallback);
	
	while (!bTerminate) 
	{
		usleep (1000);
	} 

	// It's good programming style to de-register the callback.
	Unregister_DIChangedCallback (DIChangedCallback);

	// Free library resources.
	Uninitialize();
	
	return 0;
}

void DIChangedCallback (unsigned char changedInputs, unsigned char allInputs)
{
	// This function is called from the background thread running at high priority. 
	// Thus lengthy operations (such as prinf) should not be performed as they 
	// could exceed the time slice for the cycle tick. 
	// Note that the synchronisation with the main thread is missing for the bool 
	// variable bTerminate and should be done in a proper application.
	printf ("DIChangedCallback changed=0x%02X  new=0x%02X\n", changedInputs, allInputs);

	// Has the input 2 changed?
	if (changedInputs & 4)
		bTerminate = true;
}
