// EEProm_Sample.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "EEProm_Sample.h"

#include "../../Dll/HidDeviceSDKApi.h"

#ifdef _WIN64
#pragma comment(lib, "../../Dll/x64/HidDeviceSdk.lib")
#else
#pragma comment(lib, "../../Dll/x86/HidDeviceSdk.lib")
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		// TODO: code your application's behavior here.
		//Step1: Enum Device
		uint32_t nHidDeviceCount = 0;
		HANDLE hDeviceHandle = INVALID_HANDLE_VALUE;
		int32_t nRet = 0;
		if( ERROR_SUCCESS == EnumDeviceByVid(&nHidDeviceCount, PROLIFIC_VID) ) {
			if(nHidDeviceCount > 0) {
				//Step2: Open Hid Device Array index, ex: 0
				nRet = OpenDeviceHandle(0, &hDeviceHandle);
				if( ERROR_SUCCESS == nRet ) {
					//Step3: Set EEProm Device Address and Clock
					uint8_t by7BitDeviceAddress = 0xA0;	//ingore bit 0
					//EEProm Clock = 12 MHz/(22*(SCLDIV+3)), when SCLDIV>0
					uint8_t bySclDiv = 10;	//=12 MHz/(22*(10+3) = 54.5 KHz
					nRet = SetEepCtrl(hDeviceHandle, by7BitDeviceAddress, bySclDiv);
					if(ERROR_SUCCESS == nRet) {
						printf("Set EEProm 7Bit DeviceAddress=0x%X\n", by7BitDeviceAddress);
					} else {
						printf("SetEepCtrl Fail!\n");
					}

					//Step5: AT24C02, ByteWrite Command
					uint8_t byWriteBuffer[4]={0x00, 0x01, 0x02, 0x03};
					printf("EepByteWrite, Data=");
					for(uint32_t n=0; n<4; n++) { 
						printf("0x%02X ", byWriteBuffer[n]);
					}
					printf("\n");

					for(int n=0; n<4; n++) {
						nRet = EepByteWrite(hDeviceHandle, n, byWriteBuffer[n]);
						if(ERROR_SUCCESS != nRet) {
							printf("EepByteWrite Fail!, ErrorCode=%d\n", nRet);
						}
					}

					//Step6: AT24C02, Random Read Command
					uint8_t byReadBuffer[4] = {0};
					for(int n=0; n<4; n++) {
						nRet = EepRandomRead(hDeviceHandle, n, &byReadBuffer[n]);
						if(ERROR_SUCCESS != nRet) {
							printf("EepRandomRead Fail!, ErrorCode=%d\n", nRet);
						}
					}
					printf("EepRandomRead, Data=");
					for(uint32_t n=0; n<4; n++) { 
						printf("0x%02X ", byReadBuffer[n]);
					}
					printf("\n");
				} else {
					printf("Open device Fail!\n");
				}
				//Step6: Close Hid Device
				nRet = CloseDeviceHandle(hDeviceHandle);
			} else {
				printf("No match Hid device!\n");
			}
		} else {
			printf("GetHidDeviceArrayByVid fail\n");
		}
	}
	system("pause");
	return nRetCode;
}
