#include "pch.h"
#include "MK3Base.h"
#pragma unmanaged

HANDLE Ev1 = INVALID_HANDLE_VALUE;
MK3::Epd2U* current;

void WINAPI completion(CommsHandle hComms, CompletionToken token)
{
	SetEvent(Ev1);
}
MK3::Epd2U::Epd2U(int _comport)
{
	port = _comport;
	comPort[3] = 48 + _comport;
	CommsInitialized = 0;
	epdComsHandle = INVALID_HANDLE_VALUE;
	//SetAutoCommit(0); alleen epd2
	Error = 123;
	if (Ev1 != nullptr) Ev1 = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (_comport == 0) return;
}

WORD MK3::Epd2U::WriteConfig()
{
	if (port == 0) return 1;
	return  0; // WriteDisplayConfig(00, 2, 40, 10, 2, displayConfig, 56);
}

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

void MK3::Epd2U::EndCom()
{
	if (CommsInitialized == 1) {
		if (epdComsHandle != INVALID_HANDLE_VALUE) {
			CloseReader(epdComsHandle);
			DestroyReaderInterface(epdComsHandle);
		}
	}
	CommsInitialized = 0;
	epdComsHandle = INVALID_HANDLE_VALUE;
}

MK3::Epd2U::~Epd2U()
{
	EndCom();
	if (Ev1 != nullptr) {
		CloseHandle(Ev1);  Ev1 = nullptr;
	}
	
}

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(Ev1);
	}
}

/// <summary>
/// 
/// </summary>
/// <returns>0 = success</returns>
int MK3::Epd2U::StartDiscover()
{
	int32_t rv;
		
	//System::Diagnostics::Trace::WriteLine("StartDiscover");
	Error = 0;
	if (port == 0) {
		DeviceCount = 1;
		DeviceIDs[0] = 768;
		return 1;
	}
	//
	//Cancel(epdComsHandle);
	//FlushDiscoveryCache(port);
	//FlushBuffers(port);
	int tries = 25; DeviceCount = 0; DiscRV = 1;
	ResetEvent(Ev1);
	while (tries-- > 0 && DeviceCount == 0)
	{
		//memset(DevceIDs, 0, sizeof(DeviceIDs));
		current = this;
		rv = StartDiscovery(epdComsHandle, discovery);
		if (rv==0) rv = WaitForSingleObject(Ev1, 10000);
	}
	if (rv == 0) rv=Connect(epdComsHandle, Epd, true);
	//System::Diagnostics::Trace::WriteLine(System::String::Format("Discover DeviceCount = {0}", DeviceCount));
	
	return rv;
}

void MK3::Epd2U::Open(DiscoveryId DeviceID)
{
	CurrentDeviceID = DeviceID.Id;
	if (port > 0) {
		ConRV = Connect(epdComsHandle, DeviceID,true);
		//if (ConRV == 0) Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
		//else {
		Open(DeviceID); // OpenDevice(port, CurrentDeviceID);
			//if (OpenRV == 0) Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
		}
	//}
	else { OpenRV = ConRV = 1; }
}
void MK3::Epd2U::CloseDev()
{
	if (port > 0) {
		//Close();//	CloseDevice();
		Disconnect(epdComsHandle);
	}
	//DeinitComms(port);	CommsInitialized = 0;
}

//void MK3::Epd2U::DecodeFunctionFlags()
//{
//	EpdType = (FunctionFlags & 0x1F00) >> 8;
//}


byte checkOpStatus(OpStatusFlags status, OpStatusFlags flag)
{
	if (((uint32_t)status & (uint32_t)flag) == (uint32_t)flag) return 1; else return 0;
}
byte checkFailStatus(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 MK3::Epd2U::DecodeStatus()
{
	DetectorsOn = checkOpStatus(epd3status.OperatingStatus, OpStatusFlags::EpdOn);
	EPDIssued = checkOpStatus(epd3status.OperatingStatus, OpStatusFlags::EpdIssued);
	EPDLocked = checkOpStatus(epd3status.OperatingStatus, OpStatusFlags::GainAdjustable);
	EPDTesting = checkOpStatus(epd3status.OperatingStatus, OpStatusFlags::DetectorTestRequested);
	EPDFaulty = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::EpdFaulty);

	EPDNewFault = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::EpdFaulty);
	EPDComFault = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::EarlyCommsTermination);
	EPDCalFault = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::NotCalibrated);
	EPDDetFault = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::DetectorTestFail);
	EPDEprFault = checkFailStatus(epd3status.FaultStatus, FaultStatusFlags::EepromFailure);
	EPDTrhFault = checkFailStatus(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);
}

void MK3::Epd2U::SetTime() //Only R3
{
	if (Epd.Gen == EpdGeneration::Mk3) {
		utc = TimeFunctions::NowToEpdTime(Epd.Gen == EpdGeneration::Mk2);
		ResetEvent(Ev1);
		token = BeginWriteRTC_R3(epdComsHandle, utc, completion);
		uint32_t r = Commit(epdComsHandle);
		r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		r = EndWriteRTC_R3(epdComsHandle, token);
	}
}

WORD MK3::Epd2U::ReadStatus()
{
	
	int32_t r; //0=ok
	Error = 0;
	if (port == 0) {
		EpdID = 4567;
		EpdType = EpdTypes::Mk2BetaGamma;
		isBG = 1;
		FunctionFlags = 0x000;
		Epd.Gen = EpdGeneration::None;
		Epd.MaxBaud = 0;
		Epd.Id = EpdID;
		return 0;
	}

	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;

	SetResponseTimeout(epdComsHandle, 2000);
	//ResetEvent(Ev1);
	token = BeginReadStatus(epdComsHandle, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadStatus(epdComsHandle, token, &epd3status);

	if (r != 0) {
		Error = GetErrorCode(); return r;
	}

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

	uint32_t EpdID32;
	uint32_t capabilities;
	MarkNumber_t MarkNumber;
	VersionNumber_t VersionNumber;

	//ResetEvent(Ev1);
	token = BeginReadEpdIdentities(epdComsHandle, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadEpdIdentities(epdComsHandle, token, &EpdID32, (EpdTypes*)&EpdType, &capabilities, &MarkNumber, &VersionNumber, NULL, 0);

	if (r != 0) {
		Error = GetErrorCode(); return r;
	}

	
	EpdID = EpdID32;
	isBG = (EpdType == EpdTypes::Mk2BetaGamma || EpdType == EpdTypes::Mk3BetaGamma);
	
	DecodeStatus();
	memset(WearerID, 0, WearerIDLength + 1);
	memset(WearerName, 0, WearerNameLength + 1);

	uint8_t 	length = 0;
	countsRead = 0; utc = 0; seconds = 0;
	//ResetEvent(Ev1);
	token = BeginReadCounts(epdComsHandle, nullptr, 0, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadCounts(epdComsHandle,token,Counts,MaxCounts, &countsRead,&utc,&seconds);
	// - 101 = InvalidParam
	// - 104 = FunctionFail, 
	if (r != 0 && r!=-104) {
		Error = GetErrorCode(); return r;
	}
	decodeCounters(countsRead); //HG,SG ..

	IdString_t mk3WearerID;
	//Mk2 EPDs only support Name and Primary ID
	//ResetEvent(Ev1);
	token = BeginReadWearerId(epdComsHandle, static_cast<uint16_t>(WearerIdType::WearerId_Name), nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadWearerId(epdComsHandle, token, &mk3WearerID);
	if (r != 0) {
		Error = GetErrorCode(); return r;
	}

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

	//ResetEvent(Ev1);
	token = BeginReadWearerId(epdComsHandle, static_cast<uint16_t>(WearerIdType::WearerId_Primary), nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadWearerId(epdComsHandle, token, &mk3WearerID);
	if (r != 0) {
		Error = GetErrorCode(); return r;
	}

	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;

	//1601-01-01T00:00:00Z.
	
	//MK2 .. some utc... but no real time clock
	if (utc == 0) {
		//ResetEvent(Ev1);
		token = BeginReadRTC(epdComsHandle,  nullptr);
		r = Commit(epdComsHandle);
		//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		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);

	
		
	//CommitRV =  ReadEpdStatus(&EpdClock, &RealTime, &IssueCount, &OffTime, &OperatingStatus, &ErrorStatus, &AlarmStatus, &OtherAlarms, &EEPROMBadSectors);
	//if (port == 0) {
	//	EpdClock = 123; ErrorStatus = 0;
	//};
	//if (CommitRV == 1) CommitRV = Commit();
	//if (CommitRV == 1) CommitRV = ReadEpdID(
	//	&EpdID,
	//	&HardVersion,
	//	&SoftVersion,
	//	&FunctionFlags);
	//if (CommitRV == 1) CommitRV = Commit();
	//if (CommitRV == 0) {
	//	Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	//	ReadStatusRV = ErrorReason;
	//	return 0;
	//}
	//else {
	//	if (CurrentDeviceID == 0) CurrentDeviceID = EpdID;
	//	time_t t = RealTime;
	//	TimeFunctions::UnixTimeToSystemTime(t, &tRealTime);
	//	DecodeStatus();
	//	DecodeFunctionFlags();
	//}

	//if (CommitRV == 1 && EPDIssued == 1)
	//{
	//	CommitRV = ReadWearer(
	//		WearerID,
	//		WearerIDLength,
	//		WearerName,
	//		WearerNameLength);
	//	if (CommitRV == 1) CommitRV = Commit();
	//	if (CommitRV == 0) {
	//		Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	//		ReadStatusRV = ErrorReason;
	//		return 0;
	//	}
	//	else {
	//	}
	//}

	
	//werkt niet voor MK2
	//ResetEvent(Ev1);
	//token = BeginReadMeasurandIds_R3(epdComsHandle, completion);
	//r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	//r = EndReadMeasurandIds_R3(epdComsHandle, token, mIDs, MAX_MEASUREMENTS, &nmIDs);


	return r;
}

void MK3::Epd2U::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; break;
		case SensitivityId::Sg1Sens10G: K2 = sensitivities[ix].value; break;
		case SensitivityId::Hg1Sens07G: K3 = sensitivities[ix].value; break; //Neutr=FN
		case SensitivityId::Sg1Sens07G: K4 = sensitivities[ix].value; break; //Neutr=AN
		case SensitivityId::Fb1Sens07B: K5 = sensitivities[ix].value; break;
		case SensitivityId::Sg2Sens07B: K6 = sensitivities[ix].value; break;
		default: break;
		}
	}
}
void MK3::Epd2U::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 MK3::Epd2U::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 MK3::Epd2U::decodePeakRates(int count)
{
	//Rates
	Hp10Peak = Hp07Peak = 0;
	Hp10Time = Hp07Time = 0;
	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;
			break;
		case MeasurementId::Meas_Hp10: 
		case MeasurementId::Meas_Hp10G: 
			Hp10Peak = peakRates[ix].value;
			Hp10Time = peakRates[ix].timestamp;
			break;
		}
	}
}
void MK3::Epd2U::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 MK3::Epd2U::decodeBaseCounters(int count)
{
	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 MK3::Epd2U::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 = pTHRateWarning = nullptr;
		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 MK3::Epd2U::encodeTreshold(Mk3AlarmThresholds_t* th)
{
	//th.MeasId
	float* pThDose  , *pThRate  , *pTHDoseWarning,* pTHRateWarning;
	
	th->NumberThresholds = 4;
	switch ((MeasurementId)th->MeasId) {
	case MeasurementId::Meas_Hp07:
	case MeasurementId::Meas_Hp10N:
		pThDose = &Hp07THDose;
		pTHDoseWarning = &Hp07THDose;
		pThRate = &Hp07RateOn;
		pTHRateWarning = &Hp07RateOff;
		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 = &Hp07THDose;
		pThRate = &Hp07RateOn;
		pTHRateWarning = &Hp07RateOff;
	}
	
	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;
}
void MK3::Epd2U::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


		}
	}
}
WORD MK3::Epd2U::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;

		//ResetEvent(Ev1);
		//token = BeginReadDoses(epdComsHandle, new uint8_t[]{ 0,     1 }, 2 , completion);
		token = BeginReadCalibrationData_R2(epdComsHandle,  nullptr);
		r = Commit(epdComsHandle);
		//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		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 {
		ResetEvent(Ev1);
		token = BeginReadDetectorThresholds_R3(epdComsHandle,nullptr,0, completion);
		r = Commit(epdComsHandle);
		r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		r = EndReadDetectorThresholds_R3(epdComsHandle, token, dTresholds, MaxTresholds, &numTresholds);
		decodedTresholds(numTresholds);
		
		ResetEvent(Ev1);
		token = BeginReadSensitivities(epdComsHandle,nullptr,0, completion);
		r = Commit(epdComsHandle);
		r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		r = EndReadSensitivities(epdComsHandle, token, sensitivities,MaxSensitivities,&numSensitivities);
		decodeSensitivities(numSensitivities);
	}
	return 0;
}
WORD MK3::Epd2U::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 1;
	}
	ReadDosesQualityRV = ReadPeaksRV = CommitRV = 0;

	numDoses = 0; utc = 0;
	SetResponseTimeout(epdComsHandle, 2000);
	//ResetEvent(Ev1);
	token = BeginReadDoses(epdComsHandle, nullptr, 0, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadDoses(epdComsHandle, token, doses, MaxDoses, &numDoses, &utc);
	decodeDoses(numDoses);

	//ResetEvent(Ev1);
	token = BeginReadTotalDoses(epdComsHandle, nullptr, 0, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadTotalDoses(epdComsHandle, token, totdoses, MaxDoses, &numtotDoses, &utc);
	decodetotDoses(numtotDoses);

	ResetEvent(Ev1);
	token = BeginReadQualityData(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadQualityData(epdComsHandle, token, &quality);
	Knocks = quality.Knocks;
	Resets = quality.PowerCycles;
	ResetEvent(Ev1);
	
	token = BeginReadPeakRates(epdComsHandle, nullptr, 0, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadPeakRates(epdComsHandle, token, peakRates, MaxPeakRates, &numRates);
	decodePeakRates(numRates);

	ReadSensitivitiesAndTresholds();
	
	//ResetEvent(Ev1);
	//token = BeginReadSensitivities(epdComsHandle, nullptr, 0, completion);
	//r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	//r = EndReadSensitivities(epdComsHandle, token, sensitivities, MaxSensitivities, &numSensitivities);
	//decodeSensitivities(numSensitivities);

		//ReadDosesQualityRV = ReadDosesQuality(
	//	&Hp10Dose,
	//	&Hp07Dose,
	//	&Hp10Total,
	//	&Hp07Total,
	//	&Knocks,
	//	&Resets,
	//	&QualityData);

	//if (ReadDosesQualityRV == 0) {
	//	Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	//	return 0;
	//}

	//BeginReadPeakRates(CommsHandle 	hComms,		uint8_t 	ids[],		uint8_t 	length,		CompletionCallback 	callback	)
	/*ReadPeaksRV = ReadPeaks(
		&Hp10Peak,
		&Hp07Peak,
		&Hp10Time,
		&Hp07Time);
	if (ReadPeaksRV == 0) {
		Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
		return 0;
	}*/

	// EPD2 :
	// 	   int32_t EPDDLL_API 	EndReadCalibrationData_R2 (CommsHandle hComms, CompletionToken token, 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)
	// 	EPD3
	// 	   
	//CompletionToken EPDDLL_API BeginReadSensitivities_R3(CommsHandle 	hComms,		uint8_t 	sensIds[],		uint8_t 	length,		CompletionCallback 	callback	)
	//ReadCalibrationData(
	//	&K1,
	//	&K2,
	//	&K3,
	//	&K4,
	//	&K5,
	//	&K6,
	//	&SG,
	//	&BC,
	//	&FB,
	//	&HG);
	//CommitRV = Commit();
	//if (CommitRV == 0) Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	return 1;
}
void MK3::Epd2U::ClearDoses()
{
	int32_t r = 1;
	ResetEvent(Ev1);
	token = BeginClearDose(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearDose(epdComsHandle, token);
	if (r != 0)
		goto error;

	ResetEvent(Ev1);
	token = BeginClearTotalDose(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearTotalDose(epdComsHandle, token);
	if (r != 0)
		goto error;

	ResetEvent(Ev1);
	token = BeginClearPeakRates(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearPeakRates(epdComsHandle, token);
	if (r != 0)
		goto error;

error: return ;
}
void MK3::Epd2U::ClearAlarms()
{
	ResetEvent(Ev1);
	token = BeginClearFaultStatus(epdComsHandle, completion);
	int32_t r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearFaultStatus(epdComsHandle, token);

	ResetEvent(Ev1);
	token = BeginClearLatchedAlarms(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearLatchedAlarms(epdComsHandle, token);

	ResetEvent(Ev1);
	token = BeginClearAllStatus(epdComsHandle, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndClearAllStatus(epdComsHandle, token);
}
WORD MK3::Epd2U::PrepareForIssue()
{
	if (port == 0) return 1;
	CommitRV = WriteConfig();
	ClearDoses();
	ClearAlarms();
	return 0;
}
WORD MK3::Epd2U::ReadAlarmConfig() {
	//Alleen MK3 ? leeg bij MK2
	ResetEvent(Ev1);
	token = BeginReadAlarmConfiguration(epdComsHandle, nullptr, 0, completion);
	int32_t r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadAlarmConfiguration(epdComsHandle, token, alarmConfig, MaxAlarmConfig, &numAlarm);
	return numAlarm;
}
WORD MK3::Epd2U::ReadAlarmTresholds() {
	//Alleen MK3 ? leeg bij MK2

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


	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10N; else measID = (uint8_t)MeasurementId::Meas_Hp07;

	SetResponseTimeout(epdComsHandle, 2000);
	//ResetEvent(Ev1);
	hp07tresholds.MeasId = measID;
	token = BeginReadAlarmThresholds(epdComsHandle, (uint8_t) hp07tresholds.MeasId,nullptr,0, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadAlarmThresholds(epdComsHandle, token, &hp07tresholds);
	decodeTreshold(&hp07tresholds);
	
	if (isNeutron) measID = (uint8_t)MeasurementId::Meas_Hp10G; else measID = (uint8_t)MeasurementId::Meas_Hp10;
	hp10tresholds.MeasId = 0;
	//ResetEvent(Ev1);
	token = BeginReadAlarmThresholds(epdComsHandle, (uint8_t)hp10tresholds.MeasId, nullptr, 0, nullptr);
	r = Commit(epdComsHandle);
	//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadAlarmThresholds(epdComsHandle, token, &hp10tresholds);
	decodeTreshold(&hp10tresholds);
	return r;
}
WORD MK3::Epd2U::WriteAlarmTresholds() {
	//Alleen MK3 ? leeg bij MK2
	int 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 = Commit(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 = 2;
	token = BeginWriteAlarmThresholds(epdComsHandle, (uint8_t)hp07tresholds.MeasId, (uint8_t)hp07tresholds.NumberThresholds, hp07tresholds.Thresholds, nullptr);
	r = Commit(epdComsHandle);
	if (r != 0) 
		goto error;
	r = EndWriteAlarmThresholds(epdComsHandle, token);
	if (r != 0) 
		goto error;

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

	
	return r;
	
	error:
	return r;
}

WORD MK3::Epd2U::DeIssue()
{
	int32_t r = 1;
//	if (!EPDIssued) return 0;

	ClearDoseRV = ClearTotalDoseRV = ClearPeakRatesRV = DeIssueEpdRV = 0;
	if (port == 0) return 1;
	ClearDoses();
	ClearAlarms();
	
	if (EPDIssued) {
		token = BeginDeissueEPD(epdComsHandle, nullptr);
		r = Commit(epdComsHandle);
		r = EndDeissueEPD(epdComsHandle, token);
		if (r != 0)
			r = 0;
	}

	token = BeginEpdOnOff(epdComsHandle,0, nullptr);
	r = Commit(epdComsHandle);
	r = EndEpdOnOff(epdComsHandle, token);
	if (r != 0)
		goto error;
	EndCom();
	error:
	return r;
}
WORD MK3::Epd2U::WriteWearer() {
	
	ResetEvent(Ev1);
	token = BeginSetBaselineCounters(epdComsHandle, completion);
	int32_t r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndSetBaselineCounters(epdComsHandle, token);
	
	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);
	ResetEvent(Ev1);
	token = BeginWriteWearerId(epdComsHandle, mk3WearerID, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndWriteWearerId(epdComsHandle, token);
	
	mk3WearerID.IdType = (uint16_t)WearerIdType::WearerId_Primary;
	mk3WearerID.Length = 13;
	memcpy(mk3WearerID.Utf8String, WearerID, 13);
	token = BeginWriteWearerId(epdComsHandle, mk3WearerID, completion);
	r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndWriteWearerId(epdComsHandle, token);

	return 0;
}
WORD MK3::Epd2U::Issue()
{
	uint32_t r;
	IssueEpdRV = WriteAlarmDoseThresholdsRV = WriteAlarmRateThresholdsRV = WriteWearerNameRV = OnRV = CommitRV = 0;
	if (port == 0) return 1;
	//WORD OKRV = SetFailFlag(); // all actions have been completed
	//if (OKRV) OKRV = Commit();
	//ClearAlarms();
	r= WriteAlarmTresholds();
	if (r != 0) 
		goto error;
	r= WriteWearer();
	if (r != 0) 
		goto error;
	r=WriteCal();
	if (r != 0)
		goto error;

	
	if (r != 0) 
		goto error;
	if (!DetectorsOn) {
		token = BeginEpdOnOff(epdComsHandle, 1, nullptr);
		r = Commit(epdComsHandle);
		//r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		r = EndEpdOnOff(epdComsHandle, token);
		//	OKRV = EpdOn(); OKRV = Commit(); 
		//Sleep(1500);
		}
	token = BeginIssueEPD(epdComsHandle, nullptr);
	r = Commit(epdComsHandle);
	r = EndIssueEPD(epdComsHandle, token);
	if (r != 0)
		goto error;
	EndCom();

	//if (OKRV) OKRV = WriteAlarmDoseThresholds(Hp10THDose1, Hp10THDose2, Hp07THDose);
	//if (OKRV) OKRV = WriteAlarmRateThresholds(Hp10Rate1On, Hp10Rate2On, Hp07RateOn, Hp10Rate1Off, Hp10Rate2Off, Hp07RateOff);
	//if (OKRV) OKRV = Commit();

	//if (OKRV) OKRV = IssueEpd(WearerID, WearerIDLength);
	//if (OKRV) OKRV = Commit();
	//if (OKRV) OKRV = WriteWearerName(WearerName, (WORD)strlen((char*)WearerName));
	//if (OKRV) OKRV = Commit();
	//if (OKRV) OKRV = BaseLineCounts();
	//if (OKRV == 0)
	//{
	//	Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	//}
	//ClearFailFlag(); // all actions have been completed
	//Commit();

	//if (!DetectorsOn) {
	//	OKRV = EpdOn(); OKRV = Commit(); Sleep(1500);
	//}

	//if (OKRV) {

	//	EndSession(EndSessionControl, 12);
	//	Commit();
	//} // Continuous high tone for 1.2 seconds
	//else
	//{
	//	FlushBuffers(port);
	//	Error = GetErrorDetails(&ErrorSource, &ErrorReason, &ErrorData);
	//	EndSession(0x5E, 40);
	//}

	//Close();
	////DeinitComms(port);
	//return OKRV;


	error:
	return r;
}
WORD MK3::Epd2U::EPDReadExtraStatus()
{
	if (port == 0) return 1;
	byBatADC = bySupplyADC = 0;
	/*CommitRV = ReadA2ConfigStatus(
		&byBatADC,
		&bySupplyADC,
		&byStatus3,
		&byStatus4);
	if (CommitRV == 1) CommitRV = Commit();*/
	
	ResetEvent(Ev1);
	token = BeginReadBaselineCounts(epdComsHandle, completion);
	uint32_t r = Commit(epdComsHandle);
	r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
	r = EndReadBaselineCounts(epdComsHandle, token,Counts,10,&utc,&countsRead);
	decodeBaseCounters(countsRead);
	//if (CommitRV == 1) CommitRV = ReadCounts(&D1, &D2, &D3, &D4, &CountsClock);
	//if (CommitRV == 1) CommitRV = Commit();
	//if (CommitRV == 1) CommitRV = ReadBaseCounts(&BaseD1, &BaseD2, &BaseD3, &BaseD4, &BaseCountsClock);
	//if (CommitRV == 1) CommitRV = Commit();
	return CommitRV;
}
WORD MK3::Epd2U::WriteCal()
{
	uint32_t r = 0;
	if (port == 0) return 0;

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

	if (EpdType == EpdTypes::Mk2Neutron)
	{
		Password = 9;
		ResetEvent(Ev1);
		token = BeginMfrLogin_R2(epdComsHandle, Password, completion);
		uint32_t r = Commit(epdComsHandle);
		r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		if (r != 0) 
			goto error;
		r = EndMfrLogin_R2(epdComsHandle, token);
		if (r != 0)
			goto error;
		token = BeginWriteSensitivities_R2(epdComsHandle, completion, (uint16_t)K1, (uint16_t)K2, (uint16_t)K3, (uint16_t)K4, (uint16_t)K5, (uint16_t)K6);
		r = Commit(epdComsHandle);
		if (r != 0)
			goto error;
		r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
		if (r != 0)
			goto error;
		r = EndWriteSensitivities_R2(epdComsHandle, token);
		if (r != 0)
			goto error;
	}
	return r;
	error:
	return r;
}