#include "pch.h"
#pragma unmanaged
#include "Epd3Base.h"
#include "TimeFunctions.h"
#pragma unmanaged


Epd3Base::Epd3U* current;

void WINAPI completion(CommsHandle hComms, CompletionToken token)
{
	SetEvent(current->hCompletion);
}

void WINAPI discovery(CommsHandle hComms, DiscoveryId const discovered[], int32_t count)
{
	if (count > 0)
	{
		current->CurrentDeviceID = discovered[0].Id;
		current->DeviceCount = count;
		memcpy(&current->Epd, &discovered[0], sizeof(DiscoveryId));
		SetEvent(current->hCompletion);
		current->isMK3 = (current->Epd.Gen == EpdGeneration::Mk3);
		current->EpdID = current->Epd.Id;
	}
}

void WINAPI disconnectcallback(CommsHandle hComms, DiscoveryId ID)
{
	current->CurrentDeviceID = 0;
	current->DeviceCount = 0;
	SetEvent(current->hCompletion);
}

Epd3Base::Epd3U::Epd3U(int _comport)
{
	port = _comport;
	comPort[3] = 48 + _comport;
	CommsInitialized = 0;
	epdComsHandle = INVALID_HANDLE_VALUE;
	isBG = isNG = VersionOK = 0;
	Error = 123;
	current = this;

	DeviceCount = 0;
	BaseCountsClock = 0;
	CurrentDeviceID = 0;
	countsRead = 0; utc = 0; seconds = 0;
	memset(WearerID, 0, WearerIDLength + 1);
	memset(WearerName, 0, WearerNameLength + 1);
	Error = 0;
	EpdID = 4567;
	EpdType = EpdTypes::Mk2BetaGamma;
	isBG = 1; isNG = 0; VersionOK = 1;
	isMK3 = true;
	FunctionFlags = 0x000;
	Epd.Gen = EpdGeneration::None;
	Epd.MaxBaud = 0;
	Epd.Id = EpdID;

	OperatingStatus = (OpStatusFlags)0U;
	AlarmStatus = (AlarmStatusFlags)0U;
	ErrorStatus = (FaultStatusFlags)0;
	IssueCount = OtherAlarms = EEPROMBadSectors = 0;
	RealTime = EpdClock = OffTime = EpdID = 0;
	ErrorSource = ErrorReason = ErrorData = 0;
	HardVersion = SoftVersion = FunctionFlags = 0;

	K1 = K2 = K3 = K4 = K4 = K6 = 0.0F;
	HG = SG = BC = FB = 0;
	D1 = D2 = D3 = D4 = 0;
	Hp10Total = Hp07Total = 0;
	Hp10Dose = Hp07Dose = 0;
	Hp10Peak = Hp07Peak = 0;
	Hp10Time = Hp07Time = 0;
	Hp10FTime = Hp07FTime = 0;

	Hp07THDose = 0; Hp07RateOn = 0; Hp07RateOff = 0;
	Hp07THDoseA = 0; Hp07RateAOn = 0; Hp07RateAOff = 0;
	Hp10THDose1 = 0; Hp10Rate1On = 0; Hp10Rate1Off = 0;
	Hp10THDose2 = 0; Hp10Rate2On = 0; Hp10Rate2Off = 0;


	if (_comport == 0) return;
	if (hCompletion == 0) hCompletion = CreateEvent(NULL, TRUE, FALSE, NULL);
	//if (hWaitTimer == 0) hWaitTimer = CreateEvent(NULL, TRUE, FALSE, NULL);
	

}

Epd3Base::Epd3U::~Epd3U()
{
	EndCom();
	if (hCompletion != 0) {		CloseHandle(hCompletion);  hCompletion = 0;	}
	//if (hWaitTimer != 0) { CloseHandle(hWaitTimer);  hWaitTimer = 0; }
}

DWORD Epd3Base::Epd3U::StartCom()
{
	ErrorReason = 0;
	int mx = 10;
	epdComsHandle = INVALID_HANDLE_VALUE;
	if (port == 0) {
		CommsInitialized = 1;
		return 1;
	}
	if (CommsInitialized == 0) {
		epdComsHandle = CreateReaderInterface();
		Dll3RV = OpenReader(epdComsHandle, comPort);
		if (Dll3RV == 0)
		{
			Dll3RV = SetMultipleDiscoveryMode(epdComsHandle, false);
			CommsInitialized = 1;
		}
	}
	return Dll3RV;
}




void Epd3Base::Epd3U::EndCom()
{
	int rv;
	if (CommsInitialized == 1) {
		if (epdComsHandle != INVALID_HANDLE_VALUE) {

			DisCon(0);
			
			Dll3RV = CloseReader(epdComsHandle);
			if (Dll3RV) {
				rv = 1;
			}
			Dll3RV = DestroyReaderInterface(epdComsHandle);
			if (Dll3RV) {
				rv = 1;
			}
		}
	}
	CurrentDeviceID = 0;
	CommsInitialized = 0;
	epdComsHandle = INVALID_HANDLE_VALUE;
}


/// <summary>
/// 
/// </summary>
/// <param name="tokentimeout"></param>
/// <returns>rv=1 ,ook bij timeout <>1 voor error</returns>
int Epd3Base::Epd3U::StartDiscover(int tokentimeout)
{
	int32_t rv=1;
	Error = 0;
	if (port == 0) {
		DeviceCount = 1;
		isBG = 1; 
		DeviceIDs[0] = 768;
		return 0;
	}
	Dll3RV = SetDiscoveryCacheTimeout(epdComsHandle, tokentimeout);
	//Dll3RV = Commit3(epdComsHandle);
	DeviceCount = 0; ConnectTries = 1;
	
	ResetEvent(hCompletion);
	ConnectTimerFired = 0;
	current = this;
	Dll3RV = StartDiscovery(epdComsHandle, discovery);
	if (Dll3RV == 0) {
			Dll3RV = WaitForSingleObject(hCompletion, tokentimeout);
			if (Dll3RV == WAIT_OBJECT_0) rv = 1;
			else if (Dll3RV == WAIT_TIMEOUT) {
				rv = 1; ConnectTimerFired = 1;
			} else rv = 2;
	}
	if ( DeviceCount > 0) {
		Dll3RV = Connect3(epdComsHandle, Epd, true);
		if (Dll3RV != 0) rv = 2; 
	}
	return rv;
}

int Epd3Base::Epd3U::OpenDev(DiscoveryId DeviceID)
{
	CurrentDeviceID = DeviceID.Id;
	if (epdComsHandle != INVALID_HANDLE_VALUE) 
	{
		Dll3RV = Connect3(epdComsHandle, DeviceID, true);
	}
	else { Dll3RV = 0; }
	return Dll3RV;
}

int Epd3Base::Epd3U::DisCon(UINT16 alarm)
{
	int rv = 0;
	if (CurrentDeviceID != 0) {
		ResetEvent(hCompletion);
		current = this;
		Dll3RV = SetDisconnectCallback(epdComsHandle, disconnectcallback);
		SetResponseTimeout(epdComsHandle, 2000);
		Sleep(500);
		if (alarm)
			Dll3RV = DisconnectAndNotify(epdComsHandle, EndSessionControl, 12);
		else
			Dll3RV = Disconnect(epdComsHandle);
		Dll3RV = WaitForSingleObject(hCompletion, 2000);
		if (Dll3RV == WAIT_OBJECT_0) rv = 0;
		else if (Dll3RV == WAIT_TIMEOUT) {
			rv = 2; 
		}
		else 
			rv = 3;
	}
	return rv;
}

void Epd3Base::Epd3U::CloseDev(bool CloseAll)
{
	if (epdComsHandle != INVALID_HANDLE_VALUE) {
		DisCon(0);
		if (CloseAll) {
			CloseReader(epdComsHandle);
			DestroyReaderInterface(epdComsHandle);
			epdComsHandle = INVALID_HANDLE_VALUE;
		}
	}
}

BYTE checkStatus(OpStatusFlags status, OpStatusFlags flag)
{
	if (((uint32_t)status & (uint32_t)flag) == (uint32_t)flag) return 1; else return 0;
}
BYTE checkStatus(FaultStatusFlags status, FaultStatusFlags flag)
{
	if (((uint32_t)status & (uint32_t)flag) == (uint32_t)flag) return 1; else return 0;
}
BYTE checkStatus(AlarmStatusFlags status, AlarmStatusFlags flag)
{
	uint32_t ustatus = (uint32_t)status;
	uint32_t uflag = (uint32_t)flag;
	if ((ustatus & uflag) == uflag) return 1; else return 0;
}
BYTE checkStatus(DoseAlarmFlags status, DoseAlarmFlags flag)
{
	if (((uint32_t)status & (uint32_t)flag) == (uint32_t)flag) return 1; else return 0;
}

void Epd3Base::Epd3U::DecodeStatus()
{
	DetectorsOn = checkStatus(epd3status.OperatingStatus, OpStatusFlags::EpdOn);
	EPDIssued = checkStatus(epd3status.OperatingStatus, OpStatusFlags::EpdIssued);
	EPDLocked = checkStatus(epd3status.OperatingStatus, OpStatusFlags::GainAdjustable);
	EPDTesting = checkStatus(epd3status.OperatingStatus, OpStatusFlags::DetectorTestRequested);
	EPDFaulty = checkStatus(epd3status.FaultStatus, FaultStatusFlags::EpdFaulty);

	EPDNewFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::EpdFaulty);
	EPDComFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::EarlyCommsTermination);
	EPDCalFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::NotCalibrated);
	EPDDetFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::DetectorTestFail);
	EPDEprFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::EepromFailure);
	EPDTrhFault = checkStatus(epd3status.FaultStatus, FaultStatusFlags::BadThreshold);

	for (int ix = 0; ix < 4; ix++)
	{
		DoseAlarmFlags status = epd3status.DoseAlarms[ix].Status;
		switch ((MeasurementId)epd3status.DoseAlarms[ix].Id)
		{
		case MeasurementId::Meas_Hp07:
		case MeasurementId::Meas_Hp10N:
			AlarmDoseHP07N = checkStatus(status, DoseAlarmFlags::DoseAlarm);
			AlarmRateHP07N = checkStatus(status, DoseAlarmFlags::RateAlarm);
			break;
		case MeasurementId::Meas_Hp10:
		case MeasurementId::Meas_Hp10G:
			AlarmDoseHP101G = checkStatus(status, DoseAlarmFlags::DoseAlarm);
			AlarmDoseHP102G = AlarmDoseHP101G;
			AlarmRateHP101G = checkStatus(status, DoseAlarmFlags::RateAlarm);
			AlarmRateHP102G = AlarmRateHP101G;
			break;
		}
	}
	OtherAlarmReturn = checkStatus(epd3status.AlarmStatus, AlarmStatusFlags::ReturnForRead);
	OtherAlarmBatLow = checkStatus(epd3status.AlarmStatus, AlarmStatusFlags::LowBattery);
	OtherAlarmCarrier = checkStatus(epd3status.AlarmStatus, AlarmStatusFlags::TelemetryAlert);
	OtherAlarmBatVolt = checkStatus(epd3status.AlarmStatus, AlarmStatusFlags::LowBattery);

	hasAlarm = ((int)epd3status.FaultStatus != 0) || AlarmDoseHP07N || AlarmRateHP07N || AlarmDoseHP101G || AlarmDoseHP102G || AlarmRateHP101G || AlarmRateHP102G;

}

void Epd3Base::Epd3U::SetTime() //Only R3
{
	if (Epd.Gen == EpdGeneration::Mk3) {
		utc = TimeFunctions::NowToEpdTime(Epd.Gen == EpdGeneration::Mk2);
		token = BeginWriteRTC_R3(epdComsHandle, utc, nullptr);
		uint32_t r = Commit3(epdComsHandle);
		Dll3RV = EndWriteRTC_R3(epdComsHandle, token);
	}
}

/// <summary>
/// 
/// </summary>
/// <returns>0 = ok</returns>
int Epd3Base::Epd3U::ReadStatus()
{
	int r; //0=ok
	uint8_t 	length = 0;
	countsRead = 0; utc = 0; seconds = 0;
	memset(WearerID, 0, WearerIDLength + 1);
	memset(WearerName, 0, WearerNameLength + 1);

	Error = 0;
	if (port == 0) {
		EpdID = 4567;
		EpdType = EpdTypes::Mk2BetaGamma;
		isBG = 1; isNG = 0; VersionOK = 1;
		isMK3 = true;
		FunctionFlags = 0x000;
		Epd.Gen = EpdGeneration::None;
		Epd.MaxBaud = 0;
		Epd.Id = EpdID;
		return 0;
	}

	isMK3 = Epd.Gen == EpdGeneration::Mk3;
	OperatingStatus = (OpStatusFlags)0U;
	AlarmStatus = (AlarmStatusFlags)0U;
	ErrorStatus = (FaultStatusFlags)0;
	IssueCount = OtherAlarms = EEPROMBadSectors = 0;
	RealTime = EpdClock = OffTime = EpdID = 0;
	ErrorSource = ErrorReason = ErrorData = 0;
	HardVersion = SoftVersion = FunctionFlags = 0;

	r = SetResponseTimeout(epdComsHandle, 2000);
	
	token = BeginReadStatus(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadStatus(epdComsHandle, token, &epd3status);
	if (r != 0) {
		Error = GetErrorCode(); 
		goto error;
	}

	IssueCount = epd3status.IssueCount;
	OperatingStatus = epd3status.OperatingStatus;
	AlarmStatus = epd3status.AlarmStatus;
	ErrorStatus = epd3status.FaultStatus;
	OtherAlarms = epd3status.OtherBits;

	uint32_t EpdID32;
	uint32_t capabilities;
	MarkNumber_t MarkNumber;
	VersionNumber_t VersionNumber;
	
	token = BeginReadEpdIdentities(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadEpdIdentities(epdComsHandle, token, &EpdID32, (EpdTypes*)&EpdType, &capabilities, &MarkNumber, &VersionNumber, NULL, 0);
	if (r != 0) {
		Error = GetErrorCode(); 
		goto error;
	}
	
	EpdID = EpdID32;
	isBG = (EpdType == EpdTypes::Mk2BetaGamma || EpdType == EpdTypes::Mk3BetaGamma);
	isNG = (EpdType == EpdTypes::Mk2Neutron || EpdType == EpdTypes::Mk3Neutron);
	HardVersion = MarkNumber.Major;
	SoftVersion = VersionNumber.Major;
	VersionOK = true;
	DecodeStatus();

		
	
	token = BeginReadCounts(epdComsHandle, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadCounts(epdComsHandle, token, Counts, MaxCounts, &countsRead, &utc, &seconds);
	// - 101 = InvalidParam
	// - 104 = FunctionFail, 
	if (r != 0 && r != -104) {
		Error = GetErrorCode(); 
		goto error;
	}
	decodeCounters(countsRead); //HG,SG ..

	//Wearer
	if (EPDIssued) {
		IdString_t mk3WearerID;
		//Mk2 EPDs only support Name and Primary ID
		token = BeginReadWearerId(epdComsHandle, static_cast<uint16_t>(WearerIdType::WearerId_Name), nullptr);
		r = Commit3(epdComsHandle);
		r = EndReadWearerId(epdComsHandle, token, &mk3WearerID);
		if (r != 0) {
			Error = GetErrorCode(); 
			goto error;
		}

		if (mk3WearerID.Length > WearerNameLength) mk3WearerID.Length = WearerNameLength;
		memcpy(WearerName, mk3WearerID.Utf8String, mk3WearerID.Length); WearerName[mk3WearerID.Length] = 0;

		token = BeginReadWearerId(epdComsHandle, static_cast<uint16_t>(WearerIdType::WearerId_Primary), nullptr);
		r = Commit3(epdComsHandle);
		r = EndReadWearerId(epdComsHandle, token, &mk3WearerID);
		if (r != 0) {
			Error = GetErrorCode(); 
			goto error;
		}

		if (mk3WearerID.Length > WearerIDLength) mk3WearerID.Length = WearerIDLength;
		memcpy(this->WearerID, mk3WearerID.Utf8String, mk3WearerID.Length); WearerName[mk3WearerID.Length] = 0;
		for (int i = 0; i < mk3WearerID.Length; i++)
			if (WearerID[i] == 0xb) WearerID[i] = '0'; else  WearerID[i] |= 0x30;
	}

	//Times
	//1601-01-01T00:00:00Z.
	//MK2 .. some utc... but no real time clock
	if (utc == 0) {
		token = BeginReadRTC(epdComsHandle, nullptr);
		r = Commit3(epdComsHandle);
		r = EndReadRTC(epdComsHandle, token, &utc); //EpdClock for MK2
		EpdClock = utc;
		utc = TimeFunctions::NowToEpdTime(true);
	}
	else {
		EpdClock = utc;
	}

	FILETIME fUTC;
	TimeFunctions::EpdTimeToFileTime(utc, &fUTC, Epd.Gen == EpdGeneration::Mk2);
	FileTimeToSystemTime(&fUTC, &tRealTime);

	return r;
error:
	return r;
	
}


/// <summary>
/// discover, connect and read status
/// </summary>
/// <param name="tokenSourceTimeout"></param>
/// <returns>0=success 1=connect error,  2 = no devices, 3= error reading status</returns>
int Epd3Base::Epd3U::ConnectAndStatus(int tokenSourceTimeout)
{
	WORD dllStatus;
	int rv = 1;
	if (CommsInitialized == 0) StartCom();
	dllStatus = StartDiscover(tokenSourceTimeout);
	if (dllStatus != 1) rv = 1; //Connect error
	else if (DeviceCount < 1) rv = 2;  //TO
	else if (isMK3 && ReadStatus() != 0) rv = 1; //Read Error
	else rv = 0;
	return rv;
}

/// <summary>
/// K1 = K2 = K3 = K4 = K4 = K6 (*100000 )
/// </summary>
/// <param name="count"></param>
void Epd3Base::Epd3U::decodeSensitivities(int count) {

	K1 = K2 = K3 = K4 = K4 = K6 = 0.0F;
	for (int ix = count - 1; ix >= 0; ix--) {
		switch ((SensitivityId)sensitivities[ix].id)
		{
		case SensitivityId::Hg1Sens10G: K1 = sensitivities[ix].value * 100000; break;
		case SensitivityId::Sg1Sens10G: K2 = sensitivities[ix].value * 100000; break;
		case SensitivityId::Hg1Sens07G: K3 = sensitivities[ix].value * 100000; break; //Neutr=FN
		case SensitivityId::Sg1Sens07G: K4 = sensitivities[ix].value * 100000; break; //Neutr=AN
		case SensitivityId::Fb1Sens07B: K5 = sensitivities[ix].value * 100000; break;
		case SensitivityId::Sg2Sens07B: K6 = sensitivities[ix].value * 100000; break;
		default: break;
		}
	}
}
void Epd3Base::Epd3U::decodetotDoses(int count)
{
	//doses
	Hp10Total = Hp07Total = 0;
	for (int ix = 0; ix < count; ix++)
	{
		switch ((MeasurementId)doses[ix].id) {
		case MeasurementId::Meas_Hp07: Hp07Total = doses[ix].value; break;
		case MeasurementId::Meas_Hp10: Hp10Total = doses[ix].value; break;
		case MeasurementId::Meas_Hp10N: Hp07Total = doses[ix].value; break;
		case MeasurementId::Meas_Hp10G: Hp10Total = doses[ix].value; break;
		}
	}
}
void Epd3Base::Epd3U::decodeDoses(int count)
{
	//doses
	Hp10Dose = Hp07Dose = 0;
	for (int ix = 0; ix < count; ix++)
	{
		switch ((MeasurementId)doses[ix].id) {
		case MeasurementId::Meas_Hp07: Hp07Dose = doses[ix].value; break;
		case MeasurementId::Meas_Hp10: Hp10Dose = doses[ix].value; break;
		case MeasurementId::Meas_Hp10N: Hp07Dose = doses[ix].value; break;
		case MeasurementId::Meas_Hp10G: Hp10Dose = doses[ix].value; break;
		}
	}
}

void Epd3Base::Epd3U::decodePeakRates(int count)
{
	//Rates
	Hp10Peak = Hp07Peak = 0;
	Hp10Time = Hp07Time = 0;
	
	/*SYSTEMTIME st07,st10;*/
	for (int ix = 0; ix < count; ix++)
	{
		switch ((MeasurementId)peakRates[ix].id) {
		case MeasurementId::Meas_Hp07:
		case MeasurementId::Meas_Hp10N:
			Hp07Peak = peakRates[ix].value;
			Hp07Time = peakRates[ix].timestamp;
			TimeFunctions::EpdTimeToFileTime(Hp07Time, (LPFILETIME)&Hp07FTime, false);
			//FileTimeToSystemTime(&Hp07FTime, &st07);
			break;
		case MeasurementId::Meas_Hp10:
		case MeasurementId::Meas_Hp10G:
			Hp10Peak = peakRates[ix].value;
			Hp10Time = peakRates[ix].timestamp;
			TimeFunctions::EpdTimeToFileTime(Hp10Time, (LPFILETIME)&Hp10FTime, false);
			//FileTimeToSystemTime(&Hp10FTime, &st10);
			break;
		}
	}
}
void Epd3Base::Epd3U::decodeCounters(int count)
{
	HG = SG = BC = FB = 0;
	for (int ix = 0; ix < count; ix++)
	{
		switch ((CounterType)Counts[ix].type) {
		case CounterType::Counter_Hg1: HG = Counts[ix].value; break;
		case CounterType::Counter_Sg1: SG = Counts[ix].value; break;
		case CounterType::Counter_Sg2: BC = Counts[ix].value; break;
		case CounterType::Counter_Fb1: FB = Counts[ix].value; break;
		}
	}
}
void Epd3Base::Epd3U::decodeBaseCounters(int count)
{
	D1 = D2 = D3 = D4 = 0;
	for (int ix = 0; ix < count; ix++)
	{
		switch ((CounterType)Counts[ix].type) {
		case CounterType::Counter_Hg1: D1 = Counts[ix].value; break;
		case CounterType::Counter_Sg1: D2 = Counts[ix].value; break;
		case CounterType::Counter_Sg2: D3 = Counts[ix].value; break;
		case CounterType::Counter_Fb1: D4 = Counts[ix].value; break;
		}
	}
}
void Epd3Base::Epd3U::decodeTreshold(Mk3AlarmThresholds_t* th)
{
	float* pThDose = nullptr, * pThRate = nullptr, * pTHDoseWarning = nullptr, * pTHRateWarning = nullptr;
	switch ((MeasurementId)th->MeasId)
	{
	case MeasurementId::Meas_Hp07:
	case MeasurementId::Meas_Hp10N:
		Hp07THDose = 0; Hp07RateOn = 0; Hp07RateOff = 0;
		pThDose = &Hp07THDose;
		pThRate = &Hp07RateOn;
		pTHDoseWarning = &Hp07THDoseA;
		pTHRateWarning = &Hp07RateAOn;
		break;
	case MeasurementId::Meas_Hp10:
		Hp10THDose1 = 0; Hp10THDose2 = 0;
		Hp10Rate1On = Hp10Rate2On = Hp10Rate1Off = Hp10Rate2Off = 0;
		pThDose = &Hp10THDose2;
		pThRate = &Hp10Rate2On;
		pTHDoseWarning = &Hp10THDose1;
		pTHRateWarning = &Hp10Rate1Off;
		break;
	}

	for (int ix = 0; ix < th->NumberThresholds; ix++)
	{
		switch ((ThresholdId)th->Thresholds[ix].Id) {
		case ThresholdId::Thres_DoseAlarm: if (pThDose != nullptr) *pThDose = th->Thresholds[ix].Value; break;
		case ThresholdId::Thres_DoseWarning:  if (pTHDoseWarning != nullptr) *pTHDoseWarning = th->Thresholds[ix].Value; break;
		case ThresholdId::Thres_RateAlarm: if (pThRate != nullptr) *pThRate = th->Thresholds[ix].Value; break;
		case ThresholdId::Thres_RateWarning:  if (pTHRateWarning != nullptr) *pTHRateWarning = th->Thresholds[ix].Value; break;
		}
	}
}
void Epd3Base::Epd3U::encodeTreshold(Mk3AlarmThresholds_t* th)
{
	//th.MeasId
	float* pThDose, * pThRate, * pTHDoseWarning, * pTHRateWarning;
	//Voorlopig
	Hp07THDoseA = Hp07THDose * 0.8;
	Hp07RateAOn = Hp07RateOn * 0.8;
	// einde voorlopig
	th->NumberThresholds = 4;
	switch ((MeasurementId)th->MeasId) {
	case MeasurementId::Meas_Hp07:
	case MeasurementId::Meas_Hp10N:
		pThDose = &Hp07THDose;
		pTHDoseWarning = &Hp07THDoseA;
		pThRate = &Hp07RateOn;
		pTHRateWarning = &Hp07RateAOn;
		RatePct[0].MeasId = th->MeasId;
		RatePct[0].Value = 85; // (int)(Hp07RateOff * 100.0 / Hp07RateOn);
		break;
	case MeasurementId::Meas_Hp10:
	case MeasurementId::Meas_Hp10G:
		pThDose = &Hp10THDose2;
		pThRate = &Hp10Rate2On;
		pTHDoseWarning = &Hp10THDose1;
		pTHRateWarning = &Hp10Rate1On;
		RatePct[1].MeasId = th->MeasId;
		RatePct[1].Value = 85; // (int)(Hp10Rate2Off * 100.0 / Hp10Rate2On);
		break;
	default:
		pThDose = &Hp07THDose;
		pTHDoseWarning = &Hp07THDoseA;
		pThRate = &Hp07RateOn;
		pTHRateWarning = &Hp07RateAOn;
	}

	th->Thresholds[0].Id = (uint16_t)ThresholdId::Thres_DoseAlarm;
	th->Thresholds[0].Value = *pThDose;
	th->Thresholds[1].Id = (uint16_t)ThresholdId::Thres_RateAlarm;
	th->Thresholds[1].Value = *pThRate;
	th->Thresholds[2].Id = (uint16_t)ThresholdId::Thres_DoseWarning;
	th->Thresholds[2].Value = *pTHDoseWarning;
	th->Thresholds[3].Id = (uint16_t)ThresholdId::Thres_RateWarning;
	th->Thresholds[3].Value = *pTHRateWarning;
}

/// <summary>
/// HG, SG, BC, FB, BC, FB
/// </summary>
/// <param name="numdTresholds"></param>
void Epd3Base::Epd3U::decodedTresholds(int numdTresholds)
{
	for (int ix = 0; ix < numdTresholds; ix++) {
		switch ((CounterType)dTresholds[ix].type) {
		case CounterType::Counter_Hg1: HG = dTresholds[ix].value; break;
		case CounterType::Counter_Sg1: SG = dTresholds[ix].value; break;
		case CounterType::Counter_Sg2: BC = dTresholds[ix].value; break;
		case CounterType::Counter_Fb1: FB = dTresholds[ix].value; break;
		case CounterType::Counter_An1: BC = dTresholds[ix].value; break; //AN-> BC
		case CounterType::Counter_Fn2: FB = dTresholds[ix].value; break; //FN->FB
		}
	}
}

/// <summary>
/// Read  K1 = K2 = K3 = K4 = K4 = K6 
/// </summary>
/// <returns></returns>
WORD Epd3Base::Epd3U::ReadCal()
{
	int r = 0;
	token = BeginReadSensitivities(epdComsHandle, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadSensitivities(epdComsHandle, token, sensitivities, MaxSensitivities, &numSensitivities);
	if (r != 0)
		goto error;
	decodeSensitivities(numSensitivities);
	return r;
error:
	return r;
}
/// <summary>
/// K1 .. K6, SG , BC ,FB , HG
/// </summary>
/// <returns>0 OK</returns>
WORD Epd3Base::Epd3U::ReadSensitivitiesAndTresholds()
{
	int32_t r = 0;
	if (Epd.Gen == EpdGeneration::Mk2) {
		uint16_t HGSens10;
		uint16_t SGSens10;
		uint16_t HGSens07;
		uint16_t SGSens07;
		uint16_t FBSens07;
		uint16_t BCSens07;
		uint16_t SGthresh;
		uint16_t BCthresh;
		uint16_t FBthresh;
		uint16_t HGthresh;

		token = BeginReadCalibrationData_R2(epdComsHandle, nullptr);
		r = Commit3(epdComsHandle);
		r = EndReadCalibrationData_R2(epdComsHandle, token,
			&HGSens10,
			&SGSens10,
			&HGSens07,
			&SGSens07,
			&FBSens07,
			&BCSens07,
			&SGthresh,
			&BCthresh,
			&FBthresh,
			&HGthresh
		);
		K1 = HGSens10;
		K2 = SGSens10;
		K3 = HGSens07;
		K4 = SGSens07;
		K5 = FBSens07;
		K6 = BCSens07;
		SG = SGthresh;
		BC = BCthresh;
		FB = FBthresh;
		HG = HGthresh;
	}
	else {
		token = BeginReadDetectorThresholds_R3(epdComsHandle, nullptr, 0, nullptr);
		r = Commit3(epdComsHandle);
		r = EndReadDetectorThresholds_R3(epdComsHandle, token, dTresholds, MaxTresholds, &numTresholds);
		if (r != 0)
			goto error;
		decodedTresholds(numTresholds); // HG, SG, BC, FB, BC, FB
		
		r = ReadCal();// K1 = K2 = K3 = K4 = K4 = K6 
		
	}
	return r;
error:
	return r;
}

/// <summary>
/// Doses, totDoses, Knocks + Resets ,  PeakRates, SensitivitiesAndTresholds: K1 .. K6, SG , BC ,FB , HG
/// </summary>
/// <returns>0 OK</returns>
WORD Epd3Base::Epd3U::ReadDoses()
{
	int32_t r = 1;
	if (port == 0) {
		Hp10Dose = Hp07Dose = Hp10Total = Hp07Total = 0.0;
		Knocks = Resets = QualityData = 21;
		Hp10Peak = Hp07Peak = 0.0;
		Hp10Time = Hp07Time = 1000;
		ErrorSource = ErrorReason = ErrorData = 0;
		K1 = 1; K2 = 2; K3 = 3; K4 = 4; K5 = 5;  K6 = 6;
		SG = 7; BC = 8; FB = 9; HG = 10;
		return 0;
	}
	
	numDoses = 0; utc = 0;
	SetResponseTimeout(epdComsHandle, 2000);
	
	token = BeginReadDoses(epdComsHandle, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndReadDoses(epdComsHandle, token, doses, MaxDoses, &numDoses, &utc);
	if (r != 0)
		goto error;
	decodeDoses(numDoses);

	token = BeginReadTotalDoses(epdComsHandle, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndReadTotalDoses(epdComsHandle, token, totdoses, MaxDoses, &numtotDoses, &utc);
	if (r != 0)
		goto error;
	decodetotDoses(numtotDoses);

	token = BeginReadQualityData(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndReadQualityData(epdComsHandle, token, &quality);
	if (r != 0)
		goto error;
	Knocks = quality.Knocks;
	Resets = quality.PowerCycles;
	
	token = BeginReadPeakRates(epdComsHandle, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndReadPeakRates(epdComsHandle, token, peakRates, MaxPeakRates, &numRates);
	if (r != 0)
		goto error;
	decodePeakRates(numRates);

	r= ReadSensitivitiesAndTresholds(); //K1 .. K6, SG , BC ,FB , HG
	if (r != 0)
		goto error;

	return r;
error:
	return r;
}
/// <summary>
/// 
/// </summary>
/// <returns>0 success</returns>
int  Epd3Base::Epd3U::ClearDoses()
{
	int r = 1;
	int step = 1;

	token = BeginClearTotalDose(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndClearTotalDose(epdComsHandle, token);
	if (r != 0 && r!= -105 )
		goto error;

	step++;
	token = BeginClearDose(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndClearDose(epdComsHandle, token);
	if (r != 0 && r != -105)
		goto error;

	
	step++;
	token = BeginClearPeakRates(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndClearPeakRates(epdComsHandle, token);
	if (r != 0 && r != -105)
		goto error;

	if (r == -105) r = 0;
	return r;
error: 
		return r;
}


int Epd3Base::Epd3U::ClearAlarms()
{
	int r = 0;
	int step = 0;

	step++;
	token = BeginClearFaultStatus(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndClearFaultStatus(epdComsHandle, token);
	if (r != 0 && r != -105)
		goto error;

	step++;
	token = BeginClearLatchedAlarms(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	if (!r) r = EndClearLatchedAlarms(epdComsHandle, token);
	if (r != 0 && r != -105)
		goto error;
	
	if (r == -105) r = 0;
	return r;

error:
	return r;
	
}
WORD Epd3Base::Epd3U::PrepareForIssue()
{
	int rv = 0;
	if (port == 0) return 0;
	//CommitRV = WriteConfig();
	
	
	if (DetectorsOn) {
		token = BeginEpdOnOff(epdComsHandle, 0, nullptr);
		rv = Commit3(epdComsHandle);
		if (!rv) rv = EndEpdOnOff(epdComsHandle, token);
	}

	rv = ClearDoses();
	if (rv != 0)
		goto error;

	rv = ClearAlarms();
	if (rv != 0)
		goto error;
	return rv;

error:
	return rv;
}
WORD Epd3Base::Epd3U::ReadAlarmConfig() {
	//Alleen MK3 ? leeg bij MK2
	token = BeginReadAlarmConfiguration(epdComsHandle, nullptr, 0, nullptr);
	int32_t r = Commit3(epdComsHandle);
	r = EndReadAlarmConfiguration(epdComsHandle, token, alarmConfig, MaxAlarmConfig, &numAlarm);
	return numAlarm;
}
WORD Epd3Base::Epd3U::ReadAlarmTresholds() {
	//Alleen MK3 ? leeg bij MK2
	bool isNeutron = (EpdType == EpdTypes::Mk2Neutron || EpdType == EpdTypes::Mk3Neutron);
	uint8_t measID;
	uint32_t r;

	SetResponseTimeout(epdComsHandle, 2000);

	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10N; else measID = (uint8_t)MeasurementId::Meas_Hp07;
	hp07tresholds.MeasId = measID;
	token = BeginReadAlarmThresholds(epdComsHandle, (uint8_t)hp07tresholds.MeasId, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadAlarmThresholds(epdComsHandle, token, &hp07tresholds);
	decodeTreshold(&hp07tresholds);

	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10G; else measID = (uint8_t)MeasurementId::Meas_Hp10;
	hp10tresholds.MeasId = measID;
	token = BeginReadAlarmThresholds(epdComsHandle, (uint8_t)hp10tresholds.MeasId, nullptr, 0, nullptr);
	r = Commit3(epdComsHandle);
	r = EndReadAlarmThresholds(epdComsHandle, token, &hp10tresholds);
	decodeTreshold(&hp10tresholds);

	return r;
}
WORD Epd3Base::Epd3U::WriteAlarmTresholds() {
	//Alleen MK3 ? leeg bij MK2
	uint32_t r;

	bool isNeutron = (EpdType == EpdTypes::Mk2Neutron || EpdType == EpdTypes::Mk3Neutron);
	uint8_t measID;

	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10G; else measID = (uint8_t)MeasurementId::Meas_Hp10;
	hp10tresholds.MeasId = measID;
	encodeTreshold(&hp10tresholds);
	
	token = BeginWriteAlarmThresholds(epdComsHandle, (uint8_t)hp10tresholds.MeasId, (uint8_t)hp10tresholds.NumberThresholds, hp10tresholds.Thresholds, nullptr);
	r = Commit3(epdComsHandle);
	if (r != 0)
		goto error;
	r = EndWriteAlarmThresholds(epdComsHandle, token);
	if (r != 0)
		goto error;


	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10N; else measID = (uint8_t)MeasurementId::Meas_Hp07;
	hp07tresholds.MeasId = measID;
	encodeTreshold(&hp07tresholds);
	hp07tresholds.NumberThresholds = 4;
	token = BeginWriteAlarmThresholds(epdComsHandle, (uint8_t)hp07tresholds.MeasId, (uint8_t)hp07tresholds.NumberThresholds, hp07tresholds.Thresholds, nullptr);
	r = Commit3(epdComsHandle);
	if (r != 0)
		goto error;
	r = EndWriteAlarmThresholds(epdComsHandle, token);
	if (r != 0)
		goto error;

	token = BeginWriteRateOffPercentage(epdComsHandle, RatePct, 2, nullptr);
	r = Commit3(epdComsHandle);
	if (r != 0)
		goto error;
	r = EndWriteRateOffPercentage(epdComsHandle, token);
	if (r != 0)
		goto error;

	return r;

error:
	return r;

}
WORD Epd3Base::Epd3U::DeIssue()
{
	int r = 1;
	if (port == 0) return 0;
	if (CurrentDeviceID==0) return 0;

	r = ClearAlarms();
	r = ClearDoses();
	
	if (EPDIssued) {
		token = BeginDeissueEPD(epdComsHandle, nullptr);
		r = Commit3(epdComsHandle);
		r = EndDeissueEPD(epdComsHandle, token);
		if (r != 0)			
			r = 0; // goto error;
	}

	token = BeginEpdOnOff(epdComsHandle, 0, nullptr);
	r = Commit3(epdComsHandle);
	r = EndEpdOnOff(epdComsHandle, token);
	if (r != 0)
		goto error;
	EndCom();

	return r;
error:
	return r;
}
WORD Epd3Base::Epd3U::WriteWearer() {

	int32_t r = 0;
	token = BeginSetBaselineCounters(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	r = EndSetBaselineCounters(epdComsHandle, token);
	if (r != 0) 
		goto error;

	IdString_t mk3WearerID;
	//Mk2 EPDs only support Name and Primary ID

	mk3WearerID.IdType = (uint16_t)WearerIdType::WearerId_Name;
	mk3WearerID.Length = 23;
	memcpy(mk3WearerID.Utf8String, WearerName, 23);
	
	token = BeginWriteWearerId(epdComsHandle, mk3WearerID, nullptr);
	r = Commit3(epdComsHandle);
	r = EndWriteWearerId(epdComsHandle, token);
	if (r != 0)
		goto error;

	mk3WearerID.IdType = (uint16_t)WearerIdType::WearerId_Primary;
	mk3WearerID.Length = 13;
	memcpy(mk3WearerID.Utf8String, WearerID, 13);
	
	token = BeginWriteWearerId(epdComsHandle, mk3WearerID, nullptr);
	r = Commit3(epdComsHandle);
	r = EndWriteWearerId(epdComsHandle, token);
	if (r != 0)
		goto error;

	return r;

	error:
	return r;
}
/// <summary>
/// 
/// </summary>
/// <returns>0 Success</returns>
WORD Epd3Base::Epd3U::Issue()
{
	int r=0;
	int tries = 0;
	if (port == 0) return r;

	r = 0;
	r = PrepareForIssue();
	if (r != 0)
		goto error;

	/*if (isMK3) {
		token = BeginEnableProtectedSession_R3(epdComsHandle, 1, nullptr);
		r = Commit3(epdComsHandle);
		r = EndEnableProtectedSession_R3(epdComsHandle, token);
		if (r != 0)
			goto error;
	}*/
	
	r = WriteAlarmTresholds();
	if (r != 0)
		goto error;
	r = WriteWearer();
	if (r != 0)
		goto error;
	/*r = WriteCal();
	if (r != 0)
		goto error;*/



	//EPDIssued
	//if (!DetectorsOn) {
		token = BeginEpdOnOff(epdComsHandle, 1, nullptr);
		r = Commit3(epdComsHandle);
		if (!r) r = EndEpdOnOff(epdComsHandle, token);
		//	OKRV = EpdOn(); OKRV = Commit3(); 
	
		if (r != 0)
			r=0;
	//}
	

	tries = 1;
	token = BeginIssueEPD(epdComsHandle, nullptr);
	r = Commit3(epdComsHandle);
	r = EndIssueEPD(epdComsHandle, token);
	if (r != 0) {
		tries++;
		Sleep(500);
		token = BeginIssueEPD(epdComsHandle, nullptr);
		r = Commit3(epdComsHandle);
		r = EndIssueEPD(epdComsHandle, token);
	}
		if (r)
			goto error;
	
	/*if (isMK3) {
		token = BeginEnableProtectedSession_R3(epdComsHandle, 0, nullptr);
		r = Commit3(epdComsHandle);
		r = EndEnableProtectedSession_R3(epdComsHandle, token);
		if (r) 
			goto error;
	}*/

	if (isMK3) {
		
		r = DisCon(EndSessionControl); //stops protected session
		if (r)
			goto error;
	}
	EndCom();

	return r;

error:
	return r;
}
WORD Epd3Base::Epd3U::EPDReadExtraStatus()
{
	if (port == 0) return 1;
	//byBatADC = bySupplyADC = 0;
	/*CommitRV = ReadA2ConfigStatus(
		&byBatADC,
		&bySupplyADC,
		&byStatus3,
		&byStatus4);
	if (CommitRV == 1) CommitRV = Commit3();*/

	token = BeginReadBaselineCounts(epdComsHandle, nullptr);
	uint32_t r = Commit3(epdComsHandle);
	r = EndReadBaselineCounts(epdComsHandle, token, Counts, 10, &utc, &countsRead);
	decodeBaseCounters(countsRead);
	//if (CommitRV == 1) CommitRV = ReadCounts(&D1, &D2, &D3, &D4, &CountsClock);
	//if (CommitRV == 1) CommitRV = Commit3();
	//if (CommitRV == 1) CommitRV = ReadBaseCounts(&BaseD1, &BaseD2, &BaseD3, &BaseD4, &BaseCountsClock);
	//if (CommitRV == 1) CommitRV = Commit3();
	return r;
}
WORD Epd3Base::Epd3U::WriteCal()
{
	uint32_t r = 0;
	if (port == 0) return 0;

	if (K6 > 2000)
	{
		r = 0;
		return 0;
	}

	if (EpdType == EpdTypes::Mk2Neutron)
	{
		Password = 9;
		token = BeginMfrLogin_R2(epdComsHandle, Password, nullptr);
		uint32_t r = Commit3(epdComsHandle);
		if (r != 0)
			goto error;
		r = EndMfrLogin_R2(epdComsHandle, token);
		if (r != 0)
			goto error;

		token = BeginWriteSensitivities_R2(epdComsHandle, nullptr, (uint16_t)K1, (uint16_t)K2, (uint16_t)K3, (uint16_t)K4, (uint16_t)K5, (uint16_t)K6);
		r = Commit3(epdComsHandle);
		if (r != 0)
			goto error;
		if (r != 0)
			goto error;
		r = EndWriteSensitivities_R2(epdComsHandle, token);
		if (r != 0)
			goto error;
	}
	return r;
error:
	return r;
}
int Epd3Base::Epd3U::GetAll(bool Closeconnection)
{
	int rv = 0, step=1;
	rv = ReadDoses();
	step++;
	if (!rv) rv = ReadAlarmTresholds();

	if (Closeconnection) EndCom();
	return rv;
}

int Epd3Base::Epd3U::GetAllDeissue()
{
	int rv = 0;
	rv = ReadDoses();	  //0 = success
	//rv = ReadAlarmTresholds(); //0 = success
	rv = EPDReadExtraStatus();
	rv = DeIssue(); //does close
	return rv;
}

int Epd3Base::Epd3U::IssueAndCheck(float gain)
{
	int rv = 0;
	if (isNG) {
		float kx = gain;
		rv = ReadCal();
		if (rv != 0 || K6 != 1310) { rv = 1; goto error; }
		if (K3 != kx || K4 != kx)
		{
			K3 = K4 = kx;
			rv = WriteCal();
			if (rv != 0) goto error;
		}
	}
	rv = PrepareForIssue();
	if (!rv) rv = Issue(); // data already loaded
	return rv;
error:
	return rv;
}