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

#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <windows.h>
#include <shellapi.h>
#include "mp8723xBT.h"
//#include "RTKBTMPDLL.h"

//#define MP_RTK_MP_MP872XBT

#define ESCAPE 27

//#define DBG_ON


#ifdef DBG_ON
        static void DBGPRINTF(char *prompt, ...)
        {
        char buf[2048];
        va_list argptr;
        int cnt;

        va_start(argptr, prompt);
        cnt = vsprintf(buf, prompt, argptr);
        OutputDebugString(buf);
        va_end(argptr);
        return ;
        }
  
#else
	#define DBGPRINTF printf
#endif




static HMODULE hRTKBTPortModule=NULL;

typedef bool (*API_RTKBT_OpenAdapter)(unsigned char HostType, unsigned char PortNo, unsigned long Rate);
typedef bool (*API_RTKBT_CloseAdapter)();
typedef bool (*API_RTKBT_ShowUI)(bool IsShow);
typedef unsigned long (*API_RTKBT_GetLastError)();
typedef bool (*API_RTKBT_GetStatistics)(RTKBT_TRXSTATISTICS* statistics);
typedef bool (*API_RTKBT_HCIReset)();
typedef bool (*API_RTKBT_BTTestMode)(UINT8 Type);
typedef bool (*API_RTKBT_StartPacketTx)();
typedef bool (*API_RTKBT_StartContinueTx)();
typedef bool (*API_RTKBT_StartRx)();
typedef bool (*API_RTKBT_StopTest)();
typedef bool (*API_RTKBT_SetTRxParameters)(RTKBT_TRXPARAM params);
typedef int (*API_RTKBT_GetComHandle)(HANDLE *ComHandle,HANDLE *ComEventHandle);

typedef bool	(*API_RTKBT_WriteReg)(UINT32 type, UINT32 RegAddr, UINT32 RegValue, UINT32 bitmask);
typedef UINT32 	(*API_RTKBT_ReadReg)(UINT32 type, UINT32 RegAddr, UINT32 bitmask);
typedef bool  (*API_RTKBT_TxPowertoGainValue)(int  TxPowerdB, unsigned char *pBuf);

typedef UINT8 (*API_RTKBT_ReadThermalMeter)();

static   API_RTKBT_OpenAdapter		hAPI_RTKBT_OpenAdapter=NULL;
static   API_RTKBT_CloseAdapter		hAPI_RTKBT_CloseAdapter=NULL;
static   API_RTKBT_ShowUI            hAPI_RTKBT_ShowUI=NULL; 
static   API_RTKBT_GetLastError      hAPI_RTKBT_GetLastError=NULL; 
static   API_RTKBT_GetComHandle      hAPI_RTKBT_GetComHandle=NULL; 

static API_RTKBT_GetStatistics hAPI_RTKBT_GetStatistics=NULL;
static API_RTKBT_HCIReset	hAPI_RTKBT_HCIReset=NULL;
static API_RTKBT_BTTestMode	hAPI_RTKBT_BTTestMode=NULL;
static API_RTKBT_StartPacketTx hAPI_RTKBT_StartPacketTx=NULL;
static API_RTKBT_StartContinueTx hAPI_RTKBT_StartContinueTx=NULL;
static API_RTKBT_StartRx hAPI_RTKBT_StartRx=NULL;
static API_RTKBT_StopTest hAPI_RTKBT_StopTest=NULL;
static API_RTKBT_SetTRxParameters  hAPI_RTKBT_SetTRxParameters=NULL;
static API_RTKBT_ReadThermalMeter hAPI_RTKBT_ReadThermalMeter= NULL;
static API_RTKBT_TxPowertoGainValue hAPI_RTKBT_TxPowertoGainValue=NULL;

static API_RTKBT_WriteReg hAPI_RTKBT_WriteReg=NULL;
static API_RTKBT_ReadReg hAPI_RTKBT_ReadReg=NULL;

static RTKBT_TRXSTATISTICS    rtkbt_statistics;
static RTKBT_TRXPARAM trxparams;


static DWORD t1,t2,tt;

static int BT_TX()
{
	int channel=0;
	char ch=0;
	int Delay=200;
    DBGPRINTF("*Please inpunt Tx channel Number 0~79 =");
    scanf("%d",&channel);

	trxparams.Rate =3;
	trxparams.Channel =channel;
	trxparams.TxPktCnt =0;
	trxparams.TxPKtInterval =2;
	trxparams.PayloadType =0; //ALL'0
	trxparams.PayloadLength = 8168;
	trxparams.PacketHeader =0x3ffff;
	trxparams.WhitenCoeff =0x7f;
	trxparams.TxGainIndex=7;
	strcpy(trxparams.BDAddress,"00004C002253");
	t1=GetTickCount();

	if (!hAPI_RTKBT_SetTRxParameters(trxparams))
    {
		DBGPRINTF(">>SetTRxParameters (TX) Error");
		goto exit;
    }
	t2=GetTickCount();
	DBGPRINTF(">>SetTRxParameters (TX)(Time=%d)\n",labs(t2-t1));

    DBGPRINTF("*Please inpunt Delay time mSec: ");
    scanf("%d",&Delay);


	DBGPRINTF(">> Begin Packet Tx Channel = %d \n",channel);
	t1=GetTickCount();
	if (!hAPI_RTKBT_StartPacketTx())
	{
			DBGPRINTF(">>StartPacketTx Error");
			goto exit;
	}
	t2=GetTickCount();
	DBGPRINTF(">> Begin Packet Tx Channel = %d Succress (Time= %d)\n",channel,labs(t2-t1));



	DBGPRINTF(">>please ESC Key to exit ...\n");
	t1=GetTickCount();
	while(1)
    { 
		   if ( kbhit())
		   {
				ch=getch();
				if (ch == ESCAPE )
	 			break;
		   }
		   t2=GetTickCount();
		   hAPI_RTKBT_GetStatistics(&rtkbt_statistics);
		   DBGPRINTF(">>Tx bits (%d)--Time=%d \n",rtkbt_statistics.TxBits,labs(t2-t1));
		   Sleep(Delay);	
	}

	DBGPRINTF(">>Stop Packet Tx\n");
	t1=GetTickCount();
    if (!hAPI_RTKBT_StopTest())
	{
		DBGPRINTF(">>Stop Tx Error");
		goto exit;
	}	
    t2=GetTickCount(); 
	DBGPRINTF(">>Stop Packet Tx (%d) Succress\n",labs(t2-t1));

exit:
	return 0;	
}
static void BT_HCIReset()
{
	t1=GetTickCount();
	hAPI_RTKBT_HCIReset();
	t2=GetTickCount(); 
	DBGPRINTF(">>HCI Reset... (Time=%d)\n",labs(t2-t1));
	return ;
}
static int BT_RX()
{

	int channel=0;
	char ch=0;
	int Delay=200;
    DBGPRINTF("*Please inpunt RX channel Number( 0~79)=");
    scanf("%d",&channel);
	////////////////////////////////////////////////////////////
	// Setp1[1] Set paramter
	trxparams.Rate =3;
	trxparams.Channel =channel;
	trxparams.TxPktCnt =0;
	trxparams.TxPKtInterval =2;
	trxparams.PayloadType =0; //ALL'0
	trxparams.PayloadLength = 8168;
	trxparams.PacketHeader =0x3ffff;
	trxparams.WhitenCoeff =0x7f;
	trxparams.TxGainIndex=7;
	strcpy(trxparams.BDAddress,"00004C002253");
	t1=GetTickCount();
	if (!hAPI_RTKBT_SetTRxParameters(trxparams) )
    {
		DBGPRINTF(">>SetTRxParameters (RX)Error");
		goto exit;
    }
	t2=GetTickCount();

	DBGPRINTF(">>SetTRxParameters (RX) (Time= %d)\n",labs(t2-t1));
    DBGPRINTF("*Please inpunt Delay time mSec: ");
    scanf("%d",&Delay);

    ////////////////////////////////////////////////////////////
	DBGPRINTF(">> Begin Packet Rx Channel = %d \n",channel);
	t1=GetTickCount();
	if (!hAPI_RTKBT_StartRx() )
	{
			DBGPRINTF(">>StartPacketRx Error");
			goto exit;
	}
	t2=GetTickCount();
	DBGPRINTF(">> Begin Packet Rx Channel = %d Succress (Time= %d)\n",channel,labs(t2-t1));

	
	DBGPRINTF(">>please ESC Key to exit ...\n");
	t1=GetTickCount();
	while(1)
    { 
		   if ( kbhit())
		   {
				ch=getch();
				if (ch == ESCAPE )
	 			break;
		   }
		   t2=GetTickCount();
		   tt=labs(t2-t1);
		   hAPI_RTKBT_GetStatistics(&rtkbt_statistics);
		   DBGPRINTF(">>Rx bits =%d BER=%f ErrorBits=%d (Time = %d )\n",rtkbt_statistics.RxBits ,rtkbt_statistics.RxBER,rtkbt_statistics.ErrorBits,labs(t2-t1));
		   Sleep(Delay);	
	}
	t1=GetTickCount(); 
	DBGPRINTF(">> Stop Packet Rx Channel = %d \n",channel);
	if (!hAPI_RTKBT_StopTest())
	{
			DBGPRINTF(">>Stop Rx Error");
			goto exit;
	}
   t2=GetTickCount();
   DBGPRINTF(">> Stop Packet Rx Succress (Time = %d)\n",labs(t2-t1));

exit:
	////////////////////////////////////////////////////////////////
	return 0;	
}
int BT_LoadMP87XXDLL()
{

#ifdef MP_RTK_MP_MP872XBT
	#ifdef _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
        hRTKBTPortModule = LoadLibrary(_T("mp8723xBT.dll"));
	#else
       	hRTKBTPortModule = LoadLibrary("mp8723xBT.dll");
		DBGPRINTF(">>mp8723xBT.dll Succress...\n");
	#endif
		if (hRTKBTPortModule == NULL){
		    DBGPRINTF(">> Load mp87xxxx.dll Fail...\n");
			return -1;	   
	}
	DBGPRINTF(">> Load mp8723xBT.dll Succress...\n");
#else
	#ifdef _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
        hRTKBTPortModule = LoadLibrary(_T("rtlBtmpDll.dll"));
	#else
       	hRTKBTPortModule = LoadLibrary("rtlBtmpDll.dll");
		DBGPRINTF(">>rtlBtmpDll.dll Succress...\n");
	#endif
		if (hRTKBTPortModule == NULL){
		    DBGPRINTF(">> Load rtlBtmpDll.dll Fail...\n");
			return -1;	   
	}
	DBGPRINTF(">> Load rtlBtmpDll.dll Succress...\n");

#endif
#ifdef MP_RTK_MP_MP872XBT
	hAPI_RTKBT_OpenAdapter	=	 (API_RTKBT_OpenAdapter)		GetProcAddress(hRTKBTPortModule,"@RTKBT_OpenAdapter$qucucui");
 	hAPI_RTKBT_CloseAdapter	=    (API_RTKBT_CloseAdapter)		GetProcAddress(hRTKBTPortModule,"@RTKBT_CloseAdapter$qv");
	hAPI_RTKBT_ShowUI		=    (API_RTKBT_ShowUI)				GetProcAddress(hRTKBTPortModule,"@RTKBT_ShowUI$qo");
	hAPI_RTKBT_GetLastError	=    (API_RTKBT_GetLastError)		GetProcAddress(hRTKBTPortModule,"@RTKBT_GetLastError$qv");
    hAPI_RTKBT_GetComHandle =    (API_RTKBT_GetComHandle)       GetProcAddress(hRTKBTPortModule,"@RTKBT_GetComHandle$qppvt1");
	hAPI_RTKBT_GetStatistics=	(API_RTKBT_GetStatistics)		GetProcAddress(hRTKBTPortModule,"@RTKBT_GetStatistics$qp20_RTKBT_TRXSTATISTICS");
	hAPI_RTKBT_HCIReset		=	(API_RTKBT_HCIReset)			GetProcAddress(hRTKBTPortModule,"@RTKBT_HCIReset$qv");
	hAPI_RTKBT_BTTestMode	=	(API_RTKBT_BTTestMode)			GetProcAddress(hRTKBTPortModule,"@RTKBT_BTTestMode$quc");
	hAPI_RTKBT_StartPacketTx=	(API_RTKBT_StartPacketTx)		GetProcAddress(hRTKBTPortModule,"@RTKBT_StartPacketTx$qv");
	hAPI_RTKBT_StartContinueTx=	(API_RTKBT_StartContinueTx)		GetProcAddress(hRTKBTPortModule,"@RTKBT_StartContinueTx$qv");
	hAPI_RTKBT_StartRx		=	(API_RTKBT_StartRx)				GetProcAddress(hRTKBTPortModule,"@RTKBT_StartRx$qv");
	hAPI_RTKBT_StopTest		=	(API_RTKBT_StopTest)			GetProcAddress(hRTKBTPortModule,"@RTKBT_StopTest$qv");
	hAPI_RTKBT_SetTRxParameters = (API_RTKBT_SetTRxParameters)	GetProcAddress(hRTKBTPortModule,"@RTKBT_SetTRxParameters$q15_RTKBT_TRXPARAM");
	hAPI_RTKBT_ReadThermalMeter = (API_RTKBT_ReadThermalMeter)  GetProcAddress(hRTKBTPortModule,"@RTKBT_ReadThermalMeter$qv");
	hAPI_RTKBT_WriteReg = (API_RTKBT_WriteReg)	GetProcAddress(hRTKBTPortModule,"@RTKBT_WriteReg$quiuiuiui");
	hAPI_RTKBT_ReadReg = (API_RTKBT_ReadReg)  GetProcAddress(hRTKBTPortModule,"@RTKBT_ReadReg$quiuiui");
#else
	//RTLBTMPDLL  ,new Flow 
	hAPI_RTKBT_OpenAdapter	=	 (API_RTKBT_OpenAdapter)		GetProcAddress(hRTKBTPortModule,"RTKBT_OpenAdapter");
 	hAPI_RTKBT_CloseAdapter	=    (API_RTKBT_CloseAdapter)		GetProcAddress(hRTKBTPortModule,"RTKBT_CloseAdapter");
	hAPI_RTKBT_ShowUI		=    (API_RTKBT_ShowUI)				GetProcAddress(hRTKBTPortModule,"RTKBT_ShowUI");
	hAPI_RTKBT_GetLastError	=    (API_RTKBT_GetLastError)		GetProcAddress(hRTKBTPortModule,"RTKBT_GetLastError");
    hAPI_RTKBT_GetComHandle =    (API_RTKBT_GetComHandle)       GetProcAddress(hRTKBTPortModule,"RTKBT_GetComHandle");
	hAPI_RTKBT_GetStatistics=	(API_RTKBT_GetStatistics)		GetProcAddress(hRTKBTPortModule,"RTKBT_GetStatistics");
	hAPI_RTKBT_HCIReset		=	(API_RTKBT_HCIReset)			GetProcAddress(hRTKBTPortModule,"RTKBT_HCIReset");
	hAPI_RTKBT_BTTestMode	=	(API_RTKBT_BTTestMode)			GetProcAddress(hRTKBTPortModule,"RTKBT_BTTestMode");
	hAPI_RTKBT_StartPacketTx=	(API_RTKBT_StartPacketTx)		GetProcAddress(hRTKBTPortModule,"RTKBT_StartPacketTx");
	hAPI_RTKBT_StartContinueTx=	(API_RTKBT_StartContinueTx)		GetProcAddress(hRTKBTPortModule,"RTKBT_StartContinueTx");
	hAPI_RTKBT_StartRx		=	(API_RTKBT_StartRx)				GetProcAddress(hRTKBTPortModule,"RTKBT_StartRx");
	hAPI_RTKBT_StopTest		=	(API_RTKBT_StopTest)			GetProcAddress(hRTKBTPortModule,"RTKBT_StopTest");
	hAPI_RTKBT_SetTRxParameters = (API_RTKBT_SetTRxParameters)	GetProcAddress(hRTKBTPortModule,"RTKBT_SetTRxParameters");
	hAPI_RTKBT_ReadThermalMeter = (API_RTKBT_ReadThermalMeter)  GetProcAddress(hRTKBTPortModule,"RTKBT_ReadThermalMeter");
	hAPI_RTKBT_WriteReg = (API_RTKBT_WriteReg)	GetProcAddress(hRTKBTPortModule,"RTKBT_WriteReg");
	hAPI_RTKBT_ReadReg = (API_RTKBT_ReadReg)  GetProcAddress(hRTKBTPortModule,"RTKBT_ReadReg");
	hAPI_RTKBT_TxPowertoGainValue = (API_RTKBT_TxPowertoGainValue)GetProcAddress(hRTKBTPortModule,"RTKBT_TxPowertoGainValue");
#endif	
	if ((hAPI_RTKBT_OpenAdapter == NULL) || (hAPI_RTKBT_CloseAdapter == NULL)
		||(hAPI_RTKBT_ShowUI == NULL) || (hAPI_RTKBT_StartPacketTx == NULL)
		||(hAPI_RTKBT_GetComHandle == NULL) ||(hAPI_RTKBT_ReadThermalMeter == NULL)
		)
	{
			DBGPRINTF(">>Load DLL member Fail[1]..\n");
			return -1;
    }
	if ((hAPI_RTKBT_GetStatistics == NULL) || (hAPI_RTKBT_HCIReset == NULL)
		||(hAPI_RTKBT_BTTestMode == NULL) || (hAPI_RTKBT_GetLastError == NULL)
		||(hAPI_RTKBT_StartContinueTx == NULL) || (hAPI_RTKBT_StartRx == NULL)
	    ||(hAPI_RTKBT_StopTest == NULL) || (hAPI_RTKBT_SetTRxParameters == NULL)
		)
	{
			DBGPRINTF(">>Load DLL member Fail[2]..\n");
			return -1;
    }
	return 0;
}
void BT_ReleaseMP87XXDLL()
{
	DBGPRINTF("release MP87XXDLL\n");
	if (hRTKBTPortModule != NULL)
	{
		FreeLibrary(hRTKBTPortModule);
	}
		return ;

}
int main(int argc, char* argv[])
{
       int PortNumber=4;
		int Baudrate=115200;
		int item=0;
		int bflag=0;
		UINT32 Regtype=0;
		UINT32 RegReadValue=0,RegAddr=0,Regbitmask=0xFFFF;
	   
		int HOST=1;  //0:usb ,1:uart 2:filter uart
        DBGPRINTF("============ devcon rescan==========\n");
		ShellExecute(NULL, "open", "cmd.exe", "/c devcon rescan", NULL, SW_SHOWMINNOACTIVE) ;  
        DBGPRINTF("============ MP87XX Adapter Sample==========\n");
		if (BT_LoadMP87XXDLL() !=0)
		{
			goto exit;
		}
	    rtkbt_statistics.RxBits=0;
		rtkbt_statistics.ErrorBits=0;
		rtkbt_statistics.RxBER=0;			// in %
		rtkbt_statistics.RSSI=0;			//in dBm
		rtkbt_statistics.CFO=0;				//in KHz
		rtkbt_statistics.SignalQuality=0;
		rtkbt_statistics.TxBits=0;

        DBGPRINTF("*Please inpunt Host Type: 0 ->USB 1:UART 2:Filter Uart(default is USB):");
        scanf("%d",&HOST);

		switch (HOST)
		{
        default: 
		case 0:	
        DBGPRINTF(">>Use USB Interface ...\n");
        DBGPRINTF("*Please inpunt USB Port Number:");
        scanf("%d",&PortNumber);
		break;
        case 1:
		DBGPRINTF(">>Use UART Interface ...\n");
        DBGPRINTF("*Please inpunt UART Com Port Number:");
        scanf("%d",&PortNumber);
		DBGPRINTF("*Please inpunt Baudrate:");
        scanf("%d",&Baudrate);
		break;
		case 2:
			DBGPRINTF(">>Use Filter UART Interface ...\n");
		break; 	
		}
		t1=GetTickCount();
		if (hAPI_RTKBT_OpenAdapter(HOST,PortNumber,Baudrate))
		{
			t2=GetTickCount();

			DBGPRINTF(">>[HostType=%d]Open Device Succress..(Time=%d)\n",HOST,labs(t2-t1));
		}
		else
		{
			DBGPRINTF(">>[HostType=%d]Open Device Fail..\n",HOST);
			goto exit;
		}

		
	    while (!bflag)
		{
			DBGPRINTF("*Please inpunt Test Item:0:Exit 1:PKT TX 2:PKT RX 3:HCI Rest \n");
			DBGPRINTF("*		                4 RegRead------>>");
			scanf("%d",&item);
			switch (item)
			{
				case 1:BT_TX(); break;
                case 2:BT_RX(); break;
                case 3:BT_HCIReset(); break;
				case 0:bflag=1;	break;
                case 4: 


					    DBGPRINTF("*Please inpunt Reg Type(0:RF 1:MODEM 2:Global)HEX:");
						scanf("%x",&Regtype);
						fflush(stdin);

    				    DBGPRINTF("*Please inpunt Reg address(HEX):");
						scanf("%x",&RegAddr);
							fflush(stdin);
					    DBGPRINTF("*Please inpunt Reg Mask(HEX):");
						scanf("%x",&Regbitmask);
							fflush(stdin);
						RegReadValue=	hAPI_RTKBT_ReadReg(Regtype, RegAddr,Regbitmask);
						DBGPRINTF(">>Reg[%d]%x[0x%x]=%x\n",Regtype,RegAddr,Regbitmask,RegReadValue);
                break;
				default:
					DBGPRINTF(">> Error Select Test Item...\n");	
			}	
        }
		//close
		if (hAPI_RTKBT_CloseAdapter())
			DBGPRINTF(">>Close adapter Succress..\n"); 
		else

			DBGPRINTF(">>Close adapter Fail..\n");
exit:

    BT_ReleaseMP87XXDLL();
    DBGPRINTF("============ UART Open Adapter end========== \n");
	getch();
	return 0;
}

