// TestMK3.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <wtypes.h>
#include <synchapi.h>
#include <iostream>
#include "EpdCommon.h"



char comPort[] = "COM4";
CommsHandle epdComsHandle;
uint32_t EpdID;
EpdGeneration EpdGen;
DiscoveryId Epd;

HANDLE Ev1 = INVALID_HANDLE_VALUE;
CompletionToken token;
StatusData_t status;
MeasValue_t doses[4];
uint8_t numDoses;
uint32_t utc;


void WINAPI discovery(CommsHandle hComms, DiscoveryId const discovered[], int32_t count)
{
    EpdID = 0;
    if (count > 0) {
        EpdID = discovered[0].Id;
        EpdGen = discovered[0].Gen;
    }
    memcpy(&Epd,&discovered[0],sizeof(DiscoveryId));
    SetEvent(Ev1);
}

void WINAPI completion(CommsHandle hComms, CompletionToken token)
{
    SetEvent(Ev1);
}

void GetEPD()
{
    epdComsHandle = CreateReaderInterface();
    int r = OpenReader(epdComsHandle, comPort);
    Ev1 = CreateEvent(
        NULL,               // default security attributes
        TRUE,               // manual-reset event
        FALSE,              // initial state is nonsignaled
        TEXT("WriteEvent")  // object name
    );
    r = StartDiscovery(epdComsHandle, discovery);

    std::cout << "wacht effen!\n";
    r = WaitForSingleObject(Ev1, 10000);  // no time-out interval

    std::cout << "ok!\n";
    r = Connect(epdComsHandle,Epd, true);

    ResetEvent(Ev1);
    std::cout << "get status\n";
    token = BeginReadStatus(epdComsHandle, completion);
    r = Commit(epdComsHandle);
    r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
    std::cout << "got status\n";
    r = EndReadStatus(epdComsHandle, token, &status);

    
    numDoses = 0; utc = 0;
    ResetEvent(Ev1);
    //token = BeginReadDoses(epdComsHandle, new uint8_t[]{ 0,     1 }, 2 , completion);
    token = BeginReadDoses(epdComsHandle, nullptr, 0 , completion);
    r = Commit(epdComsHandle);
    r = WaitForSingleObject(Ev1, 10000);  // no time-out interval
    std::cout << "got doses\n";
    r = EndReadDoses(epdComsHandle, token, doses, 2, &numDoses, &utc);


}


int main()
{
   
    
    GetEPD();
    std::cout << "Hello World!\n";
    std::getchar();
}

// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
//C:\Program Files (x86)\Thermo Scientific\Unmanaged HtmlFiles
// 
// Tips for Getting Started: 
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
