/***************************************************************************************************************:')

ESMgr.h

ES distance sensor handling.

Fabrice Le Bars

Created: 2009-06-24

Version status: Not finished

***************************************************************************************************************:)*/

#ifndef ESMGR_H
#define ESMGR_H

#include "OSThread.h"
#include "OSCriticalSection.h"
#include "ESCfg.h"

/*
Debug macros specific to ESMgr.
*/
#ifdef _DEBUG_MESSAGES_ESUTILS
#	define _DEBUG_MESSAGES_ESMGR
#endif // _DEBUG_MESSAGES_ESUTILS

#ifdef _DEBUG_WARNINGS_ESUTILS
#	define _DEBUG_WARNINGS_ESMGR
#endif // _DEBUG_WARNINGS_ESUTILS

#ifdef _DEBUG_ERRORS_ESUTILS
#	define _DEBUG_ERRORS_ESMGR
#endif // _DEBUG_ERRORS_ESUTILS

#ifdef _DEBUG_MESSAGES_ESMGR
#	define PRINT_DEBUG_MESSAGE_ESMGR(params) PRINT_DEBUG_MESSAGE(params)
#else
#	define PRINT_DEBUG_MESSAGE_ESMGR(params)
#endif // _DEBUG_MESSAGES_ESMGR

#ifdef _DEBUG_WARNINGS_ESMGR
#	define PRINT_DEBUG_WARNING_ESMGR(params) PRINT_DEBUG_WARNING(params)
#else
#	define PRINT_DEBUG_WARNING_ESMGR(params)
#endif // _DEBUG_WARNINGS_ESMGR

#ifdef _DEBUG_ERRORS_ESMGR
#	define PRINT_DEBUG_ERROR_ESMGR(params) PRINT_DEBUG_ERROR(params)
#else
#	define PRINT_DEBUG_ERROR_ESMGR(params)
#endif // _DEBUG_ERRORS_ESMGR

#define DISTANCE_POLLING_MODE_ES 0x00000001

struct ESMGR
{
	HES hES;
	char szDevice[256];
	THREAD_IDENTIFIER ThreadId;
	int PollingTimeInterval;
	int PollingMode;
	BOOL bRunThread;
	BOOL bConnected;
	CRITICAL_SECTION ESCS;
	CRITICAL_SECTION distanceCS;
	UINT distancecounter;
	double distance;
	BOOL bWaitForFirstData;
};
typedef struct ESMGR* HESMGR;

#define INVALID_HESMGR_VALUE NULL

/*
Private function.
Thread function that handles the polling and automatic reconnection of a ES.

LPVOID lpParam : (INOUT) Parameter of the thread.

Return : 0.
*/
EXTERN_C THREAD_PROC_RETURN_VALUE ESMgrThreadProc(void* lpParam);

/*
Private function.
Open a ES and get data from it.

HES hES : (IN) Identifier of the ES.

Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int ConnectToES(HESMGR hESMgr)
{
	// No critical section is needed here because the other functions 
	// should not try to access the device or data while the device is
	// not connected (bConnected = FALSE).

	if (OpenES(&hESMgr->hES, hESMgr->szDevice) != EXIT_SUCCESS)
	{
		PRINT_DEBUG_MESSAGE_ESMGR(("Unable to connect to a ES\n"));
		return EXIT_FAILURE;
	}

	// Get data before setting bConnected to TRUE to be sure that
	// the other functions will get valid data.
	if (hESMgr->bWaitForFirstData)
	{
		if (hESMgr->PollingMode & DISTANCE_POLLING_MODE_ES)
		{
			if (GetDistanceES(hESMgr->hES, &hESMgr->distance) != EXIT_SUCCESS)
			{
				PRINT_DEBUG_MESSAGE_ESMGR(("Unable to connect to a ES\n"));
				return EXIT_FAILURE;
			}
		}
	}

	hESMgr->bConnected = TRUE;
	PRINT_DEBUG_MESSAGE_ESMGR(("ES connected\n"));

	return EXIT_SUCCESS;
}

/*
Initialize a structure that manage the polling and the reconnection of a ES.

HESMGR* phESMgr : (INOUT) Valid pointer that will receive an identifier of
the structure.
char* szDevice : (IN) ES serial port to open.
int PollingTimeInterval : (IN) Time interval between 2 requests of data (in ms).
int PollingMode : (IN) DISTANCE_POLLING_MODE_ES.
int Priority : (IN) Priority of the thread that manages the polling and the 
reconnection of the device. See SetThreadDefaultPriority().
BOOL bWaitForFirstData : (IN) TRUE to wait for the first entire data in 
InitESMgr(), FALSE if it does not matter if the first data after the 
connection to the device is invalid during some seconds.

Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int InitESMgr(HESMGR* phESMgr, char* szDevice, 
						 int PollingTimeInterval,
						 int PollingMode,
						 int Priority,
						 BOOL bWaitForFirstData)
{
	*phESMgr = (HESMGR)calloc(1, sizeof(struct ESMGR));

	if (*phESMgr == NULL)
	{
		PRINT_DEBUG_ERROR_ESMGR(("InitESMgr error (%s) : %s"
			"(szDevice=%s)\n", 
			strtime_m(), 
			"Out of memory. ", 
			szDevice));
		return EXIT_FAILURE;
	}

	sprintf((*phESMgr)->szDevice, "%s", szDevice);

	(*phESMgr)->PollingTimeInterval = PollingTimeInterval;
	(*phESMgr)->PollingMode = PollingMode;
	(*phESMgr)->bConnected = FALSE;
	(*phESMgr)->bRunThread = TRUE;
	(*phESMgr)->distancecounter = 0;
	(*phESMgr)->distance = 0;
	(*phESMgr)->bWaitForFirstData = bWaitForFirstData;

	if (
		(InitCriticalSection(&(*phESMgr)->ESCS) != EXIT_SUCCESS)||
		(InitCriticalSection(&(*phESMgr)->distanceCS) != EXIT_SUCCESS)
		)
	{
		PRINT_DEBUG_ERROR_ESMGR(("InitESMgr error (%s) : %s"
			"(szDevice=%s)\n", 
			strtime_m(), 
			"Error creating a critical section. ", 
			szDevice));
		DeleteCriticalSection(&(*phESMgr)->distanceCS);
		DeleteCriticalSection(&(*phESMgr)->ESCS);
		free(*phESMgr);
		return EXIT_FAILURE;
	}

	// First attempt to connect to the device.
	ConnectToES(*phESMgr);

	if (CreateDefaultThread(ESMgrThreadProc, (void*)*phESMgr, &(*phESMgr)->ThreadId) != EXIT_SUCCESS)
	{
		PRINT_DEBUG_ERROR_ESMGR(("InitESMgr error (%s) : %s"
			"(szDevice=%s)\n", 
			strtime_m(), 
			"Error creating a thread. ", 
			szDevice));
		if ((*phESMgr)->bConnected)
		{
			CloseES(&(*phESMgr)->hES);
		}
		DeleteCriticalSection(&(*phESMgr)->distanceCS);
		DeleteCriticalSection(&(*phESMgr)->ESCS);
		free(*phESMgr);
		return EXIT_FAILURE;
	}

#ifdef ENABLE_PRIORITY_HANDLING
	if (SetThreadDefaultPriority((*phESMgr)->ThreadId, Priority) != EXIT_SUCCESS)
	{
		PRINT_DEBUG_WARNING_ESMGR(("InitESMgr error (%s) : %s"
			"(szDevice=%s)\n", 
			strtime_m(), 
			"Error setting the priority of a thread. ", 
			szDevice));
	}
#else
	UNREFERENCED_PARAMETER(Priority);
#endif // ENABLE_PRIORITY_HANDLING

	return EXIT_SUCCESS;
}

/*
Get the distance from a ES (thread safe).
If PollingMode have the DISTANCE_POLLING_MODE_ES flag set, get the last data 
polled in the last PollingTimeInterval, otherwise a direct thread safe request 
is made to the device.

HESMGR hESMgr : (IN) Identifier of the structure that manages the polling 
and the reconnection of a ES.
double* pDistance : (INOUT) Valid pointer receiving the distance (in m).

Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int GetDistanceESMgr(HESMGR hESMgr, double* pDistance)
{
	if (hESMgr->PollingMode & DISTANCE_POLLING_MODE_ES)
	{
		EnterCriticalSection(&hESMgr->distanceCS);

		if (!hESMgr->bConnected)
		{ 
			PRINT_DEBUG_ERROR_ESMGR(("GetDistanceESMgr error (%s) : %s"
				"(hESMgr=%#x)\n", 
				strtime_m(), 
				"Device not currently connected. ", 
				hESMgr));

			LeaveCriticalSection(&hESMgr->distanceCS);
			return EXIT_FAILURE;
		}

		// Get the last value stored.
		*pDistance = hESMgr->distance;

		LeaveCriticalSection(&hESMgr->distanceCS);
	}
	else
	{
		EnterCriticalSection(&hESMgr->ESCS);

		if (!hESMgr->bConnected)
		{ 
			PRINT_DEBUG_ERROR_ESMGR(("GetDistanceESMgr error (%s) : %s"
				"(hESMgr=%#x)\n", 
				strtime_m(), 
				"Device not currently connected. ", 
				hESMgr));

			LeaveCriticalSection(&hESMgr->ESCS);
			return EXIT_FAILURE;
		}

		// Get the value directly from the device.
		if (GetDistanceES(hESMgr->hES, pDistance) != EXIT_SUCCESS)
		{
			PRINT_DEBUG_MESSAGE_ESMGR(("Connection to a ES lost\n"));
			PRINT_DEBUG_ERROR_ESMGR(("GetDistanceESMgr error (%s) : %s"
				"(hESMgr=%#x)\n", 
				strtime_m(), 
				"Error getting data from the device. ", 
				hESMgr));

			// The device was supposed to be connected before.
			// Notify the thread to try to reconnect the device.
			hESMgr->bConnected = FALSE; 
			CloseES(&hESMgr->hES);

			LeaveCriticalSection(&hESMgr->ESCS);
			return EXIT_FAILURE;
		}
		
		LeaveCriticalSection(&hESMgr->ESCS);
	}

	return EXIT_SUCCESS;
}

/*
Release a structure that manage the polling and the reconnection of a ES.

HESMGR* phESMgr : (INOUT) Valid pointer to the identifier of the structure  
that manages the polling and the reconnection of a ES.

Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int ReleaseESMgr(HESMGR* phESMgr)
{
	BOOL bError = FALSE;

	// Indicate to the thread that it should terminate its loop.
	(*phESMgr)->bRunThread = FALSE;

	if (WaitForThread((*phESMgr)->ThreadId) != EXIT_SUCCESS)
	{
		PRINT_DEBUG_ERROR_ESMGR(("ReleaseESMgr error (%s) : %s"
			"(*phESMgr=%#x)\n", 
			strtime_m(), 
			"Error waiting for the thread. ", 
			*phESMgr));
		bError = TRUE;
	}

	DeleteCriticalSection(&(*phESMgr)->distanceCS);
	DeleteCriticalSection(&(*phESMgr)->ESCS);

	free(*phESMgr);

	*phESMgr = INVALID_HESMGR_VALUE;

	if (bError)
	{
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

#endif // ESMGR_H
