/***************************************************************************
 *   Property rights (C) 2004-2006 by EVER Sp. z o.o.                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <unistd.h>
#include <string.h>
#include <stdio.h>

#include "ftccomm.h"
#include "conf.h"
#include "common.h"

#define SINLINEXL_USB_DRIVER_BUILD 1
#include "sinlinexl_usb.h"

/* Global variable declarations */
FTCComm commSinlineXLUSB;
supsp g_SinlineXLUSB_sup;
sdrv_config	sdcSinlineXLUSB;
int g_iSinlineXLUSB_FirmwareRev;
int	g_iSinlineXLUSB_UpsSeries, g_iSinlineXLUSB_UpsFamily;
int	g_iSinlineXLUSB_ExtError;

/* static variables */
static bool g_bSinlineXLUSB_BadFirmwarePass = false;
static bool g_bSinlineXLUSB_ConfigInitiated = false;
static int iSinlineXLUSB_AccuCount = 0;

static unsigned int uiUpsInformation[ UPS_INFORMATION_COUNT ];
static unsigned int uiUpsStatistics[ UPS_STATISTICS_COUNT ];

/* IMPLEMENTATION */

// Function name	: ioctl
// Description		: Control function
int sinlinexlusb_ioctl(long lCommand, void *lpvBuff, int *lpiBuffSize)
{
	switch(lCommand)
	{
	case IOCTL_INIT: 
		return SinlineXLUSB_DoInit(lpvBuff, lpiBuffSize);

	case IOCTL_UNINIT:
		return SinlineXLUSB_DoUnInit(lpvBuff, lpiBuffSize);

	case IOCTL_AUTOCONFIGURE: 
		return SinlineXLUSB_DoAutoConfigure(lpvBuff, lpiBuffSize);

	case IOCTL_CONFIGURE: 
		return SinlineXLUSB_DoConfigure(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSINFOMASK: 
		return SinlineXLUSB_DoGetUpsInfoMask(lpvBuff, lpiBuffSize);

	case IOCTL_SET_UPSINFOMASK:
		return SinlineXLUSB_DoSetUpsInfoMask(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSTATESMASK:
		return SinlineXLUSB_DoGetUpsStateMask(lpvBuff, lpiBuffSize);

	case IOCTL_SET_UPSSTATESMASK:
		return SinlineXLUSB_DoSetUpsStateMask(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSTATE:
		return SinlineXLUSB_DoGetUpsState(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSPARAMSMASK:
		return SinlineXLUSB_DoGetUpsParamsMask(lpvBuff, lpiBuffSize);

	case IOCTL_SET_UPSPARAMSMASK:
		return SinlineXLUSB_DoSetUpsParamsMask(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSPARAMS:
		return SinlineXLUSB_DoGetUpsParams(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSETUPPARAMSMASK:
		return SinlineXLUSB_DoGetUpsSetupParamsMask(lpvBuff, lpiBuffSize);

	case IOCTL_SET_UPSSETUPPARAMSMASK:
		return SinlineXLUSB_DoSetUpsSetupParamsMask(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSETUPPARAMS:
		return SinlineXLUSB_DoGetUpsSetupParams(lpvBuff, lpiBuffSize);

	case IOCTL_SET_UPSSETUPPARAMS:
		return SinlineXLUSB_DoSetUpsSetupParams(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSCHARACTERISTICMASK:
		return SinlineXLUSB_DoGetUpsCharacteristicMask(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSCHARACTERISTIC:
		return SinlineXLUSB_DoGetUpsCharacteristic(lpvBuff, lpiBuffSize);

	case IOCTL_GET_DRIVER_INFO:
		return SinlineXLUSB_DoGetDriverInfo(lpvBuff, lpiBuffSize);

	case IOCTL_GET_TABLE_INFORMATIONS:
		return SinlineXLUSB_DoGetUPSStructures(EU_INFORMATION, lpvBuff, lpiBuffSize);

	case IOCTL_GET_TABLE_SETUP:
		return SinlineXLUSB_DoGetUPSStructures(EU_SETUP, lpvBuff, lpiBuffSize);

	case IOCTL_GET_ERRORNO:
		return SinlineXLUSB_DoGetExtendedError(lpvBuff, lpiBuffSize);

	case IOCTL_TESTUPSLINK:
		return SinlineXLUSB_DoTestUpsLink(lpvBuff, lpiBuffSize);

	case IOCTL_GETCONFIGPARAMSCOUNT:
		return SinlineXLUSB_DoGetConfigParamsCount(lpvBuff, lpiBuffSize);

	case IOCTL_GETCONFIGPARAMS:
		return SinlineXLUSB_DoGetConfigParams(lpvBuff, lpiBuffSize);

	case IOCTL_GETCONFIGPARAM:
		return SinlineXLUSB_DoGetConfigParam(lpvBuff, lpiBuffSize);

	case IOCTL_SETCONFIGPARAMS:
		return SinlineXLUSB_DoSetConfigParams(lpvBuff, lpiBuffSize);

	case IOCTL_SETCONFIGPARAM:
		return SinlineXLUSB_DoSetConfigParam(lpvBuff, lpiBuffSize);

	case IOCTL_UPDATECONFIG:
		return SinlineXLUSB_DoUpdateConfig(lpvBuff, lpiBuffSize);

	case IOCTL_SHUTDOWNUPS:
		return SinlineXLUSB_DoUpsShutdown(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSTATISTICSCOUNT:
		return SinlineXLUSB_DoGetUpsStatisticsCount(lpvBuff, lpiBuffSize);

	case IOCTL_GET_UPSSTATISTICS:
		return SinlineXLUSB_DoGetUpsStatistics(lpvBuff, lpiBuffSize);

	case IOCTL_GETCONFIGFILENAME:
		return SinlineXLUSB_DoGetConfigFileName(lpvBuff, lpiBuffSize);
	
	default:
		return IOCTL_ERROR_CMD_NOTSUPPORTED;
	}
}

// Function name	: SinlineXLUSB_DoInit
// Description		: Inicjalizacja drivera
int SinlineXLUSB_DoInit( void *lpvBuff, int *lpiBuffSize )
{
	g_iSinlineXLUSB_ExtError = 0;

	g_iSinlineXLUSB_UpsSeries=0;
	g_iSinlineXLUSB_FirmwareRev=0;
	g_bSinlineXLUSB_BadFirmwarePass=false;

	if (SinlineXLUSB_DoReadConfig() != IOCTL_ERROR_SUCCESS)
		return IOCTL_ERROR_CONFIG_READFAIL;

	commSinlineXLUSB.init(sdcSinlineXLUSB.szSerialNumber, 19200);
	if (commSinlineXLUSB.open()!=COMM_SUCCESS) {
		g_iSinlineXLUSB_ExtError=IOCTL_ERROR_COMM_INITFAIL;
		return IOCTL_ERROR;
	}
	
	g_iSinlineXLUSB_ExtError = 0;
	if (SinlineXLUSB_DoUpdateConfig(NULL, NULL) != IOCTL_ERROR_SUCCESS)
		return IOCTL_ERROR;

	return IOCTL_ERROR_SUCCESS;

}

// Function name	: SinlineXLUSB_DoUnInit
// Description		: Deinicjalizacja drivera
int SinlineXLUSB_DoUnInit( void *lpvBuff, int *lpiBuffSize )
{
	if (commSinlineXLUSB.close()!=COMM_SUCCESS) {
		g_iSinlineXLUSB_ExtError=0;
		return IOCTL_ERROR;
	}
	
	return IOCTL_ERROR_SUCCESS;

}

// Function name	: SinlineXLUSB_DoAutoConfigure
// Description		: Self configure
int SinlineXLUSB_DoAutoConfigure( void *lpvBuff, int *lpiBuffSize )
{
	strcpy( sdcSinlineXLUSB.szSerialNumber, DRIVER_UPS_SERIALNUMBER );
	g_bSinlineXLUSB_ConfigInitiated = true;
	
	if (commSinlineXLUSB.isInitialized()) {
		int iSize = UPS_CONFIGURATION_COUNT;
		if (SinlineXLUSB_DoGetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
		iSize = UPS_CONFIGURATION_COUNT;
		int iErrPos = -1;
		if (SinlineXLUSB_DoSetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iErrPos) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
	} else {
		SinlineXLUSB_DoUnInit(NULL, NULL);
		if (SinlineXLUSB_DoInit(NULL, NULL) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_COMM_INITCFGFAIL;
		int iSize = UPS_CONFIGURATION_COUNT;
		if (SinlineXLUSB_DoGetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
		iSize = UPS_CONFIGURATION_COUNT;
		int iErrPos = -1;
		if (SinlineXLUSB_DoSetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iErrPos) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
	}
	
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoConfigure
// Description		: Configure driver to work properly with UPS
int SinlineXLUSB_DoConfigure( void *lpvBuff, int *lpiBuffSize )
{
	strcpy( sdcSinlineXLUSB.szSerialNumber, DRIVER_UPS_SERIALNUMBER );
	g_bSinlineXLUSB_ConfigInitiated = true;
	
	if (commSinlineXLUSB.isInitialized()) {
		SinlineXLUSB_DoUnInit(NULL, NULL);
		SinlineXLUSB_DoInit(NULL, NULL);
	}
	
	if (commSinlineXLUSB.isInitialized()) {
		int iSize = UPS_CONFIGURATION_COUNT;
		if (SinlineXLUSB_DoGetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
		iSize = UPS_CONFIGURATION_COUNT;
		int iErrPos = -1;
		if (SinlineXLUSB_DoSetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iErrPos) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
	} else {
		SinlineXLUSB_DoUnInit(NULL, NULL);
		if (SinlineXLUSB_DoInit(NULL, NULL) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_COMM_INITCFGFAIL;
		int iSize = UPS_CONFIGURATION_COUNT;
		if (SinlineXLUSB_DoGetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
		iSize = UPS_CONFIGURATION_COUNT;
		int iErrPos = -1;
		if (SinlineXLUSB_DoSetUPSStructures(EU_SETUP, &sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iErrPos) != IOCTL_ERROR_SUCCESS)
			return IOCTL_ERROR_CONFIGURATIONFAIL;
	}
	
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsInfoMask
// Description		: Zwraca informacje o wypelnieniu struktury informacji o UPS-ie
int SinlineXLUSB_DoGetUpsInfoMask( void *lpvBuff, int *lpiBuffSize )
{
	unsigned long ulMask = UI_PARAMETERS | UI_SETUP_PARAMETERS | UI_UPS_STATE | UI_UPS_STATISTICS;

	if ( *lpiBuffSize == sizeof( unsigned long ) )
		memcpy( lpvBuff, &ulMask, sizeof( unsigned long ) );
	else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUpsInfoMask
// Description		: 
int	SinlineXLUSB_DoSetUpsInfoMask(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_CMD_NOTSUPPORTED;
}

// Function name	: SinlineXLUSB_DoGetUpsStateMask
// Description		: 
int	SinlineXLUSB_DoGetUpsStateMask(void *lpvBuff, int *lpiBuffSize)
{
	unsigned long ulMask = US_POWERON | US_POWERFAIL | US_STANDBY | US_OVERLOAD | US_FAILURE |
		US_AVRUP | US_AVRLOWER | US_SHORT | US_BATTERYLOW | US_BYPASS | US_TEMPERATURETOOHIGH |
		US_BATTERYDEPLETED | US_BADEXTERNALMODULES | US_BATTERYCHARGING;

	if ( *lpiBuffSize == sizeof( unsigned long ) )
		memcpy( lpvBuff, &ulMask, sizeof( unsigned long ) );
	else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUpsStateMask
// Description		: 
int	SinlineXLUSB_DoSetUpsStateMask(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_CMD_NOTSUPPORTED;
}

// Function name	: SinlineXLUSB_DoGetUpsState
// Description		: Return actual UPS state
int	SinlineXLUSB_DoGetUpsState(void *lpvBuff, int *lpiBuffSize)
{
#undef CONVERT_BIT
#define CONVERT_BIT(src, sbit, dest, dbit) { if (src & sbit) dest |= dbit; else dest &= ~(dbit); }

	unsigned int *lpuiInfoTable = NULL;
	unsigned long ulUpsState = 0;
	int	iRet, iSize;

	if (lpiBuffSize != NULL)
		if (*lpiBuffSize < sizeof(ulUpsState))
			return IOCTL_ERROR_INVALIDARGUMENT;

	iSize = UPS_INFORMATION_COUNT;
	lpuiInfoTable = new unsigned int[iSize];
	if (!lpuiInfoTable)
		return IOCTL_ERROR;
	iRet = SinlineXLUSB_DoGetUPSStructures(EU_INFORMATION, lpuiInfoTable, &iSize);
	if (iRet != IOCTL_ERROR_SUCCESS) {
		delete [] lpuiInfoTable;
		return iRet;
	}

	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0001, ulUpsState, US_AVRUP );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0002, ulUpsState, US_AVRLOWER );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0004, ulUpsState, US_SHORT );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0008, ulUpsState, US_OVERLOAD );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0010, ulUpsState, US_TEMPERATURETOOHIGH );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0020, ulUpsState, US_BATTERYDEPLETED );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0040, ulUpsState, US_BATTERYLOW );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0080, ulUpsState, US_BADEXTERNALMODULES );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0100, ulUpsState, 0x0 );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0200, ulUpsState, US_BYPASS );
	CONVERT_BIT( lpuiInfoTable[UII_STATES], 0x0800, ulUpsState, US_BATTERYCHARGING );

	switch((lpuiInfoTable[UII_STATES] & 0xF000) >> 12) {
		default:
		case 0: ulUpsState |= 0x0;			break;
		case 1: ulUpsState |= US_POWERON;	break;
		case 2: ulUpsState |= US_POWERFAIL;	break;
		case 3: ulUpsState |= US_STANDBY;	break;
		case 4: ulUpsState |= US_STANDBY;	break;
		case 5: ulUpsState |= US_BYPASS;	break;
		case 6: ulUpsState |= US_FAILURE;	break;
	}

	delete [] lpuiInfoTable;
	
	memcpy( lpvBuff, &ulUpsState, *lpiBuffSize );

	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsParamsMask
// Description		: 
int	SinlineXLUSB_DoGetUpsParamsMask(void *lpvBuff, int *lpiBuffSize)
{
	long long iMask = UP_VLT_INPUT | UP_VLT_OUTPUT | UP_VLT_BATTERY | UP_FRQ_INPUT | 
		UP_FRQ_OUTPUT | UP_PWR_EFFECTIVE | UP_PWR_APPARENT | UP_PRC_POWERWEIGHT | 
		UP_CUR_OUTPUT | UP_PRC_BATTERYCAPACITY | UP_TMV_AUTONOMY | UP_UID_VERSION | 
		UP_UID_MODEL | UP_PWR_COEFFICIENT |
		// extended params
		UP_EX_CUR_ACCU | UP_EX_CUR_INPUT | UP_EX_PWR_INP_APPARENT | 
		UP_EX_PWR_INP_COEFF | UP_EX_PWR_INP_EFFECTIVE | 
		UP_EX_TMP_INVERTER_LEFT | UP_EX_TMP_INVERTER_RIGHT;
	if ( *lpiBuffSize == sizeof( __int64 ) )
		memcpy( lpvBuff, &iMask, sizeof( __int64 ) );
	else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUpsParamsMask
// Description		: 
int	SinlineXLUSB_DoSetUpsParamsMask(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_CMD_NOTSUPPORTED;
}

// Function name	: SinlineXLUSB_DoGetUpsParams
// Description		: 
int	SinlineXLUSB_DoGetUpsParams(void *lpvBuff, int *lpiBuffSize)
{
	unsigned int *lpuiInfoTable = NULL;
	int	iSize, iRet, iv[2], iv2[2];
	
	if (lpiBuffSize != NULL)
		if (*lpiBuffSize < sizeof(supsp))
			return IOCTL_ERROR_INVALIDARGUMENT;

	iSize = UPS_INFORMATION_COUNT;
	lpuiInfoTable = new unsigned int[iSize];
	iRet = SinlineXLUSB_DoGetUPSStructures(EU_INFORMATION, lpuiInfoTable, &iSize);
	if (iRet != IOCTL_ERROR_SUCCESS) {
		delete [] lpuiInfoTable;
		return iRet;
	}
	// standard parameters
	g_SinlineXLUSB_sup.iMask = UP_VLT_INPUT | UP_VLT_OUTPUT | UP_VLT_BATTERY | UP_FRQ_INPUT | 
		UP_FRQ_OUTPUT | UP_PWR_EFFECTIVE | UP_PWR_APPARENT | UP_PRC_POWERWEIGHT | 
		UP_CUR_OUTPUT | UP_PRC_BATTERYCAPACITY | UP_TMV_AUTONOMY | UP_UID_VERSION | 
		UP_UID_MODEL | UP_PWR_COEFFICIENT |
		// extended parameters
		UP_EX_CUR_ACCU | UP_EX_CUR_INPUT | UP_EX_PWR_INP_APPARENT | 
		UP_EX_PWR_INP_COEFF | UP_EX_PWR_INP_EFFECTIVE | 
		UP_EX_TMP_INVERTER_LEFT | UP_EX_TMP_INVERTER_RIGHT;


	/* 
	 * Modified on 20/april/2006, added support for multiple families (currently two)
	 */
	g_iSinlineXLUSB_UpsFamily = (lpuiInfoTable[UII_TYPE] >> 8) & 0xFF;
	switch(g_iSinlineXLUSB_UpsFamily) {
		case UPS_FAMILYP9:
			sprintf((char*)g_SinlineXLUSB_sup.sz__uid_family, ("%s"), DRIVER_UPS_FAMILYP9);
			sprintf((char*)g_SinlineXLUSB_sup.sz__uid_model, ("%s %ldVA/%ldW"), 
				DRIVER_UPS_PREFIXP9, lpuiInfoTable[UII_PWR_APPARENT], lpuiInfoTable[UII_PWR_EFFECTIVE]);
			break;
		case UPS_FAMILYP25:
			sprintf((char*)g_SinlineXLUSB_sup.sz__uid_family, ("%s"), DRIVER_UPS_FAMILYP25);
			sprintf((char*)g_SinlineXLUSB_sup.sz__uid_model, ("%s %ldVA/%ldW"), 
				DRIVER_UPS_PREFIXP25, lpuiInfoTable[UII_PWR_APPARENT], lpuiInfoTable[UII_PWR_EFFECTIVE]);
			break;
	}

	g_iSinlineXLUSB_UpsSeries = 0;

	g_iSinlineXLUSB_FirmwareRev = (lpuiInfoTable[UII_FIRMMWARE] >> 8) & 0xFF;
	iv[0] = (g_iSinlineXLUSB_FirmwareRev & 0xFF) >> 4;
	iv[1] = (g_iSinlineXLUSB_FirmwareRev & 0x0F);

	if ((g_bSinlineXLUSB_BadFirmwarePass==false) &&
		(g_iSinlineXLUSB_FirmwareRev>FIRMWARE_LAST || g_iSinlineXLUSB_FirmwareRev<FIRMWARE_FIRST))
	{
		g_bSinlineXLUSB_BadFirmwarePass=true;
		iv2[0] = ( FIRMWARE_LAST & 0xFF ) >> 4;
		iv2[1] = ( FIRMWARE_LAST & 0x0F );
		
		// unsupported version of UPS firmware alert message
		console_report(TXT_ERR_FIRMWARE_UNSUPPORTED, g_SinlineXLUSB_sup.sz__uid_model, iv[0], iv[1], iv2[0], iv2[1]);

		delete [] lpuiInfoTable;
		return IOCTL_CRITICAL_ERROR;
	}

	sprintf((char*)g_SinlineXLUSB_sup.sz__uid_version, ("Firmware: %d.%d #:%d"), 
		/*version*/iv[0], iv[1], /*build*/lpuiInfoTable[UII_FIRMMWARE] & 0xFF);

	g_SinlineXLUSB_sup.ui__vlt_input = lpuiInfoTable[UII_VOLT_INP];
	g_SinlineXLUSB_sup.ui__vlt_input_div = 1;

	g_SinlineXLUSB_sup.ui__vlt_output = lpuiInfoTable[UII_VOLT_OUT];
	g_SinlineXLUSB_sup.ui__vlt_output_div = 1;

	g_SinlineXLUSB_sup.ui__cur_output = lpuiInfoTable[UII_CUR_OUT];
	g_SinlineXLUSB_sup.ui__cur_output_div = 10;

	g_SinlineXLUSB_sup.ui__frq_input = lpuiInfoTable[UII_FREQ_INP];
	g_SinlineXLUSB_sup.ui__frq_input_div = 10;

	g_SinlineXLUSB_sup.ui__frq_output = lpuiInfoTable[UII_FREQ_OUT];
	g_SinlineXLUSB_sup.ui__frq_output_div = 10;

	g_SinlineXLUSB_sup.ui__pwr_effective = lpuiInfoTable[UII_PWR_EFFECTIVE_OUT];
	g_SinlineXLUSB_sup.ui__pwr_effective_div = 1;

	g_SinlineXLUSB_sup.ui__pwr_apparent = lpuiInfoTable[UII_PWR_APPARENT_OUT];
	g_SinlineXLUSB_sup.ui__pwr_apparent_div = 1;

	g_SinlineXLUSB_sup.ui__pwr_coefficient = lpuiInfoTable[UII_PWR_OUT_COEFF];
	g_SinlineXLUSB_sup.ui__pwr_coefficient_div = 100;

	g_SinlineXLUSB_sup.ui__prc_powerweight = lpuiInfoTable[UII_PWR_OUT_PERC];
	g_SinlineXLUSB_sup.ui__prc_powerweight_div = 1;

	g_SinlineXLUSB_sup.ui__prc_batterycapacity = lpuiInfoTable[UII_CAPACITY_ACCU];
	g_SinlineXLUSB_sup.ui__prc_batterycapacity_div = 1;

	g_SinlineXLUSB_sup.ui__tmv_autonomy = lpuiInfoTable[UII_TIME_AUTONOMY];
	g_SinlineXLUSB_sup.ui__tmv_autonomy_div = 1;

	g_SinlineXLUSB_sup.ui__vlt_battery = lpuiInfoTable[UII_VOLT_ACCU];
	g_SinlineXLUSB_sup.ui__vlt_battery_div = 10;

	if (g_SinlineXLUSB_sup.ui__pwr_effective > g_SinlineXLUSB_sup.ui__pwr_apparent)
		g_SinlineXLUSB_sup.ui__pwr_effective = g_SinlineXLUSB_sup.ui__pwr_apparent;

	if (g_SinlineXLUSB_sup.ui__prc_powerweight<0) g_SinlineXLUSB_sup.ui__prc_powerweight=0;
	
	g_SinlineXLUSB_sup.ui_ex_pwr_inp_coeff = lpuiInfoTable[UII_PWR_IN_COEFF];
	g_SinlineXLUSB_sup.ui_ex_pwr_inp_coeff_div = 100;

	g_SinlineXLUSB_sup.ui_ex_cur_battery = lpuiInfoTable[UII_CUR_ACCU];
	g_SinlineXLUSB_sup.ui_ex_cur_battery_div = 10;

	g_SinlineXLUSB_sup.ui_ex_cur_input = lpuiInfoTable[UII_CUR_INP];
	g_SinlineXLUSB_sup.ui_ex_cur_input_div = 10;

	g_SinlineXLUSB_sup.ui_ex_pwr_inp_effective = lpuiInfoTable[UII_PWR_EFFECTIVE_INP];
	g_SinlineXLUSB_sup.ui_ex_pwr_inp_effective_div = 1;

	g_SinlineXLUSB_sup.ui_ex_pwr_inp_apparent = lpuiInfoTable[UII_PWR_APPARENT_INP];
	g_SinlineXLUSB_sup.ui_ex_pwr_inp_apparent_div = 1;

	g_SinlineXLUSB_sup.ui_ex_tmp_inverter_left = lpuiInfoTable[UII_TEMP_INTERNAL1];
	g_SinlineXLUSB_sup.ui_ex_tmp_inverter_left_div = 1;

	g_SinlineXLUSB_sup.ui_ex_tmp_inverter_right = lpuiInfoTable[UII_TEMP_INTERNAL2];
	g_SinlineXLUSB_sup.ui_ex_tmp_inverter_right_div = 1;

	memcpy(lpvBuff, &g_SinlineXLUSB_sup, sizeof(supsp));

	delete [] lpuiInfoTable;

	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsSetupParamsMask
// Description		: 
int	SinlineXLUSB_DoGetUpsSetupParamsMask(void *lpvBuff, int *lpiBuffSize)
{
	unsigned long ulMask = UP_SET_AAL_ON|UP_SET_TMR_POWERFAILTOSTANDBY|
		UP_SET_PST_AVRLOW|UP_SET_PST_LOWER|UP_SET_PST_UPPER;

	if ( *lpiBuffSize == sizeof( unsigned long ) )
		memcpy( lpvBuff, &ulMask, sizeof( unsigned long ) );
	else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUpsSetupParamsMask
// Description		: 
int	SinlineXLUSB_DoSetUpsSetupParamsMask(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_CMD_NOTSUPPORTED;
}

// Function name	: SinlineXLUSB_DoGetUpsSetupParams
// Description		: 
int	SinlineXLUSB_DoGetUpsSetupParams(void *lpvBuff, int *lpiBuffSize)
{
	supssp	susp;

	susp.ulMask = UP_SET_AAL_ON|UP_SET_TMR_POWERFAILTOSTANDBY|
		UP_SET_PST_AVRLOW|UP_SET_PST_LOWER|UP_SET_PST_UPPER;

	susp.ui__set_aal_on = flag_check((unsigned long)sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL], UCCI_BUZZER_ENABLED);
	susp.ui__set_tmr_powerfailtostandby = sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY];
	susp.ui__set_tmr_powerfailtostandby_div = 1;
	susp.ui__set_pst_avrlow = sdcSinlineXLUSB.uiUpsConfiguration[UCI_AVR_TRIM_TRANSFER_TRESHOLDS];
	susp.ui__set_pst_avrlow_div = 1;
	susp.ui__set_pst_lower = sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_LOWER_TRANSFER_TRESHOLDS];
	susp.ui__set_pst_lower_div = 1;
	susp.ui__set_pst_upper = sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_UPPER_TRANSFER_TRESHOLDS];
	susp.ui__set_pst_upper_div = 1;

	memcpy( lpvBuff, &susp, *lpiBuffSize );

	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUpsSetupParams
// Description		: 
int	SinlineXLUSB_DoSetUpsSetupParams(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetDriverInfo
// Description		: 
int	SinlineXLUSB_DoGetDriverInfo(void *lpvBuff, int *lpiBuffSize)
{
	if (*lpiBuffSize != sizeof(sdrv_info))
		return IOCTL_ERROR_INVALIDARGUMENT;

	sprintf( (char*)(( lpsdrv_info )lpvBuff )->szName, "%s/%s", DRIVER_UPS_PREFIXP9, DRIVER_UPS_PREFIXP25 );
	sprintf( (char*)(( lpsdrv_info )lpvBuff )->szFamily, "%s/%s", DRIVER_UPS_FAMILYP9, DRIVER_UPS_FAMILYP25 );
	((lpsdrv_info)lpvBuff)->eLink = ul_usb;
	((lpsdrv_info)lpvBuff)->uiVersionMajor = DRIVER_VERSION_MAJOR;
	((lpsdrv_info)lpvBuff)->uiVersionMinor = DRIVER_VERSION_MINOR;
	strcpy(((lpsdrv_info)lpvBuff)->szCfgFileName, DRIVER_CONFIG_FILE);
	strcpy(((lpsdrv_info)lpvBuff)->szBmpFileName, DRIVER_BITMAP_FILE);


	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetExtendedError
// Description		: Get extended error information - return value of last error
int	SinlineXLUSB_DoGetExtendedError(void *lpvBuff, int *lpiBuffSize)
{
	return g_iSinlineXLUSB_ExtError;
}

// Function name	: SinlineXLUSB_DoGetUpsCharacteristicMask
// Description		: 
int	SinlineXLUSB_DoGetUpsCharacteristicMask(void *lpvBuff, int *lpiBuffSize)
{
	unsigned long ulMask = 0;

	if ( *lpiBuffSize == sizeof( unsigned long ) )
		memcpy( lpvBuff, &ulMask, sizeof( unsigned long ) );
	else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsCharacteristic
// Description		: 
int	SinlineXLUSB_DoGetUpsCharacteristic(void *lpvBuff, int *lpiBuffSize)
{
	return IOCTL_ERROR_CMD_NOTSUPPORTED;
}

// Function name	: SinlineXLUSB_DoTestUpsLink
// Description		: 
int	SinlineXLUSB_DoTestUpsLink(void *lpvBuff, int *lpiBuffSize)
{
	unsigned int *lpuiInfoTable = new unsigned int[UPS_INFORMATION_COUNT];
	int	iSize = UPS_INFORMATION_COUNT, iRet;

	iRet = SinlineXLUSB_DoGetUPSStructures(EU_INFORMATION, lpuiInfoTable, &iSize);
	delete [] lpuiInfoTable;

	return iRet;
}

// Function name	: SinlineXLUSB_DoGetUPSStructures
// Description		: Return specified structure from UPS
int SinlineXLUSB_DoGetUPSStructures(eups_structs eType, void *lpvBuff, int *lpiBuffSize)
{
// Helper macros
#undef COMMIOFAIL
#define COMMIOFAIL( v, en ) { if ( COMMFAIL( v ) ) {	\
	g_iSinlineXLUSB_ExtError = en; return IOCTL_ERROR_COMM_LINKFAIL; } }

	unsigned char	ucDataBuff[0xFF] = { 0 },
					ucLength = 0,
					ucCRC = 0;
	int				iindex;
	unsigned int	uiDataBuff[0xFF] = { 0 };
	unsigned long	ulCRC = 0, ulCRC2 = 0;
	bool			bInitialized = false;
	
	if (!commSinlineXLUSB.isInitialized())
		return IOCTL_ERROR_NOTYETINITIALIZED;

	// Zapytanie UPS'a
	for (int i = 0; i < 10; i++) {
		ucDataBuff[0] = 0;

		commSinlineXLUSB.flush(1,1);
		
		commSinlineXLUSB.send(FRAME_INITCODE);
		commSinlineXLUSB.receive(&ucDataBuff[0]);

		if (ucDataBuff[0] == FRAME_INITCODE) {
			bInitialized = true;
			break;
		}
		usleep(20000);
	}
	if (!bInitialized) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDCODE;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	COMMIOFAIL( commSinlineXLUSB.send( FRAME_START ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucLength = 3;
	COMMIOFAIL( commSinlineXLUSB.send( ucLength ), IOCTL_ERROR_COMM_FAILTOSEND );
	COMMIOFAIL( commSinlineXLUSB.send( FRAME_CMD_GET ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucCRC += FRAME_CMD_GET;
	COMMIOFAIL( commSinlineXLUSB.send( eType ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucCRC += eType;
	ucCRC %= 256;
	COMMIOFAIL( commSinlineXLUSB.send( ucCRC ), IOCTL_ERROR_COMM_FAILTOSEND );
	/* 
	 * Odpowiedz od UPS'a
	 */
	ucDataBuff[0] = ucDataBuff[1] = ucDataBuff[2] = 0;
	COMMIOFAIL( commSinlineXLUSB.receive( &ucDataBuff[0] ), IOCTL_ERROR_COMM_FAILTORECEIVE );
	if (ucDataBuff[0] != FRAME_START) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDFRAME;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	
	COMMIOFAIL( commSinlineXLUSB.receive( &ucLength ), IOCTL_ERROR_COMM_FAILTORECEIVE );

	/* :: length = (length - crc_byte) / 2 */
	if ( ((ucLength - 1) / 2) > *lpiBuffSize ) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDLENGTH;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	ulCRC=0;
	iindex=0;

	for (int i = 0; i < *lpiBuffSize; i++) {
		COMMIOFAIL( commSinlineXLUSB.receive( &ucDataBuff[0] ), IOCTL_ERROR_COMM_FAILTORECEIVE );
		COMMIOFAIL( commSinlineXLUSB.receive( &ucDataBuff[1] ), IOCTL_ERROR_COMM_FAILTORECEIVE );
		uiDataBuff[iindex]=(unsigned int)(ucDataBuff[0] + (ucDataBuff[1]<<8));
		ulCRC += ucDataBuff[1] + ucDataBuff[0];
		iindex++;
	}

	//CRC
	COMMIOFAIL( commSinlineXLUSB.receive( &ucCRC ), IOCTL_ERROR_COMM_FAILTORECEIVE );

	ulCRC %= 256;
	if (ulCRC != ucCRC) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDCRC;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	
	memcpy( lpvBuff, &uiDataBuff, *lpiBuffSize * sizeof( unsigned int ) );

	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetUPSStructures
// Description		: 
int SinlineXLUSB_DoSetUPSStructures(eups_structs eType, void *lpvBuff, int *lpiBuffSize, int *lpiBuffErrPos )
{
// Helper macros
#undef COMMIOFAIL
#define COMMIOFAIL( v, en ) { if ( COMMFAIL( v ) ) {	\
	g_iSinlineXLUSB_ExtError = en; return IOCTL_ERROR_COMM_LINKFAIL; } }

	unsigned char	ucDataBuff[0xFF] = { 0 },
					ucLength = 0,
					ucErrCode = 0,
					ucCRC = 0;
	unsigned int	uiDataBuff[0xFF] = { 0 };
	unsigned long	ulCRC = 0;
	bool			bInitialized = false;

	if ( !commSinlineXLUSB.isInitialized() )
		return IOCTL_ERROR_NOTYETINITIALIZED;

	if ( !lpvBuff )
		return IOCTL_ERROR_INVALIDARGUMENT;
	memcpy( &uiDataBuff, lpvBuff, *lpiBuffSize * sizeof(unsigned int));

	/* 
	 * Zapytanie UPS'a
	 */
	for (int i = 0; i < 10; i++) {
		ucDataBuff[0] = 0;

		commSinlineXLUSB.flush(1, 1);

		commSinlineXLUSB.send(FRAME_INITCODE);
		commSinlineXLUSB.receive(&ucDataBuff[0]);

		if (ucDataBuff[0] == FRAME_INITCODE) {
			bInitialized = true;
			break;
		}
		usleep(50000);
	}
	if (!bInitialized) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDCODE;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	commSinlineXLUSB.flush(1, 0);
	COMMIOFAIL( commSinlineXLUSB.send( FRAME_START ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucLength = 3 + (*lpiBuffSize * 2);
	//ucLength = 3 + (*lpiBuffSize);
	ucCRC = 0;
	COMMIOFAIL( commSinlineXLUSB.send( ucLength ), IOCTL_ERROR_COMM_FAILTOSEND );
	COMMIOFAIL( commSinlineXLUSB.send( FRAME_CMD_SET ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucCRC += FRAME_CMD_SET;
	COMMIOFAIL( commSinlineXLUSB.send( eType ), IOCTL_ERROR_COMM_FAILTOSEND );
	ucCRC += eType;
	//COMMIOFAIL( commSinlineXLUSB.Send2b( (unsigned int *)lpvBuff, *lpiBuffSize ), IOCTL_ERROR_COMM_FAILTOSEND );

	for (int i = 0; i < *lpiBuffSize; i++) {
		ucDataBuff[0] = uiDataBuff[i] & 0x00FF;
		ucDataBuff[1] = (uiDataBuff[i] & 0xFF00) >> 8;
		COMMIOFAIL( commSinlineXLUSB.send( ucDataBuff[0] ), IOCTL_ERROR_COMM_FAILTOSEND );
		COMMIOFAIL( commSinlineXLUSB.send( ucDataBuff[1] ), IOCTL_ERROR_COMM_FAILTOSEND );
		ucCRC += ucDataBuff[0] + ucDataBuff[1];
	}
	ucCRC %= 256;
	
	COMMIOFAIL( commSinlineXLUSB.send( ucCRC ), IOCTL_ERROR_COMM_FAILTOSEND );

	// Odpowiedz od UPS'a
	ucDataBuff[0] = ucDataBuff[1] = ucDataBuff[2] = 0;

	usleep(100000);
	commSinlineXLUSB.receive( ucDataBuff, 2 );
	if (ucDataBuff[0] != FRAME_START) {
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_INVALIDFRAME;
		return IOCTL_ERROR_COMM_LINKFAIL;
	}
	ucErrCode = ucDataBuff[1];
	switch( ucErrCode )
	{
	case 0x05:	// Nieprawidowa ilo�bajt� w ramce
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_BADFRAMELENGTH;
		return IOCTL_ERROR_COMM_LINKFAIL;
	case 0x0A:	// Nieznany typ rozkazu
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_UNKNOWNCOMMANDTYPE;
		return IOCTL_ERROR_COMM_LINKFAIL;
	case 0x15:	// Nieznany rozkaz
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_UNKNOWNCOMMAND;
		return IOCTL_ERROR_COMM_LINKFAIL;
	case 0x20:	// Bd CRC
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_BADCRC;
		return IOCTL_ERROR_COMM_LINKFAIL;
	case 0x5F:	// Data integrity error
		COMMIOFAIL( commSinlineXLUSB.receive( &ucErrCode ), IOCTL_ERROR_COMM_FAILTORECEIVE );
		if ( lpiBuffErrPos != NULL )
			*lpiBuffErrPos = ucErrCode;
		g_iSinlineXLUSB_ExtError = IOCTL_ERROR_COMM_DATAINTEGRITY;
		return IOCTL_ERROR_COMM_LINKFAIL;
	case 0xFF:	// Success = no error
		break;
	}

	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetConfigParamsCount
// Description		: 
int	SinlineXLUSB_DoGetConfigParamsCount(void *lpvBuff, int *lpiBuffSize)
{
	unsigned long ulCount = INT_MAX_SETUPITEMS;

	if ( lpiBuffSize != NULL )
		if ( *lpiBuffSize < sizeof( unsigned long ) )
			return IOCTL_ERROR_INVALIDARGUMENT;

	memcpy( lpvBuff, &ulCount, sizeof( ulCount ) );

	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetConfigParams
// Description		:
int	SinlineXLUSB_DoGetConfigParams(void *, int *)
{
	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetConfigParams
// Description		:
int	SinlineXLUSB_DoSetConfigParams(void *lpvBuff, int *lpiBuffSize)
{
	int	iSize, iRet;
	unsigned long ulSize;
	scfg_value scfgvaldef[ INT_MAX_SETUPITEMS ];
	char szDrvCfgPath[MAX_PATH];

	if ( *lpiBuffSize != (sizeof(scfg_value) * INT_MAX_SETUPITEMS) )
		return IOCTL_ERROR_INVALIDARGUMENT;
	else
		memcpy( &scfgvaldef, lpvBuff, *lpiBuffSize );

	strcpy(sdcSinlineXLUSB.szSerialNumber, DRIVER_UPS_SERIALNUMBER);

	if (scfgvaldef[ INT_UPSCFG_BUZZER ].value.iValue == 1)
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] |= UCCI_BUZZER_ENABLED;
	else
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] &= ~(UCCI_BUZZER_ENABLED);

	if (scfgvaldef[ INT_UPSCFG_FORCE_STANDBY ].value.iValue == 1)
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] |= UCCI_FORCE_STANDBY;
	else
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] &= ~(UCCI_FORCE_STANDBY);

	sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_UPPER_TRANSFER_TRESHOLDS] = 
		scfgvaldef[INT_UPSCFG_TR_TSH_UPPER].value.iValue;
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_LOWER_TRANSFER_TRESHOLDS] = 
		scfgvaldef[INT_UPSCFG_TR_TSH_LOWER].value.iValue;

	sdcSinlineXLUSB.uiUpsConfiguration[UCI_AVR_TRIM_TRANSFER_TRESHOLDS] = 
		scfgvaldef[INT_UPSCFG_TR_TSH_AVRTRIM].value.iValue;

	if ((int)(scfgvaldef[ INT_UPSCFG_STANDBYDELAY ].value.iValue) < 60) {
		console_report( TXT_INF_STANDBYTIMETOOSHORT );
	}
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY] = (int)(
		scfgvaldef[INT_UPSCFG_STANDBYDELAY].value.iValue * 
		scfgvaldef[INT_UPSCFG_STANDBYDELAY].dDivider);
	if (sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY]<0) 
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY]=0;

	sdcSinlineXLUSB.uiUpsConfiguration[UCI_MODULE_NO] = (int)(
		scfgvaldef[INT_UPSCFG_MODULE_NO].value.iValue * 
		scfgvaldef[INT_UPSCFG_MODULE_NO].dDivider);

	if (commSinlineXLUSB.isInitialized()) {
		iSize = UPS_CONFIGURATION_COUNT;
		int iExtErrCode = 0;
		iRet = SinlineXLUSB_DoSetUPSStructures(EU_SETUP, sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iExtErrCode);
		if (iRet != IOCTL_ERROR_SUCCESS) {
			sdcSinlineXLUSB.iConfigError = g_iSinlineXLUSB_ExtError;
			sdcSinlineXLUSB.iConfigErrorArg = iExtErrCode;
			iSize = UPS_CONFIGURATION_COUNT;
			iRet = SinlineXLUSB_DoGetUPSStructures(EU_SETUP, sdcSinlineXLUSB.uiUpsConfiguration, &iSize);
			return iRet;
		}
	}

	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetConfigParam
// Description		: 
int	SinlineXLUSB_DoGetConfigParam(void *lpvBuff, int *lpiBuffSize)
{
	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoSetConfigParam
// Description		: 
int	SinlineXLUSB_DoSetConfigParam(void *lpvBuff, int *lpiBuffSize)
{
	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoUpdateConfig
// Description		: 
int	SinlineXLUSB_DoUpdateConfig(void *lpvBuff, int *lpiBuffSize)
{
	g_iSinlineXLUSB_ExtError = 0;

	if (SinlineXLUSB_DoReadConfig() != IOCTL_ERROR_SUCCESS)
		return IOCTL_ERROR_CONFIG_READFAIL;
	
	if (sdcSinlineXLUSB.bAudibleAlarm)
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] |= UCCI_BUZZER_ENABLED;
	else
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] &= ~(UCCI_BUZZER_ENABLED);

	if (sdcSinlineXLUSB.bForceStandby)
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] |= UCCI_FORCE_STANDBY;
	else
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_CONTROL] &= ~(UCCI_FORCE_STANDBY);

	sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_UPPER_TRANSFER_TRESHOLDS] = sdcSinlineXLUSB.uiTransferTrsh_Upper;
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_PF_LOWER_TRANSFER_TRESHOLDS] = sdcSinlineXLUSB.uiTransferTrsh_Lower;
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_AVR_BOOST_TRANSFER_TRESHOLDS] = sdcSinlineXLUSB.uiTransferTrsh_AVRBoost;

	// timer in sec. for powerfail to online transfer
	if (sdcSinlineXLUSB.uiStandbyDelay < 60) {
		console_report( TXT_INF_STANDBYTIMETOOSHORT );
	}
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY] = sdcSinlineXLUSB.uiStandbyDelay;
	if (sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY]<0) 
		sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STANDBY]=90;
	
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_MODULE_NO] = sdcSinlineXLUSB.uiModuleNumber;
	
	// capacity treshold at which ups will switch to online mode
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_CAPACITY_FOR_STARTUP] = 0;
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_FREQ_OUT] = 500;
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_VOLT_OUT] = 230;
	
	// timer in sec. for standby to online transfer
	sdcSinlineXLUSB.uiUpsConfiguration[UCI_TIMER_STARTUP] = 0;

	if (commSinlineXLUSB.isInitialized()) {
		int iSize = UPS_CONFIGURATION_COUNT;
		int iExtErrCode = 0;
		int iRet = SinlineXLUSB_DoSetUPSStructures(EU_SETUP, sdcSinlineXLUSB.uiUpsConfiguration, &iSize, &iExtErrCode);
		if (iRet != IOCTL_ERROR_SUCCESS) {
			sdcSinlineXLUSB.iConfigError = g_iSinlineXLUSB_ExtError;
			sdcSinlineXLUSB.iConfigErrorArg = iExtErrCode;
			return iRet;
		}
	}

	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoUpsShutdown
// Description		: 
int SinlineXLUSB_DoUpsShutdown(void *lpvBuff, int *lpiBuffSize)
{
	unsigned int *lpuiSetupTable = NULL;
	int iRet, iSize;

	iSize = UPS_CONFIGURATION_COUNT;
	lpuiSetupTable = new unsigned int[iSize];
	iRet = SinlineXLUSB_DoGetUPSStructures( EU_SETUP, lpuiSetupTable, &iSize );
	if (iRet != IOCTL_ERROR_SUCCESS) {
		delete [] lpuiSetupTable;
		return iRet;
	}
	unsigned int uiTemp = lpuiSetupTable[UCI_CONTROL];
	memcpy(lpuiSetupTable, sdcSinlineXLUSB.uiUpsConfiguration, sizeof(unsigned int)*UPS_CONFIGURATION_COUNT);
	lpuiSetupTable[UCI_CONTROL] = uiTemp;
	lpuiSetupTable[UCI_CONTROL] &= ~(UCCI_FORCE_STANDBY);
	lpuiSetupTable[UCI_CONTROL] |= UCCI_FORCE_STANDBY;

	iSize = UPS_CONFIGURATION_COUNT;
	iRet = SinlineXLUSB_DoSetUPSStructures( EU_SETUP, lpuiSetupTable, &iSize, NULL );
	if ( iRet != IOCTL_ERROR_SUCCESS ) {
		delete [] lpuiSetupTable;
		return iRet;
	}

	delete [] lpuiSetupTable;
	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsStatisticsCount
// Description		: 
int	SinlineXLUSB_DoGetUpsStatisticsCount(void *lpvBuff, int *lpiBuffSize)
{
	unsigned long ulCount = 0, ulTest = 0;
	if (lpvBuff != NULL) {
		memcpy(&ulTest, lpvBuff, sizeof(unsigned long));
		if (ulTest & 0x1)	// main statistics
			ulCount += UPS_STATISTICS_COUNT;
		if (ulTest & 0x2)	// extended statistic
			ulCount += UPS_FACTORYCONTROL_COUNT;
		if (ulTest == 0)
			ulCount = UPS_STATISTICS_COUNT;
	} else
		return IOCTL_ERROR_INVALIDARGUMENT;

	if (lpiBuffSize != NULL)
		if (*lpiBuffSize < sizeof(unsigned long))
			return IOCTL_ERROR_INVALIDARGUMENT;

	memcpy(lpvBuff, &ulCount, sizeof(ulCount));
	g_iSinlineXLUSB_ExtError = 0;
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetUpsStatistics
// Description		: 
int	SinlineXLUSB_DoGetUpsStatistics(void *lpvBuff, int *lpiBuffSize)
{
	if ((*lpiBuffSize != (sizeof(STATISTIC)*UPS_STATISTICS_COUNT)) &&
		(*lpiBuffSize != (sizeof(STATISTIC)*UPS_FACTORYCONTROL_COUNT)) &&
		(*lpiBuffSize != (sizeof(STATISTIC)*(UPS_STATISTICS_COUNT + UPS_FACTORYCONTROL_COUNT))))
		return IOCTL_ERROR_INVALIDARGUMENT;

	LPSTATISTIC pStat = (LPSTATISTIC)lpvBuff;

	if (*lpiBuffSize == (sizeof(STATISTIC)*UPS_STATISTICS_COUNT)) {
		unsigned int uiStats[UPS_STATISTICS_COUNT];
		char tabStatNames[UPS_STATISTICS_COUNT][STAT_NAME_MAX] = {
			TXT_STAT_PWRFAILURE, TXT_STAT_PWRDROP, TXT_STAT_PWRINCREASE, TXT_STAT_OVERLOAD,
			TXT_STAT_SHORT, TXT_STAT_DISCHARGE, TXT_STAT_AVRTRIM, TXT_STAT_AVRBOOST, TXT_STAT_OVERHEAT,
			TXT_STAT_OVERLOAD_TIME, TXT_STAT_PWROK_TIME, TXT_STAT_PWRFAIL_TIME, TXT_STAT_SYNCLOST
		};

		if (commSinlineXLUSB.isInitialized()) {
			int iSize = UPS_STATISTICS_COUNT;
			int iRet = SinlineXLUSB_DoGetUPSStructures(EU_STATS, uiStats, &iSize);
			if (iRet != IOCTL_ERROR_SUCCESS)
				return iRet;
		}
		for (int i = 0; i < UPS_STATISTICS_COUNT; i++) {
			strcpy(pStat[i].statName, tabStatNames[i]);
			pStat[i].value = uiStats[i];
		}
	}
	if (*lpiBuffSize == (sizeof(STATISTIC)*UPS_FACTORYCONTROL_COUNT)) {
		unsigned int uiStats[UPS_FACTORYCONTROL_COUNT];
		char tabStatNames[UPS_FACTORYCONTROL_COUNT][STAT_NAME_MAX] = {
			TXT_FCTL_CHARGE_H, TXT_FCTL_CHARGE_L, TXT_FCTL_PWRFAIL_TIME_MIN,
			TXT_FCTL_OVERLOAD_TIME_SEC, TXT_FCTL_PWROK_TIME_MIN
		};

		if (commSinlineXLUSB.isInitialized()) {
			int iSize = UPS_FACTORYCONTROL_COUNT;
			int iRet = SinlineXLUSB_DoGetUPSStructures(EU_FACTORYCTL, uiStats, &iSize);
			if (iRet != IOCTL_ERROR_SUCCESS)
				return iRet;
		}
		for (int i = 0; i < UPS_FACTORYCONTROL_COUNT; i++) {
			strcpy(pStat[i].statName, tabStatNames[i]);
			pStat[i].value = uiStats[i];
		}
	}
	if (*lpiBuffSize == (sizeof(STATISTIC)*(UPS_STATISTICS_COUNT+UPS_FACTORYCONTROL_COUNT))) {
		unsigned int uiStats1[UPS_STATISTICS_COUNT], uiStats2[UPS_FACTORYCONTROL_COUNT];
		char tabStatNames1[UPS_STATISTICS_COUNT][STAT_NAME_MAX] = {
			TXT_STAT_PWRFAILURE, TXT_STAT_PWRDROP, TXT_STAT_PWRINCREASE, TXT_STAT_OVERLOAD,
			TXT_STAT_SHORT, TXT_STAT_DISCHARGE, TXT_STAT_AVRTRIM, TXT_STAT_AVRBOOST, TXT_STAT_OVERHEAT,
			TXT_STAT_OVERLOAD_TIME, TXT_STAT_PWROK_TIME, TXT_STAT_PWRFAIL_TIME, TXT_STAT_SYNCLOST
		}, tabStatNames2[UPS_FACTORYCONTROL_COUNT][STAT_NAME_MAX] = {
			TXT_FCTL_CHARGE_H, TXT_FCTL_CHARGE_L, TXT_FCTL_PWRFAIL_TIME_MIN,
			TXT_FCTL_OVERLOAD_TIME_SEC, TXT_FCTL_PWROK_TIME_MIN
		};
		if (commSinlineXLUSB.isInitialized()) {
			int iSize = UPS_STATISTICS_COUNT;
			int iRet = SinlineXLUSB_DoGetUPSStructures(EU_STATS, uiStats1, &iSize);
			if (iRet != IOCTL_ERROR_SUCCESS)
				return iRet;
			iSize = UPS_FACTORYCONTROL_COUNT;
			iRet = SinlineXLUSB_DoGetUPSStructures(EU_FACTORYCTL, uiStats2, &iSize);
			if (iRet != IOCTL_ERROR_SUCCESS)
				return iRet;
		}
		for (int i = 0; i < UPS_STATISTICS_COUNT; i++) {
			strcpy(pStat[i].statName, tabStatNames1[i]);
			pStat[i].value = uiStats1[i];
		}
		for (int i = UPS_STATISTICS_COUNT; i < (UPS_STATISTICS_COUNT+UPS_FACTORYCONTROL_COUNT); i++) {
			strcpy(pStat[i].statName, tabStatNames2[i-UPS_STATISTICS_COUNT]);
			pStat[i].value = uiStats2[i-UPS_STATISTICS_COUNT];
		}
	}

	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoReadConfig
// Description		: 
int	SinlineXLUSB_DoReadConfig()
{
	char *fp;
	fp = get_config_filepath(DRIVER_CONFIG_FILE);
	if (fp==NULL) {
		return IOCTL_ERROR;
	}
	CConf *pCfgDev = new CConf;
	if (pCfgDev->init(fp)!=CONF_SUCCESS) {
		free(fp);
		delete pCfgDev;
		return IOCTL_ERROR_CONFIG_READFAIL;
	} else {
		free(fp);
		pCfgDev->parse_config();
	}
	
	char szBuf[128] = "", *s;
	
	// serial port number (/dev/ttyS0 is used by default)
	s = pCfgDev->getcfgitemvalue("serialnumber");
	strcpy(sdcSinlineXLUSB.szSerialNumber, (!strlen(s)) ? DRIVER_UPS_SERIALNUMBER : s);
	// buzzer mode
	s = pCfgDev->getcfgitemvalue("audible_alarm");
	sdcSinlineXLUSB.bAudibleAlarm = (bool)atoi((!strlen(s)) ? "1" : s);
	// transfer tresholds (upper, lower, avr trimmer)
	s = pCfgDev->getcfgitemvalue("transfer_treshold_upper");
	sdcSinlineXLUSB.uiTransferTrsh_Upper = (unsigned int)strtoul((!strlen(s)) ? "265" : s, NULL, 10);
	s = pCfgDev->getcfgitemvalue("transfer_treshold_lower");
	sdcSinlineXLUSB.uiTransferTrsh_Lower = (unsigned int)strtoul((!strlen(s)) ? "160" : s, NULL, 10);
	s = pCfgDev->getcfgitemvalue("transfer_treshold_avr_booster");
	sdcSinlineXLUSB.uiTransferTrsh_AVRBoost = (unsigned int)strtoul((!strlen(s)) ? "200" : s, NULL, 10);
	// powerfail to standby transfer delay in seconds
	// 90 seconds by default should be enough for most systems to shutdown gracefully
	s = pCfgDev->getcfgitemvalue("powerfail_to_standby_timeout");
	sdcSinlineXLUSB.uiStandbyDelay = (unsigned int)strtoul((!strlen(s)) ? "90" : s, NULL, 10);
	
	// battery extension modules
	s = pCfgDev->getcfgitemvalue("extension_module_number");
	sdcSinlineXLUSB.uiModuleNumber = (unsigned int)strtoul((!strlen(s)) ? "0" : s, NULL, 10);

	delete pCfgDev;
	
	return IOCTL_ERROR_SUCCESS;
}

// Function name	: SinlineXLUSB_DoGetConfigFileName
// Description		: 
int SinlineXLUSB_DoGetConfigFileName( void *lpvBuff, int *lpiBuffSize )
{
	if (lpvBuff != NULL) {
		if ( *lpiBuffSize >= strlen(DRIVER_CONFIG_FILE) )
			strcpy((char *)lpvBuff, DRIVER_CONFIG_FILE );
		else
			return IOCTL_ERROR_INVALIDARGUMENT;
	} else
		return IOCTL_ERROR_INVALIDARGUMENT;
	return IOCTL_ERROR_SUCCESS;
}
