//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <dbt>
#include <initguid.h>
#include <direct.h>
#include <stdio.h>
#include <time.h>


#include "FormMainUnit.h"
#include "FormBTRDUnit.h"
#include "rtkbtTrxThreadUnit.h"
#include "rtkbtTScriptThread.h"
#include <stdio.h>
#include "bt_mp_calibration_base.h"

#define                 OLD_ROM_VERSION  0x0c
#define                 NEW_ROM_VERSION  0x0d
//#define ACTS_BUMBLEBEE
//#define ACTS_BUMBLEBEE_UART
#define DISABLE_CAL_PAGE

#define DISABLE_RadioGroup_Thermal
//#define BBPRO_TEMP_READ_TX_INDEX

//#define BBPRO_RF_TOOL

//#define BBPro_newRom_Version       //BBPro_newRom_Version

/*///////////////////////////////////////////////////////////////////////*/


/*///////////////////////////////////////////////////////////////////////*/
extern "C"
{
        #include "bt_mp_dll_build.h"
        #include "RtlBluetoothMP.h"
       // #include "bt_Actsio.h"
}
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CGAUGES"
#pragma resource "*.dfm"
TForm_Main *Form_Main;

#define   DBG_ON

#ifdef DBG_ON

        void DBGPRINTF(char *prompt, ...)
        {
        char buf[16384];
        va_list argptr;
    //    int cnt;

        va_start(argptr, prompt);
        vsprintf(buf, prompt, argptr);
        OutputDebugString(buf);
        va_end(argptr);
        return ;
        }
#else
        void DBGPRINTF(char *prompt, ...)
        {
          return ;
        }
#endif


unsigned char TxGainTable[4][7]={
                                                {0x49,0x4d,0x69,0x89,0x8d,0xa9,0xa9},  //RTL8723A
                                                {0x49,0x4d,0x69,0x89,0x8d,0xa9,0xa9},  //RTL8723B
                                                {0x49,0x4d,0x69,0x89,0x8d,0xa9,0xa9},  //RTL8821A
                                                {0x49,0x4d,0x69,0x89,0x8d,0xa9,0xa9}   //RTL8761A
                };  //RTL8761 Table
unsigned char TxDACTable[4][5]={
                                                {0x10,0x11,0x12,0x13,0x14},   //RTL8723A
                                                {0x10,0x11,0x12,0x13,0x14},   //RTL8723B
                                                {0x10,0x11,0x12,0x13,0x14},   //RTL8821A
                                                {0x10,0x11,0x12,0x13,0x14}    //RTL8761A
                                                };

char InterFaceTypeDesc[][30] ={
	"USB" ,
	"COM UART",
	"Filter UART",
        "SDIO",
	"Adb for BT UART",
	"Adb for BT USB",
	"Socket for BT UART",
	"Socket for BT USB",
	"Bumble Bee USB",

};

#define InterFaceTypeDescNumber   9

#define VERSION_STR  ""


/*
//DEFINE_GUID( GUID_CLASS_USBHUB,    0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, \
//             0xa0, 0xc9, 0x06, 0xbe, 0xd8);
//DEFINE_GUID(GUID_CLASS_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, \
//             0xC0, 0x4F, 0xB9, 0x51, 0xED);


//HDEVNOTIFY      gNotifyDevHandle;
//HDEVNOTIFY      gNotifyHubHandle;
*/


int CFO_CALLBACK(BT_VERIFY_REPORT *pReport);


static void bt_mp_skip_blanks(char **p)
{
	while (**p == ' ')
		(*p)++;
}

static unsigned int string_to_num(char **p, int DefaultValue)
{
      //	unsigned char NegativeNum;
	unsigned int Value = 0;
	unsigned char   UseDefault;

    //	NegativeNum = 0;
	UseDefault = 1;
	bt_mp_skip_blanks(p);

	if(**p == '0' &&*(*p+1) == 'x')
	{
		(*p) = (*p)+2;

		while ( ((**p)<= '9' && (**p)>= '0') ||
			((**p)<= 'f' && (**p)>= 'a') ||
			((**p)<= 'F' && (**p)>= 'A') )
		{
			if (**p >= 'a')
	 			Value = Value * 16 + (**p) - 'a' + 10;
			else if (**p >= 'A')
				Value = Value * 16 + (**p) - 'A' + 10;
			else
				Value = Value * 16 + (**p) - '0';

			UseDefault = 0;
			(*p)++;
		}
	}
	else if ( (**p) == '-')
	{
		(*p)++;
	
		while ( ((**p)<= '9' && (**p)>= '0') )
		{
			Value = Value * 10 + (**p) - '0';
			UseDefault = 0;
			(*p)++;
		}

		Value = (-1)*Value;
	}
	else
	{
		while ( ((**p)<= '9' && (**p)>= '0') )
		{
			Value = Value * 10 + (**p) - '0';
			UseDefault = 0;
			(*p)++;
		}
	
	}

	if(UseDefault)
		return DefaultValue;
	else
		return Value;
}


void TForm_Main::MSGPRINTF(String dstr)
{
	Memo_msg->Lines->Add(dstr);
	return;
}


#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 2048

int TForm_Main::DetectAttachedPorts()
{
	HKEY hKey;
	LONG retCode;
	String dstr;
	unsigned int ComNo;

	Cbx_Interface_port->Items->Clear();

	retCode = RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,
		_T("HARDWARE\\DEVICEMAP\\SerialComm"),
		0,
		KEY_READ,
		&hKey);
	if (retCode == ERROR_SUCCESS)
	{
		DWORD    cSubKeys = 0;            // number of subkeys
		DWORD    cValues;				  // number of values for key

		retCode = RegQueryInfoKey(
			hKey,					// hKey: key handle
			NULL,					// lpClass: A pointer to a buffer that receives the user-defined class of the key
			NULL,					// lpcClass: A pointer to a variable that specifies the size of the buffer pointed to by the lpClass
			NULL,					// reserved
			&cSubKeys,				// lpcSubKeys: number of subkeys
			NULL,					// lpcMaxSubKeyLen: longest subkey size
			NULL,					// lpcMaxClassLen: longest class string
			&cValues,				// lpcValues: number of values for this key
			NULL,					// lpcMaxValueNameLen: longest key value name
			NULL,					// lpcMaxValueLen: longest key value data
			NULL,					// security descriptor
			NULL);					// last write time
		if (retCode != ERROR_SUCCESS)
		{
			dstr.sprintf("DetectAttachedPorts: RegQueryInfoKey failed, retCode %d\n", retCode);
			Memo_msg->Lines->Add(dstr);
			return 0;
		}
		//else
		//{
			//dstr.sprintf("DetectAttachedPorts: subkeys number: %d, key values num %d\n", cSubKeys, cValues);
			//Memo_msg->Lines->Add(dstr);
		//}

		// Enumerate the key values. 
		if (cValues)
		{
			TCHAR  achValue[MAX_VALUE_NAME];
			DWORD cchValue = MAX_VALUE_NAME;
			DWORD lpType = 0;
			BYTE lpData[MAX_VALUE_NAME];
			char *p;
			DWORD lpcbData = MAX_VALUE_NAME;

			for (DWORD i = 0, retCode = ERROR_SUCCESS; i < cValues; i++)
			{
				cchValue = MAX_VALUE_NAME;
				achValue[0] = '\0';
				lpcbData = MAX_VALUE_NAME;

				retCode = RegEnumValue(hKey, i,
					achValue,
					&cchValue,
					NULL,
					&lpType,
					lpData,
					&lpcbData);
				if (retCode == ERROR_SUCCESS)
				{
					dstr.sprintf("DetectAttachedPorts: (%d) %s\n",  i, (LPTSTR)lpData);
					Memo_msg->Lines->Add(dstr);

					if( (lpData[0]=='C') && (lpData[1]=='O') && (lpData[2]=='M') )
					{
						p = lpData+3;
						ComNo = string_to_num( &p, 0);
						dstr.sprintf("%d",  ComNo);
						
						Cbx_Interface_port->Items->Add(dstr);
					}
					
				}
			}
		} // cValues

	}

	Cbx_Interface_port->ItemIndex=0;

	return 0;
}




int __fastcall TForm_Main::DeviceChgMsg(TMessage &Message)
{
	switch (Message.WParam) 
	{
		case DBT_DEVICEARRIVAL:
			//Memo_msg->Lines->Add("新插入了一項裝置!");
			DetectAttachedPorts();
			//Button_DetectedModulePortNumClick(NULL);
		break;
		 
		case DBT_DEVICEREMOVECOMPLETE:
			DetectAttachedPorts();
			//Memo_msg->Lines->Add("卸除了一項裝置!");
			//Button_DetectedModulePortNumClick(NULL);
		break;
		 
		//case DBT_DEVNODES_CHANGED:
		//	Memo_msg->Lines->Add("DBT_DEVNODES_CHANGED");
		//break;
	}
	return 0;
}


__fastcall TForm_Main::TForm_Main(TComponent* Owner)
        : TForm(Owner)
{
	HFONT hFont;
	HIMAGELIST himl;
	HICON hicon;
	DEV_BROADCAST_DEVICEINTERFACE broadcastInterface;

        TObject *Sender;
	String dstr;
        Xtal_tracking_function_Support=0;
	int n=0;

	float AntennaGain;
        //---------------------------------------------------//
        FormBTDebug_flag=0;
         TabSheet_TXTALCAL->TabVisible = false;
                 //basic fuction
	bt_debug_Open= NULL;
	bt_debug_Send=NULL;
	bt_debug_Recv=NULL;
	bt_debug_Close=NULL;
	bt_debug_WaitMs=NULL;
        FormBTDebug_flag=0;
        TabSheet_ThermalPowerTrackingDebug->TabVisible = false;
        GroupBox_LBT->Visible=false;
        GroupBox_PowerCtrl->Visible=false;
        GroupBox_BLE2M->Visible=false;

	GroupBox_Show->Visible=false;
       TabSheet_CFO->TabVisible= false;
	ShowUI=NULL;
      //  Form_Main->Caption = 
	UI_Init();
	//dll object
	pBaseDLLObject = NULL;
	//module
	pBluetoothModule=NULL;
	pBaseInterface=NULL;

	//pBluetoothModule=&BluetoothModuleMemory;
	//pBaseInterface=&BaseInterfaceModuleMemory;

	//UI
        TabSheet_FLASHDLL->TabVisible = false;
	Cbx_Interface->Items->Clear();
	for (n =0 ; n< LEN_4_BYTE; n++ )
	{
		dstr.sprintf("%s",InterFaceTypeDesc[n]);
		Cbx_Interface->Items->Add(dstr);

	}
	Cbx_Interface_port->Visible=true;
	Cbx_Interface_baudrate->Visible=false;
	Thread_TRX=NULL;
	Cbx_Actionexec->ItemIndex=0;
	Cbx_PayloadType->ItemIndex=0;
	Cbx_PktType->ItemIndex=0;
	Cbx_NoLink_Ch->ItemIndex=0;
	Cbx_Hopping_PktType->ItemIndex = 0;

	Cbx_Interface_port->ItemIndex=4;
	Cbx_Interface->ItemIndex=1;
	ComboBox_LeTest_Action->ItemIndex = 0;

	CheckBox_Fw_TxRx_Mode->Enabled = false;

	Btn_Dev_Close->Enabled=false;
        CreatsButtonArray();
        CreatsXtalCATArray();
        GetExeDllVersionInfo();
        dstr.sprintf("Bluetooth RF Test Tool (%s)",show_versiom);
        Form_Main->Caption = dstr;
   //     Form_Main->Icon->lo
        Page_function->ActivePage = TabSheet_NONLINK;


        Cbx_RTL8761_XTAL->Visible=true;
        Label1_CFOResult->Visible=false;
        Application->Title = "Realtek Bluetooth RF Test Tool";



        LBT_TabSheet->TabVisible = false;


#ifdef ACTS_BUMBLEBEE
       Application->Title = "Bluetooth Test Tool"  ;
       Application->Icon->LoadFromFile("acts_logo_24.ico");
       CheckBox_VERIFYTX->Enabled=false;
       CheckBox_VERIFYRX->Enabled=false;
        TabSheet_Efuse->TabVisible=false;
        TabSheet_LETest->TabVisible=true;

       // Cbx_Interface->Enabled=false;
       Form_Main->Width += 20;
       Cbx_Interface->Items->Clear();
       Cbx_Interface->Items->Add("BT ONLY UART");
       Cbx_Interface->Items->Add("ACT MP USB");
       Cbx_Interface->ItemIndex=1;
     //  Cbx_InterfaceChange(Sender);
   //    Page_function->ActivePage = TabSheet_CFO;
       Page_functionChange(Sender);
       Image1->AutoSize=true;
       Image1->Picture->LoadFromFile("acts.JPG");
       Image1->Left = Image1->Left+80;
    //   Btn_Dev_Open->Left =Btn_Dev_Open->Left -200;
    //   Btn_Dev_Close->Left=Btn_Dev_Close->Left-200;
     //  Cb_downloadpatch->Left=Cb_downloadpatch->Left-200;
    //   Image1->Height =Image1->Height =
     //  GroupBox3->Width = GroupBox3->Width -200;
       Form_Main->Icon->LoadFromFile("acts_logo_16.ico");
       FWExeJobMode1->Checked=false;
       isOnly_BLE=0;

       BitBtn_TRXReadThermal->Visible=false;
       TabSheet_CFO->TabVisible= true;
Label_VERIFY_TX->Visible=false;
Label_VERIFY_RX->Visible=false;
CheckBox_VERIFYTX->Visible=false;
CheckBox_VERIFYRX->Visible=false;
Label1_CFOResult->Visible=true;
Label1_CFOResult->Caption="Ready....";
PageControl5->Visible=false;
 DebugCFOUI();
 Form_Main->Width = Memo_msg->Left+Memo_msg->Width+10;
 Form_Main->Height= Form_Main->Height +15;

  TabSheet_Cal->TabVisible=false;
  TabSheet_DAC->TabVisible=false;


#endif



#ifdef DISABLE_CAL_PAGE
       TabSheet_CFO->TabVisible= false;
#else
       TabSheet_CFO->TabVisible= true;
#endif

Edit_PktHeader->Enabled=false;
Label_VERIFY_TX->Visible=false;
Label_VERIFY_RX->Visible=false;
CheckBox_VERIFYTX->Visible=false;
CheckBox_VERIFYRX->Visible=false;
Label1_CFOResult->Visible=true;
Label1_CFOResult->Caption="Ready....";


Cbx_InterfaceChange(Sender);
api_tcpip_bt_mp_InitDefaultParameter();

	ComboBox_HitAddr->ItemIndex =1;
	Cbx_PayloadType->ItemIndex =7;
	ComboBox_MPDebugReportChange(Sender);
	TabSheet_Efuse->TabVisible = false;
	TabSheet_MPDebug->TabVisible = false;
        TabSheet_40MCal->TabVisible = false;
        TabSheet_Efuse_Map->TabVisible = false;


	//BBpro
	TabSheet_Cal->TabVisible = false;
	TabSheet_DAC->TabVisible = false;
	TabSheet_RW->TabVisible = false;
	TabSheet_Hopping->TabVisible = true;
	TabSheet_Ant_Info->TabVisible = false;
        LBT_TabSheet->TabVisible = false;
	TabSheet_BBPro_BatteryResistanceCal->TabVisible = false;





        Cb_downloadpatch->Visible=false;
        Cb_ConfigFile->Visible=false;
        TabSheet_BBProFlash->TabVisible =false;


	 BitBtn_Patch->Visible = false;
	BitBtn_GetChipInfo->Visible = false;
	ComboBox_PHY_STATUS->Visible = false;
	Button_GetBTStage->Visible = false;
	Btn_LoadScript->Visible = false;
	BitBtn_TRXReadThermal->Visible = false;
	Button_ReadBDAddr->Visible = false;
	BitBtn_ShowTxPower->Visible = false;
	Button_GetPowerTracking->Visible = false;
	Button_SetPowerTracking->Visible = false;
	RadioGroup_PowerTracking->Visible = false;
	ComboBox_LeTest_TxGainIndex->Enabled = true;
	CheckBox_EnableTxDac->Visible = false;
	StaticText8->Visible = false;
	BitBtn1->Visible = false;
        BitBtnSetBQBUART->Visible = false;

	ComboBox_AdaptivityAntennaGain->Items->Clear();
	for (AntennaGain=-10; AntennaGain<=6; AntennaGain+=0.5)
	{
		dstr.sprintf("%.1f dBi",AntennaGain);
		ComboBox_AdaptivityAntennaGain->Items->Add(dstr);
	}
	ComboBox_AdaptivityAntennaGain->Items->Add("No Used");
	ComboBox_AdaptivityAntennaGain->ItemIndex = 20;

	ComboBox_BREDRPowerControlLevelNumberChange(NULL);


	DetectAttachedPorts();	

	Cbx_Hopping_PktTypeChange(NULL);

        // Create Worker Thread.
        pWorkerThread = new WorkerThread(false);
        if (pWorkerThread == NULL)
        {
                ShowMessage("Create Bee Worker Thread Failed.");
                Application->Terminate();
                return;
        }
        else
        {
                dwThreadId = pWorkerThread->ThreadID;
        }	
	

#if 0
	// Register to receive notification when a USB device is plugged in.
	broadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	broadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;

	memcpy( &(broadcastInterface.dbcc_classguid),
			&(GUID_CLASS_USB_DEVICE),
			sizeof(struct _GUID));

	gNotifyDevHandle = RegisterDeviceNotification(Handle,
										&broadcastInterface,
										DEVICE_NOTIFY_WINDOW_HANDLE);

	// Now register for Hub notifications.
	memcpy( &(broadcastInterface.dbcc_classguid),
				&(GUID_CLASS_USBHUB),
				sizeof(struct _GUID));

#endif

#if 0
	TabSheet_NONLINK->TabVisible= false;
	TabSheet_Hopping->TabVisible= false;
	TabSheet_RW->TabVisible= false;
	TabSheet_LED->TabVisible= false;
	TabSheet_CFO->TabVisible= false;
	TabSheet_PhysicalEfuse->TabVisible= false;
#endif
                GroupBox_TXLevel->Visible=false;
         return ;
}



void TForm_Main::UI_Clear_TXReport(int Tx_Rx)
{
	int n=0;
	if ((Tx_Rx ==0) || (Tx_Rx >2))
	{
		StringGrid_TXReport->ColCount=2;
		StringGrid_TXReport->RowCount=3;

		for (n=0;n<StringGrid_TXReport->RowCount;n++)
			StringGrid_TXReport->RowHeights[n]=15;

		StringGrid_TXReport->Cells[0][0] = "Item";
		StringGrid_TXReport->Cells[1][0] = "Value";
		StringGrid_TXReport->Cells[0][1] = "Tx bits";
		StringGrid_TXReport->Cells[0][2] = "Tx Pkt Count";
		StringGrid_TXReport->ColWidths[0]=100;
		StringGrid_TXReport->ColWidths[1]=StringGrid_TXReport->Width- StringGrid_TXReport->ColWidths[0];

		StringGrid_TXReport->Cells[1][1]="000000";  //tx bits
		StringGrid_TXReport->Cells[1][2]="000000" ; //Tx Pkt Count
	}

	if ((Tx_Rx ==1) || (Tx_Rx >2))
	{
		StringGrid_RXReport->ColCount=2;
		StringGrid_RXReport->RowCount=7;
		StringGrid_RXReport->Cells[0][0] = "Item";
		StringGrid_RXReport->Cells[1][0] = "Value";

		StringGrid_RXReport->Cells[0][1] = "Rssi";
		StringGrid_RXReport->Cells[0][2] = "Rx bits";
		StringGrid_RXReport->Cells[0][3] = "Rx Error bits";
		StringGrid_RXReport->Cells[0][4] = "Rx Pkt Count";
		StringGrid_RXReport->Cells[0][5] = "ber";
		StringGrid_RXReport->Cells[0][6] = "cfo";

		StringGrid_RXReport->ColWidths[0]=100;
		StringGrid_RXReport->ColWidths[1]=StringGrid_TXReport->Width- StringGrid_TXReport->ColWidths[0];

		StringGrid_RXReport->Cells[1][1]="-90";     //Rssi
		StringGrid_RXReport->Cells[1][2]="000000" ; //Rx bits
		StringGrid_RXReport->Cells[1][3]="000000";  //Rx Error bits
		StringGrid_RXReport->Cells[1][4]="000000" ; //Rx Pkt Count
		StringGrid_RXReport->Cells[1][5]="000000";  //ber
		StringGrid_RXReport->Cells[1][6]="0";  //cfo
        
		for (n=0;n<StringGrid_RXReport->RowCount;n++)
			StringGrid_RXReport->RowHeights[n]=15;
	}
	return ;
}



void TForm_Main::UI_Init()
{
	int n=0;
	int i;
	
	String dstr;
	// channel
	Cbx_NoLink_Ch->Items->Clear();
	for (n=0;n<79;n++)
	{
		dstr.sprintf("%d",n);
		Cbx_NoLink_Ch->Items->Add(dstr);
	}
	Cbx_NoLink_Ch->ItemIndex=0;
	//-------------------------------
        //hopping page

       //	ComboBox_Hopping_PayloadType->Visible =true;
      //	ComboBox_Hopping_TxGainIndex->Visible=true;
      //	Edit_Hopping_TxGainValue->Visible=true;
      //	ComboBox_Hopping_TxDac->Visible=true;
     //	Cbx_TxDacIndex->Visible = false;

	ComboBox_Hopping_PayloadType->Enabled=false;
	ComboBox_Hopping_TxGainIndex->Enabled=false;
	Edit_Hopping_TxGainValue->Enabled=false;
	ComboBox_Hopping_TxDac->Enabled=false;
	Cbx_TxDacIndex->Enabled = false;
      //  Ckb_Whitening->Enabled=false;

	//port
	Cbx_Interface_port->Items->Clear();
	for (n=0;n<10;n++)
	{
		dstr.sprintf("%d",n);
		Cbx_Interface_port->Items->Add(dstr);
	}

	//Barudate
	Cbx_Interface_baudrate->ItemIndex=1;

	//TStringGrid *StringGrid_RXReport;
	//TStringGrid *StringGrid_TXReport;


	//report
	//==================================================================
	UI_Clear_TXReport(3);


	PageControl2->ActivePage= TabSheet_Para1;
	PageControl_Report->ActivePage= TabSheet_TXReport;


	ComboBox_LeTest_Channel->Items->Clear();
	for (i=0; i<=39; i++)
	{
		dstr.sprintf("%d",i);
		ComboBox_LeTest_Channel->Items->Add(dstr);
                ComboBox_LESingleTone_Ch->Items->Add(dstr);
	}
        ComboBox_LESingleTone_Ch->ItemIndex = 0;
	ComboBox_LeTest_Channel->ItemIndex = 0;
	ComboBox_LeTest_PayloadType->ItemIndex = 0;
	Edit_LeTest_RxCount->Enabled = false;



	ComboBox_LedNo->Items->Clear();
	ComboBox_LedLevel->Items->Clear();

	for( i=0; i<2; i++)
	{
		dstr.sprintf("%d",i);
		ComboBox_LedNo->Items->Add(dstr);
	}


	dstr.sprintf("0 : output low ");	
	ComboBox_LedLevel->Items->Add(dstr);
	dstr.sprintf("1 : output high ");	
	ComboBox_LedLevel->Items->Add(dstr);
	dstr.sprintf("2 : output Hi-Z or input  ");	
	ComboBox_LedLevel->Items->Add(dstr);

	ComboBox_LedNo->ItemIndex = 0;
	ComboBox_LedLevel->ItemIndex = 0;
	
	return ;
}



int TForm_Main::API_bt_LoadMpDll()
{
	// load dll
	pBaseDLLObject = &mBaseDLLObject;
#ifdef ACTS_BUMBLEBEE
	if (BuildBTMPDLLObject(pBaseDLLObject,NULL,1)!=0)
		return -1;
#else
	if (BuildBTMPDLLObject(pBaseDLLObject,NULL,0)!=0)
		return -1;
#endif
	return 0;
}



void TForm_Main::API_bt_releaseMpDll()
{
       if (!FormBTDebug_flag)
	ReleaseBTPMPDLLObject(pBaseDLLObject);

	return;
}



int TForm_Main::API_bt_inface(int interface_type,int PortNo,int Baudrate, unsigned char *pData)
{
	int rtn=0;


        if ((FormBTDebug_flag) &&
                (bt_debug_Open != NULL )
	        &&(bt_debug_Send !=NULL)
	        &&(bt_debug_Recv !=NULL)
	        &&(bt_debug_Close!=NULL)
	        &&(bt_debug_WaitMs!=NULL))
        {
            	rtn=pBaseDLLObject->BTMPAPI_BuildInterfaceVendor(
			&pBaseInterface,
			&BaseInterfaceModuleMemory,
	                //Parmater
	                0,
	                1,
	                115200,
	                NULL,
	                //basic fuction
	                bt_debug_Open,
	                bt_debug_Send,
	                bt_debug_Recv,
	                bt_debug_Close,
	                bt_debug_WaitMs

                );
        }
        else
        {
	rtn=pBaseDLLObject->BTMPAPI_BuildInterfaceRTK(
			&pBaseInterface,
			&BaseInterfaceModuleMemory,
			interface_type,
			PortNo,
			(unsigned long)Baudrate,
			pData
			);
        }
	if (rtn != 0)
		goto exit;

	if (pBaseInterface == NULL)
	{
 		rtn = -1;
		goto exit;
	}
	pBluetoothModule=&BluetoothModuleMemory;
	pBluetoothModule->BuildStatus=0;
	if (pBaseDLLObject->BTMPAPI_BuildBluetoothModule(
			&BluetoothModuleMemory,
			pBaseInterface,
			NULL,
			TxGainTable[3],
			TxDACTable[3]) !=0
			)
	{
		rtn = -1;
		goto exit;
	}


	if (pBluetoothModule->BuildStatus ==0)
		rtn = -1;
	
exit:           
	return rtn;
}



void __fastcall TForm_Main::FormClose(TObject *Sender,
      TCloseAction &Action)
{ 

	Btn_Dev_CloseClick(Sender);

      API_bt_releaseMpDll();

	return;
}
//---------------------------------------------------------------------------
int TForm_Main::API_ReadCurrentTxDacValue(unsigned char  *TxDacValue)
{
	String dstr,msg;
	unsigned long  TxDac=0;
	msg.sprintf(">>To updat current tx dac GUI Value...\n");
	if (pBluetoothModule->GetMdRegMaskBits(pBluetoothModule,0x38,7,3,&TxDac) !=0)
	{
		msg.sprintf(">>Read tx dac current value error..!!\n");
		//    ShowMessage(msg);
		return -1;
	}
	dstr.sprintf("0x%x",TxDac);
	Cbx_TxDacIndex->Text = dstr;
	ComboBox_Hopping_TxDac->Text=dstr;
	msg.sprintf(">>Read Tx dac current value = 0x%x!!\n",TxDac);
	Memo_msg->Lines->Add(msg);
	*TxDacValue = TxDac;
	return 0;

}

#define MAX_DESC_SIZE 50
typedef struct BT_DEF_TX_POWER_INDEX_STRUCT{
	char Desc[MAX_DESC_SIZE];
	int  Index_USB_PCIE;
	int  Index_UART;
}BT_DEF_TX_POWER_INDEX_STRUCT,*pBT_DEF_TX_POWER_INDEX_STRUCT;

void TForm_Main::API_bt_GetBTDefaultTxPower(unsigned int ChipType,int *Power_Inde)
{
	int Index = 0xFF;

	BT_DEF_TX_POWER_INDEX_STRUCT BT_DEF_TX_POWER_INDEX [NumOfRTKCHID]=
	{
		//Name                  USB/PCIE  ,UART
		{"RTK_BT_CHIP_ID_RTL8723A",6,6},
		{"RTK_BT_CHIP_ID_RTL8723B",6,4},
		{"RTK_BT_CHIP_ID_RTL8821A",7,7},
		{"RTK_BT_CHIP_ID_RTL8761A",6,6},
		{"RTK_BT_CHIP_ID_RTL8703A",6,6},
		{"RTK_BT_CHIP_ID_RTL8763A",6,6},
		{"RTK_BT_CHIP_ID_RTL8703B",6,6},
		{"RTK_BT_CHIP_ID_RTL8723C",6,6},
		{"RTK_BT_CHIP_ID_RTL8822B",6,6},
		{"RTK_BT_CHIP_ID_RTL8723D",6,6},
	};
   /////
    FILE *pf=NULL;

    pf = fopen("BTPowerIndex.ini", "r+");
    if (pf != NULL)
    {
        char sline[256],tmp1[256],tmp2[256],tmp3[256];
        String stmp1,stmp2,stmp3,stmp0;
        int n=0;

        while(1)
        {
          ZeroMemory(sline, sizeof(sline));
          ZeroMemory(tmp1, sizeof(tmp1));
          ZeroMemory(tmp2, sizeof(tmp2));
          ZeroMemory(tmp3, sizeof(tmp3));
           if(feof(pf))
                break;

          fgets(sline, 256, pf);
          if ( (sline[0] != '/') && (sline[1] != '/') && (sline[0] != NULL) && (sline[0] != '\n') )
          {

              sscanf(sline, "%s %s %s", tmp1, tmp2 ,tmp3);
              //Desc
              stmp1.sprintf("%s", tmp1);
              stmp1=stmp1.LowerCase();
              //usb/pcie
              if ((tmp2[0] == '/') &&  (tmp2[1] == '/'))
              stmp2.sprintf("6");
              else
              stmp2.sprintf("%s", tmp2);
              //uart
              if ((tmp3[0] == '/') &&  (tmp3[1] == '/'))
              stmp3.sprintf("6");
              else
              stmp3.sprintf("%s", tmp3);

              for (n=0;n<NumOfRTKCHID;n++)
              {
                 stmp0.sprintf("%s",BT_DEF_TX_POWER_INDEX[n].Desc);
                 stmp0=stmp0.LowerCase();
                 if (stmp0 == stmp1)
                 {
                    BT_DEF_TX_POWER_INDEX[n].Index_USB_PCIE = stmp2.ToInt();
                    BT_DEF_TX_POWER_INDEX[n].Index_UART=stmp3.ToInt();
                    break;
                 }
              }//end for (n=0;n<NumOfRTKCHID;n++)

          }//end  if ( (sline[0] != '/') && (sline[1] != '/') && (sline[0] != NULL) && (sline[0] != '\n') )
        }
       fclose(pf);
    }

    if (ChipType == RTK_BT_CHIP_ID_UNKNOWCHIP)
    {
        return ;
    }

    if (InterfaceType ==  TYPE_UART)
        Index = BT_DEF_TX_POWER_INDEX[ChipType].Index_UART;
    else
        Index = BT_DEF_TX_POWER_INDEX[ChipType].Index_USB_PCIE;//And SDIO

     if ((Index < 7) &&  (Power_Inde != NULL ))
     {
        *Power_Inde =  Index;
     }


     return ;

}


int TForm_Main::OpenDevice()
{
	BT_PARAMETER *pParam=&mBT_PARAMETER;	
	int  PortNo;
	int  Baudrate=115200;
	unsigned int ChipType=0xFF;
	int BarudRate_Arrary[]={9600,115200,921600,1500000,2000000,3000000,4000000};
	int i;
	int rtn=-1;
        String subStr;

	int Power_Index=0xFF;
	String dstr;
	unsigned char pData[MAX_DATA_LEN]; 

	if(Cbx_Interface->Text == "Adb for BT UART")//"Adb for BT UART"
	{
		AnsiString Str = Cbx_Interface_port->Text;
		memset(pData, 0, MAX_DATA_LEN);
		strcpy(pData, Str.c_str());	
	}
	else 
	{
		PortNo=StrToInt(Cbx_Interface_port->Text);
		
		AnsiString Str = Edit_Ip_Addr->Text;
		memset(pData, 0, MAX_DATA_LEN);
		strcpy(pData, Str.c_str());
	}

	Btn_Dev_Open->Enabled=false;
        	
	GroupBox_Show->Visible=true;
	Panel_LED->Color=clRed;
	Panel_LED->Caption="X";
	if (ShowUI != NULL)
	{
             ShowUI->Terminate();
             ShowUI =NULL;
	}
	ShowUI =  new SowObject(true);
	ShowUI->SetMode(0);
	switch (InterfaceType)
	{
			case 0:  ShowUI->SetTimeOutTime(1000,100);   break;
			case 1:  ShowUI->SetTimeOutTime(2500,250);     break;
                        case 2:  ShowUI->SetTimeOutTime(2500,250);     break ;
			case 3:  ShowUI->SetTimeOutTime(1000,100);   break;
			case 4:  ShowUI->SetTimeOutTime(4000,400);    break;
			case 5:  ShowUI->SetTimeOutTime(4000,400);   break;
			default:
			ShowUI->SetTimeOutTime(3000,300);
	}
	// ShowUI->SetPara(5);
	ShowUI->Priority = tpNormal;
	ShowUI->Resume();

        subStr=   Cbx_Interface_baudrate->Text.SubString(0,8);
        if (subStr == "Baudrate")
        {
	        Baudrate=BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
        }
        else
        {
          Baudrate= StrToInt(Cbx_Interface_baudrate->Text);
        }

	if (API_bt_inface(InterfaceType,PortNo,Baudrate,pData) !=0)
	{
		Memo_msg->Lines->Add(">>Build interface Fail...");
		goto exit;
	}
	
	if(pBaseInterface->Open(pBaseInterface)!=0)
	{
		Memo_msg->Lines->Add("Open device Fail...");
		goto exit;
	}

	Memo_msg->Lines->Add(">>Open device Success...");

	if (Cb_downloadpatch->Checked && (Cb_downloadpatch->Visible==true) )
	{//download patch code

		if (API_bt_Download_PatchCode(1,NULL) !=0)
		{
			Memo_msg->Lines->Add(">>Download MP patch code  Fail...");
		}
		else
		{
			Memo_msg->Lines->Add(">>Download patch code  Success...");
		}
	}
	Sleep(100);
	if (API_bt_GetChipInfo(&ChipType) !=0)
	{
		Memo_msg->Lines->Add(">>Get Chip info error!!");
	}
	else
	{
		API_bt_GetBTDefaultTxPower(ChipType,&Power_Index);
		if (Power_Index < 7)
		{
			dstr.sprintf("%d", Power_Index);
			Cbx_TxGainIndex->Text = dstr;
			Cbx_TxGainIndex->Update();
			//if (!EnableControlBTTxPowerIndex1->Checked)
				//Cbx_TxGainIndex->Enabled=false;
			dstr.sprintf(">>BT Default Power Index = %d ",Power_Index);
			Memo_msg->Lines->Add(dstr);
		}
	}

	Panel_LED->Color=clLime;
	Panel_LED->Caption="O";

	pParam->ParameterIndex= SET_DEFAULT_TX_GAIN_TABLE;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	pBluetoothModule->ActionControlExcute(pBluetoothModule);

	pBluetoothModule->ActionReport(pBluetoothModule,REPORT_TX_GAIN_TABLE, &mBT_DEVICE_REPORT);

	ComboBox_LeTest_TxGainIndex->Text = "6";

        //to updat current tx dac GUI Value
         if(mBT_CHIPINFO.ChipType == RTK_BT_CHIP_ID_RTL8761A)
        {
                unsigned char  TxDacValue=0;
                API_ReadCurrentTxDacValue( &TxDacValue);
        }
        rtn=0;
 exit:
	GroupBox_Show->Visible=false;
 	Btn_Dev_Close->Enabled=true;

	delete ShowUI;
	ShowUI =NULL;

	return rtn;
}

//#define HCI_VENDOR_READ_RTK_CHIP_ID 0xFC6F
void TForm_Main::MPFunctionShow(int chipID)
{
        switch (chipID)
        {
                case RTK_BT_CHIP_ID_RTL8761A:
                break;

        }
        return ;
}
void __fastcall TForm_Main::Btn_Dev_OpenClick(TObject *Sender)
{


	unsigned char TxDacValue;
	int  PortNo;
	int  Baudrate=115200;
	int BarudRate_Arrary[]={9600,115200,921600,1500000,2000000,3000000,4000000};
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;
	int i;
	String dstr;
        String subStr;
	unsigned long data;

	unsigned char pData[512];
	unsigned char pEvtBuf[512];
	
        ReadTmeter1->Checked= false;

        Page_function->ActivePage=TabSheet_NONLINK;
        //defult 
	TabSheet_BBProFlash->TabVisible=false;

	if(Cbx_Interface->Text == "Adb for BT UART")//"Adb for BT UART"
	{
		AnsiString Str = Cbx_Interface_port->Text;
		memset(pData, 0, MAX_DATA_LEN);
		strcpy(pData, Str.c_str());	
	}
	else 
	{
                if (Cbx_Interface_port->Text.Length()>0)
                {
		        PortNo=StrToInt(Cbx_Interface_port->Text);
		}
                else
                {
                    PortNo =0;
                }
		AnsiString Str = Edit_Ip_Addr->Text;
		memset(pData, 0, MAX_DATA_LEN);
		strcpy(pData, Str.c_str());
	}

	Cbx_TxGainIndex->Text  = "6";
	Btn_Dev_Open->Enabled=false;
        	
	GroupBox_Show->Visible=true;
	Panel_LED->Color=clRed;
	Panel_LED->Caption="X";
	if (ShowUI != NULL)
	{
		ShowUI->Terminate();
		ShowUI =NULL;
	}
	ShowUI =  new SowObject(true);
	ShowUI->SetMode(0);
	switch (InterfaceType)
	{
		case 0:  ShowUI->SetTimeOutTime(4000,50);   break;    //"USB"
		case 1:  ShowUI->SetTimeOutTime(5500,100);     break;  //"COM UART",
		case 2:  ShowUI->SetTimeOutTime(30000,500);   break;    //"SDIO",
                case 3:                                                       //"Filter UART",
 		case 4:  ShowUI->SetTimeOutTime(6000,100);    break;   //
		case 5:  ShowUI->SetTimeOutTime(5000,100);   break;
		default:
			ShowUI->SetTimeOutTime(5000,100);
	}
	// ShowUI->SetPara(5);
	ShowUI->Priority = tpNormal;
	ShowUI->Resume();
        subStr=   Cbx_Interface_baudrate->Text.SubString(0,8);
        if (subStr == "Baudrate")
        {
	        Baudrate=BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
        }
        else
        {
          Baudrate= StrToInt(Cbx_Interface_baudrate->Text);
        }
        if ((ComboBox_KeyWord->ItemIndex == 1) || (ComboBox_KeyWord->ItemIndex == 2))     //Ameba Z/Ameba D
        {
             int Enter1_Leave2 =1;
             int chip_type = RTK_BT_CHIP_ID_AMEBAD;
             int end_need_close =1;
             int Delay = 1000* ComboBox_DelayTime->ItemIndex;
             if (ComboBox_KeyWord->ItemIndex == 1)
             chip_type =RTK_BT_CHIP_ID_AMEBAD ;//  =15,
             else
             chip_type=RTK_BT_CHIP_ID_AMEBAZII;// 16,

             //Btn_Dev_CloseClick(Sender);
        //     pBaseDLLObject->ExternFunctionRTK
             if (pBaseDLLObject->ExternFunctionRTK != NULL)
             {
             int keyWord_rtn= pBaseDLLObject->ExternFunctionRTK(
	        chip_type,
	        Enter1_Leave2,
	        NULL,
	        NULL,//BASE_INTERFACE_MODULE *pBaseInterfaceModuleMemory,
	        InterfaceType,
	        PortNo,
	        Baudrate,
	        NULL,//unsigned char *pWriting,
	        NULL,//unsigned char *pReading,
	        1, //YES , CHECK
                NULL,      // extern data
	        end_need_close,    //need close
                Delay ) ;

                if (keyWord_rtn !=0 )
                {
                   	Memo_msg->Lines->Add(">>Send key string Faid!! exit tool.");
		        goto exit;
                }

             }
        }



	if (API_bt_inface(InterfaceType,PortNo,Baudrate,pData) !=0)
	{
		Memo_msg->Lines->Add(">>Build interface Fail...");
		goto exit;
	}
     //   pBaseInterface->
	if(pBaseInterface->Open(pBaseInterface)!=0)
	{
		Memo_msg->Lines->Add(">>Open device Fail...");
		goto exit;
	}
	
        Memo_msg->Lines->Add(">>Open device finish ...");
	if (Cb_downloadpatch->Checked)
	{//download patch code

		if (API_bt_Download_PatchCode(1,NULL) !=0)
		{
                        if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8723D)
                        {
                           	Memo_msg->Lines->Add(">>Download patch code  Fail...");
                                if (!ByPassCheckChipID1->Checked)
                                        goto exit;
                        }
		}
		else
		{
			Memo_msg->Lines->Add(">>Download patch code  Success...");
		}
	}
        else
        {
            Memo_msg->Lines->Add(">>Skip download patch code...");
        }

	if (API_bt_GetChipInfo(NULL) !=0)
        {
            if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8723D)
            {
                if (!ByPassCheckChipID1->Checked)
                        goto exit;
            }
        }
	API_bt_ShowTxDefaultPower();

	if(mBT_CHIPINFO.ChipType < RTK_BT_CHIP_ID_RTL8822B)
	{
		CheckBox_Fw_TxRx_Mode->Checked = false;
		CheckBox_Fw_TxRx_Mode->Enabled = true;			
		bFwTxRxMode = 0;
	}
	else
	{
		CheckBox_Fw_TxRx_Mode->Checked = true;
		CheckBox_Fw_TxRx_Mode->Enabled = false;
		bFwTxRxMode = 0;
	}

   //----------------------------------------------------------------------------------------------------------------
	if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8822C)
	{
		pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule,  0xFC6F,  LEN_0_BYTE, pData, 0x0E, pEvtBuf);
		if(pEvtBuf[EVT_STATUS] !=0 || (pEvtBuf[EVT_BYTE1] !=pEvtBuf[EVT_BYTE2]))
		{
		       ::MessageBox(this->Handle,"RTL8822C Efuse ID error", "Warning", 48);

		}
	}
   //-----------------------------------------------------------------------------------------------------------------

	//Read Dac
        if(mBT_CHIPINFO.ChipType == RTK_BT_CHIP_ID_RTL8761A)
	{
                API_ReadCurrentTxDacValue( &TxDacValue);
        }
	BitBtn_GetChipInfoClick(Sender); 
	ComboBox_LeTest_ActionChange(Sender);
        GroupBox9->Visible=false;
        LBT_TabSheet->TabVisible=false;

#ifdef SONY_HOPPING_RX
        GroupBox9->Visible=true;
#endif
        GroupBox_BLESingleTone->Visible = false;
        if (AllFunction1->Checked)
        {
          mBT_CHIPINFO.ChipType= RTK_BT_CHIP_ID_RTL8763B;
          Memo_msg->Lines->Add(">>All Function open , to set chip type is RTL8763B...");
          ComboBox_LeTest_ActionChange(Sender);
        }
        CheckBLE_SPEC();
        GroupBox_TxCal->Visible=false;

 	if((mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8763B) || (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8763C ) || (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8773B ))
	{
		//BBpro
                if (!AllFunction1->Checked)
                {       //only rtl8763b support
                        if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8763B)
		        {
                                pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0x03);
		                pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, 0x62, 7, 0, &data);
		                pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0x00);
		                if(data == 7)
		                {
                                dstr.sprintf(">>Open device UART is Successfully,Device not ready..error mode type = %x(NO Patch)", data);
			        Memo_msg->Lines->Add(dstr);
			        goto exit;
		                }
                        }
                }
		TabSheet_Cal->TabVisible = true;
                GroupBox_TxCal->Visible=true;
		//xtal
		Cbx_RTL8761_XTAL->Items->Clear();
		for (i=0; i<128; i++)
		{
			dstr.sprintf("0x%.2x",i);
			Cbx_RTL8761_XTAL->Items->Add(dstr);
		}
		Cbx_RTL8761_XTAL->ItemIndex=0x3f;


		TabSheet_DAC->TabVisible = false;

		TabSheet_RW->TabVisible = false;
		TabSheet_Hopping->TabVisible = true;
		LBT_TabSheet->TabVisible = true;
		TabSheet_BBPro_BatteryResistanceCal->TabVisible = true;

		BitBtn_GetChipInfo->Visible = false;
		ComboBox_PHY_STATUS->Visible = true;
		Button_GetBTStage->Visible = true;
		Btn_LoadScript->Visible = false;
		BitBtn_TRXReadThermal->Visible = false;
		Button_ReadBDAddr->Visible = false;
		BitBtn_ShowTxPower->Visible = false;
		Button_GetPowerTracking->Visible = true;
		Button_SetPowerTracking->Visible = true;
		RadioGroup_PowerTracking->Visible = true;
		ComboBox_LeTest_TxGainIndex->Enabled = true;
		CheckBox_EnableTxDac->Visible = false;
		StaticText8->Visible = false;
		Cbx_TxDacIndex->Visible = false;
		BitBtn1->Visible = false;
		Button_BBPro_WriteToFlashConfig->Visible = true;
		TabSheet_BBProFlash->TabVisible = true;


                StaticText20->Visible=false;
                ComboBox_LeTest_TxGainIndex->Visible=false;
                //read thermal power tracking default
                Button_GetPowerTrackingClick(Sender);
                 LBT_TabSheet->TabVisible=true;
                 BitBtn_ShowTxPower->Visible=true;

                 CheckBox_FixGainClick(Sender);
                 API_bt_ShowTxDefaultPower();
                 BitBtn_TxGetClick(Sender);

                //temp : close d cut Write flash function

	}
        else if ((mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8822C) || (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8761B))
        {
		TabSheet_Cal->TabVisible = true;
                GroupBox_TxCal->Visible=true;

                TabSheet_Efuse_Map->TabVisible = true;
                TabSheet_BBProFlash->TabVisible = false;
                
		//xtal
		Cbx_RTL8761_XTAL->Items->Clear();
		for (i=0; i<128; i++)
		{
			dstr.sprintf("0x%.2x",i);
			Cbx_RTL8761_XTAL->Items->Add(dstr);
		}
		Cbx_RTL8761_XTAL->ItemIndex=0x3f;


		TabSheet_DAC->TabVisible = false;

		TabSheet_RW->TabVisible = false;
		TabSheet_Hopping->TabVisible = true;
		LBT_TabSheet->TabVisible = true;
		
		BitBtn_GetChipInfo->Visible = true;
		ComboBox_PHY_STATUS->Visible = true;
		Button_GetBTStage->Visible = true;
		Btn_LoadScript->Visible = true;
		BitBtn_TRXReadThermal->Visible = true;
		Button_ReadBDAddr->Visible = true;
		BitBtn_ShowTxPower->Visible = false;
		Button_GetPowerTracking->Visible = true;
		Button_SetPowerTracking->Visible = true;
		RadioGroup_PowerTracking->Visible = true;
		ComboBox_LeTest_TxGainIndex->Enabled = true;
		CheckBox_EnableTxDac->Visible = false;
		StaticText8->Visible = false;
		Cbx_TxDacIndex->Visible = false;
		BitBtn1->Visible = false;
		Button_BBPro_WriteToFlashConfig->Visible = true;

	      //	StaticText12->Visible = true;
	      //	ComboBox_LEE_PHY->Visible = true;
	      //	StaticText14->Visible = true;
	      //	ComboBox_LEE_Modulation->Visible = true;
	      //	TabSheet_BBProFlash->TabVisible = true;

		{
			Button_LoadFromDevice->Visible = false;
			Button_WriteRFtoFlashConfig->Visible = false;
			GroupBox_Flatness->Visible = false;
			Panel2->Visible = false;
			Button_8822C_SetTxPower->Visible = true;
	      	}

		LBT_TabSheet->TabVisible = false;
                StaticText20->Visible=false;
                ComboBox_LeTest_TxGainIndex->Visible=false;
                //read thermal power tracking default
                Button_GetPowerTrackingClick(Sender);
                Button_BBPro_WriteToFlashConfig->Visible=false;
                BitBtn_TxCalSave->Visible=false;
                Button_GetPowerTrackingClick(Sender);

        }
	else
	{
		//the others 
		if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8761A)
		{
			TabSheet_Cal->TabVisible = true;
			//xtal
			Cbx_RTL8761_XTAL->Items->Clear();
			for (i=0; i<64; i++)
			{
				dstr.sprintf("0x%.2x",i);
				Cbx_RTL8761_XTAL->Items->Add(dstr);
			}
			Cbx_RTL8761_XTAL->ItemIndex=0x20;
		}

		if(mBT_CHIPINFO.ChipType < RTK_BT_CHIP_ID_RTL8822B)
		{
			TabSheet_DAC->TabVisible = true;
		}

		TabSheet_BBPro_BatteryResistanceCal->TabVisible = false;
		TabSheet_RW->TabVisible = true;
		TabSheet_Hopping->TabVisible = true;
		TabSheet_LED->TabVisible= false;
		
	        LBT_TabSheet->TabVisible = false;
		BitBtn_GetChipInfo->Visible = true;
		ComboBox_PHY_STATUS->Visible = true;
		Button_GetBTStage->Visible = true;
		Btn_LoadScript->Visible = true;
		BitBtn_TRXReadThermal->Visible = true;
		Button_ReadBDAddr->Visible = true;
		BitBtn_ShowTxPower->Visible = true;
		Button_GetPowerTracking->Visible = true;
		Button_SetPowerTracking->Visible = true;
		RadioGroup_PowerTracking->Visible = true;
		ComboBox_LeTest_TxGainIndex->Enabled = true;
		CheckBox_EnableTxDac->Visible = true;
		StaticText8->Visible = true;
		Cbx_TxDacIndex->Visible = true;
		BitBtn1->Visible = true;
                isOnly_BLE=1;
                //BLE Only
               // if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8762C)
                if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8762C) //bee2
                {
		Button_BBPro_WriteToFlashConfig->Visible = true;
		TabSheet_BBProFlash->TabVisible = true;
                Cbx_TxGainIndex->Visible=false;


                StaticText20->Visible=false;
                ComboBox_LeTest_TxGainIndex->Visible=false;
               	TabSheet_Cal->TabVisible = true;

                MPBLEFunctionShow(40);
                BitBtn_TestModeEnable->Visible=false;

               }
                else if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD) //BLE 5.0 Olny
                {
	                Button_BBPro_WriteToFlashConfig->Visible = true;
		        TabSheet_BBProFlash->TabVisible = true;
                        Cbx_TxGainIndex->Visible=false;
                           MPBLEFunctionShow(50);

                        StaticText20->Visible=false;
                        ComboBox_LeTest_TxGainIndex->Visible=false;

                        TabSheet_NONLINK->TabVisible= true;
                        Page_function->ActivePage=TabSheet_LETest;
                        GroupBox_BLESingleTone->Visible = true;
                        TabSheet_Cal->TabVisible =true;
                        GroupBox_XTAL->Visible=false;
                        GroupBox_TxCal->Visible=true;
                        GroupBox_BLESingleTone->Visible=false;
                        BitBtn_TestModeEnable->Visible=false;

                        Button_LoadFromDevice->Visible = false;
                        Button_WriteRFtoFlashConfig->Visible = false;
                        Panel2->Visible = false;

                        Cbx_Actionexec->ItemIndex=4;
                        Cbx_ActionexecChange(Sender);

                        Cbx_Hopping_PktType->ItemIndex=9;
                        Cbx_Hopping_PktType->Enabled=false;
                        Cbx_Hopping_PktTypeChange(Sender);
                        BitBtn_Txflatness->Visible = false;

                }
                else if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII) //BLE4.0 Only
                {

	                Button_BBPro_WriteToFlashConfig->Visible = true;
		        TabSheet_BBProFlash->TabVisible = true;
                        Cbx_TxGainIndex->Visible=false;

		        ///ComboBox_LeTest_DataLen->Items->Clear();
                        StaticText20->Visible=false;
                        ComboBox_LeTest_TxGainIndex->Visible=false;

                        TabSheet_NONLINK->TabVisible= true;
                        Page_function->ActivePage=TabSheet_LETest;
                        GroupBox_BLESingleTone->Visible = true;

	                Button_BBPro_WriteToFlashConfig->Visible = true;
		        TabSheet_BBProFlash->TabVisible = true;
                        Cbx_TxGainIndex->Visible=false;
                        MPBLEFunctionShow(40);
                        StaticText20->Visible=false;
                        ComboBox_LeTest_TxGainIndex->Visible=false;


                        Page_function->ActivePage=TabSheet_LETest;
	                Button_BBPro_WriteToFlashConfig->Visible = true;
		        TabSheet_BBProFlash->TabVisible = true;
                        Cbx_TxGainIndex->Visible=false;


                        StaticText20->Visible=false;
                        ComboBox_LeTest_TxGainIndex->Visible=false;

                        TabSheet_NONLINK->TabVisible= true;
                        Page_function->ActivePage=TabSheet_LETest;
                        GroupBox_BLESingleTone->Visible = true;

	                Button_BBPro_WriteToFlashConfig->Visible = true;
		        TabSheet_BBProFlash->TabVisible = true;
                        Cbx_TxGainIndex->Visible=false;


                        StaticText20->Visible=false;
                        ComboBox_LeTest_TxGainIndex->Visible=false;


                        Page_function->ActivePage=TabSheet_LETest;
                        GroupBox_BLESingleTone->Visible = true;
                        TabSheet_Cal->TabVisible =true;
                        GroupBox_XTAL->Visible=false;
                        GroupBox_TxCal->Visible=true;
                        GroupBox_BLESingleTone->Visible=false;
                        BitBtn_TestModeEnable->Visible=false;

                        Button_LoadFromDevice->Visible = false;
                        Button_WriteRFtoFlashConfig->Visible = false;
                        Panel2->Visible = false;

                        Cbx_Actionexec->ItemIndex=4;
                        Cbx_ActionexecChange(Sender);

                        Cbx_Hopping_PktType->ItemIndex=9;
                        Cbx_Hopping_PktType->Enabled=false;
                        Cbx_Hopping_PktTypeChange(Sender);
                        BitBtn_Txflatness->Visible = false;
                       

                }//----------------------------------------------------------------------
                else
                {


	       	        StaticText12->Visible = false;
	      	        ComboBox_LEE_PHY->Visible = false;
	      	        StaticText14->Visible = false;
	      	        ComboBox_LEE_Modulation->Visible = false;
		        Button_BBPro_WriteToFlashConfig->Visible = false;

                }
	}
	
	if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8822C)
	{
		ComboBox_SetAnt->Visible=true;
		BitBtn_SetAnt->Visible=true;
	}
	else
	{
		ComboBox_SetAnt->Visible=false;
		BitBtn_SetAnt->Visible=false;
	}
	Button_Get_TPM_IQMClick(Sender);  

	GroupBox_Show->Visible=false;

	Btn_Dev_Close->Enabled=true;

	delete ShowUI;
	ShowUI =NULL;

	api_tcpip_bt_mp_InitDefaultParameter();
	//debug
	if(EnableReadWriteRegisterPage->Checked ==true)
	{
		TabSheet_RW->TabVisible =true;
                Btn_LoadScript->Visible=true;

	}

	Panel_LED->Color=clLime;
	Panel_LED->Caption="O";

        Btn_Dev_Open->Enabled=true;

	Memo_msg->Lines->Add(">>Open device successfully...");

        Xtal_tracking_function_Support=0;
        BitBtn12Click(Sender);
        if (XTALThermalTrackingPageEnable1->Checked)
        Xtal_tracking_function_Support =1;

        if (Xtal_tracking_function_Support ==1)
        {
           TabSheet_TXTALCAL->TabVisible= true;
        }
        else
        {
          TabSheet_TXTALCAL->TabVisible = false;
        }
       // XTALThermalTrackingPageEnable1Click(Sender);

	Page_function->ActivePage=TabSheet_NONLINK;
	return;

 exit:

	GroupBox_Show->Visible=false;
        ShowUI->Terminate();
        Sleep(100);
 	delete ShowUI;
	ShowUI =NULL;

 	Btn_Dev_Close->Enabled=true;
         Page_function->ActivePage=TabSheet_NONLINK;
	::MessageBox(this->Handle,"Open Device Failed  ", "ERROR", 16);
	return;

}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Cbx_InterfaceChange(TObject *Sender)
{
	int i;
	String dstr;
        String cmp_str;
	int Index = Cbx_Interface->ItemIndex;

        for (i=0;i<TYPE_NUMBER;i++)
        {
             cmp_str.sprintf("%s",InterFaceTypeDesc[i]);
              dstr= Cbx_Interface->Text;
             if(cmp_str == dstr )
             {
                Index= i;
                break;
             }
        }

	Cbx_RTL8761_XTAL->Visible=true;
	Edit_CFO->Text = "0x20";

	switch(Index)
	{
		case TYPE_USB: //usb
			Cbx_Interface_port->Items->Clear();
			for (i=0; i<10; i++)
			{
				dstr.sprintf("%d",i);
				Cbx_Interface_port->Items->Add(dstr);
			}
			
			Cbx_Interface_port->Visible=false;
			Label19->Visible=false;
			Cbx_Interface_port->ItemIndex=1;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=false;

			InterfaceType =  TYPE_USB ;
		break;
                case TYPE_SDIO:
 			Cbx_Interface_port->Visible=false;
			Label19->Visible=false;
			Cbx_Interface_port->ItemIndex=1;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=false;
                        InterfaceType =  TYPE_SDIO ; ;
                break;
		case TYPE_UART: //COM uart
			Cbx_Interface_port->Items->Clear();
			for (i=0; i<10; i++)
			{
				dstr.sprintf("%d",i);
				Cbx_Interface_port->Items->Add(dstr);
			}
			Label19->Visible=true;		
			Cbx_Interface_port->Visible=true;
			Cbx_Interface_port->ItemIndex=4;			
			Cbx_Interface_baudrate->Visible=true;
			Edit_Ip_Addr->Visible=false;

			InterfaceType =  TYPE_UART ;
		break;

		case TYPE_FILTER_UART: //Filter UART
			Cbx_Interface_port->Visible=false;
			Label19->Visible=false;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=false;

			InterfaceType =  TYPE_FILTER_UART ;
		break;

		case TYPE_ADB_UART: //ADB  UART
			Cbx_Interface_port->Items->Clear();
			for (i=0; i<5; i++)
			{
				dstr.sprintf("/dev/ttyS%d",i);
				Cbx_Interface_port->Items->Add(dstr);
			}
			
			Cbx_Interface_port->Visible=true;
			Label19->Visible=true;			
			Cbx_Interface_port->ItemIndex=1;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=false;

			InterfaceType =  TYPE_ADB_UART ;
		break;

		case TYPE_ADB_USB: //ADB  USB
			Cbx_Interface_port->Visible=false;
			Label19->Visible=false;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=false;

			InterfaceType =  TYPE_ADB_USB ;
		break;

  		case TYPE_SOCKET_DEVICE_UART:
			Cbx_Interface_port->Items->Clear();
			for (i=0; i<10; i++)
			{
				dstr.sprintf("%d",i);
				Cbx_Interface_port->Items->Add(dstr);
			}
			
			Cbx_Interface_port->Visible=true;
			Cbx_Interface_port->ItemIndex=1;
			Label19->Visible=true;
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=true;

			InterfaceType =  TYPE_SOCKET_DEVICE_UART ;
		break;
		
		case TYPE_SOCKET_DEVICE_USB:
			Cbx_Interface_port->Visible=false;
			Label19->Visible=false;	
			Cbx_Interface_baudrate->Visible=false;
			Edit_Ip_Addr->Visible=true;
			InterfaceType =  TYPE_SOCKET_DEVICE_USB ;
		break;


	}

	return ;
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::Btn_HoppingRunClick(TObject *Sender)
{

	BT_PARAMETER 	*pParam=&mBT_PARAMETER;
      //	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

	unsigned char  PayloadType = ComboBox_Hopping_PayloadType->ItemIndex;
	unsigned char  TxGainValue =  StrToInt(Edit_Hopping_TxGainValue->Text);
	unsigned char  TxGainIndex = ComboBox_Hopping_TxGainIndex->ItemIndex;
	unsigned char  TxDac = StrToInt(ComboBox_Hopping_TxDac->Text);
	String dstr;

	if(Cbx_Hopping_PktType->Text == "LE")
	{
		pParam->mPacketType = BT_PKT_LE;
	}
	else
	{
		pParam->mPacketType = (BT_PKT_TYPE)( Cbx_Hopping_PktType->ItemIndex);
	}


	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return ;
	}

        Btn_HoppingRun->Enabled = false;

	if (Ckb_Whitening->Checked)
	{
		pParam->mWhiteningCoeffValue=0x7f;
	}
	else
	{
		pParam->mWhiteningCoeffValue=0x80;
	}
	
	if (ComboBox_Hopping_Type->Text== "Hopping")
	{
		pParam->bHoppingFixChannel= 0;
		pParam->mParamData[0] = StrToInt(ComboBox_Hopping_StartCh->Text);
		pParam->mParamData[1] = StrToInt(ComboBox_Hopping_StopCh->Text);
	}
	else
	{
		pParam->bHoppingFixChannel= 1;
		pParam->mChannelNumber=StrToInt(ComboBox_Hopping_StartCh->Text);
	}

	pParam->mPayloadType = PayloadType;
	pParam->mTxGainIndex = TxGainIndex;
	pParam->mTxGainValue = TxGainValue;
	pParam->mTxDAC = TxDac;

	//update
	pParam->ParameterIndex = HOPPING_DWELL_TIME;
	//  int siz = sizeof(BT_PARAMETER);
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	//dwell time command

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add(">>Run hopping mode failed");
                Btn_HoppingRun->Enabled = true;
	}
	else
	{
		Memo_msg->Lines->Add(">>Run hopping mode Begin....succress!!");
                Btn_Hopping_Stop->Enabled = true;
	}

	return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Btn_Hopping_StopClick(TObject *Sender)
{
	//dwell time command
	BT_PARAMETER 	*pParam=&mBT_PARAMETER;
	String dstr;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        Btn_Hopping_Stop->Enabled = false;

	pParam->ParameterIndex = HCI_RESET;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add(">>Stop hopping mode failed...");
                Btn_Hopping_Stop->Enabled = true;
	}
        else
        {
        	Memo_msg->Lines->Add(">>Stop hopping mod succress!!");
                Btn_HoppingRun->Enabled = true;
        }
}
//---------------------------------------------------------------------------

int TForm_Main::API_bt_HciReset()
{
	BT_PARAMETER 	*pParam=&mBT_PARAMETER;
	String dstr;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
	pParam->ParameterIndex = HCI_RESET;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		dstr.sprintf(">>HCI Reset Fail...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
        dstr.sprintf(">>HCI Reset Succress...!!\n");Memo_msg->Lines->Add(dstr);
	TrxFixObject(true);
	return 0;

}
//---------------------------------------------------------------------------
int TForm_Main::API_bt_GetChipInfo(unsigned int *ChipType)
{
	String dstr;
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;
	BT_CHIPINFO	        *pBTInfo=NULL;
        if (ChipType !=NULL)
                *ChipType = 0xFF;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}

	if (pBluetoothModule->ActionReport(pBluetoothModule,REPORT_CHIP,pModuleBtReport) !=0)
	{
		dstr.sprintf(">>Get Chip Info is Fail...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
	pBTInfo=  pModuleBtReport->pBTInfo;
    if (pBTInfo == NULL)
    {
		dstr.sprintf(">>Get Chip Info is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
	memcpy(&mBT_CHIPINFO,pBTInfo,sizeof(BT_CHIPINFO));   Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>ChipType=(%x)\n",pBTInfo->ChipType); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>HCI_SubVersion=0x%x\n",pBTInfo->HCI_SubVersion); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>HCI_Version=0x%x\n",pBTInfo->HCI_Version); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>LMP_SubVersion=0x%x\n",pBTInfo->LMP_SubVersion); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>LMP_Version=0x%x\n",pBTInfo->LMP_Version); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>Version=%.2x\n",pBTInfo->Version+9); Memo_msg->Lines->Add(dstr);
	dstr.sprintf(">>Is_After_PatchCode=%d\n",pBTInfo->Is_After_PatchCode);Memo_msg->Lines->Add(dstr);
        if (ChipType !=NULL)
        *ChipType=pBTInfo->ChipType;
exit:
	return 0;

}


int TForm_Main::API_bt_fw_read_power_info()
{
	BT_PARAMETER *pParam=&mBT_PARAMETER;
	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	String dstr;
	int i;

#ifdef BBPRO_TEMP_READ_TX_INDEX
        if((pBTInfo->ChipType ==RTK_BT_CHIP_ID_RTL8763B) || (pBTInfo->ChipType ==RTK_BT_CHIP_ID_RTL8763C )|| (pBTInfo->ChipType ==RTK_BT_CHIP_ID_RTL8773B ))
        {
 /*
Opcode 0xFD14
Sub-opcode: 0 (no set anything, just get the current setting); others (event with current setting)

Event length: 12
Byte[0] : tx_gaink
Byte[2:1] : tx_gain_flatk
Byte[3]: path_loss
Byte[4]: iqm_max_tx_gain_1M
Byte[5]: iqm_max_tx_gain_2M
Byte[6]: iqm_max_tx tx_gain_3M
Byte[7]: iqm_max_tx tx_gain_LE1M
Byte[8]: iqm_max_tx tx_gain_LE2M
Byte[9]: tpm_max_tx_gain_1M
Byte[10]: tpm_max_tx_gain_LE1M
Byte[11]: tpm_max_tx_gain_LE2M


*/
	unsigned char pData[512]= {0};
	unsigned char pEvtBuf[512]={0};

        pData[0]=0;
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xfd14,LEN_1_BYTE, pData, 0x0E, pEvtBuf)!=0)
        {
            return 0;
        }

        if (pEvtBuf[9] ==0 && pEvtBuf[10]==0)
           return 0;

        dstr.sprintf(">>BT Tx Power index :(1M 0x%x),(2M 0x%x),(3M 0x%x),(LE 1M 0x%x),(LE 2M 0x%x),(LE LR 0x%x)",pEvtBuf[9], pEvtBuf[10], pEvtBuf[11], pEvtBuf[12], pEvtBuf[13], pEvtBuf[12]);
       	Memo_msg->Lines->Add(dstr);
        return 0;

        }
#endif
	memset(pParam, 0, sizeof(BT_PARAMETER));	
	pParam->ParameterIndex = FW_READ_TX_POWER_INFO;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) != BT_FUNCTION_SUCCESS)
		goto error;

	pBluetoothModule->ActionReport(pBluetoothModule,REPORT_TX_POWER_INFO, &mBT_DEVICE_REPORT);

	memcpy(TxPowerLevelInfo, mBT_DEVICE_REPORT.ReportData, LEN_7_BYTE);
	if ((pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8822C) || (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8761B)
          || (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8763B)
          || (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8763C)
          || (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8773B)
           ) 
	{
                if ((TxPowerLevelInfo[1]==0)&& (TxPowerLevelInfo[2]==0))
                {
                       BitBtn_ShowTxPower->Visible= false;
                       return 0;
                }        
                if ((TxPowerLevelInfo[5] ==0 ) && (TxPowerLevelInfo[6] ==0 ))
                { //same BLE 1M
                  Memo_msg->Lines->Add(">>BLE 2M /LR Tx power same as BLE 1M");
                  TxPowerLevelInfo[5] = TxPowerLevelInfo[4] ;
                  TxPowerLevelInfo[6]= TxPowerLevelInfo[4] ;
                }
		dstr.sprintf(">>BT Max Tx Power :Upper 0x%x,  Default Power Index:(1M 0x%x),(2M 0x%x),(3M 0x%x),(LE 1M 0x%x),(LE 2M 0x%x),(LE LR 0x%x)",TxPowerLevelInfo[0], TxPowerLevelInfo[1], TxPowerLevelInfo[2], TxPowerLevelInfo[3], TxPowerLevelInfo[4], TxPowerLevelInfo[5], TxPowerLevelInfo[6]);
	}
        else if((mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD) ||(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII))
	{
		dstr.sprintf(">>BT Max Tx Power Index:0x%0x,  Default Power Index:(BLE 1M 0x%x),(BLE 2M 0x%x)",TxPowerLevelInfo[0], TxPowerLevelInfo[1], TxPowerLevelInfo[2]);
	}
        else
        {
               dstr.sprintf(">>BT Max Tx Power :Upper 0x%x,  Default Power Index:(1M 0x%x),(2M 0x%x),(3M 0x%x),(LE 0x%x)",TxPowerLevelInfo[0], TxPowerLevelInfo[1], TxPowerLevelInfo[2], TxPowerLevelInfo[3], TxPowerLevelInfo[4]);
        }

	Memo_msg->Lines->Add(dstr);
	Cbx_TxGainIndex->Items->Clear();
	if(pBTInfo->ChipType <RTK_BT_CHIP_ID_RTL8763B)
	{
		for ( i=0; i<=TxPowerLevelInfo[MAX_TX_POWER_INDEX]; i++)
		{
			dstr.sprintf("%x", i);
			dstr=dstr.UpperCase();
			Cbx_TxGainIndex->Items->Add(dstr);
		}
		dstr.sprintf("%x", TxPowerLevelInfo[DEFAULT_1M_TX_POWER_INDEX]);
		Cbx_TxGainIndex->Text = dstr;
	}
	else
	{
		Cbx_TxGainIndex->Text = "Max";
	}

	if(pBTInfo->ChipType >=RTK_BT_CHIP_ID_RTL8822C)
	{
		dstr.sprintf("0x%x", TxPowerLevelInfo[1]);
		ComboBox_MaxTxPowerofLegacy1M->Items->Clear();
		ComboBox_MaxTxPowerofLegacy1M->Text = dstr;
		
		dstr.sprintf("0x%x", TxPowerLevelInfo[2]);
		ComboBox_MaxTxPowerofLegacy2M->Items->Clear();
		ComboBox_MaxTxPowerofLegacy2M->Text = dstr;

		dstr.sprintf("0x%x", TxPowerLevelInfo[3]);
		ComboBox_MaxTxPowerofLegacy3M->Items->Clear();
		ComboBox_MaxTxPowerofLegacy3M->Text = dstr;

		dstr.sprintf("0x%x", TxPowerLevelInfo[4]);
		ComboBox_TxPowerofLE1MLR->Items->Clear();
		ComboBox_TxPowerofLE1MLR->Text = dstr;

		dstr.sprintf("0x%x", TxPowerLevelInfo[5]);
		ComboBox_TxPowerofLE2M->Items->Clear();
		ComboBox_TxPowerofLE2M->Text = dstr;
	}

	return 0;

error:

	Memo_msg->Lines->Add(">>FW Read Power Info : ERROR");

	return 1;

}


int TForm_Main::API_bt_get_power_index()
{
    //	BT_PARAMETER *pParam=&mBT_PARAMETER;	
	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
	int Power_Index=0xff;
	String dstr;
	int i;

	API_bt_GetBTDefaultTxPower(pBTInfo->ChipType, &Power_Index);
	if (Power_Index < 7)
	{
		ComboBox_LeTest_TxGainIndex->Items->Clear();
		for ( i=0; i<LEN_7_BYTE; i++)
		{
			dstr.sprintf("%d", i+1);
			ComboBox_LeTest_TxGainIndex->Items->Add(dstr);
		}

		Cbx_TxGainIndex->Items->Clear();
		for ( i=0; i<LEN_7_BYTE; i++)
		{
			dstr.sprintf("%d", i+1);
			Cbx_TxGainIndex->Items->Add(dstr);
		}

		dstr.sprintf("%d", Power_Index);
		Cbx_TxGainIndex->Text = dstr;
		ComboBox_LeTest_TxGainIndex->Text  = dstr;
		Cbx_TxGainIndex->Update();
			
		dstr.sprintf(">>BT Default Power Index = %d ",Power_Index);
		Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf(">>ERROR : BT Default Power Index = %d ",Power_Index);
		Memo_msg->Lines->Add(dstr);
	}

        return 0;

}


int TForm_Main::API_bt_ShowTxDefaultPower()
{
	BT_PARAMETER *pParam=&mBT_PARAMETER;
	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	String dstr;
	int i;

	unsigned char pData[512];
	unsigned char pEvtBuf[512];	

	dstr.sprintf(">>API_bt_ShowTxDefaultPower  ChipId= %d ",pBTInfo->ChipType);
	Memo_msg->Lines->Add(dstr);

	if(pBTInfo->ChipType < RTK_BT_CHIP_ID_RTL8822B)
	{
		API_bt_get_power_index();
		pParam->ParameterIndex = SET_DEFAULT_TX_GAIN_TABLE;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		pBluetoothModule->ActionControlExcute(pBluetoothModule);
		pBluetoothModule->ActionReport(pBluetoothModule,REPORT_TX_GAIN_TABLE, &mBT_DEVICE_REPORT);
	}
	else if(pBTInfo->ChipType < RTK_BT_CHIP_ID_RTL8763B)
	{
		if (API_bt_fw_read_power_info() !=0)
		{
			Memo_msg->Lines->Add(">>Read Power info is Fail ....");
			return -1;
		}

		ComboBox_LeTest_TxGainIndex->Items->Clear();
		for ( i=0; i<=TxPowerLevelInfo[MAX_TX_POWER_INDEX]; i++)
		{
			dstr.sprintf("%x", i);
			ComboBox_LeTest_TxGainIndex->Items->Add(dstr);
		}

		dstr.sprintf("%x", TxPowerLevelInfo[DEFAULT_LE_TX_POWER_INDEX]);
		ComboBox_LeTest_TxGainIndex->Text = dstr;
	}
	else
	{
		if (API_bt_fw_read_power_info() !=0)
		{
			Memo_msg->Lines->Add(">>Read Power info is Fail ....");
			return -1;
		}
	}


	return 0;
}


#define MAX_SET_CONFIG_FILE_SIZE  58


int TForm_Main::API_bt_Download_PatchCode(int Defaultpath_Flag,char *new_Filepath)
{
        int patch_type=0;
	char tmp_FileName[][50]={
		{"BTPatchCode\\patch_rtl8723a.bin"}, // 0
		{"BTPatchCode\\patch_rtl8723b.bin"}, // 1
		{"BTPatchCode\\patch_rtl8821a.bin"}, // 2
		{"BTPatchCode\\patch_rtl8761a.bin"}, // 3
		{"BTPatchCode\\patch_rtl8703a.bin"}, // 4
		{"BTPatchCode\\patch_rtl8763a.bin"}, // 5
		{"BTPatchCode\\patch_rtl8703b.bin"}, // 6
		{"BTPatchCode\\patch_rtl8723c.bin"}, // 7
		{"BTPatchCode\\patch_rtl8822b.bin"}, // 8
		{"BTPatchCode\\patch_rtl8723d.bin"}, // 9
		{"BTPatchCode\\patch_rtl8821c.bin"}, // 10
		{"BTPatchCode\\NotUse.bin"}, // 11
		{"BTPatchCode\\NotUse.bin"}, // 12
		{"BTPatchCode\\patch_rtl8822c.bin"}, // 13
                {"BTPatchCode\\patch_rtl8761b.bin"}, // 14
                {"BTPatchCode\\patch_rtl8721d.bin"}, // 15  amebaZII
                {"BTPatchCode\\patch_rtl8710c.bin"}, // 16  amebaD
	};
	char app_FileName[][50]={
		{"BTPatchCode\\app_8761att.bin"}, // 0
        };
	BT_CHIPINFO	        *pBTInfo=&mBT_CHIPINFO;
        BT_PARAMETER            *pParam=&mBT_PARAMETER;
	char *buffer =NULL;
        AnsiString file_path;
	int lSize=0;
	int rtn=0;
        int n=0;
        int config_len=0;
	String dstr;
	FILE *DataFile=NULL;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
//	if (Defaultpath_Flag)
	{
		if (API_bt_GetChipInfo(NULL) !=0 )
		{
			Memo_msg->Lines->Add(">>Get Chip info error!!");
			rtn=-1;
			goto exit;
		}
	}

	if((pBTInfo->Is_After_PatchCode) &&  (InterfaceType !=  TYPE_BUMBLE_BEE_USB ))  //bumble must to download
	{
		Memo_msg->Lines->Add(">>Skip patch code !!");
		rtn=0;
		goto exit;

	}
	////////////////////////////////////////////////////////////////////////////////////
	//config File
	//API_bt_Download_PatchCode
	if (Cb_ConfigFile->Checked)
	{
		char *pConbuffer =NULL;
		int ConfigSize=0;
		FILE *ConfigFile=NULL;
		int  ConfigFileMaxIndex =0;
		ConfigFile = fopen("mp_config.bin", "r+b");
		if (ConfigFile == NULL)
		{
			dstr.sprintf(">>Error config File path => mp_config.bin..\n");
			Memo_msg->Lines->Add(dstr);
		}
		else
		{
			fseek(ConfigFile, 0, SEEK_END);
			ConfigSize = ftell(ConfigFile);
			fseek(ConfigFile, 0, SEEK_SET);
			if (ConfigSize > 256 )
			{
				dstr.sprintf(">>[ERROR]Config file size > 256 \n");
				Memo_msg->Lines->Add(dstr);
				goto exit;
			}
			pConbuffer = (char *)malloc(ConfigSize);
			if (pConbuffer ==NULL)
			{
				dstr.sprintf(">>Faild to malloc the config file buffer..\n");
				Memo_msg->Lines->Add(dstr);
			}
			else
			{
				if (fread(pConbuffer,1,ConfigSize,ConfigFile) == 0)
				{
					dstr.sprintf(">>read config file error = mp_config.bin..\n");
					Memo_msg->Lines->Add(dstr);
				}
				else
				{
					int cur_len=0;
					int pcur=0;
                                        if (ConfigSize>=6)
                                        {
                                                config_len =  (pConbuffer[5]<<8)+pConbuffer[4];
                                                if (config_len != (ConfigSize-6))
                                                {

                                                  dstr.sprintf(">>Config Len= %d ConfigSize=%d no match -->ConfigSize = %d(Config Len +6)",config_len,ConfigSize);
                                                  ConfigSize = (config_len+6);
                                                }
                                                else
                                                {
                                                   dstr.sprintf(">>Config Len= %d ConfigSize=%d ",config_len,ConfigSize);
                                                }
                                        }
					//64 -6
					ConfigFileMaxIndex = (ConfigSize / MAX_SET_CONFIG_FILE_SIZE) +1;    //config packet
					dstr.sprintf(">>SetConfig file:: begin --> total_index = %d total_len=%d\n",ConfigFileMaxIndex,ConfigSize);
					Memo_msg->Lines->Add(dstr);
					//new Config File process   0xa5,0xb5,total_index, total_len ,current_index,current_len
					for (n=0;n<ConfigFileMaxIndex;n++)
					{
						if (ConfigSize <= MAX_SET_CONFIG_FILE_SIZE)
						{
							cur_len = ConfigSize;
						}
						else if ( (ConfigSize - pcur) < MAX_SET_CONFIG_FILE_SIZE )
						{
							cur_len = MAX_SET_CONFIG_FILE_SIZE;
						}
						else
						{
							cur_len = ConfigSize - pcur;
						}

						pParam->mParamData[0] = 0xa5;
						pParam->mParamData[1] = 0xb5;
						pParam->mParamData[2] = ConfigFileMaxIndex;
						pParam->mParamData[3] = ConfigSize;
						pParam->mParamData[4] = n;
						pParam->mParamData[5] = cur_len;
						memcpy(&pParam->mParamData[6],&pConbuffer[pcur], cur_len );

						pcur += cur_len;
						pParam->ParameterIndex = SET_CONFIG_FILE_DATA;
						pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
						if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
						{
							Memo_msg->Lines->Add(">>Set config File Error...");
							goto Config_fail;
						}
						else
						{
							dstr.sprintf(">>SetConfig::current_index = %d ,current_len = %d \n",n,cur_len);
							Memo_msg->Lines->Add(dstr);
						}

					}
				}
			}
		}

Config_fail:

		if (pConbuffer != NULL)
			free(pConbuffer);
		if (ConfigFile !=NULL)
			fclose(ConfigFile);
		dstr.sprintf(">>SetConfig file:: End --> FileName:mp_config.bin\n");
		Memo_msg->Lines->Add(dstr);

	}

	//////////////////////////////////////////////////////////////
        patch_type =0;
	if (Defaultpath_Flag)
	{
#if 0
//------------------------------------------------------------------------------
                if( (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8761A) && ((pBTInfo->Version+9) == 0x0e))
                { //8761att app patch


                        int  message_btn=Application->MessageBox("Download MP Patch Code..\nYes :MP        Patch Code \nNo :Normal Patch Code", "Patch Code select",32+ MB_YESNOCANCEL);
                        if (message_btn == IDNO)
                        {
                                patch_type =1;
                        }else if (message_btn == IDCANCEL)
                        {

  	                	Memo_msg->Lines->Add(">>Skip patch code !!");
	                	rtn=0;
	                	goto exit;
                        }
                        else
                        {
                            patch_type =0;
                        }


                }
//------------------------------------------------------------------------------
#endif

                if (patch_type == 1)
                {
                        AnsiString cur_exe_path =  ExtractFilePath(Application->ExeName);

                        file_path.sprintf(("%s%s"),cur_exe_path,app_FileName[0]);
                        DataFile = fopen(file_path.c_str(), "r+b");


                }
                else
                {
                //20160804  Dean add
                //Get cur_rtlbtapp.exe path
                AnsiString cur_exe_path =  ExtractFilePath(Application->ExeName);

                file_path.sprintf(("%s%s"),cur_exe_path,tmp_FileName[pBTInfo->ChipType]);
                DataFile = fopen(file_path.c_str(), "r+b");
                //
	       //	DataFile = fopen(tmp_FileName[pBTInfo->ChipType], "r+b");

               }
	}
	else
	{
		if (new_Filepath == NULL)
		{
			Memo_msg->Lines->Add(">>Path is NULL!!");
			rtn=-1;
			goto exit;
		}
		else
		{
			DataFile = fopen(new_Filepath, "r+b");
		}	
	}

 	if (DataFile == NULL)
	{
		dstr.sprintf(">>Error File path = %s..\n",file_path.c_str());
		Memo_msg->Lines->Add(dstr);
		rtn= -1;
		goto exit;
	}
	else
	{
		dstr.sprintf(">>Open File path = %s..\n",file_path.c_str());
		Memo_msg->Lines->Add(dstr);
		fseek(DataFile, 0, SEEK_END);
		lSize = ftell(DataFile);
		fseek(DataFile, 0, SEEK_SET);
	}

	buffer = (char *)malloc(lSize);
	if (buffer ==NULL)
	{
		dstr.sprintf(">>allocate File patch error = %s..\n",file_path.c_str());    //tmp_FileName[pBTInfo->ChipType
		Memo_msg->Lines->Add(dstr);
		rtn= -1;
		goto exit;
	}
	
	if (fread(buffer,1,lSize,DataFile) == 0)
	{
		dstr.sprintf(">>read file error = %s..\n",file_path.c_str());
		Memo_msg->Lines->Add(dstr);
		rtn= -1;
		goto exit;
	}

	if (pBluetoothModule->DownloadPatchCode(pBluetoothModule,buffer,lSize,1) != BT_FUNCTION_SUCCESS)
	{
		Memo_msg->Lines->Add(">>Download patch code Faild!!..\n");

		rtn= -1;
		goto exit;
	}
	else
	{

		Memo_msg->Lines->Add(">>Download patch code Success!!\n");
                if (patch_type == 1)
                {
                 ShowMessage(">>Download Normal patch Code Succress<< ");
                }
	}

exit:
 	if (buffer !=NULL)
		free(buffer);
	if (DataFile !=NULL)
		fclose(DataFile);

	return rtn;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_PatchClick(TObject *Sender)
{
	OpenDialog1->Options.Clear();
	OpenDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
	OpenDialog1->Filter = "Bin files (*.bin)|*.bin|All files (*.*)|*.*";
	OpenDialog1->FileName="rlt8723a_chip_b_cut_bt40_fw_asic_rom_patch.bin";
	OpenDialog1->FilterIndex=0;
	if(OpenDialog1->Execute())
	{
		if (API_bt_Download_PatchCode(0,OpenDialog1->FileName.c_str()) !=0)
		{
			Memo_msg->Lines->Add(">>Select patch code download error!!");
		}
		API_bt_ShowTxDefaultPower();		
#if 1
		if(mBT_CHIPINFO.ChipType < RTK_BT_CHIP_ID_RTL8822B)
		{
			CheckBox_Fw_TxRx_Mode->Checked = false;		
			CheckBox_Fw_TxRx_Mode->Enabled = true;			
			bFwTxRxMode = 0;
		}
		else
		{
			CheckBox_Fw_TxRx_Mode->Checked = true;
			CheckBox_Fw_TxRx_Mode->Enabled = false;
			bFwTxRxMode = 0;
		}				
#endif
	}

	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::FormCreate(TObject *Sender)
{
	Memo_msg->Lines->Clear();
        String dstr,VerStr;

#ifdef ACTS_BUMBLEBEE
        VerStr="ACTSBluetoothRF.dll";
#else
        VerStr="RtlBluetoothMP.dll";
#endif
	if (API_bt_LoadMpDll() !=0)
	{
		Btn_Dev_Open->Enabled=false;
		Btn_Dev_Close->Enabled=false;

                dstr.sprintf(">>Load %s Fail!!",VerStr) ;


                Memo_msg->Lines->Add(dstr);

                BitBtn_CFO_BEGIN->Enabled=false;
                BitBtn_GETCFO->Enabled=false;
                TabSheet8->Enabled=false;
                Btn_Dev_Open->Enabled=false;
                BitBtn_CFO_STOP->Enabled=false;
           BitBtn_CFO_REGWR->Enabled = false;
           BitBtn_CFO_REGRD->Enabled = false;
           BitBtn_CFO_EFUSEWR->Enabled = false;
           BitBtn_CFO_EFUSERD->Enabled = false;
               // ShowMessage(dstr);
	}
	else
	{
                dstr.sprintf(">>Load %s Success!!",VerStr) ;
		Memo_msg->Lines->Add(dstr);
                BitBtn_CFO_BEGIN->Enabled=true;
                BitBtn_GETCFO->Enabled=true;
                TabSheet8->Enabled=true;
                 Btn_Dev_Open->Enabled=true;
                 BitBtn_CFO_STOP->Enabled=true;
           BitBtn_CFO_REGWR->Enabled = true;
           BitBtn_CFO_REGRD->Enabled = true;
           BitBtn_CFO_EFUSEWR->Enabled = true;
           BitBtn_CFO_EFUSERD->Enabled = true;

	}
}
//---------------------------------------------------------------------------

void  TForm_Main::CloseDevice()
{
        TObject *Sender;
   	Btn_Dev_Close->Enabled=false;
	if (pBaseInterface != NULL)
	{
		Sleep(100);
		Btn_ActionStopClick(Sender) ;
		pBaseInterface->Close(pBaseInterface);
	}
	Memo_msg->Lines->Add(">>Close Device Success!!");
	Panel_LED->Color=clRed;
	Panel_LED->Caption="X";

  	Btn_Dev_Open->Enabled=true;

         return ;

}
void __fastcall TForm_Main::Btn_Dev_CloseClick(TObject *Sender)
{


        CloseDevice();

       if ((ComboBox_KeyWord->ItemIndex == 1) || (ComboBox_KeyWord->ItemIndex == 2))
        {
	     int  PortNo;
	     int  Baudrate=115200;
             int BarudRate_Arrary[]={9600,115200,921600,1500000,2000000,3000000,4000000};
             int Enter1_Leave2 =2;
              int end_need_close =1;
              int Delay = 0;
              String subStr;
              subStr=   Cbx_Interface_baudrate->Text.SubString(0,8);
                if (subStr == "Baudrate")
                {
	                Baudrate=BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
                }
                else
                {
                        Baudrate= StrToInt(Cbx_Interface_baudrate->Text);
                }
             int chip_type = RTK_BT_CHIP_ID_AMEBAD;
                if (Cbx_Interface_port->Text.Length()>0)
                {
		        PortNo=StrToInt(Cbx_Interface_port->Text);
		}
                else
                {
                    PortNo =0;
                }
             if (ComboBox_KeyWord->ItemIndex == 1)
             chip_type =RTK_BT_CHIP_ID_AMEBAD ;//  =15,
             else
             chip_type=RTK_BT_CHIP_ID_AMEBAZII;// 16,
             if (pBaseDLLObject->ExternFunctionRTK != NULL)
             {
             int keyWord_rtn= pBaseDLLObject->ExternFunctionRTK(
	        chip_type,
	        Enter1_Leave2,
	        NULL,
	        NULL,//BASE_INTERFACE_MODULE *pBaseInterfaceModuleMemory,
	        InterfaceType,
	        PortNo,
	        Baudrate,
	        NULL,//unsigned char *pWriting,
	        NULL,//unsigned char *pReading,
	        1, //YES , CHECK
                NULL,      // extern data
	        end_need_close,
                Delay ) ;
             }
        }

	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn3Click(TObject *Sender)
{
	Btn_ActionStopClick(Sender);
	API_bt_HciReset();
        return ;
}

//---------------------------------------------------------------------------
void __fastcall TForm_Main::Btn_ActionExecClick(TObject *Sender)
{
	BT_PARAMETER *pParam=&mBT_PARAMETER;
        BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	pParam->mChannelNumber = Cbx_NoLink_Ch->ItemIndex;
	pParam->mPacketType = Cbx_PktType->ItemIndex;
	pParam->mPayloadType = Cbx_PayloadType->ItemIndex;
	pParam->mTxPacketCount = StrToInt(Edit_PktCount->Text);

	if (Cbx_TxGainIndex->Text == "Max" )
	{
		pParam->mTxGainIndex = 0x0;
	}
	else
	{
		pParam->mTxGainIndex = StrToInt("0x"+Cbx_TxGainIndex->Text);
	}

	pParam->mPacketHeader = StrToInt(Edit_PktHeader->Text);
	pParam->mTxDAC = StrToInt(Cbx_TxDacIndex->Text);
     //	pParam->PHY = ComboBox_LEE_ContTx_PHY->ItemIndex + 1; //from 1
        pParam->PHY =  Cbx_PktType->ItemIndex+1;

	if(CheckBox_WhiteningEnable->Checked == true)
	{
		pParam->mWhiteningCoeffValue = 0x7f;
	}
	else
	{
		pParam->mWhiteningCoeffValue = 0x80;
	}
	
	//hit address
        pParam->mHitTarget= StrToInt64(ComboBox_HitAddr->Text);
		
	
	unsigned long trx_updata=0;
	String dstr;

	Cbx_Actionexec->Enabled=false;
	Btn_ActionExec->Enabled=false;
	Btn_ActionClearReport->Enabled=false;
	TrxFixObject(false);
	
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);

		goto exit;
	}
	
	if(pBTInfo->ChipType >= RTK_BT_CHIP_ID_RTL8763B)  
	{
		if (pParam->mTxGainIndex != 0x0)
		{
			pParam->mTxGainValue= pParam->mTxGainIndex;
			pParam->mTxGainIndex=0xFF;
		}
	}

	if ((CheckBox_EnableTxDac->Checked)&& (pParam->mTxDAC!=0))
	{
		pParam->ParameterIndex = SET_POWER_DAC;  
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Set Dac Fail...!!\n");Memo_msg->Lines->Add(dstr);
			return;
		}
	}

	if (FWExeJobMode1->Checked)
	{
		pParam->ExeMode = 1;
	}
	else
	{
		pParam->ExeMode = 0;
	}
	
	switch (Cbx_Actionexec->ItemIndex)
	{
		case CONT_TX_ACTION : //Cont Tx
			if(bFwTxRxMode == 0)
			{
				pParam->ParameterIndex = CONTINUE_TX_START;
				trx_updata=REPORT_CON_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}
			else
			{
				pParam->ParameterIndex = FW_CONTINUE_TX_START;
				trx_updata=REPORT_FW_CONTINUE_TX;				
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}

			break;

		case PKT_TX_ACTION : //Pkt Tx
			if(bFwTxRxMode == 0)
			{
				pParam->ParameterIndex = PACKET_TX_START;
				trx_updata=REPORT_PKT_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}
			else
			{
				pParam->ParameterIndex = FW_PACKET_TX_START;
				trx_updata=REPORT_FW_PACKET_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}

			break;
			
		case PKT_RX_ACTION : //Pkt Rx
			if(bFwTxRxMode == 0)
			{		
				pParam->ParameterIndex = PACKET_RX_START;
				trx_updata=REPORT_RKT_RX;
				PageControl_Report->ActivePage=TabSheet_RxReport;
			}
			else
			{
				pParam->ParameterIndex = FW_PACKET_RX_START;
				trx_updata=REPORT_FW_PACKET_RX;
				PageControl_Report->ActivePage=TabSheet_RxReport;			
			}
			
			break;
			
		case SINGLE_TONE_ACTION :  //Single Tone
           if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD || mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII )
                  {
                        pParam->ParameterIndex = FW_SINGLETONE_TX_START;
                        pParam->mTxGainIndex = 0x23;
                  }
                  else
                  {
			if(bFwTxRxMode == 0)
			{				
				pParam->ParameterIndex = CONTINUE_TX_START;
				trx_updata=REPORT_CON_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;

				pParam->mTxPacketCount=0;
				pParam->mWhiteningCoeffValue=0x80;
				pParam->mPayloadType= BT_PAYLOAD_TYPE_ALL0;
				pParam->mPacketType= BT_PKT_3DH5;
			}
			else
			{
				pParam->ParameterIndex = FW_CONTINUE_TX_START;
				trx_updata=REPORT_FW_CONTINUE_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;

				pParam->mTxPacketCount=0;
				pParam->mWhiteningCoeffValue=0x80;
				pParam->mPayloadType= BT_PAYLOAD_TYPE_ALL0;
				pParam->mPacketType= BT_PKT_3DH5;
			}
                  }

			break;

		case LE_CONT_TX_ACTION :	//LE Cont Tx

			if(mBT_CHIPINFO.ChipType >=RTK_BT_CHIP_ID_RTL8763B)
			{
				switch(pParam->PHY)
				{
					case LE5_TX_1M_PHY:
						pParam->mPacketType = BT_PKT_LE;
						break;
								
					case LE5_TX_2M_PHY:
						pParam->mPacketType = BT_PKT_LE_2M;
						break;
								
					case LE5_TX_CODED_PHY_S8:
						pParam->mPacketType = BT_PKT_LE_CODED_S8;
						break;

					case LE5_TX_CODED_PHY_S2:
						pParam->mPacketType = BT_PKT_LE_CODED_S2;
						break;
				}
			}

			if(bFwTxRxMode == 0)
			{
				pParam->ParameterIndex = LE_CONTINUE_TX_START;
				trx_updata=REPORT_LE_CONTINUE_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}
			else
			{
				pParam->ParameterIndex = FW_LE_CONTINUE_TX_START;
				trx_updata=REPORT_FW_LE_CONTINUE_TX;
				PageControl_Report->ActivePage=TabSheet_TXReport;
			}

			break;
		
		default:
			dstr.sprintf(">>Error ActionControlExcute...!!");Memo_msg->Lines->Add(dstr);
			return;
	}

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		dstr.sprintf(">>ActionControlExcute(%s) Fail...!!\n",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
		return;
	}

	//thread enable
	if (!TXRXThreadDisable1->Checked)
	{
		if (Thread_TRX == NULL)
		{
			Thread_TRX = new rtkbtTrx(true);
			Thread_TRX->SetTxRxUpdata(pBluetoothModule,trx_updata,pParam);
			Thread_TRX->Priority = tpHigher;//tpNormal;
			Thread_TRX->Resume();
		}
		dstr.sprintf(">>Enable TRX Thread Mode...!!",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf(">>Disable TRX Thread Mode...!!",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
	}
	
	dstr.sprintf(">>ActionControlExcute(%s) Success...!!",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
	return;
	
exit:
	Cbx_Actionexec->Enabled=true;
	Btn_ActionExec->Enabled=true;
	Btn_ActionClearReport->Enabled=true;
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Btn_ActionStopClick(TObject *Sender)
{
	//BT_PARAMETER mParam;
	//BT_PARAMETER *pParam= &mParam;
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	if (FWExeJobMode1->Checked)
	{
		pParam->ExeMode = 1;
	}
	Btn_ActionStop->Enabled = false;
	if (Thread_TRX!=NULL)
	{
		Thread_TRX->Terminate();
		Sleep(100);
		delete(Thread_TRX);
		Thread_TRX=NULL;

		switch (Cbx_Actionexec->ItemIndex)
		{
			case CONT_TX_ACTION :
				if(bFwTxRxMode == 0)
				{
					pParam->ParameterIndex=CONTINUE_TX_STOP; 
				}
				else
				{
					pParam->ParameterIndex=FW_CONTINUE_TX_STOP; 
				}
				break;

			case PKT_TX_ACTION : 
				if(bFwTxRxMode == 0)
				{
					pParam->ParameterIndex=PACKET_TX_STOP; 
				}
				else
				{
					pParam->ParameterIndex=FW_PACKET_TX_STOP; 
				}
				break;

			case PKT_RX_ACTION :
				if(bFwTxRxMode == 0)
				{			
					pParam->ParameterIndex=PACKET_RX_STOP;
				}
				else
				{
					pParam->ParameterIndex=FW_PACKET_RX_STOP;
				}
				break;

			case SINGLE_TONE_ACTION :
                                Cbx_PayloadType->Enabled = false;
                                Cbx_PktType->Enabled = false;
                          if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD || mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII )
                                {
                                        pParam->ParameterIndex = FW_SINGLETONE_TX_STOP;
                                 }
                                 else
                                 {
                                        if(bFwTxRxMode == 0)
			                {
			       	                pParam->ParameterIndex=CONTINUE_TX_STOP;
			                }
			                else
                                        {
			                	pParam->ParameterIndex=FW_CONTINUE_TX_STOP;
                                        }
                                 }
				break;

			case LE_CONT_TX_ACTION :
				if(bFwTxRxMode == 0)
				{
					pParam->ParameterIndex=LE_CONTINUE_TX_STOP;
				}
				else
				{
					pParam->ParameterIndex=FW_LE_CONTINUE_TX_STOP;
				}
				break;

		 	default:
				dstr.sprintf(">>Error ActionControlExcute...!!");Memo_msg->Lines->Add(dstr);
			goto exit;
		}
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>ActionControlExcute(%s) Fail...!!\n",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
		}
		else
		{
			dstr.sprintf(">>ActionControlExcute(%s) Stop...!!\n",Cbx_Actionexec->Text);Memo_msg->Lines->Add(dstr);
		}

        }
        if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD || mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII )
        {
               Cbx_Actionexec->ItemIndex=4;
               Cbx_Actionexec->Enabled=false;
        }
        else
        {
                Cbx_Actionexec->Enabled=true;
        }
	Btn_ActionExec->Enabled=true;
	Btn_ActionClearReport->Enabled=true;
        if(Cbx_Actionexec->ItemIndex == 4)
        {
                Cbx_NoLink_Ch->Enabled=true;
	        Cbx_PktType->Enabled=false;
	        Cbx_PayloadType->Enabled=false;
	        Edit_PktCount->Enabled=false;
        }
        else
        {
	        TrxFixObject(true);
        }

exit:
	Btn_ActionStop->Enabled = true;
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Btn_ActionClearReportClick(TObject *Sender)
{
	//BT_PARAMETER mParam;
	//BT_PARAMETER *pParam=&mParam;
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER; 
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		goto exit;
	}

        Btn_ActionClearReport->Enabled=false;

	pParam->ParameterIndex= REPORT_CLEAR;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		dstr.sprintf(">>ActionControlExcute(REPORT_CLEAR) Fail...!!");Memo_msg->Lines->Add(dstr);
		goto exit;
	}
	else
	{
		dstr.sprintf(">>ActionControlExcute(REPORT_CLEAR) Success...!!");Memo_msg->Lines->Add(dstr);
	}
 exit:
	dstr.sprintf("00000000.0");
	StringGrid_RXReport->Cells[1][1] = dstr;
	StringGrid_RXReport->Cells[1][2] = dstr;
	StringGrid_RXReport->Cells[1][3] = dstr;
	StringGrid_RXReport->Cells[1][4] = dstr;
	StringGrid_RXReport->Cells[1][5] = dstr;
	StringGrid_TXReport->Cells[1][1] = dstr;
	StringGrid_TXReport->Cells[1][2] = dstr;
        Btn_ActionClearReport->Enabled=true;

	return;
}


//---------------------------------------------------------------------------
void TForm_Main::TrxFixObject(bool Fix)
{
	Cbx_NoLink_Ch->Enabled=Fix;
	Cbx_PktType->Enabled=Fix;
	Cbx_PayloadType->Enabled=Fix;
	Edit_PktCount->Enabled=Fix;

	return;
}
//---------------------------------------------------------------------------

#define HCI_VENDOR_RF_RADIO_REG_READ_PI     0xFD4B
#define HCI_VENDOR_RF_RADIO_REG_WRITE_PI    0xFD4C

void __fastcall TForm_Main::BitBtn8Click(TObject *Sender)
{
	int rtn=0;
	int Page = 0;
	String str_RW_Addr = Edit_RW_ADDR->Text;
	String str_Value = Edit_RW_VALUE->Text;
	unsigned long RegStartAddr;
	unsigned char Msb=StrToInt(Edit_RW_MSB->Text);
	unsigned char Lsb=StrToInt(Edit_RW_LSB->Text);
	unsigned long Value, ReadingValue;
	String szType,dstr;
	unsigned char pData[512];
	unsigned char pEvtBuf[512];
	unsigned long Mask;
	unsigned char Shift;
	int i;


	if( (str_RW_Addr.Pos("0x")==0) &&(str_RW_Addr.Pos("0X")==0) )
	{
		RegStartAddr = StrToInt("0x"+str_RW_Addr);
	}
	else
	{
		RegStartAddr = StrToInt(str_RW_Addr);
	}
	

	if( (str_Value.Pos("0x")==0) && (str_Value.Pos("0X")==0) )
	{
		Value = StrToInt("0x"+str_Value);
	}
	else
	{
		Value = StrToInt(str_Value);
	}

	Value=0;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
	if (RadioButton_RF->Checked)
	{
		szType= "RF Regiser:";

		if(mBT_CHIPINFO.ChipType <RTK_BT_CHIP_ID_RTL8822C)
		{
			rtn=pBluetoothModule->GetRfRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,&Value);
		}
		else
		{
			//PI Access
			pData[0] = RegStartAddr& 0x7f;
                        pData[1] = 0;
			rtn=pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, HCI_VENDOR_RF_RADIO_REG_READ_PI,  LEN_2_BYTE, pData, 0x0E, pEvtBuf);

			ReadingValue = ( (pEvtBuf[EVT_BYTE1]<<8) + pEvtBuf[EVT_BYTE0] );
			
			// Generate mask and shift according to MSB and LSB.
			Mask = 0;

			for(i = Lsb; i < (unsigned char)(Msb + 1); i++)
				Mask |= 0x1 << i;

			Shift = Lsb;

			Value = (ReadingValue & Mask) >> Shift;
		}
	}
	else  if (RadioButton_MD->Checked)
	{
		szType= "Modem Regiser:";
		
		Page = StrToInt(Edit_RW_Page->Text);

		if(mBT_CHIPINFO.ChipType <RTK_BT_CHIP_ID_RTL8822C)
		{
			//Md switch Page
			pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, Page);
			
			rtn=pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, RegStartAddr, Msb, Lsb, &Value);

			//Md switch Page = 0
			pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0);
		}
		else
		{
			//PI Access
			pData[0] = ( RegStartAddr / 2 ) | 0x80;
			pData[1] = Page;
			rtn=pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, HCI_VENDOR_RF_RADIO_REG_READ_PI, LEN_2_BYTE, pData, 0x0E, pEvtBuf);

			ReadingValue = ( (pEvtBuf[EVT_BYTE1]<<8) + pEvtBuf[EVT_BYTE0] );

			// Generate mask and shift according to MSB and LSB.
			Mask = 0;

			for(i = Lsb; i < (unsigned char)(Msb + 1); i++)
				Mask |= 0x1 << i;

			Shift = Lsb;

			Value = (ReadingValue & Mask) >> Shift;
			
		}
	}
	else  if (RadioButton_BT->Checked)
	{
		szType= "BT Regiser:";
		Page = Combo_BBRegPageNo->ItemIndex;
		rtn=pBluetoothModule->GetBBRegMaskBits(pBluetoothModule,Page,RegStartAddr,Msb,Lsb,&Value);
	}
	else if (RadioButton_MAC->Checked)
	{
		szType= "MAC Regiser:";
		rtn=pBluetoothModule->GetSysRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,&Value);
	}

	if (rtn==0)
	{
		dstr.sprintf(">>%sRead<--%d,0x%x,[%d:%d] = 0x%x",szType,Page,RegStartAddr,Msb,Lsb,Value);
		Memo_msg->Lines->Add(dstr);
		dstr.sprintf("%x",Value);
		Edit_RW_VALUE->Text=dstr;
                Assign_DataToBtn();
	}
	else
	{
		dstr.sprintf(">>%s Read Error!!...",szType);Memo_msg->Lines->Add(dstr);
	}

	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn14Click(TObject *Sender)
{
	int rtn=0;
	int Page = 0;
	unsigned long RegStartAddr;
	unsigned char Msb=StrToInt(Edit_RW_MSB->Text);
	unsigned char Lsb=StrToInt(Edit_RW_LSB->Text);
	unsigned long Value;
	String str_RW_Addr = Edit_RW_ADDR->Text;
	String str_Value = Edit_RW_VALUE->Text;

	if( (str_RW_Addr.Pos("0x")==0) &&(str_RW_Addr.Pos("0X")==0) )
	{
		RegStartAddr = StrToInt("0x"+str_RW_Addr);
	}
	else
	{
		RegStartAddr = StrToInt(str_RW_Addr);
	}
	

	if( (str_Value.Pos("0x")==0) && (str_Value.Pos("0X")==0) )
	{
		Value = StrToInt("0x"+str_Value);
	}
	else
	{
		Value = StrToInt(str_Value);
	}

	String szType,dstr;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
	if (RadioButton_RF->Checked)
	{
		szType= "RF Register:";
		pBluetoothModule->SetRfRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
	}
	else  if (RadioButton_MD->Checked)
	{
		szType= "Modem Register:";
		
		Page = StrToInt(Edit_RW_Page->Text);

		//Md switch Page
		pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, Page);
			
		rtn=pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);

		//Md switch Page = 0
		pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0);

	}
	else  if (RadioButton_BT->Checked)
	{
		szType= "BT Register:";
		Page = Combo_BBRegPageNo->ItemIndex;
		rtn=pBluetoothModule->SetBBRegMaskBits(pBluetoothModule,Page,RegStartAddr,Msb,Lsb,Value);
	}
	else if (RadioButton_MAC->Checked)
	{
		szType= "MAC Register:";
		rtn=pBluetoothModule->SetSysRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
	}

	if (rtn==0)
	{
		dstr.sprintf(">>%sWrite-->%d, 0x%x,[%d:%d] = 0x%x",szType,Page,RegStartAddr,Msb,Lsb,Value);Memo_msg->Lines->Add(dstr);
                Assign_DataToBtn();
	}
	else
	{
		dstr.sprintf(">>%s Write Error!!...",szType);Memo_msg->Lines->Add(dstr);
	}
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_GetChipInfoClick(TObject *Sender)
{
	Memo_msg->Lines->Add("=============================");
	if (API_bt_GetChipInfo(NULL) !=0 )
	{
		Memo_msg->Lines->Add(">>Get Chip info error!!");
	}
	Memo_msg->Lines->Add("=============================");
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ClearLog1Click(TObject *Sender)
{
	Memo_msg->Lines->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::SaveLogas1Click(TObject *Sender)
{
	SaveDialog1->Options.Clear();
	SaveDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
	SaveDialog1->Filter = "Txt files (*.txt)|All files (*.*)|*.*";
	SaveDialog1->FileName="rtkBtApp.txt";
	SaveDialog1->FilterIndex=0;
	if(SaveDialog1->Execute())
	{
		Memo_msg->Lines->SaveToFile(SaveDialog1->FileName);
	}
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::LoadLog1Click(TObject *Sender)
{
	OpenDialog1->Options.Clear();
        OpenDialog1->Title = "Load Log File";
	OpenDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
	OpenDialog1->Filter = "Txt files (*.txt)|All files (*.*)|*.*";
	OpenDialog1->FileName="rtkBtApp.txt";
	OpenDialog1->FilterIndex=0;
	if(OpenDialog1->Execute())
	{
		Memo_msg->Lines->LoadFromFile(OpenDialog1->FileName);
	}
	return ;
}


void __fastcall TForm_Main::BitBtn_TestModeEnableClick(TObject *Sender)
{

	BT_PARAMETER *pParam=&mBT_PARAMETER;
	String dstr;

 	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return ;
	}

	pParam->ParameterIndex = TEST_MODE_ENABLE;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add("Test Mode Enable Fail...");
	}
	else
	{
		Memo_msg->Lines->Add("Test Mode Enable...");
	}
		
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::BitBtn_SetTxGainTable2DefaultClick(TObject *Sender)
{

	BT_PARAMETER 	*pParam=&mBT_PARAMETER;

	String dstr;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex= SET_DEFAULT_TX_GAIN_TABLE;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);	
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!=0)
	{
		dstr.sprintf(">>Set Default Tx Gain Table Fail..!!");Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf(">>Set Default Tx Gain Table Success..!!");Memo_msg->Lines->Add(dstr);
	}




	return;

}



//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_SetTxDACTable2DefaultClick(
      TObject *Sender)
{


	BT_PARAMETER *pParam=&mBT_PARAMETER;

	String dstr;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex= SET_DEFAULT_TX_DAC_TABLE;
	
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!=0)
	{
		dstr.sprintf(">>Set Default Tx DAC Table Fail..!!");Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf(">>Set Default Tx DAC Table Success..!!");Memo_msg->Lines->Add(dstr);
	}
	return ;

}

//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SetRtl8761XtalClick(TObject *Sender)
{

	BT_PARAMETER *pParam=&mBT_PARAMETER;

	String dstr;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return ;
	}
        
 	BitBtn_GetRtl8761Xtal->Enabled = false;
	BitBtn_SetRtl8761Xtal->Enabled = false;
	Button_BBPro_WriteToFlashConfig->Enabled = false;
        
	pParam->ParameterIndex = SET_XTAL;

        pParam->Rtl8761Xtal = Cbx_RTL8761_XTAL->ItemIndex;

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
                Memo_msg->Lines->Add("Set Crystal Fail...");
	}
	else
	{
		dstr.sprintf("Set Crystal = 0x%x",pParam->Rtl8761Xtal);
		Memo_msg->Lines->Add(dstr);
	}
 	BitBtn_GetRtl8761Xtal->Enabled = true;
	BitBtn_SetRtl8761Xtal->Enabled = true;
	Button_BBPro_WriteToFlashConfig->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_ReadThermalClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
	
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionReport(pBluetoothModule,REPORT_THERMAL, &mBT_DEVICE_REPORT)!=0)
	{
		Memo_msg->Lines->Add("Read Thermal Fail...");
	}
	else
	{
        	dstr.sprintf("0x%x", mBT_DEVICE_REPORT.CurrThermalValue);
		Memo_msg->Lines->Add("Read Thermal..."+dstr);
	}	
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::BitBtn_GetRtl8761XtalClick(TObject *Sender)
{
	//   BT_PARAMETER 	*pParam=&mBT_PARAMETER;

	String dstr;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

 	BitBtn_GetRtl8761Xtal->Enabled = false;
	BitBtn_SetRtl8761Xtal->Enabled = false;
	Button_BBPro_WriteToFlashConfig->Enabled = false;

	if(pBluetoothModule->ActionReport(pBluetoothModule,REPORT_XTAL, &mBT_DEVICE_REPORT)!=0)
	{
                Memo_msg->Lines->Add("Get Crystal Fail...");
		goto error;
	}
	else
	{
		dstr.sprintf("Get Crystal = 0x%x",mBT_DEVICE_REPORT.CurrRtl8761Xtal);
		Memo_msg->Lines->Add(dstr);
	}


        Cbx_RTL8761_XTAL->ItemIndex = mBT_DEVICE_REPORT.CurrRtl8761Xtal;
error:
 	BitBtn_GetRtl8761Xtal->Enabled = true;
	BitBtn_SetRtl8761Xtal->Enabled = true;
	Button_BBPro_WriteToFlashConfig->Enabled = true;
        return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_GetBTStageClick(TObject *Sender)
{
	//BT_PARAMETER 	*pParam=&mBT_PARAMETER;

	String dstr;

        char ShowStr[][50] = {
         {" Stage"},
         {" version"},
         {" FT k"},
         {" MODULE k"},
         {" POWER_TRACKING"},
         {" FACTOR_SETTING"}
        };

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return ;
	}
/*
PHY_STAGE    0
PHY_VERSION   1
PHY_FT        2
PHY_MODULE    3
PHY_POWER_TRACKING  4
PHY_FACTOR_SETTING   5
*/
        switch (ComboBox_PHY_STATUS->ItemIndex)
        {
           case 1:   mBT_DEVICE_REPORT.CurrStage = 1; break;
           case 2:   mBT_DEVICE_REPORT.CurrStage = 2; break;
           case 3:   mBT_DEVICE_REPORT.CurrStage = 3; break;
           case 4:   mBT_DEVICE_REPORT.CurrStage = 4; break;
           case 5:   mBT_DEVICE_REPORT.CurrStage = 5; break;
           case 0:
           default:
                     mBT_DEVICE_REPORT.CurrStage = 0;
           break;
        }

	if(pBluetoothModule->ActionReport(pBluetoothModule, REPORT_BT_STAGE, &mBT_DEVICE_REPORT)!=0)
	{
                dstr.sprintf(">>Get PHY %s Fail!!",ShowStr[mBT_DEVICE_REPORT.CurrStage]);
		Memo_msg->Lines->Add(dstr);

	}
	else
	{
                if (mBT_DEVICE_REPORT.CurrStage ==0)
		{
                        dstr.sprintf(">>Get BT Stage... Stage= %d",mBT_DEVICE_REPORT.CurrStage) ;
                }
                else
                {
                  dstr.sprintf(">>Get PHY %s ...(Please check DebugView log)",ShowStr[mBT_DEVICE_REPORT.CurrStage]) ;
                }
		Memo_msg->Lines->Add(dstr);

                if (ComboBox_PHY_STATUS->ItemIndex == 1)   //phy version
                {
                   dstr.sprintf("PHY Version : %d ,%d ,%d ,% d",mBT_DEVICE_REPORT.ReportData[25],mBT_DEVICE_REPORT.ReportData[24],mBT_DEVICE_REPORT.ReportData[23],mBT_DEVICE_REPORT.ReportData[22] ) ;
                   Memo_msg->Lines->Add(dstr);
                }
	}
	return;


}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::TXRXThreadDisable1Click(TObject *Sender)
{
	TXRXThreadDisable1->Checked=! TXRXThreadDisable1->Checked;
}

//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_PGMPDataClick(TObject *Sender)
{
	String dstr;
	unsigned long long  BDADDR= StrToInt64(Edit_Efuse_BDAddr->Text) ;
	unsigned char Thermal=StrToInt(Edit_Efuse_Thermal->Text)&0xFF;
	unsigned char dac=StrToInt(Edit_Efuse_Dac->Text)&0xFF;
	unsigned char Xtal=StrToInt(Edit_Efuse_Xtal->Text)&0xFF;

	BitBtn_PGMPData->Enabled=false;
	WriteMpParamterToEfuse((unsigned char *)&BDADDR,Thermal,dac,Xtal);

	if (CheckBox_Efuse_PowerOn->Checked)
		WriteMpPowerOnFunctionToEfuse(ComboBox_PowerOnEnable->ItemIndex,ComboBox_PowerOnActive->ItemIndex);

	dstr.sprintf(">>Write Efuse MP Data process end... \n");
	Memo_msg->Lines->Add(dstr);

	BitBtn_PGMPData->Enabled=true;
		
	return;
}
//---------------------------------------------------------------------------




int TForm_Main::BaseWriteMpParamterToEfuse(unsigned char Index, unsigned char *pData)
{
	BT_PARAMETER *pParam=	&mBT_PARAMETER;

	int n=0;

	unsigned char *pPGRawData;

	DBGPRINTF(">>++RTKBT_BaseWriteMpParamterToEfuse()\n");

	pParam->ParameterIndex = WRITE_EFUSE_DATA;
	pPGRawData = pParam->mPGRawData;
	memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

	if (Index == SET_INDEX_BT_ADDR)
	{
		if ((pData[0] != 0x00) || (pData[1] != 0x00) ||(pData[2] != 0x00)
		||  (pData[3] != 0x00)|| (pData[4] != 0x00) ||(pData[5] != 0x00))
		{
			pPGRawData[0] = 0x01; // BT Efuse
			pPGRawData[1] = 0x3c; // offset low byte
			pPGRawData[2] = 0x00; // offset high byte
			pPGRawData[3] = 0x06; // len
			for (n=0; n < 6; n++) // 6-byte mac addr
				pPGRawData[n+4]= pData[n];
		}
	}
	else if (Index == SET_INDEX_TX_POWER_DAC)
	{
		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x60; // offset low byte
		pPGRawData[2] = 0x01; // offset high byte
		pPGRawData[3] = 0x02; // len
		pPGRawData[4] = 0xfe; // low byte value
		pPGRawData[5] = pData[0]; // dac value
	}
	else if (Index == SET_INDEX_THERMAL)
	{
		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x80; // offset low byte
		pPGRawData[2] = 0x01; // offset high byte
		pPGRawData[3] = 0x02; // len
		pPGRawData[4] = 0x00; // low byte value
		pPGRawData[5] = pData[0]; // thermal value
	}
	else if(Index == SET_INDEX_XTAL)
	{
		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0xe6; // offset low byte
		pPGRawData[2] = 0x01; // offset hight byte
		pPGRawData[3] = 0x01; // len
		pPGRawData[4] = pData[0] & 0x3f; // 1-byte crystal	
	}
	else if(Index == SET_INDEX_USB_VID_PID)
	{
		pPGRawData[0] = 0x02; // SYS Efuse
		pPGRawData[1] = 0x24; // offset low byte
		pPGRawData[2] = 0x00; // offset high byte
		pPGRawData[3] = 0x04; // len
		for (n = 0; n < 4; n++) // 4-byte usb vid, pid
			pPGRawData[n+4] = pData[n];	
	}		
	else
	{
		DBGPRINTF(">>No Write efuse MP Data...\n");	
		return 0;
	}

	if (pBluetoothModule == NULL)
	{
		DBGPRINTF(">>BluetoothModule is NULL...!!\n");
		goto exit;
	}
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);


	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		DBGPRINTF(">>Raw Data Exec Fail...\n");
		goto exit;
	}
	else
	{
		DBGPRINTF(">>Raw Data Exec Success...\n");
	}

	DBGPRINTF(">>--RTKBT_BaseWriteMpParamterToEfuse\n");
	
	return 0;
exit:

	DBGPRINTF(">>--RTKBT_BaseWriteMpParamterToEfuse : ERROR\n");
	
	return 1;
}





//---------------------------------------------------------------------------
int TForm_Main:: WriteMpParamterToEfuse(unsigned char *BD_Addr,unsigned char ThermalValue,unsigned char TxPowerDac, unsigned char Xtal)  //Output
{
	
	if (CheckBox_Efuse_BDAddr->Checked)
	{
		BaseWriteMpParamterToEfuse(SET_INDEX_BT_ADDR, BD_Addr);
	}

	if (CheckBox_Efuse_Thermal->Checked)
	{
		BaseWriteMpParamterToEfuse(SET_INDEX_THERMAL, &ThermalValue);
	}

	if (CheckBox_Efuse_Dac->Checked)
	{
		BaseWriteMpParamterToEfuse(SET_INDEX_TX_POWER_DAC, &TxPowerDac);
	}

	if (CheckBox_Efuse_Xtal->Checked)
	{
		BaseWriteMpParamterToEfuse(SET_INDEX_XTAL, &Xtal);
	}

	return 0;

}

//---------------------------------------------------------------------------
int TForm_Main::BaseWriteMpParamterToEfuseMap(unsigned char Index, unsigned char *pData)
{
	BT_PARAMETER *pParam=	&mBT_PARAMETER;
	int n=0;
	unsigned char *pPGRawData;
	DBGPRINTF(">>++RTKBT_BaseWriteMpParamterToEfuse()\n");
	pParam->ParameterIndex = WRITE_EFUSE_DATA;
	pPGRawData = pParam->mPGRawData;
	memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

	if (Index == SET_INDEX_BT_ADDR)
	{
		if ((pData[0] != 0x00) || (pData[1] != 0x00) ||(pData[2] != 0x00)
		||  (pData[3] != 0x00)|| (pData[4] != 0x00) ||(pData[5] != 0x00))
		{
			pPGRawData[0] =0x01; // BT Efuse
                        pPGRawData[1] =0x30; // offset low byte
                        pPGRawData[2] =0x00; // offset high byte
                        pPGRawData[3] =0x06; // len low byte
                        pPGRawData[4] =0x00; // len high byte

			for (n=0; n < 6; n++) // 6-byte mac addr
				pPGRawData[n+5]= pData[n];
		}
	}
	else if (Index == SET_INDEX_TX_POWER_GAIN_CAL)
	{
	        unsigned char *pReport;
	        String dstr;

                // Read 0x278 first
	        pParam->ParameterIndex = READ_EFUSE_DATA;
	        pPGRawData = pParam->mPGRawData;
	        pReport = mBT_DEVICE_REPORT.ReportData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x78; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len

                pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr 0x278");
			Memo_msg->Lines->Add(dstr);

		}
		else
		{
                        memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02X",pReport[5]);
			//Edit_Efuse_Map_BDAddr->Text=dstr;
			Memo_msg->Lines->Add(">>Read BDAddr 0x278 Efuse Success: "+dstr);
		}

                // Write
                if(pReport[5]==0xff)
                {
                        pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                pPGRawData = pParam->mPGRawData;
	                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
                        pPGRawData[0] = 0x01; // BT Efuse
		        pPGRawData[1] = 0x78; // offset low byte
		        pPGRawData[2] = 0x02; // offset high byte
		        pPGRawData[3] = 0x02; // len
		        pPGRawData[4] = 0x00; // low byte value
		        pPGRawData[5] = 0x02; //set TX gain K valid bit offset 0x278[1]=1
                        pPGRawData[6] = pData[0]; //set TX Gain K offset =0x279
                }
                else
                {
                        if( ((pReport[5]>>2) && 0x01) == 0x00 )
                        {
                                pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                        pPGRawData = pParam->mPGRawData;
	                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
                                pPGRawData[0] = 0x01; // BT Efuse
		                pPGRawData[1] = 0x78; // offset low byte
		                pPGRawData[2] = 0x02; // offset high byte
		                pPGRawData[3] = 0x02; // len
		                pPGRawData[4] = 0x00; // low byte value
		                pPGRawData[5] = 0x02; //set TX gain K valid bit offset 0x278[1]=1
                                pPGRawData[6] = pData[0]; //set TX Gain K offset =0x279
                        }
                        else
                        {
                                pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                        pPGRawData = pParam->mPGRawData;
	                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
                                pPGRawData[0] = 0x01; // BT Efuse
		                pPGRawData[1] = 0x78; // offset low byte
		                pPGRawData[2] = 0x02; // offset high byte
		                pPGRawData[3] = 0x02; // len
		                pPGRawData[4] = 0x00; // low byte value
		                pPGRawData[5] = 0x06; //set TX gain K valid bit offset 0x278[1]=1
                                pPGRawData[6] = pData[0]; //set TX Gain K offset =0x279
                        }
                }
	}
        else if (Index == SET_INDEX_FLATNESS_CAL)
	{
                unsigned char *pReport;
                unsigned char TxPowerGainCal;

	        String dstr;

                // Read 0x278 first
	        pParam->ParameterIndex = READ_EFUSE_DATA;
	        pPGRawData = pParam->mPGRawData;
	        pReport = mBT_DEVICE_REPORT.ReportData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x78; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len

                pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr 0x278");
			Memo_msg->Lines->Add(dstr);

		}
		else
		{
                        memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02X",pReport[5]);
                        TxPowerGainCal = pReport[6];
			//Edit_Efuse_Map_BDAddr->Text=dstr;
			Memo_msg->Lines->Add(">>Read BDAddr 0x278 Efuse Success: "+dstr);
		}

                // Write
                if(pReport[5]==0xff)
                {
                        pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                pPGRawData = pParam->mPGRawData;
	                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

                     	pPGRawData[0] = 0x01; // BT Efuse
		        pPGRawData[1] = 0x78; // offset low byte
		        pPGRawData[2] = 0x02; // offset high byte
		        pPGRawData[3] = 0x04; // len
		        pPGRawData[4] = 0x00; // low byte value
		        pPGRawData[5] = 0x04; // set TX gain K valid bit offset 0x278[1]=1
                        pPGRawData[6] = 0xff; //
                        //pPGRawData[7]= (unsigned char)(pData[0]&0xff);
                        //pPGRawData[8]= (unsigned char)(pData[0]>>8)&0xff;
                        pPGRawData[7]= pData[0];
                        pPGRawData[8]= pData[1];
                }
                else
                {
                        if( ((pReport[5]>>1) && 0x01) == 0x00 )
                        {
                                pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                        pPGRawData = pParam->mPGRawData;
	                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
                                pPGRawData[0] = 0x01; // BT Efuse
		                pPGRawData[1] = 0x78; // offset low byte
		                pPGRawData[2] = 0x02; // offset high byte
		                pPGRawData[3] = 0x04; // len
		                pPGRawData[4] = 0x00; // low byte value
		                pPGRawData[5] = 0x04; // set TX gain K valid bit offset 0x278[1]=1
                                pPGRawData[6] = 0xff; //
                                //pPGRawData[7]= (unsigned char)(pData[0]&0xff);
                                //pPGRawData[8]= (unsigned char)(pData[0]>>8)&0xff;
                                pPGRawData[7]= pData[0];
                                pPGRawData[8]= pData[1];
                        }
                        else
                        {
                                pParam->ParameterIndex = WRITE_EFUSE_DATA;
	                        pPGRawData = pParam->mPGRawData;
	                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
                                pPGRawData[0] = 0x01; // BT Efuse
		                pPGRawData[1] = 0x78; // offset low byte
		                pPGRawData[2] = 0x02; // offset high byte
		                pPGRawData[3] = 0x04; // len
		                pPGRawData[4] = 0x00; // low byte value
		                pPGRawData[5] = 0x06; //set TX gain K valid bit offset 0x278[1]=1
                                pPGRawData[6] = TxPowerGainCal; //set TX Gain K offset =0x279
                                pPGRawData[7]= (unsigned char)(pData[0]&0xff);
                                pPGRawData[8]= (unsigned char)(pData[1]&0xff);
                        }
                }
	}
        else if (Index == SET_INDEX_TX_POWER_AND_FLATNESS_CAL)
	{
		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x78; // offset low byte
		pPGRawData[2] = 0x02; // offset high byte
		pPGRawData[3] = 0x04; // len
		pPGRawData[4] = 0x00; // low byte value
		pPGRawData[5] = 0x06; // set TX gain K valid bit offset 0x278[1]=1
                pPGRawData[6] = pData[2]; //
                pPGRawData[7]= (unsigned char)(pData[0]&0xff);
                //pPGRawData[8]= (unsigned char)(pData[0]>>8)&0xff;
                pPGRawData[8]= (unsigned char)(pData[1]&0xff);

	}
	else if (Index == SET_INDEX_THERMAL)
	{
                unsigned char *pReport;

	        String dstr;

                // Read 0x28c first
	        pParam->ParameterIndex = READ_EFUSE_DATA;
	        pPGRawData = pParam->mPGRawData;
	        pReport = mBT_DEVICE_REPORT.ReportData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x8c; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len

                pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr 0x28c");
			Memo_msg->Lines->Add(dstr);

		}
		else
		{
                        memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02X",pReport[6]);
			//Edit_Efuse_Map_BDAddr->Text=dstr;
			//Memo_msg->Lines->Add(">>Read BDAddr 0x278 Efuse Success: "+dstr);
		}

                // Write
                pParam->ParameterIndex = WRITE_EFUSE_DATA;
                pPGRawData = pParam->mPGRawData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x8c; // offset low byte
		pPGRawData[2] = 0x02; // offset high byte
		pPGRawData[3] = 0x02; // len
		pPGRawData[4] = 0x00; // low byte value
		pPGRawData[5] = pData[0]; // thermal value
                pPGRawData[6] = pReport[6];
	}
	else if(Index == SET_INDEX_XTAL)
	{
		pPGRawData[0] = 0x02; // System Efuse
		pPGRawData[1] = 0x16; // offset low byte
		pPGRawData[2] = 0x00; // offset hight byte
		pPGRawData[3] = 0x02; // len low byte
		pPGRawData[4] = 0x00; // len high byte
                pPGRawData[5] = pData[0]; // CrystalCapValue;
                pPGRawData[6] = pData[0]; // CrystalCapValue;

	}
        else if(Index == SET_INDEX_BANDEDGE)
	{
                unsigned char *pReport;
	        String dstr;
                unsigned char data;
                // Read 0x1E4 first
	        pParam->ParameterIndex = READ_EFUSE_DATA;
	        pPGRawData = pParam->mPGRawData;
	        pReport = mBT_DEVICE_REPORT.ReportData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0xE4; // Logical Address LSB
                pPGRawData[2] = 0x01; // Logical Address MSB
                pPGRawData[3] = 0x04; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len

                pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr 0x1E4");
			Memo_msg->Lines->Add(dstr);

		}
		else
		{
                        memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02X",pReport[7]);
                        data = pReport[7];
			//Edit_Efuse_Map_BDAddr->Text=dstr;
			Memo_msg->Lines->Add(">>Read BDAddr 0x1E6 Efuse Success: "+dstr);
		}

                // Write
                pParam->ParameterIndex = WRITE_EFUSE_DATA;
                pPGRawData = pParam->mPGRawData;
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);
		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0xE4; // offset low byte
		pPGRawData[2] = 0x01; // offset hight byte
		pPGRawData[3] = 0x04; // len low byte
		pPGRawData[4] = 0x00; // len high byte
                pPGRawData[5] = (unsigned char)(pData[1]&0xFF); // (unsigned char)(40M_bandedge_F_cal&0xFF);
                pPGRawData[6] = (unsigned char)(pData[2]&0xFF);
                pPGRawData[7] = data;
                pPGRawData[8] = (unsigned char)(pData[0]&0xFF);

	}
	else if(Index == SET_INDEX_USB_VID_PID)
	{
		pPGRawData[0] = 0x02; // SYS Efuse
		pPGRawData[1] = 0x24; // offset low byte
		pPGRawData[2] = 0x00; // offset high byte
		pPGRawData[3] = 0x04; // len
		for (n = 0; n < 4; n++) // 4-byte usb vid, pid
			pPGRawData[n+4] = pData[n];	
	}
	else
	{
		DBGPRINTF(">>No Write efuse MP Data...\n");	
		return 0;
	}
        
	if (pBluetoothModule == NULL)
	{
		DBGPRINTF(">>BluetoothModule is NULL...!!\n");
		goto exit;
	}
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);


	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		DBGPRINTF(">>Raw Data Exec Fail...\n");
		goto exit;
	}
	else
	{
		DBGPRINTF(">>Raw Data Exec Success...\n");
	}

	DBGPRINTF(">>--RTKBT_BaseWriteMpParamterToEfuse\n");

	return 0;
exit:

	DBGPRINTF(">>--RTKBT_BaseWriteMpParamterToEfuse : ERROR\n");

	return 1;
}


//---------------------------------------------------------------------------
int TForm_Main:: WriteMpParamterToEfuseMap(unsigned char *BD_Addr,unsigned char ThermalValue,unsigned char TXPower, unsigned char *Flatness, unsigned char Xtal, unsigned char* Bandedge)  //Output
{

	if (CheckBox_Efuse_Map_BDAddr->Checked)
	{
		BaseWriteMpParamterToEfuseMap(SET_INDEX_BT_ADDR, BD_Addr);
	}

	if (CheckBox_Efuse_Map_Thermal->Checked)
	{
		BaseWriteMpParamterToEfuseMap(SET_INDEX_THERMAL, &ThermalValue);
        }

	if (CheckBox_Efuse_Map_TX->Checked && !CheckBox_Efuse_Map_Flatness->Checked)
	{
                BaseWriteMpParamterToEfuseMap(SET_INDEX_TX_POWER_GAIN_CAL, &TXPower);
	}

        if (!CheckBox_Efuse_Map_TX->Checked && CheckBox_Efuse_Map_Flatness->Checked)
        {
                BaseWriteMpParamterToEfuseMap(SET_INDEX_FLATNESS_CAL, Flatness);
        }

        if (CheckBox_Efuse_Map_TX->Checked && CheckBox_Efuse_Map_Flatness->Checked)
        {
                Flatness[2]=TXPower;
                BaseWriteMpParamterToEfuseMap(SET_INDEX_TX_POWER_AND_FLATNESS_CAL, Flatness);
        }

	if (CheckBox_Efuse_Map_Xtal->Checked)
	{
		BaseWriteMpParamterToEfuseMap(SET_INDEX_XTAL, &Xtal);
	}

        if (CheckBox_Efuse_Map_40M->Checked)
	{
		BaseWriteMpParamterToEfuseMap(SET_INDEX_BANDEDGE, Bandedge);
	}

	return 0;

}


int TForm_Main:: WriteMpPowerOnFunctionToEfuse(int PowerOn_enable,int PowerOn_Active)  //Output
{
        String dstr;
        BT_PARAMETER 	*pParam=&mBT_PARAMETER;
        pParam->ParameterIndex = WRITE_EFUSE_DATA;
        unsigned char *pData = pParam->mPGRawData;
        memset(pData,0x00,64);

        if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}

        pData[0] = 0x01; // BT Efuse
        pData[1] = 0x76; // offset low byte
        pData[2] = 0x01; // offset high byte
        pData[3] = 0x02; // len
        pData[4] = 0x20; // low byte value

       if (PowerOn_enable == 0)
                pData[5]=0x3c;
       else
                pData[5]=0x3d;

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add("Raw Data Exec Fail...");
		return -1;
	}
	else
	{
		Memo_msg->Lines->Add("Raw Data Exec Success...");
	}
	
	pData[0] = 0x01; // BT Efuse
	pData[1] = 0x30; // offset low byte
	pData[2] = 0x00; // offset high byte
	pData[3] = 0x02; // len

	if (PowerOn_Active == 0) // high level active, keep low when idle
	{
		pData[4]=0x40;
		pData[5]=0x52;
	}
	else // low level active, keep high when idle
	{
		pData[4]=0x52;
		pData[5]=0x50;
	}

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add("Raw Data Exec Fail...");
		return -1;
	}
	else
	{
		Memo_msg->Lines->Add("Raw Data Exec Success...");
	}
	return 0;
}



//---------------------------------------------------------------------------



#define LE_TX_DUT_TEST 0
#define LE_RX_DUT_TEST 1


void __fastcall TForm_Main::Btn_LeTest_StartClick(TObject *Sender)
{
	String dstr;

	BT_PARAMETER *pParam=&mBT_PARAMETER;
	DWORD t_start,t_end,t;

	unsigned char LeTest_Action = ComboBox_LeTest_Action->ItemIndex;
	unsigned char LeTest_Channel = ComboBox_LeTest_Channel->ItemIndex;
	unsigned char LeTest_DataLen = ComboBox_LeTest_DataLen->ItemIndex;
	unsigned char LeTest_PayloadType =ComboBox_LeTest_PayloadType->ItemIndex;
	unsigned long LeTest_TxGainIndex = StrToInt(ComboBox_LeTest_TxGainIndex->Text);
	unsigned long LeTest_PHY = ComboBox_LEE_PHY->ItemIndex;
	unsigned long LeTest_Modulation = ComboBox_LEE_Modulation->ItemIndex;	


        //////////////////////////////////////////////////////////////////
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

#if 0
	if(pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8723D)
	{
		pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x3C, 13, 13, 0);
	}
	
	pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x3C, 12, 12, 0);
	pBluetoothModule->SetBBRegMaskBits(pBluetoothModule, 0, 0x178, 15, 0, LeTest_TxGainValue);
	pBluetoothModule->SetBBRegMaskBits(pBluetoothModule, 0, 0x17A, 15, 0, 0x382);
#endif

	pParam->mChannelNumber= LeTest_Channel;
	pParam->mParamData[0] = LeTest_DataLen;
	pParam->mPayloadType= LeTest_PayloadType;
	pParam->PHY = LeTest_PHY + 1; //from 1
	pParam->ModulationIndex = LeTest_Modulation;	
	pParam->mTxGainIndex = LeTest_TxGainIndex;

        Memo_msg->Lines->Add(dstr);

	if(LeTest_Action == LE_TX_DUT_TEST)
	{
		pParam->ParameterIndex = LE_TX_DUT_TEST_CMD;
		dstr.sprintf(">>LeTest_Start : PKT TX\n");
	}
	else
	{
		pParam->ParameterIndex = LE_RX_DUT_TEST_CMD;
		dstr.sprintf(">>LeTest_Start : PKT RX\n");
	}

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		dstr.sprintf(">>ActionControlExcute(%d) Fail...!!\n",pParam->ParameterIndex );
		Memo_msg->Lines->Add(dstr);
		return ;
	}

	Btn_LeTest_Start->Enabled = false;
	Btn_LeTest_Stop->Enabled = true;

	Memo_msg->Lines->Add(dstr);

        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Btn_LeTest_StopClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
	//RadioGroup_Thermal_Panel->Enabled=true;
	if (ShowUI != NULL)
	{
		ShowUI->Terminate();
		ShowUI =NULL;
	}
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	if( (ComboBox_LeTest_Action->ItemIndex == LE_TX_DUT_TEST) || 
		(ComboBox_LeTest_Action->ItemIndex == LE_RX_DUT_TEST) )
	{
		pParam->ParameterIndex = LE_DUT_TEST_END_CMD;
	}

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		dstr.sprintf(">>ActionControlExcute(%d) Fail...!!\n",pParam->ParameterIndex );
		Memo_msg->Lines->Add(dstr);
		return;
	}

	pBluetoothModule->ActionReport(pBluetoothModule,REPORT_LE_RX, &mBT_DEVICE_REPORT);

	dstr.sprintf("%d",mBT_DEVICE_REPORT.TotalRxCounts);
	
	Edit_LeTest_RxCount->Text=dstr;	
	
	Btn_LeTest_Start->Enabled = true;
	Btn_LeTest_Stop->Enabled = false;

	dstr.sprintf(">>LeTest_Stop\n");
	Memo_msg->Lines->Add(dstr);

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ComboBox_LeTest_ActionChange(TObject *Sender)
{

	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;
  	ComboBox_LeTest_DataLen->Enabled = true;
       	ComboBox_LeTest_PayloadType->Enabled = true;
        Edit_LeTest_RxCount->Enabled = true;
        if ((mBT_DEVICE_REPORT.pBTInfo == NULL) || (AllFunction1->Checked))
        {
			ComboBox_LEE_PHY->Enabled = true;
			ComboBox_LEE_Modulation->Enabled = true;

			ComboBox_LEE_PHY->Items->Clear();
			ComboBox_LEE_PHY->Items->Add("LE 1M PHY");
			ComboBox_LEE_PHY->Items->Add("LE 2M PHY");
                        if(mBT_CHIPINFO.ChipType != RTK_BT_CHIP_ID_RTL8773B)
                        {
			        ComboBox_LEE_PHY->Items->Add("LE Coded PHY with S=8");
			        ComboBox_LEE_PHY->Items->Add("LE Coded PHY with S=2");
                        }
			ComboBox_LEE_PHY->ItemIndex = 0;

                        return ;
        }

	if(ComboBox_LeTest_Action->ItemIndex == LE_TX_DUT_TEST)
	{
		ComboBox_LeTest_DataLen->Enabled = true;
		ComboBox_LeTest_PayloadType->Enabled = true;
		Edit_LeTest_RxCount->Enabled = false;


	}
	else if(ComboBox_LeTest_Action->ItemIndex == LE_RX_DUT_TEST)
	{
		ComboBox_LeTest_DataLen->Enabled = false;
		ComboBox_LeTest_PayloadType->Enabled = false;
		Edit_LeTest_RxCount->Enabled = true;

	  /*	if(pModuleBtReport->pBTInfo->ChipType>=RTK_BT_CHIP_ID_RTL8763B)
		{
			ComboBox_LEE_PHY->Enabled = true;
			ComboBox_LEE_Modulation->Enabled = true;

			ComboBox_LEE_PHY->Items->Clear();
			ComboBox_LEE_PHY->Items->Add("LE 1M PHY");
			ComboBox_LEE_PHY->Items->Add("LE 2M PHY");
			ComboBox_LEE_PHY->Items->Add("LE Coded PHY");
			ComboBox_LEE_PHY->ItemIndex = 0;
		}
            */    
	}
	else
	{
		ComboBox_LeTest_DataLen->Enabled = false;
		ComboBox_LeTest_PayloadType->Enabled = false;
		Edit_LeTest_RxCount->Enabled = false;
	}

        
	return ;
}
//---------------------------------------------------------------------------
#if 0
#define LEN_6_BYTE	6

int TForm_Main::WriteMpParamterToConfig(unsigned char Index, unsigned char *pData) 
{
	BT_PARAMETER *pParam =	&mBT_PARAMETER;

	unsigned char *pParamData;

	unsigned long i;

	String dstr;
	
	pParam->ParameterIndex = WRITE_PARAM_TO_FACTORY_AREA;
	pParamData = pParam->mParamData;
	
	pParamData[0] = Index;

	if(Index == SET_INDEX_BT_ADDR)
	{
		for( i = 0; i <LEN_6_BYTE; i++)
		{
			pParamData[i+1] = pData[i];
		}
	}
	else if(Index == SET_INDEX_XTAL)
	{
		pParamData[1] = pData[0];
		pParamData[2] = pData[0];
		pParamData[3] = 1;
		pParamData[4] = pData[0];
	}
	else
	{
		dstr.sprintf(">>No Write MP Data To Config...");
		Memo_msg->Lines->Add(dstr);
		goto exit;
	}

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!");
		Memo_msg->Lines->Add(dstr);		
		goto exit;
	}
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);


	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		goto exit;
	}
	
	dstr.sprintf(">>--RTKBT_WriteMpParamterToConfig");
	Memo_msg->Lines->Add(dstr);	
	return 0;
	
exit:
	dstr.sprintf(">>--RTKBT_WriteMpParamterToConfig : ERROR");
	Memo_msg->Lines->Add(dstr);	
	
	return 1;

}
#endif

void __fastcall TForm_Main::Button_ToFactoryAreaClick(TObject *Sender)
{
#if 0
	unsigned long long  BDADDR= StrToInt64(Edit1->Text) ;
	unsigned char Thermal=StrToInt(Edit2->Text)&0xFF;
	unsigned char dac=StrToInt(Edit3->Text)&0xFF;
	unsigned char Xtal=StrToInt(Edit4->Text)&0xFF;

	WriteMpParamterToConfig(SET_INDEX_BT_ADDR, (unsigned char *)&BDADDR);

	WriteMpParamterToConfig(SET_INDEX_XTAL, &Xtal);

#endif
	return ;    
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::CheckBox_EnableTxDacClick(TObject *Sender)
{
	unsigned int i;
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}	
		
	pParam->ParameterIndex= SET_DEFAULT_TX_DAC_TABLE;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!=0)
	{
		goto error;
	}

	pBluetoothModule->ActionReport(pBluetoothModule,REPORT_TX_DAC_TABLE, &mBT_DEVICE_REPORT);

	if (CheckBox_EnableTxDac->Checked)
	{
		Cbx_TxDacIndex->Enabled = true;
	}
	else
	{
		Cbx_TxDacIndex->Enabled = false;
	}

	Cbx_TxDacIndex->Items->Clear();
	for (i=0; i<MAX_TXDAC_TABLE_SIZE; i++ )
	{
		dstr.sprintf("0x%.2x",mBT_DEVICE_REPORT.CurrTXDACTable[i]);
		Cbx_TxDacIndex->Items->Add(dstr);
	}

error:

	return;
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::Button_LedSetClick(TObject *Sender)
{

	String dstr;

	unsigned char pData[512];
	unsigned char pEvtBuf[512];

	pData[0] = ComboBox_LedNo->ItemIndex;
	pData[1] = ComboBox_LedLevel->ItemIndex;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xfc37, 2, pData, 0x0E, pEvtBuf);

	if(pEvtBuf[5] != 0)
	{
		dstr.sprintf("Led Set : ERROR !!\n");Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf("Led Set : Success !!\n");Memo_msg->Lines->Add(dstr);
	}
	return;        
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_ReadEfuseClick(TObject *Sender)
{


	unsigned char *pPGRawData;
	unsigned char *pReport;
	
	String dstr;
	BT_PARAMETER *pParam;
	pParam=	&mBT_PARAMETER;
	
	pParam->ParameterIndex = READ_EFUSE_DATA;
	pPGRawData = pParam->mPGRawData;
	pReport = mBT_DEVICE_REPORT.ReportData;

 	BitBtn_ReadEfuse->Enabled=false;	

	if (CheckBox_Efuse_BDAddr->Checked)
	{
		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x3c;
		pPGRawData[2] = 0x00;
		pPGRawData[3] = 0x06;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr efuse");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0X%02X%02X%02X%02X%02X%02X",pReport[9], pReport[8], pReport[7], pReport[6], pReport[5], pReport[4]);
			Edit_Efuse_BDAddr->Text=dstr;
			Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
		}
	}

	if (CheckBox_Efuse_Thermal->Checked)
	{
		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x81;
		pPGRawData[2] = 0x01;
		pPGRawData[3] = 0x01;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
		     	dstr.sprintf(">>Failed to read Thermal efuse");
		      	Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x",pReport[4]);
			Edit_Efuse_Thermal->Text=dstr;
			Memo_msg->Lines->Add(">>Read Thermal Efuse Success: " + dstr);
		}
	}

	if (CheckBox_Efuse_Dac->Checked)
	{

		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x61;
		pPGRawData[2] = 0x01;
		pPGRawData[3] = 0x01;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read DAC Efuse");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%.2x",pReport[4]);
			Edit_Efuse_Dac->Text=dstr;
                        Memo_msg->Lines->Add(">>Read DAC Efuse Success: " + dstr);
		}
	}

	if (CheckBox_Efuse_Xtal->Checked)
	{
		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0xE6;
		pPGRawData[2] = 0x01;
		pPGRawData[3] = 0x01;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to Read Xtal Efuse");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x",pReport[4]);
			Edit_Efuse_Xtal->Text=dstr;
			Memo_msg->Lines->Add(">>Read Xtal Efuse Success: " + dstr);
		}
	}


	if (CheckBox_Efuse_PowerOn->Checked)
	{

		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x76;
		pPGRawData[2] = 0x01;
		pPGRawData[3] = 0x02;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to Read PowerOn Efuse");
			Memo_msg->Lines->Add(dstr);
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);

			if( (pReport[4] == 0x20) && (pReport[5] == 0x3C) )
			{
				ComboBox_PowerOnEnable->ItemIndex=0;
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Efuse Successl[Disable]: " + dstr);
			}
			else if ( (pReport[4] == 0x20) && (pReport[5] == 0x3D) ) 
			{
				ComboBox_PowerOnEnable->ItemIndex=1;
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Efuse Success[Enable]: " + dstr);
			}
			else
			{
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Efuse Success[Invalid data]: " + dstr);
			}
		}



		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
		pPGRawData[1] = 0x30;
		pPGRawData[2] = 0x00;
		pPGRawData[3] = 0x02;
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to Read PowerOn Active level Efuse");
			Memo_msg->Lines->Add(dstr);
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);

			if( (pReport[4] == 0x40) && (pReport[5] == 0x52) )
			{
				ComboBox_PowerOnActive->ItemIndex=0;
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Active level Efuse Success[High active]: " + dstr);
			}
			else if ( (pReport[4] == 0x52) && (pReport[5] == 0x50) ) 
			{
				ComboBox_PowerOnActive->ItemIndex=1;
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Active level Efuse Success[Low active]: " + dstr);
			}
			else
			{
				dstr.printf("0x%02x,0x%02x", pReport[4], pReport[5]);
				Memo_msg->Lines->Add(">>Read PowerOn Active level Efuse Success[Invalid data]: " + dstr);
			}
		}
	}

 	BitBtn_ReadEfuse->Enabled=true;
	
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Btn_LoadScriptClick(TObject *Sender)
{
	OpenDialog1->Options.Clear();
	OpenDialog1->Title = "Load Script"  ;
	OpenDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
	OpenDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
	OpenDialog1->FileName="scrip.txt";
	OpenDialog1->FilterIndex=0;
	if(OpenDialog1->Execute())
	{
		Sctipt_Process(OpenDialog1->FileName.c_str());
	}
}
//---------------------------------------------------------------------------
int  TForm_Main::Register_Write(unsigned char regType,
                                unsigned long RegStartAddr,
                                unsigned char Page,
                                unsigned char Msb,
                                unsigned char Lsb,
                                unsigned long Value)
{
	int rtn=0;
	String szType,dstr;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");
                Memo_msg->Lines->Add(dstr);
                rtn=-1;
		goto exit;
	}
        switch (regType)
        {
            case 0 :
            		szType= "RF Regiser:";
		        pBluetoothModule->SetRfRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
            break;
            case 1:
		szType= "Modem Regiser:";
		rtn=pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
            break;
            case 2:
		szType= "MAC Regiser:";
		rtn=pBluetoothModule->SetSysRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
            break;
            case 3:
		szType= "BT Regiser:";
		rtn=pBluetoothModule->SetBBRegMaskBits(pBluetoothModule,Page,RegStartAddr,Msb,Lsb,Value);
            break;

        }
	if (rtn==0)
	{
                if (regType == 3)
                dstr.sprintf(">>%sWrite-->%d, 0x%x,[%d:%d] = 0x%x",szType,Page,RegStartAddr,Msb,Lsb,Value);
                else
		dstr.sprintf(">>%sWrite-->0x%x,[%d:%d] = 0x%x",szType,RegStartAddr,Msb,Lsb,Value);
	}
	else
	{
		dstr.sprintf(">>%s Write Error!!...",szType);
	}
        Memo_msg->Lines->Add(dstr);
exit:
        return rtn;
}

//---------------------------------------------------------------------------

int  TForm_Main::Sctipt_Process(char *filename)
{
	FILE *DataFile = NULL;
	char cmd[100];
	unsigned long  address,value;
     //	unsigned char page;
      //	int rtn;
	String szType,dstr;

	DataFile = fopen(filename, "r+");
	
     //	page=0;
	while(!feof(DataFile))
	{
		memset(cmd, 0, 100);
		fscanf(DataFile,"%s", cmd);

		if (strcmp(cmd , "ow") ==0)
		{
			fscanf(DataFile,"%x %x", &address, &value);
			szType = "Modem Regiser:";
			 pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, address, 15, 0, value);
		}
		else if (strcmp(cmd , "iw") ==0)
		{
			fscanf(DataFile,"%x", &address);
			szType = "Modem Regiser:";
			pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, address, 15, 0, &value);
		}
		else if (strcmp(cmd , "orf") == 0)
		{
			fscanf(DataFile,"%x %x", &address, &value);
			szType = "RF Regiser:";
			pBluetoothModule->SetRfRegMaskBits(pBluetoothModule, address, 15, 0, value);
		}
		else if (strcmp(cmd , "irf") == 0)
		{
			fscanf(DataFile,"%x", &address);
			szType = "RF Regiser:";
			pBluetoothModule->GetRfRegMaskBits(pBluetoothModule, address, 15, 0, &value);
		}
	}

	Memo_msg->Lines->Add(dstr);

	if (DataFile != NULL)
		fclose(DataFile);

	return 0;
}

void __fastcall TForm_Main::FormKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
  switch(Key)
  {
    case 112:  //F1
  //  LoadScipt1Click(Sender);
    break;
    case 113:  //F2
  //  SaveScipt1Click(Sender);
    break;
    case 116:  //F5
        Btn_LoadScriptClick(Sender);
    break;

  }
}
//---------------------------------------------------------------------------
#define sbtnArray_TOP_SHIFT 130     //150
int TForm_Main::CreatsButtonArray()
{

   int i=0;
   String dstr;
   int count=0;
   for (i=0;i<MAX_SBTN_NUM_BTAPP;i++)
   {
      if (sbtnArray[i] == NULL)
      {
        sbtnArray[i]= new TSpeedButton(this);
        sbtnArray[i]->Tag=i;
        sbtnArray[i]->Parent=TabSheet_RW;
        sbtnArray[i]->Width=25;
        sbtnArray[i]->Height=25;
        sbtnArray[i]->Top= (i/16)*50 + sbtnArray_TOP_SHIFT;
        sbtnArray[i]->Cursor=crHandPoint;
        if (i%4 ==0)
        {
         count++;

        }
        sbtnArray[i]->Left= (TabSheet_RW->Left+TabSheet_RW->Width)- 25 *i -count *20 - 100;
     //   if (((i/8)%2) == 0) {
      //  sbtnArray[i]->Left= (GroupBox1->Left+GroupBox1->Width) - (((i%16)+1)*(sbtnArray[i]->Height+5));
     //   }
     //   else{
     //   sbtnArray[i]->Left= (GroupBox1->Left+GroupBox1->Width)-(((i%16)+1)*(sbtnArray[i]->Height+5))-20;
    //    }
        sbtnArray[i]->Caption="0";//IntToStr(i);
        sbtnArray[i]->Font->Color=clRed;
        sbtnArray[i]->Font->Size=12;
        sbtnArray[i]->OnClick = sButtonOnClick;
        sbtnArray[i]->Show();
        //Lable
        sLabelArray[i] = new TLabel(this);
        sLabelArray[i]->Tag=i;
        sLabelArray[i]->Parent=TabSheet_RW;
        sLabelArray[i]->Width=25;
        sLabelArray[i]->Height=25;
        sLabelArray[i]->Font->Size=12;
        sLabelArray[i]->Top= sbtnArray[i]->Top -20;  //(i/16)*50 + 150
        sLabelArray[i]->Left=sbtnArray[i]->Left;
        sLabelArray[i]->Caption=IntToStr(i);
       } 

   }
   sButtonOnClick(NULL);
   return 0;

}
void __fastcall TForm_Main::sButtonOnClick(TObject *Sender)
{

  TSpeedButton *btn = NULL;
 // int Index =0;

  if (Sender !=NULL)
  {
        btn=dynamic_cast<TSpeedButton *>(Sender);
        if (btn->Caption == "0")
        {
        btn->Caption ="1";
        btn->Font->Color=clLime;
        }
        else
        {
        btn->Caption ="0";
        btn->Font->Color=clRed;
        }
   }
   Assign_BtnToData();
   return ;


}
void  TForm_Main::Assign_DataToBtn()
{
	unsigned long Value;
	int i;
	String str_Value = Edit_RW_VALUE->Text;


	if( (str_Value.Pos("0x")==0) && (str_Value.Pos("0X")==0) )
	{
		Value = StrToInt("0x"+str_Value);
	}
	else
	{
		Value = StrToInt(str_Value);
	}

	for (i=0;i<16;i++)
	{
		if (((Value >> i) & 0x01 )  == 0x01)
		{
			sbtnArray[i]->Caption ="1";
			sbtnArray[i]->Font->Color=clLime;
		}
		else
		{
			sbtnArray[i]->Caption ="0";
			sbtnArray[i]->Font->Color=clRed;
		}
	}
	
	return;
}
void  TForm_Main::Assign_BtnToData()
{
	unsigned long Value = 0;//StrToInt(Edit_RW_VALUE->Text);
	int i=0;
	String dstr;

	for (i=0;i<16;i++)
	{
		Value = Value<<1;
		if (sbtnArray[15-i]->Caption =="1")
		{
			Value |= 0x01;
		}
	}
	dstr.sprintf("%x",Value);
	dstr=dstr.UpperCase();
	Edit_RW_VALUE->Text=dstr;
	return;
}

void  TForm_Main::Assign_BtnShow()
{
	int i=0;
	unsigned char Msb=StrToInt(Edit_RW_MSB->Text);
	unsigned char Lsb=StrToInt(Edit_RW_LSB->Text);
	for (i=0;i<16;i++)
	{
		if ((i>=Lsb )  && (i<=Msb))
			sbtnArray[i]->Enabled = true;
		else
			sbtnArray[i]->Enabled = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_RW_MSBKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
         if (Key==13)
        {
         Assign_BtnShow();
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_RW_LSBKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
        if (Key==13)
        {
           Assign_BtnShow();
        }
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Edit_RW_MSBExit(TObject *Sender)
{
        Assign_BtnShow();
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_RW_LSBExit(TObject *Sender)
{
        Assign_BtnShow();        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_RW_VALUEKeyDown(TObject *Sender,
      WORD &Key, TShiftState Shift)
{
         if (Key==13)
        {
           Assign_DataToBtn();
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_RW_VALUEExit(TObject *Sender)
{
        Assign_DataToBtn();        
}
//---------------------------------------------------------------------------

int   TForm_Main::API_ReadThermalValue(unsigned long *Value)
{

        /*        if (pBluetoothModule->SetBBRegMaskBits(pBluetoothModule,0,0x1ba,15,0,0x800f) !=0)
                {
                        return -1;
                }

                if (pBluetoothModule->GetBBRegMaskBits(pBluetoothModule,0,0x1ba,13,9,Value) !=0 )
                {
                        return -1;
                }
         */
 	String dstr;
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;
     //	BT_CHIPINFO	        *pBTInfo=NULL;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}

	if (pBluetoothModule->ActionReport(pBluetoothModule,REPORT_THERMAL,pModuleBtReport) !=0)
	{
		dstr.sprintf(">>Get Thermal  is Fail...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
	dstr.sprintf(">>Thermal=(%d) use SI\n",pModuleBtReport->CurrThermalValue ); Memo_msg->Lines->Add(dstr);



                return 0;
}
//---------------------------------------------------------------------------
int   TForm_Main::API_SetNewPowerValue(unsigned long Value)
{
     	pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x3C, 12, 12, 0);
	pBluetoothModule->SetBBRegMaskBits(pBluetoothModule, 0, 0x178, 15, 8, Value&0xFF);
	pBluetoothModule->SetBBRegMaskBits(pBluetoothModule, 0, 0x17A, 15, 0, 0x382);
        return 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm_Main::BitBtn_TRXReadThermalClick(TObject *Sender)
{
                unsigned long newThermalValue=0;
                String dstr;


	        if (pBluetoothModule == NULL)
	        {
		        dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
                        return ;
	        }
                if (API_ReadThermalValue(&newThermalValue) !=0)
                {
                  Memo_msg->Lines->Add("Read Thermal Fail...");
                  return ;
                }

                return ;
}










void __fastcall TForm_Main::SpeedButton1Click(TObject *Sender)
{
	unsigned char  TxDacValue=0;
	API_ReadCurrentTxDacValue( &TxDacValue);

	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn1Click(TObject *Sender)
{
	unsigned char  TxDacValue=0;
	API_ReadCurrentTxDacValue( &TxDacValue);
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::EnableControlBTTxPowerIndex1Click(
      TObject *Sender)
{
	EnableControlBTTxPowerIndex1->Checked =!EnableControlBTTxPowerIndex1->Checked;
	if (EnableControlBTTxPowerIndex1->Checked)
	{

                GroupBox_TXLevel->Visible=true;
                CheckBox_FixGain->Visible=true;
                Cbx_TxGainIndex->Visible=true;

                if(mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_RTL8763B)
                {

                   Button_Get_TPM_IQMClick(Sender);

                }
	}
}
//------CALLBACK----------------------------------------------------------------------
int TForm_Main::Verify_GetLastError(BT_VERIFY_PARMERTER *pCfoParamter)
{

     int error=0;
     String dstr;
     char Msg[][100] = {
     "The correction job is fail, please re-test!!",
     "The Offset correction process is succress.",
     "The Gold sample open fail ,please reconnect the SUT Device in PC...!!",
     "The DUT open fail，Please reconnect the DUT device and PC!!",
     };
     pCfoParamter->ParamterIndex = VERIFY_GET_LAST_ERROR;


     error =pBaseDLLObject->BTMPAPI_BluetoothVerify(pCfoParamter,NULL);

     dstr.sprintf("%s",Msg[error+1]);
     Form_Main->Memo_msg->Lines->Add(dstr);

     return error;

}
void __fastcall TForm_Main::BitBtn_CFO_BEGINClick(TObject *Sender)
{

        int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
        unsigned long Value;
        float cfo_kHz;
        String in_dstr;
        String dstr;
        DWORD t1,t2,t;
        int test_item=0;
        BT_VERIFY_PARMERTER btCfoParamter;
        BT_VERIFY_REPORT    btCfoReport;

        t1=GetTickCount();

        btCfoParamter.GoldSample_PortNumber= 1;

        btCfoParamter.ParamterIndex = VERIFY_TEST_BEGIN;

        btCfoParamter.InterfaceType = InterfaceType;
        btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
        btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
        btCfoParamter.pFunc =CFO_CALLBACK;
        if (FWExeJobMode1->Checked)
        {
           btCfoParamter.ExeMode = 1;

	}
        else
         btCfoParamter.ExeMode = 0;

        Label1_CFOResult->Caption="Testing....";
        Label1_CFOResult->Color =  clWhite;

        btCfoParamter.Test_XTAL = FALSE;
        if (CheckBox_CALXTAL->Checked)
        {
                Label_CFO_RET->Caption= "Begin Test....";
                btCfoParamter.Test_CALXTAL=TRUE;
                Label_CFO_RET->Update();
        }
        else
         btCfoParamter.Test_CALXTAL=FALSE;
        if (CheckBox_VERIFYTX->Checked)
        {
         Label_VERIFY_TX->Caption= "Begin Test....";
         btCfoParamter.Test_TX=TRUE ;
         Label_VERIFY_TX->Update();
        }
        else
        btCfoParamter.Test_TX=FALSE;

        if (CheckBox_VERIFYRX->Checked)
        {
         Label_VERIFY_RX->Caption= "Begin Test....";
         btCfoParamter.Test_RX=TRUE;
          Label_VERIFY_RX->Update();
        }
        else
        btCfoParamter.Test_RX=FALSE;

        in_dstr = Edit_CFO_IN->Text;
        if (in_dstr.Length() ==0)
        btCfoParamter.def_CFOVaule=0x00000000;
        else
        btCfoParamter.def_CFOVaule= StrToInt(in_dstr);

    //    Label_CFO_RET->Caption= "Begin Test....";
    //    Label_CFO_RET->Update();
        //Sleep(50);

        btCfoReport.mFloatData=0;  btCfoReport.CFO_Value =0;
       if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,&btCfoReport) != 0)
        {
            t2=GetTickCount();
            t=abs(t2-t1);
             if (CheckBox_CALXTAL->Checked)
            {
            dstr.sprintf("[Test ERROR]CFO = %f KHz CFO Value = 0x%x (Time= %d )",btCfoReport.mFloatData,btCfoReport.CFO_Value,t);
            Label_CFO_RET->Caption=  dstr;
            Form_Main->Memo_msg->Lines->Add(dstr);
            Verify_GetLastError(&btCfoParamter);
            }
            else
            {
                dstr.sprintf("[Test ERROR]Time= %d ",t);
                Verify_GetLastError(&btCfoParamter);
            }
        }
        else
        {

            t2=GetTickCount();
            t=abs(t2-t1);
            if (CheckBox_CALXTAL->Checked)
            {
                test_item=1;
                dstr.sprintf("CFO = %f KHz ,CFO Value = 0x%x (Time = %d )",btCfoReport.mFloatData,btCfoReport.CFO_Value,t);
                Form_Main->Memo_msg->Lines->Add(dstr);
                Label_CFO_RET->Caption= dstr;
                dstr.sprintf("0x%x",btCfoReport.CFO_Value);

                Edit_CFO->Text=dstr;
                int thIndex =  ComboBox_CFO_TH->ItemIndex;
                float thoffset=(float) ((thIndex+1)*5 );
                float getoffset =0;
                if (btCfoReport.mFloatData < 0)
                   getoffset = ((-1)*btCfoReport.mFloatData);
                else
                   getoffset = btCfoReport.mFloatData;
                if ( getoffset<=thoffset)
                { //pass
                  Label1_CFOResult->Caption="PASS";
                  Label1_CFOResult->Color = clLime;
                  if (CheckBox_CFO_NOCHANGE->Checked)
                  {
                          dstr.sprintf("Write CFO Value = 0x%x to k-default value",btCfoReport.CFO_Value);
                          Form_Main->Memo_msg->Lines->Add(dstr);
                          dstr.sprintf("0x%x",btCfoReport.CFO_Value);
                          Edit_CFO_IN->Text = dstr;
                  }
                  if (CheckBox_CFO_Efuse->Checked)
                  {
                        btCfoParamter.ParamterIndex = VERIFY_EFUSE_WRITE;
                        btCfoParamter.def_CFOVaule = btCfoReport.CFO_Value;


                        if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,NULL) != 0)
                        {
                                dstr.sprintf("[ERROR]Failed to Write Efuse CFO Value = 0x%x",btCfoReport.CFO_Value);
                                Form_Main->Memo_msg->Lines->Add(dstr);
                        }
                        else
                        {
                        dstr.sprintf("To Write Efuse CFO Value = 0x%x",btCfoReport.CFO_Value);
                        Form_Main->Memo_msg->Lines->Add(dstr);
                        }

                   }

                }
                else
                {
                 Label1_CFOResult->Caption="FAIL";
                 Label1_CFOResult->Color = clRed;
                }

            }

            if (CheckBox_VERIFYTX->Checked)
            {
              test_item=2;
              dstr.sprintf("rssi = %d , ber = %f", btCfoReport.VerifyTX_Rssi,btCfoReport.VerifyTX_ber);
              Label_VERIFY_TX->Caption= dstr;
            }
            if (CheckBox_VERIFYRX->Checked)
            {
               test_item=3;
               dstr.sprintf("rssi= %d , ber= %f, recv_bits=%d,err_bits =%d", btCfoReport.VerifyRX_Rssi,btCfoReport.VerifyRX_ber,btCfoReport.VerifyRX_bits,btCfoReport.VerifyRX_error_bits);
               Label_VERIFY_RX->Caption= dstr;
            }


            dstr.sprintf("Test End (Time = %d )",t);
            Form_Main->Memo_msg->Lines->Add(dstr);
        }

        if (test_item == 0)
        {

                 Label1_CFOResult->Caption="Ready ";
                 Label1_CFOResult->Color =  clWhite;

        }
        return ;

}
//---------------------------------------------------------------------------
void __fastcall TForm_Main::BitBtn_CFO_STOPClick(TObject *Sender)
{
	BT_VERIFY_PARMERTER btCfoParamter;

	btCfoParamter.ParamterIndex = VERIFY_TEST_STOP;

	pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,NULL);
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Page_functionChange(TObject *Sender)
{
        if (FormBTDebug_flag)
	{
          GroupBox3->Caption="Interface";
          return ;
        }
	Btn_Dev_Open->Visible =true;
	Btn_Dev_Close->Visible =true;

	GroupBox3->Caption="Interface";
	if (Page_function->ActivePage == TabSheet_CFO)
	{
		Btn_Dev_Open->Visible =false;
		Btn_Dev_Close->Visible =false;
		GroupBox3->Caption="DUT Interface";
	}
}
//---------------------------------------------------------------------------
void __fastcall TForm_Main::BitBtn_CFO_EFUSEWRClick(TObject *Sender)
{
                unsigned long Value;
                String dstr;
                BT_VERIFY_PARMERTER btCfoParamter;
                int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
                btCfoParamter.InterfaceType = InterfaceType;
                btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
                btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
                btCfoParamter.pFunc =CFO_CALLBACK;
                btCfoParamter.ParamterIndex = VERIFY_EFUSE_WRITE;
                 dstr = Edit_CFO->Text;
                if (dstr.Length() ==0)
                {
                   Form_Main->Memo_msg->Lines->Add("Input Vaule is NULL!!");
                   return ;
                }
                Value = StrToInt(Edit_CFO->Text);
                btCfoParamter.def_CFOVaule = Value;

                if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,NULL) != 0)
                {
                        dstr.sprintf("[ERROR]Failed to Write Efuse CFO Value = 0x%x",Value);
                        Form_Main->Memo_msg->Lines->Add(dstr);
                }
                else
                {
                      dstr.sprintf("Write Efuse CFO Value = 0x%x",Value);
                      Form_Main->Memo_msg->Lines->Add(dstr);
                }
                return ;
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::BitBtn_CFO_REGWRClick(TObject *Sender)
{
                unsigned long Value;
                int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
                String dstr;
                BT_VERIFY_PARMERTER btCfoParamter;
                btCfoParamter.InterfaceType = InterfaceType;
                btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
                btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
                btCfoParamter.pFunc =CFO_CALLBACK;
                btCfoParamter.ParamterIndex = VERIFY_REG_WRITE;
                dstr = Edit_CFO->Text;
                if (dstr.Length() ==0)
                {
                   Form_Main->Memo_msg->Lines->Add("Input Vaule is NULL!!");
                   return ;
                }

                Value = StrToInt(Edit_CFO->Text);
                btCfoParamter.def_CFOVaule = Value;

                if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,NULL) != 0)
                {
                        dstr.sprintf("[ERROR]Failed to Write Efuse CFO Value = 0x%x",Value);
                        Form_Main->Memo_msg->Lines->Add(dstr);
                }
                else
                {
                      dstr.sprintf("Write Efuse CFO Value = 0x%x",Value);
                      Form_Main->Memo_msg->Lines->Add(dstr);
                }
                return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_CFO_REGRDClick(TObject *Sender)
{

                String dstr;
                BT_VERIFY_PARMERTER btCfoParamter;
                BT_VERIFY_REPORT    btCfoReport;
                int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
                btCfoParamter.InterfaceType = InterfaceType;
                btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
                btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
                btCfoParamter.pFunc =CFO_CALLBACK;
                btCfoParamter.ParamterIndex = VERIFY_REG_READ;

                if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,&btCfoReport) != 0)
                {
                        dstr.sprintf("[ERROR]Failed to Read Xtal CFO Value...");
                        Form_Main->Memo_msg->Lines->Add(dstr);

                }
                else
                {
                      dstr.sprintf("Read Xtal CFO Value = 0x%x",btCfoReport.CFO_Value);
                      Form_Main->Memo_msg->Lines->Add(dstr);
                      dstr.sprintf("0x%x",btCfoReport.CFO_Value);
                      Edit_CFO->Text = dstr;
                }
                return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_CFO_EFUSERDClick(TObject *Sender)
{

                String dstr;
                BT_VERIFY_PARMERTER btCfoParamter;
                int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
                BT_VERIFY_REPORT    btCfoReport;
                btCfoParamter.InterfaceType = InterfaceType;
                btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
                btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];
                btCfoParamter.pFunc =CFO_CALLBACK;
                btCfoParamter.ParamterIndex = VERIFY_EFUSE_READ;
                 if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,&btCfoReport) != 0)
                {
                        dstr.sprintf("[ERROR]Failed to Read EFUSE Xtal CFO Value....");
                        Form_Main->Memo_msg->Lines->Add(dstr);
                }
                else
                {
                       dstr.sprintf("Read Efuse CFO Value = 0x%x",btCfoReport.CFO_Value);
                       Form_Main->Memo_msg->Lines->Add(dstr);
                       dstr.sprintf("0x%x",btCfoReport.CFO_Value);
                       Edit_CFO->Text=  dstr;
                }
                return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_GETCFOClick(TObject *Sender)
{

	int BarudRate_Arrary[]={9600,115200,921600,1500000,3000000,4000000};
	unsigned long Value;
	float cfo_kHz;
	String dstr;
	BT_VERIFY_PARMERTER btCfoParamter;
	BT_VERIFY_REPORT    btCfoReport;

	btCfoParamter.GoldSample_PortNumber= 1;

	btCfoParamter.ParamterIndex = VERIFY_GET_CFOVALUE;

	btCfoParamter.InterfaceType = InterfaceType;
	btCfoParamter.PortNo= StrToInt(Cbx_Interface_port->Text);
	btCfoParamter.Baudrate =  BarudRate_Arrary[Cbx_Interface_baudrate->ItemIndex ];

	btCfoParamter.def_CFOVaule= StrToInt(Edit_CFO->Text);
	btCfoParamter.Test_XTAL = TRUE;
	btCfoParamter.Test_CALXTAL=FALSE;
	btCfoParamter.Test_TX=FALSE;
	btCfoParamter.Test_RX=FALSE;

	Label_CFO_RET->Caption= "Begin Test....";
	Label_CFO_RET->Update();
	Sleep(50);
	if (pBaseDLLObject->BTMPAPI_BluetoothVerify(&btCfoParamter,&btCfoReport) != 0)
	{
		dstr.sprintf("[ERROR]CFO = %f KHz CFO Value = 0x%x",btCfoReport.mFloatData,btCfoReport.CFO_Value);
		Label_CFO_RET->Caption=  dstr;
		Form_Main->Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf("CFO = %f KHz ",btCfoReport.mFloatData);
		Form_Main->Memo_msg->Lines->Add(dstr);
		Label_CFO_RET->Caption= dstr;
	}

	return;

}
//---------------------------------------------------------------------------

int CFO_CALLBACK(BT_VERIFY_REPORT *pReport)
{
	String dstr;
	int index = pReport->pData[0];
	switch(index)
	{
	case 1: //CFO
		if (Form_Main->InterfaceType == TYPE_BUMBLE_BEE_USB)
		{
			dstr.sprintf("HOSCI_BC_SEL = 0x%x ,HOSCI_TC_SEL =0x%x ==>%f ",pReport->pData[1],pReport->pData[2],pReport->mFloatData) ;
		}
		else
		{
			dstr.sprintf("xtal = 0x%x  ==>%f ",pReport->pData[2],pReport->mFloatData) ;
		}
	break;
	
	case 2: //TX
		dstr.sprintf("Rssi = %d Bits = %d ErrorBits = %d  ",pReport->Rssii,pReport->pData[2],pReport->pData[4]) ;
		Form_Main->Label_VERIFY_TX->Caption=dstr;
		dstr ="Tx Test -->"+dstr;
	break;
	
	case 3: //RX
		dstr.sprintf("Rssi = %d Bits = %d ErrorBits = %d ber = %f ",pReport->Rssii,pReport->pData[2],pReport->pData[4],pReport->ber) ;
		Form_Main->Label_VERIFY_RX->Caption=dstr;
		dstr ="Rx Test -->"+dstr;
	break;
	}

	if (dstr.Length() ==0)
		return 0;
       
	Form_Main->Memo_msg->Lines->Add(dstr);
	Form_Main->Memo_msg->Update();

	return 0;
}

void __fastcall TForm_Main::CFOPage1Click(TObject *Sender)
{
	CFOPage1->Checked= !CFOPage1->Checked;
	if (CFOPage1->Checked)
	{
		TabSheet_CFO->TabVisible= true;
	}
	else
	{
		TabSheet_CFO->TabVisible= false;
	}
}
//---------------------------------------------------------------------------

void TForm_Main::DebugCFOUI()
{
	if (Debug2->Checked)
	{
		BitBtn_CFO_REGWR->Visible = true;
		BitBtn_CFO_REGRD->Visible = true;
		BitBtn_CFO_EFUSEWR->Visible = true;
		BitBtn_CFO_EFUSERD->Visible = true;
		BitBtn_GETCFO->Visible=true;
	}
	else
	{
		BitBtn_CFO_REGWR->Visible = false;
		BitBtn_CFO_REGRD->Visible = false;
		BitBtn_CFO_EFUSEWR->Visible = false;
		BitBtn_CFO_EFUSERD->Visible = false;
		BitBtn_GETCFO->Visible= false;
	}

	if (DebugRFProgram1->Checked )
	{
		TabSheet_NONLINK->TabVisible =false;

		TabSheet_Hopping->TabVisible =false;
		TabSheet_RW->TabVisible =false;
		TabSheet_LETest->TabVisible =false;

		Page_function->ActivePage = TabSheet_CFO;
		Cbx_Interface->Enabled=false;
		Image1->Left = 488;

	}
	else
	{
		TabSheet_NONLINK->TabVisible =true;

		TabSheet_Hopping->TabVisible =true;
		TabSheet_RW->TabVisible =true;
		TabSheet_LETest->TabVisible =true;
		Cbx_Interface->Enabled=true;
		Image1->Left = 568;
	}
	TObject *Sender;
	Page_functionChange(Sender);
	return;
}

void __fastcall TForm_Main::Debug2Click(TObject *Sender)
{
	Debug2->Checked = !Debug2->Checked ;
	DebugCFOUI();
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::DebugRFProgram1Click(TObject *Sender)
{
	DebugRFProgram1->Checked = !DebugRFProgram1->Checked;
	DebugCFOUI();
}
//---------------------------------------------------------------------------
//
//   Matlab  call BTAPP  Begin
//
//---------------------------------------------------------------------------
enum MPCOMMAND_TAG{
       BT_MP_REGRW =0,
       BT_MP_HCICOMMAND,
       BT_MP_REPORT,
       BT_MP_EXEC,
       BT_MP_SETPARAM,
       BT_MP_GETPARAM,
       RTLBTMP,
       BT_MP_RECVEVT,
  //     BT_MP_DEVICE_DISABLE,
       ///////////
       NUMBEROFMPCOMMAND

};
enum  MPREGTYPE_TAG{
       BT_MP_REG_MODEM=0,
       BT_MP_REG_RF,
       BT_MP_REG_SYS,
       BT_MP_REG_BB
};
#define BT_MP_REG_WRITE 1
#define BT_MP_REG_READ  0

typedef struct   _BTREG_Offset_struct_{
       UINT16   page_16b;
       UINT16   addr_16b;
}BTREG_Offset_struct;

union  BTREG_Offset{
       BTREG_Offset_struct   addr_32b;
       UINT32   BTREG_Offset_32b;
};

typedef struct  _MEX_MP_BTREG{
       UINT8   id_8b;
       UINT8   rw_8b;
       BTREG_Offset  Offset_32b;
       UINT8   msb_8b;
       UINT8   lsb_8b;
       UINT16  data_16b;
}MEX_MP_BTREG;
typedef struct  _MEX_MP_BTDEVICECTRL{
       UINT8   InterfaceType;
       UINT8   Actions;
       UINT8   Port;
       UINT16  Baudrate;

}MEX_MP_BTDEVICECTRL;
#define MAX_MEX_BUF_LEN     512
#define MAX_MEX_MP_CMD_SIZE 50
char szMPCommand[NUMBEROFMPCOMMAND][MAX_MEX_MP_CMD_SIZE]={
      "bt_mp_regrw",          //
      "bt_mp_hcicmd",
      "bt_mp_report",
      "bt_mp_exec",
      "bt_mp_setparam",
      "bt_mp_getparam",
      "rtlbtmp",
      "bt_mp_RecvEvt"
};
int TForm_Main::api_tcpip_bt_mp_Exec_process(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
       int rtn =0;
	BT_PARAMETER 	*pParam=&mBT_PARAMETER;
	String dstr;      
       UINT8  pbuf[MAX_MEX_BUF_LEN];
       int  buf_len=0;
       UINT8    Actions=0xFF;


       DBGPRINTF("+ api_tcpip_bt_mp_Exec_process() \n");
       *pRtnLen=0;

       memset(pbuf,0,sizeof(UINT8)*MAX_MEX_BUF_LEN);

       if (api_parse_str2buf(pcmd,pbuf,&buf_len) !=0)
       {
           goto exit;
       }
       Actions = pbuf[0];

       DBGPRINTF("Actions = %d \n",Actions );
        //---------------------------------------------
       //call process
       //---------------------------------------------

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}
	pParam->ParameterIndex = Actions;
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		rtn= -1;
                goto exit;
	}
        rtn=0;

exit:
       pRtn[0] = rtn;
       DBGPRINTF("- api_tcpip_bt_mp_Exec_process(%x) \n",rtn);
       return rtn;

}
int TForm_Main::api_tcpip_bt_mp_rtlbtmp_enable_process(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
       int rtn =0;
       UINT8  pbuf[MAX_MEX_BUF_LEN];

     //  UINT16   Type =0;
       UINT8    Port=0;
       UINT32   Baudrate=0;
       char     szType[50];
       char     szmode[50];
       String   dstr;
       char     *dest= NULL;
    //   char     *sour=NULL;

       DBGPRINTF("+ api_tcpip_bt_mp_rtlbtmp_enable_process() \n");
       *pRtnLen=0;

  //     dstr.sprintf("");

       memset(szType,0,50);
       memset(szmode,0,50);
       dest = pcmd;

       while(*dest)
       {
          if ((*dest == ',') || (*dest == ':'))
          {
              *dest=' ';
          }
          *dest++;
       }
       sscanf(pcmd,"%s %s %d %d",szmode,szType,&Port,&Baudrate);

       if (strncmp(szmode,"enable",strlen("enable")) ==0)
       {
          DBGPRINTF(">> to enable the Device\n");
          DBGPRINTF(">> Type = %s  port= %d , baudrate = %d\n",szType,Port,Baudrate);
          if (strncmp(szType,"usb",strlen("usb")) ==0)
          {
                //---------------------------------------------
                //call process
                //---------------------------------------------
                Cbx_Interface->ItemIndex =TYPE_USB;

          }
          else if (strncmp(szType,"uart",strlen("uart")) ==0)
          {
       //---------------------------------------------
       //call process
       //---------------------------------------------
                Cbx_Interface->ItemIndex =TYPE_UART;
          }
          else
          {
           rtn=-1;
           goto exit;
          }
                TObject *Sender;
                Cbx_InterfaceChange(Sender);
                rtn=OpenDevice();
                if (rtn !=0)
                {
                   goto exit;
                }

       }
       else if (strncmp(szmode,"disable",strlen("disable")) ==0)
       {
          DBGPRINTF(">> to Disable the Device\n");
       //---------------------------------------------
       //call process
       //---------------------------------------------
          CloseDevice();
       }
       else
       {
          rtn=-1;
          goto exit;
       }

       rtn=0;

exit:
       pRtn[0]=rtn;
       *pRtnLen=1;
       DBGPRINTF("- api_tcpip_bt_mp_rtlbtmp_enable_process(%x) \n",rtn);
       return rtn;

}
int TForm_Main::api_tcpip_bt_mp_HciCmd_process(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
       int rtn =0;
       UINT8  pbuf[MAX_MEX_BUF_LEN];
       int  buf_len=0;
       UINT16   OpCode =0;
       UINT16    para_len=0;
       UINT16   EVT_length=0;
       UINT8    para[MAX_MEX_BUF_LEN];
       unsigned char pEvtBuf[512];
       DBGPRINTF("+ api_tcpip_bt_mp_HciCmd_process() \n");

       memset(pbuf,0,sizeof(UINT8)*MAX_MEX_BUF_LEN);
       memset(para,0,sizeof(UINT8)*MAX_MEX_BUF_LEN);
       memset(pEvtBuf,0,512);
       *pRtnLen =0;
       if (api_parse_str2buf(pcmd,pbuf,&buf_len) !=0)
       {

          goto exit;
       }
       OpCode =  (pbuf[1]<<8) + pbuf[0];
       para_len= pbuf[2];
       if (para_len > MAX_MEX_BUF_LEN)
          para_len = MAX_MEX_BUF_LEN;

       memcpy(para,&pbuf[3],para_len);
       DBGPRINTF(">>OpCode = 0x%x  , para_len = %d para[] = %x %x %x %x %x %x %x %x \n",OpCode,para_len,para[0],para[1],para[2],para[3],para[4],para[5],para[6],para[7] );
       //---------------------------------------------
       //call process
      //	String dstr;

    //	unsigned char pData[512];


	if(pBluetoothModule == NULL)
	{
	     //	dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
                DBGPRINTF(">>[ERROR]OpCode = 0x%x  , para_len = %d para[] = %x %x %x %x %x %x %x %x \n",OpCode,para_len,para[0],para[1],para[2],para[3],para[4],para[5],para[6],para[7] );
                DBGPRINTF(">>[ERROR]BluetoothModule is NULL...!!\n");
		rtn=-1;
                goto exit;
	}

	rtn=pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, OpCode, para_len, para, 0x0E, pEvtBuf);

	if((pEvtBuf[5] != 0) || (rtn !=0))
	{
	       //	dstr.sprintf("Led Set : ERROR !!\n");Memo_msg->Lines->Add(dstr);
                   DBGPRINTF(">>[ERROR]OpCode = 0x%x  , para_len = %d para[] = %x %x %x %x %x %x %x %x  is Error!!(Status !=0)\n",OpCode,para_len,para[0],para[1],para[2],para[3],para[4],para[5],para[6],para[7] );
                   rtn=-1;
                   goto exit;
	}
        else
        {
                DBGPRINTF(">>OpCode = 0x%x  , para_len = %d para[] = %x %x %x %x %x %x %x %x \n",OpCode,para_len,para[0],para[1],para[2],para[3],para[4],para[5],para[6],para[7] );
               // dstr.sprintf("Led Set : Success !!\n");Memo_msg->Lines->Add(dstr);
                DBGPRINTF("EVT[]= %x %x %x %x %x %x %x %x %x %x %x %x %x  \n",pEvtBuf[0],pEvtBuf[1],pEvtBuf[2],pEvtBuf[3],pEvtBuf[4],pEvtBuf[5],pEvtBuf[6],pEvtBuf[7],pEvtBuf[8],pEvtBuf[9],pEvtBuf[10],pEvtBuf[11],pEvtBuf[12]);
        }
        //---------------------------------------------
       rtn=0;
       EVT_length = pEvtBuf[1]+1;
       if (EVT_length > 255 )
           EVT_length = 255;
       memcpy(&pRtn[0],pEvtBuf,EVT_length);
       *pRtnLen = EVT_length;
exit:
    //   pRtn[0] = rtn;
       DBGPRINTF("- api_tcpip_bt_mp_HciCmd_process(%x) \n",rtn);
       return rtn;
}
int TForm_Main::api_tcpip_bt_mp_parse_data(char *psur,ULONG *data,int max_dataNumber,int *dataNum,char *pdesc)
{
          int n=0;
          String dstr,tmpstr;
          int end=0;
          int pos=0;
          int rtn=0;
          tmpstr.printf ("%s",psur);
          tmpstr=StringReplace(tmpstr," ","",TReplaceFlags()<<rfReplaceAll);
          tmpstr=StringReplace(tmpstr,"\n","",TReplaceFlags()<<rfReplaceAll);
          tmpstr=StringReplace(tmpstr,"\0","",TReplaceFlags()<<rfReplaceAll);
          memset(data,0,sizeof(ULONG)*max_dataNumber);
          *dataNum=0;
          while(tmpstr.Length() >0)
          {
               pos=tmpstr.Pos(",");
               if (pos <=0)
               {
                 dstr= tmpstr;
                 end=1;
               }
               else
              {
              dstr=tmpstr.SubString(0,pos-1);
              }
               dstr=StringReplace(dstr,";","",TReplaceFlags()<<rfReplaceAll);
              if (dstr.Length()<=0)
                  break;
               if (n >=max_dataNumber)
                  break;

               data[n]= StrToInt(dstr);
               tmpstr = tmpstr.SubString(pos+1,tmpstr.Length());
               n++;

               if (end)
               break;

          }
          *dataNum = n;
          if (pdesc != NULL)
          {
            memcpy(pdesc,tmpstr.c_str(),tmpstr.Length());
          }
          rtn=0;
exit:
          return rtn;
}
int TForm_Main::api_tcpip_bt_mp_RegRW_process(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
       int rtn =-1,Buf_Num;
       ULONG pBuf[10];
       char  pdesc[MAX_MEX_BUF_LEN];
       int Page = 0;
	unsigned long RegStartAddr=0;
	unsigned char Msb=0;
	unsigned char Lsb=0;
	unsigned long Value = 0;
        UINT8 id_8b=0,rw_8b=0;


       DBGPRINTF("+ api_tcpip_bt_mp_RegRW_process() \n");
       *pRtnLen=0;
       memset(pBuf,0,sizeof(ULONG)*10);
       if (api_tcpip_bt_mp_parse_data(pcmd,pBuf,10,&Buf_Num,NULL) !=0)
       {

          rtn=-1;
          goto exit;
       }
       rtn=0;
       id_8b = pBuf[0];
       rw_8b=  pBuf[1];
       RegStartAddr =pBuf[2] ;
       Msb = pBuf [3];
       Lsb =pBuf [4] ;
       Value = pBuf[5];

      if (BT_MP_REG_WRITE ==rw_8b)
       { //write
        switch(id_8b)
        {
        case BT_MP_REG_MODEM:
                if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
            DBGPRINTF("reg[MD][w]0x%x[%d:%d]=0x%x",RegStartAddr,Msb,Lsb,Value );
            rtn=pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
        break;
        case BT_MP_REG_RF:
                if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
             DBGPRINTF("reg[RF][w]0x%x[%d:%d]=0x%x",RegStartAddr,Msb,Lsb,Value );
            rtn = pBluetoothModule->SetRfRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
        break;

        case BT_MP_REG_SYS:
                if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
             DBGPRINTF("reg[SY][w]0x%x[%d:%d]=0x%x",RegStartAddr,Msb,Lsb,Value );
                rtn=pBluetoothModule->SetSysRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,Value);
        break;
        case BT_MP_REG_BB:
                Page = pBuf[2];
                RegStartAddr =pBuf[3] ;
                Msb = pBuf [4];
                Lsb =pBuf [5] ;
                Value = pBuf[6];
                 if ((Msb > 15) || (Msb < Lsb) || (Page > 15) )
                {
                  rtn=-1;
                  goto exit;

                }                
             DBGPRINTF("reg[BB][w] page =%d,0x%x[%d:%d]=0x%x",Page,RegStartAddr,Msb,Lsb,Value );
             rtn=pBluetoothModule->SetBBRegMaskBits(pBluetoothModule,Page,RegStartAddr,Msb,Lsb,Value);
        break;
        default :
            DBGPRINTF("[ERR]no match  registe id ...");
                rtn = -1;
        }
         if (rtn !=0)
          goto exit;
       }
       else
       {//read
        Value=0;
        switch(id_8b)
        {

        case BT_MP_REG_MODEM:
                 if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
                rtn=pBluetoothModule->GetMdRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,&Value);
                DBGPRINTF("reg[MD][R]0x%x[%d:%d]=0x%x(%x)",RegStartAddr,Msb,Lsb,Value,rtn);
        break;
        case BT_MP_REG_RF:
                if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
                rtn = pBluetoothModule->GetRfRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,&Value);
                DBGPRINTF("reg[RF][R]0x%x[%d:%d]=0x%x(%x)",RegStartAddr,Msb,Lsb,Value,rtn);
        break;

        case BT_MP_REG_SYS:
                if ((Msb > 15) || (Msb < Lsb) )
                {
                  rtn=-1;
                  goto exit;

                }
                rtn=pBluetoothModule->GetSysRegMaskBits(pBluetoothModule,RegStartAddr,Msb,Lsb,&Value);
                DBGPRINTF("reg[SY][R]0x%x[%d:%d]=0x%x(%x)",RegStartAddr,Msb,Lsb,Value,rtn);
        break;
        case BT_MP_REG_BB:
                Page = pBuf[2];
                RegStartAddr =pBuf[3] ;
                Msb = pBuf [4];
                Lsb =pBuf [5] ;
                 if ((Msb > 15) || (Msb < Lsb) || (Page > 15) )
                {
                  rtn=-1;
                  goto exit;

                }
            //    pBluetoothModule->RecvAnyHciEvent
                rtn=pBluetoothModule->GetBBRegMaskBits(pBluetoothModule,Page,RegStartAddr,Msb,Lsb,&Value);
                DBGPRINTF("reg[BB][R] Page =%d,0x%x[%d:%d]=0x%x(%x)",Page,RegStartAddr,Msb,Lsb,Value,rtn);
        break;
        default :
                rtn = -1;
        }



       }

       //---------------------------------------------
         if (rtn !=0)
           goto exit;       
        //assign tje return data
        pRtn[0] = Value & 0xFF;
        pRtn[1] = (Value>>8) & 0xFF;
        *pRtnLen=2;
        rtn=0;
exit:
      // pRtn[0] = rtn;

       DBGPRINTF("- api_tcpip_bt_mp_RegRW_process(%x) \n",rtn);
       return rtn;

}
int TForm_Main::api_parse_str2buf(char *parse_str,char *pbuf,int *pbuf_len)
{
        int rtn=0;
        char *pch;
        char *p;
        String tmpstr;
        int  pLen=0;
        int  size =0;
        int  n=0;
        UINT32  max_value;
        p= parse_str;
        pch = strtok(p,",");

        while (pch != NULL)
        {


                tmpstr.printf ("%s",pch);
                tmpstr=StringReplace(tmpstr," ","",TReplaceFlags()<<rfReplaceAll);
                tmpstr=StringReplace(tmpstr,"\n","",TReplaceFlags()<<rfReplaceAll);
                tmpstr=StringReplace(tmpstr,"\0","",TReplaceFlags()<<rfReplaceAll);
             //   if ( tmpstr.SubString(0,2) != "0x")
             //   {
             //      tmpstr= "0x"+tmpstr;
              //  }
                max_value =StrToInt(tmpstr);
                if (max_value <=0xFF ){
                 size=1;
                }else if (max_value <=0xFFFF ){
                 size=2;
                }else{
                 size=4;
                }
                for (n=0;n<size;n++)
                {
                    pbuf[pLen] =  ((max_value>>(n*8))&0xFF);
                    pLen++;
                }


                if (pLen > MAX_MEX_BUF_LEN)
                        goto exit;

                pch = strtok (NULL, ",");
        }
exit:
       *pbuf_len =  pLen;
       if (pLen ==0)
        rtn = -1;

       return rtn;


}
int TForm_Main::api_tcpip_bt_mp_RecvEvtprocess(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
        int rtn =0;
    DBGPRINTF("+ api_tcpip_bt_mp_RecvEvtprocess() \n");
    rtn=pBluetoothModule->RecvAnyHciEvent(pBluetoothModule,pRtn);
    if (rtn !=0)
      *pRtnLen =255;
    else
       *pRtnLen=0;
         
exit:
    DBGPRINTF("- api_tcpip_bt_mp_RecvEvtprocess(%x) \n",rtn);
 return rtn;

}
int TForm_Main::api_process_tcpip_command(char *pcmd, int Index,UINT8 *pRtn,UINT16 *pRtnLen)
{
       int rtn =0;
       switch (Index)
       {

       case BT_MP_REGRW:      rtn = api_tcpip_bt_mp_RegRW_process(pcmd,pRtn,pRtnLen);  break;
       case BT_MP_HCICOMMAND: rtn = api_tcpip_bt_mp_HciCmd_process(pcmd,pRtn,pRtnLen);  break;
     //  case BT_MP_REPORT:       break;
       case BT_MP_EXEC:       rtn = api_tcpip_bt_mp_Exec_process(pcmd,pRtn,pRtnLen);  break;
     //  case BT_MP_SETPARAM:     break;
     //  case BT_MP_GETPARAM:     break;
       case RTLBTMP:     rtn=api_tcpip_bt_mp_rtlbtmp_enable_process(pcmd,pRtn,pRtnLen);break;
       case BT_MP_RECVEVT : rtn = api_tcpip_bt_mp_RecvEvtprocess(pcmd,pRtn,pRtnLen);   break;
       default:
            DBGPRINTF("No support the cmd  = %s \n",pcmd);
            rtn =-1;
       }
exit:
      return rtn;
}
int TForm_Main::api_parse_tcpip_command(char *pcmd,UINT8 *pRtn,UINT16 *pRtnLen)
{
  int n=0;
  int Cmd_Index=-1;
  int cmd_length=0;
  int rtn =-1;
  if (pcmd == NULL)
  {
     DBGPRINTF("tcpip_cmd is NULL!!\n");
     goto exit;
  }
  cmd_length = strlen(pcmd);
  if (cmd_length <= 0)
  {
     DBGPRINTF("tcpip_cmd length is  zero!!\n");
     goto exit;
  }
  DBGPRINTF("tcpip_cmd  = %s length =%d  \n",pcmd,cmd_length);
  Cmd_Index=-1;
  // parse the string
   if ((pcmd[0] == '%') || ((pcmd[0] == '/')&& (pcmd[1] == '/')))
   {
        DBGPRINTF("is bypass tcpip_cmd is %s(%d) \n",cmd_length);
        goto exit;
   }
   for (n=0;n<NUMBEROFMPCOMMAND;n++)
   {
        if (strncmp(szMPCommand[n],pcmd,strlen(szMPCommand[n])) == 0)
        {
               Cmd_Index=n;
               break;
        }

   }
   if (Cmd_Index < 0)
   {
      DBGPRINTF("tcpip_cmd is %s(%d)  no match mp command!!\n",pcmd,cmd_length);
      goto exit;
   }
   DBGPRINTF("tcpip_cmd is %s(%d) , Index = %d \n",szMPCommand[n],cmd_length,n);


   if (api_process_tcpip_command(&pcmd[strlen(szMPCommand[n])], Cmd_Index,pRtn,pRtnLen) !=0)
   {

     goto exit;
   }
   rtn=0;
exit:
     return  rtn;
 
}
//---------------------------------------------------------------------------
//
//   Matlab  call BTAPP  End
//
//---------------------------------------------------------------------------







#define RTNBUFFER_RTN    4
#define RTNBUFFER_SIZE  256+RTNBUFFER_RTN




void __fastcall TForm_Main::FWExeJobMode1Click(TObject *Sender)
{
        FWExeJobMode1->Checked != FWExeJobMode1->Checked;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Internet1Click(TObject *Sender)
{
        String  dstr;
        Internet1->Checked = !Internet1->Checked;
         if (Internet1->Checked)
         {
              TabSheet_LED->Caption="LED/TCPIP"  ;
              api_tcpip_GetHostNameAndIPAddress();
              dstr.sprintf(">>Host Server is enable...");
              ServerSocket1->Active=true;
         }
         else
         {
               TabSheet_LED->Caption="LED"  ;
               dstr.sprintf(">>Host Server is disable...");
               ServerSocket1->Active=false;
         }
         Memo_msg->Lines->Add(dstr);
         return ;
}
//---------------------------------------------------------------------------
void TForm_Main::api_tcpip_GetHostNameAndIPAddress()
{
        WORD   wVersionRequested;
        String dstr;
        WSADATA   wsaData;
        wVersionRequested   =   MAKEWORD(1,   1);
        WSAStartup(wVersionRequested,   &wsaData);
        hostent   *host;
        char   hostname[80];
        char   *ipaddress;
        gethostname(hostname,   80);
        host   =   gethostbyname(hostname);
        ipaddress   =   inet_ntoa(*((in_addr   *)host-> h_addr));
        Label14-> Caption=ipaddress;

        GroupBox4-> Caption   =hostname   ;
        dstr.sprintf(">>HostName:%s",hostname);
        Memo_msg->Lines->Add(dstr);
        dstr.sprintf(">>HostIP:%s",ipaddress);
        Memo_msg->Lines->Add(dstr);
    //    dstr.sprintf(">>Control Port:%d",ServerSocket_BTMPAPP->Port);
    //    Memo_msg->Lines->Add(dstr);
        WSACleanup();
        return ;
}
//---------------------------------------------------------------------------
void __fastcall TForm_Main::GetIPHostName1Click(TObject *Sender)
{
        api_tcpip_GetHostNameAndIPAddress();        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ServerSocket1Accept(TObject *Sender,
      TCustomWinSocket *Socket)
{

    String dstr;
  //  int Port= Socket->RemotePort;

    dstr.sprintf(">>[TCPIP]RTKBTMPAPP Accept...Addr = %s ,Port = %d\n",Socket->LocalAddress,Socket->LocalPort );
   // DBGPRINTF(">>[TCPIP]ServerSocket RTKBTMPAPP Accept...Port = %d\n",Port );
    Memo_msg->Lines->Add(dstr);
    return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ServerSocket1ClientConnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
            String dstr;
            dstr.sprintf(">>[TCPIP]RTKBTMPAPP->ClientConnect...Addr = %s ,Port = %d\n",Socket->LocalAddress,Socket->LocalPort );
          // DBGPRINTF(">>[TCPIP]ServerSocket RTKBTMPAPP->ClientConnect...\n")  ;
          Memo_msg->Lines->Add(dstr);
          
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ServerSocket1ClientDisconnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
         String dstr;
        // DBGPRINTF(">>[TCPIP]ServerSocket RTKBTMPAPP -->ClientDisconnect...")  ;
          dstr.sprintf(">>[TCPIP]RTKBTMPAPP -->ClientDisconnect...")  ;
         Memo_msg->Lines->Add(dstr);
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ServerSocket1ClientRead(TObject *Sender,
      TCustomWinSocket *Socket)
{
 String dstr;
 UINT16 Rtn_Len =0;
 UINT8  Rtnbuf[RTNBUFFER_SIZE];
 //DBGPRINTF(">>[TCPIP]RTKBTMPAPP ClientRead<--%s",sRecv)  ;
 AnsiString sRecv =  Socket->ReceiveText();
 dstr.sprintf(">>[TCPIP]RTKBTMPAPP ClientRead<--%s",sRecv)  ;
 Memo_msg->Lines->Add(dstr);
 sRecv =  sRecv.LowerCase();
 memset(Rtnbuf,0,RTNBUFFER_SIZE);
 if (api_parse_tcpip_command(sRecv.c_str(),&Rtnbuf[RTNBUFFER_RTN],&Rtn_Len) !=0)
  {
       //Socket->SendText("NAK");      //Fail

      // Socket->SendBuf(Rtnbuf);

     Rtnbuf[0] = 0xFF;
     Rtnbuf[1] = 0x00;
     Rtnbuf[2] = 0x00;
     Rtnbuf[3] = 0xFF;

     Rtn_Len =4;

  }
 else
  {
     Rtnbuf[0] =0x00;
     Rtnbuf[1] =Rtn_Len & 0xFF;
     Rtnbuf[2] =(Rtn_Len>>8) & 0xFF;
     Rtnbuf[3] =0x00;

     Rtn_Len += 4;

   }
   Socket->SendBuf(Rtnbuf,Rtn_Len);

   return ;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_SendTcpipClick(TObject *Sender)
{
  String dstr,astr;
  UINT16 Rtn_Len =0;
  int n=0;
  UINT8  Rtnbuf[RTNBUFFER_SIZE];
  memset(Rtnbuf,0,RTNBUFFER_SIZE);
   if (api_parse_tcpip_command(Edit_tcpip->Text.c_str(),&Rtnbuf[RTNBUFFER_RTN],&Rtn_Len) !=0)
  {
     Rtnbuf[0] = 0xFF;
     Rtnbuf[1] = 0x00;
     Rtnbuf[2] = 0x00;
     Rtnbuf[3] = 0xFF;

     Rtn_Len =4;

  }
 else
  {
     Rtnbuf[0] =0x00;
     Rtnbuf[1] =Rtn_Len & 0xFF;
     Rtnbuf[2] =(Rtn_Len>>8) & 0xFF;
     Rtnbuf[3] =0x00;

     Rtn_Len += 4;

   }
  dstr.sprintf("[%x %x %x %x]",Rtnbuf[0],Rtnbuf[1],Rtnbuf[2],Rtnbuf[3]);
  for (n=0;n<Rtn_Len;n++);
  {
    astr.sprintf(",%x",Rtnbuf[4+n]);
    dstr+=astr;
  }
  Memo_msg->Lines->Add(dstr);
  return ;
}
//---------------------------------------------------------------------------



//---------------------------------------------------------------------------
void TForm_Main::api_tcpip_bt_mp_InitDefaultParameter()
{

  	BT_PARAMETER *pParam=&tcpip_mBT_PARAMETER;

	pParam->mChannelNumber = Cbx_NoLink_Ch->ItemIndex;
	pParam->mPacketType = Cbx_PktType->ItemIndex;
	pParam->mPayloadType = Cbx_PayloadType->ItemIndex;
	pParam->mTxPacketCount = StrToInt(Edit_PktCount->Text);
	//pParam->mTxGainIndex = StrToInt(Cbx_TxGainIndex->Text);
	pParam->mPacketHeader = StrToInt(Edit_PktHeader->Text);
	pParam->mTxDAC = StrToInt(Cbx_TxDacIndex->Text);
	if(CheckBox_WhiteningEnable->Checked == true)
	{
		pParam->mWhiteningCoeffValue = 0x7f;
	}
	else
	{
		pParam->mWhiteningCoeffValue = 0x80;
	}
	//hit address
        pParam->mHitTarget= StrToInt64(ComboBox_HitAddr->Text);

        return ;

}

//---------------------------------------------------------------------------

void __fastcall TForm_Main::Cbx_PktTypeChange(TObject *Sender)
{
	String dstr;
	int i=0;
	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
	int PacketHeader[] = {0x33820, 0x39858, 0xA078, 0x33820, 0xC050, 0x3F870, 0x15C40, 0x39858, 0xA078};


	if ( (pBTInfo->ChipType >= RTK_BT_CHIP_ID_RTL8822B) && (pBTInfo->ChipType < RTK_BT_CHIP_ID_RTL8763B) )
	{
		if(Cbx_PktType->ItemIndex<= BT_PKT_1DH5)
		{
			dstr.sprintf("%d", TxPowerLevelInfo[DEFAULT_1M_TX_POWER_INDEX]);
		}
		else if(Cbx_PktType->ItemIndex<= BT_PKT_2DH5)
		{
			dstr.sprintf("%d", TxPowerLevelInfo[DEFAULT_2M_TX_POWER_INDEX]);

		}
		else
		{
			dstr.sprintf("%d", TxPowerLevelInfo[DEFAULT_3M_TX_POWER_INDEX]);
		}

		Cbx_TxGainIndex->Text = dstr;
	}

        dstr.sprintf("0x%x", PacketHeader[Cbx_PktType->ItemIndex]);     
        Edit_PktHeader->Text = dstr;
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Cbx_ActionexecChange(TObject *Sender)
{

	String dstr;
	unsigned char ChannelNum;
	unsigned char OldChannelIndex;
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

	OldChannelIndex = Cbx_NoLink_Ch->ItemIndex;
        StaticText2->Caption = "Packet Type";
        Cbx_PktType->Clear();
         Cbx_PktType->Items->Add("DH1");
	        Cbx_PktType->Items->Add("DH3");
            Cbx_PktType->Items->Add("DH5");
	        Cbx_PktType->Items->Add("2DH1");
            Cbx_PktType->Items->Add("2DH3");
	        Cbx_PktType->Items->Add("2DH5");
            Cbx_PktType->Items->Add("3DH1");
	        Cbx_PktType->Items->Add("3DH3");
	        Cbx_PktType->Items->Add("3DH5");
            Cbx_PktType->Text = "DH5";
            Cbx_PktType->ItemIndex=2;
        if (mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAD || mBT_CHIPINFO.ChipType==RTK_BT_CHIP_ID_AMEBAZII )
        {
                Cbx_Actionexec->ItemIndex=4;
                Cbx_Actionexec->Enabled=false;
        }

	switch (Cbx_Actionexec->ItemIndex)
	{
		case SINGLE_TONE_ACTION :
			CheckBox_WhiteningEnable->Enabled = false;
			Edit_PktCount->Enabled = false;
			Cbx_PayloadType->Enabled = false;
			Cbx_PktType->Enabled = false;
			
			CheckBox_WhiteningEnable->Checked = false;
			Cbx_PayloadType->ItemIndex = BT_PAYLOAD_TYPE_ALL0;
			Cbx_PktType->ItemIndex = BT_PKT_3DH5;
			//ComboBox_LEE_ContTx_PHY->Enabled = false;
			ChannelNum = 79;
		break;
		
		case LE_CONT_TX_ACTION :
                        //change show combo box
                         StaticText2->Caption = "PHY";
 			Cbx_PktType->Clear();
            Cbx_PktType->Items->Add("LE 1M PHY");
	        Cbx_PktType->Items->Add("LE 2M PHY");
            Cbx_PktType->Items->Add("LE Coded PHY with S=8");
	        Cbx_PktType->Items->Add("LE Coded PHY with S=2");

            Cbx_PktType->Text = "LE 1M PHY";
            Cbx_PktType->ItemIndex=0;
                        //---------------------------------------
			CheckBox_WhiteningEnable->Enabled = false;
			Edit_PktCount->Enabled = false;
			Cbx_PayloadType->Enabled = false;
			Cbx_PktType->Enabled = true;

			CheckBox_WhiteningEnable->Checked = true;
			Cbx_PayloadType->ItemIndex = BT_PAYLOAD_TYPE_PRBS9;
			Cbx_PktType->ItemIndex = BT_PKT_1DH1;

		      //	if(pModuleBtReport->pBTInfo->ChipType>=RTK_BT_CHIP_ID_RTL8763B)
		     //	{
		      //		ComboBox_LEE_ContTx_PHY->Enabled = true;
		      //	}
			
			ChannelNum = 40;
		break;
		
		default:
			CheckBox_WhiteningEnable->Enabled = true;
			Edit_PktCount->Enabled = true;
			Cbx_PayloadType->Enabled = true;
			Cbx_PktType->Enabled = true;
			//ComboBox_LEE_ContTx_PHY->Enabled = false;
			ChannelNum = 79;
		break;
	}

	Cbx_NoLink_Ch->Items->Clear();
	for (int i=0; i<ChannelNum; i++)
	{
		dstr.sprintf("%d",i);
		Cbx_NoLink_Ch->Items->Add(dstr);
	}

	if(OldChannelIndex < ChannelNum)
	{
		Cbx_NoLink_Ch->ItemIndex = OldChannelIndex;
	}
	else
	{
		Cbx_NoLink_Ch->ItemIndex = ChannelNum-1;
	}

	Cbx_PktTypeChange(Sender);
	
	return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_SetPowerTrackingClick(TObject *Sender)
{

	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;	
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex = TX_POWER_TRACKING;

	pParam->mParamData[0] = 0; //set
	pParam->mParamData[1] = RadioGroup_PowerTracking->ItemIndex; //on or off

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add("Set Power Tracking failed");
 	}
	else
	{
		dstr.sprintf("Set Power Tracking : %d", RadioGroup_PowerTracking->ItemIndex);
		Memo_msg->Lines->Add(dstr);
 	}
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Button_PhysicalEfuseReadClick(TObject *Sender)
{
	String dstr, astr;

	BT_PARAMETER *pBtParam=&mBT_PARAMETER;
	BT_DEVICE_REPORT *pBtReport= &mBT_DEVICE_REPORT;

	unsigned char *pReportData;
	unsigned char *pPGRawData;

   //	int PhyEfuseBank =0;
	int PhyEfuseAddr =0;
	int PhyEfuseLen =0;

    //	PhyEfuseBank = StrToInt( Edit_PhyEfuseBank->Text );
	PhyEfuseAddr = StrToInt( Edit_PhyEfuseAddr->Text );
	PhyEfuseLen = StrToInt( Edit_PhyEfuseLen->Text );
	
	pPGRawData = pBtParam->mPGRawData;
	pReportData = pBtReport->ReportData;

	pBtParam->ParameterIndex = READ_EFUSE_DATA;
	
	memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

	pPGRawData[0] = 0x03; // BT Efuse
	pPGRawData[1] = (PhyEfuseAddr&0xFF); // offset low byte
	pPGRawData[2] = ((PhyEfuseAddr>>BYTE_SHIFT)&0xFF); // offset high byte
	pPGRawData[3] = (PhyEfuseLen&0xFF);  //Len 

	DBGPRINTF(">>++BT_ReadUserDefinedFromEfuse() : header : 0X%02X%02X%02X%02X\n", pPGRawData[0], pPGRawData[1], pPGRawData[2], pPGRawData[3]);
	
	pBluetoothModule->UpDataParameter(pBluetoothModule,pBtParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		DBGPRINTF(">>BT_ReadUserDefinedFromEfuse Exec Fail...\n");
	}
	else
	{
		memset(pReportData,0x00, MAX_USERAWDATA_SIZE);
		pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
		astr.sprintf("0x%02X%02X%02X%02X%02X%02X%02X%02X",pReportData[11], pReportData[10],pReportData[9], pReportData[8], pReportData[7], pReportData[6], pReportData[5], pReportData[4]);
		Edit_PhyEfuseValue->Text = astr;
	}


error:
	return;
}

//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_PhysicalEfuseWriteClick(TObject *Sender)
{
	String dstr, astr;
	
	BT_PARAMETER *pParam = &mBT_PARAMETER;	
	unsigned char *pPGRawData;
	
       //	int PhyEfuseBank;
	int PhyEfuseAddr;
	int PhyEfuseLen;
	unsigned int PhyEfuseValueLow;
	unsigned int PhyEfuseValueHigh;

	unsigned int PhyEfuseValueTextLen;

	String tmp;

     //	PhyEfuseBank = StrToInt( Edit_PhyEfuseBank->Text );
	PhyEfuseAddr = StrToInt( Edit_PhyEfuseAddr->Text );
	PhyEfuseLen = StrToInt( Edit_PhyEfuseLen->Text );
	PhyEfuseValueTextLen = Edit_PhyEfuseValue->Text.Length();

	astr = Edit_PhyEfuseValue->Text;

	while( (18 - PhyEfuseValueTextLen) > 0 )
	{
		astr.Insert("0", 3);
		PhyEfuseValueTextLen++;
	}

	tmp = astr.SubString(1, 10);
	PhyEfuseValueHigh = StrToInt(tmp);

	tmp = astr.SubString(11, 18);
	tmp.Insert("0x", 1);
	PhyEfuseValueLow = StrToInt(tmp);

	pPGRawData = pParam->mPGRawData;
	
	pParam->ParameterIndex = WRITE_EFUSE_DATA;
	
	memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

	pPGRawData[0] = 0x03; // BT Efuse
	pPGRawData[1] = (PhyEfuseAddr&0xFF); // offset low byte
	pPGRawData[2] = ((PhyEfuseAddr>>BYTE_SHIFT)&0xFF); // offset high byte
	pPGRawData[3] = (PhyEfuseLen&0xFF);  //Len 

	pPGRawData[4] = (PhyEfuseValueLow&0xFF);
	pPGRawData[5] = ((PhyEfuseValueLow>>BYTE_SHIFT*1)&0xFF); 
	pPGRawData[6] = ((PhyEfuseValueLow>>BYTE_SHIFT*2)&0xFF); 
	pPGRawData[7] = ((PhyEfuseValueLow>>BYTE_SHIFT*3)&0xFF);
	pPGRawData[8] = (PhyEfuseValueHigh&0xFF);
	pPGRawData[9] = ((PhyEfuseValueHigh>>BYTE_SHIFT*1)&0xFF);
	pPGRawData[10] = ((PhyEfuseValueHigh>>BYTE_SHIFT*2)&0xFF);
	pPGRawData[11] = ((PhyEfuseValueHigh>>BYTE_SHIFT*3)&0xFF);
	
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add(">>BT_WriteUserDefinedToEfuse Exec Fail...\n");
		goto exit;
	}
	else
	{
		Memo_msg->Lines->Add(">>BT_WriteUserDefinedToEfuse Success...\n");
	}

exit:
 
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::CheckBox_Fw_TxRx_ModeClick(TObject *Sender)
{
	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if (CheckBox_Fw_TxRx_Mode->Checked)
	{
		bFwTxRxMode = 1;
		if(pBTInfo->ChipType < RTK_BT_CHIP_ID_RTL8822B)
		{
			API_bt_fw_read_power_info();
		}
	}
	else
	{
		bFwTxRxMode = 0;
		if(pBTInfo->ChipType < RTK_BT_CHIP_ID_RTL8822B)
		{
			API_bt_get_power_index();
		}
	}

	return;        
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::Cbx_Hopping_PktTypeChange(TObject *Sender)
{
	String dstr;
	int i;
	Ckb_Whitening->Visible= true;
	if(Cbx_Hopping_PktType->Text == "LE")
	{
		ComboBox_Hopping_Type->ItemIndex = 0;
		ComboBox_Hopping_Type->Enabled = false;

		ComboBox_Hopping_StopCh->Items->Clear();
		
		for (i=2; i<=39; i++)
		{
			dstr.sprintf("%d",i);
			ComboBox_Hopping_StopCh->Items->Add(dstr);
		}
		
		ComboBox_Hopping_StopCh->Text = "39";
                Ckb_Whitening->Visible= false;

	}
	else
	{
		ComboBox_Hopping_Type->Enabled = true;

		ComboBox_Hopping_StopCh->Items->Clear();		
		for (i=20; i<=78; i++)
		{
			dstr.sprintf("%d",i);
			ComboBox_Hopping_StopCh->Items->Add(dstr);
		}
		ComboBox_Hopping_StopCh->Text = "78";		
	}

        ComboBox_Hopping_TypeChange(Sender);
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::DumpRFRegister1Click(TObject *Sender)
{
	String dstr;
        int n=0;
	unsigned long  Value=0;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
                for (n=0;n<0x3f;n++)
                {
		pBluetoothModule->GetRfRegMaskBits(pBluetoothModule,n,15,0,&Value);
                dstr.sprintf(">>Read rf 0x%x = 0x%x",n,Value);
		Memo_msg->Lines->Add(dstr);
                }

	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Page01Click(TObject *Sender)
{
         Page01->Checked = ! Page01->Checked;
}
//---------------------------------------------------------------------------
int  TForm_Main::GetPowerTrackingStatus(unsigned char  *status)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
   //		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return -1;
	}

	pParam->ParameterIndex = TX_POWER_TRACKING;

	pParam->mParamData[0] = 1; //set

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
     //		Memo_msg->Lines->Add("Get Power Tracking failed");
		goto error;
 	}

	pBluetoothModule->ActionReport(pBluetoothModule, REPORT_POWER_TRACKING, &mBT_DEVICE_REPORT);

        *status =  mBT_DEVICE_REPORT.ReportData[0];
       //	RadioGroup_PowerTracking->ItemIndex = mBT_DEVICE_REPORT.ReportData[0];

       //	dstr.sprintf("Get Power Tracking : %d", mBT_DEVICE_REPORT.ReportData[0]);
       //	Memo_msg->Lines->Add(dstr);
        return 0;

error:
	return -1;
}
void __fastcall TForm_Main::Button_GetPowerTrackingClick(TObject *Sender)
{
   String dstr;
   /*	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex = TX_POWER_TRACKING;

	pParam->mParamData[0] = 1; //set

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{
		Memo_msg->Lines->Add("Get Power Tracking failed");
		goto error;
 	}

	pBluetoothModule->ActionReport(pBluetoothModule, REPORT_POWER_TRACKING, &mBT_DEVICE_REPORT);
        */
        unsigned char status=0;
        if (GetPowerTrackingStatus(&status) !=0 )
        {
                Memo_msg->Lines->Add("Get Power Tracking failed");
		goto error;
        }
	RadioGroup_PowerTracking->ItemIndex = status;

	dstr.sprintf("Get Power Tracking : %d", status);
	Memo_msg->Lines->Add(dstr);


error:
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::MDPage21Click(TObject *Sender)
{
        MDPage21->Checked = ! MDPage21->Checked;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Dump1Click(TObject *Sender)
{
	String dstr;
        int n=0;
	unsigned long  Value=0;
	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

                pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x0000,15,0,0x0000);
                if (Page01->Checked)
                {
                        Memo_msg->Lines->Add("===== Modem Page 0 ==============");
                        for (n=0;n<0x7e;n+=2)
                        {
		        pBluetoothModule->GetMdRegMaskBits(pBluetoothModule,n,15,0,&Value);
                        dstr.sprintf(">>Read md 0x%x = 0x%x",n,Value);
		        Memo_msg->Lines->Add(dstr);
     	                }
                }
                if (MDPage21->Checked)
                {
                        Memo_msg->Lines->Add("===== Modem Page 1 ==============");
                        pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x0000,15,0,0x0001);
                        for (n=0;n<0x7e;n+=2)
                        {
		        pBluetoothModule->GetMdRegMaskBits(pBluetoothModule,n,15,0,&Value);
                        dstr.sprintf(">>Read md 0x%x = 0x%x",n,Value);
		        Memo_msg->Lines->Add(dstr);
     	                }
                }
                pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x0000,15,0,0x0000);

	return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::EnableEfusePageClick(TObject *Sender)
{

	if(EnableEfusePage->Checked == false)
	{
		EnableEfusePage->Checked = true;
	}
	else
	{
		EnableEfusePage->Checked = false;
	}

	if (EnableEfusePage->Checked)
	{
		TabSheet_Efuse->TabVisible= true;
	}
	else
	{
		TabSheet_Efuse->TabVisible= false;
	}

	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::DisableReportUpdateMenuItemClick(
      TObject *Sender)
{
        if(DisableReportUpdateMenuItem->Checked == false)
        {
                DisableReportUpdateMenuItem->Checked = true;
        }
        else
        {
                DisableReportUpdateMenuItem->Checked = false;
        }
}
//---------------------------------------------------------------------------





void __fastcall TForm_Main::EnableMPDebugPage_PopMenuClick(TObject *Sender)
{
	if(EnableMPDebugPage_PopMenu->Checked == false)
	{
		EnableMPDebugPage_PopMenu->Checked = true;
	}
	else
	{
		EnableMPDebugPage_PopMenu->Checked = false;
	}

	if (EnableMPDebugPage_PopMenu->Checked)
	{
		TabSheet_MPDebug->TabVisible= true;
	}
	else
	{
		TabSheet_MPDebug->TabVisible= false;
	}

        return;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ComboBox_MPDebugReportChange(TObject *Sender)
{
 	int i;

	if(ComboBox_MPDebugReport->ItemIndex == 0)
	{
		StringGrid_MPDebugReport->ColCount=2;
		StringGrid_MPDebugReport->RowCount=15;
		StringGrid_MPDebugReport->Cells[0][0] = "Item";
		StringGrid_MPDebugReport->Cells[1][0] = "Value";

		StringGrid_MPDebugReport->Cells[0][1] = "efuse max tx power index";
		StringGrid_MPDebugReport->Cells[0][2] = "efuse 1M tx power index";
		StringGrid_MPDebugReport->Cells[0][3] = "efuse 2M tx power index";
		StringGrid_MPDebugReport->Cells[0][4] = "efuse 3M tx power index";
		StringGrid_MPDebugReport->Cells[0][5] = "efuse LE tx power index";
		StringGrid_MPDebugReport->Cells[0][6] = "current 1M tx power index";
		
		StringGrid_MPDebugReport->Cells[0][7] = "current 2M tx power index";
		StringGrid_MPDebugReport->Cells[0][8] = "current 3M tx power index";
		StringGrid_MPDebugReport->Cells[0][9] = "current LE tx power index";
		StringGrid_MPDebugReport->Cells[0][10] = "thermal_now";
		StringGrid_MPDebugReport->Cells[0][11] = "thermal_default";		
		StringGrid_MPDebugReport->Cells[0][12] = "1M bluewiz max power gain";	
		StringGrid_MPDebugReport->Cells[0][13] = "2M bluewiz max power gain";	
		StringGrid_MPDebugReport->Cells[0][14] = "3M bluewiz max power gain";			

		StringGrid_MPDebugReport->ColWidths[0]=150;
		StringGrid_MPDebugReport->ColWidths[1]=50;

		for( i = 1; i<StringGrid_MPDebugReport->RowCount; i++)
			StringGrid_MPDebugReport->Cells[1][i]="0x00";
	        
		for ( i = 0; i<StringGrid_MPDebugReport->RowCount; i++)
			StringGrid_MPDebugReport->RowHeights[i]=15;
	}
	else
	{

		StringGrid_MPDebugReport->ColCount=2;
		StringGrid_MPDebugReport->RowCount=10;
		StringGrid_MPDebugReport->Cells[0][0] = "Item";
		StringGrid_MPDebugReport->Cells[1][0] = "Value";

		StringGrid_MPDebugReport->Cells[0][1] = "iqk_x";
		StringGrid_MPDebugReport->Cells[0][2] = "iqk_y";
		StringGrid_MPDebugReport->Cells[0][3] = "lok";
		StringGrid_MPDebugReport->Cells[0][4] = "thermal value";
		StringGrid_MPDebugReport->Cells[0][5] = "RCK";
		StringGrid_MPDebugReport->Cells[0][6] = "lok valid";
		
		StringGrid_MPDebugReport->Cells[0][7] = "txiqk valid";
		StringGrid_MPDebugReport->Cells[0][8] = "tmeter valid";
		StringGrid_MPDebugReport->Cells[0][9] = "rck valid";

		StringGrid_MPDebugReport->ColWidths[0]=150;
		StringGrid_MPDebugReport->ColWidths[1]=50;

		for( i = 1; i<StringGrid_MPDebugReport->RowCount; i++)
			StringGrid_MPDebugReport->Cells[1][i]="0x00";
	        
		for ( i = 0; i<StringGrid_MPDebugReport->RowCount; i++)
			StringGrid_MPDebugReport->RowHeights[i]=15;

	}

        return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_MPDebugReportClick(TObject *Sender)
{
	String dstr;

	if(ComboBox_MPDebugReport->ItemIndex == 0)
	{
		pBluetoothModule->ActionReport(pBluetoothModule,REPORT_MP_DEBUG_MESSAGE, &mBT_DEVICE_REPORT);
		
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[0]);		StringGrid_MPDebugReport->Cells[1][1] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[1]);		StringGrid_MPDebugReport->Cells[1][2] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[2]);		StringGrid_MPDebugReport->Cells[1][3] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[3]);		StringGrid_MPDebugReport->Cells[1][4] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[4]);		StringGrid_MPDebugReport->Cells[1][5] = dstr;

		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[5]);		StringGrid_MPDebugReport->Cells[1][6] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[6]);		StringGrid_MPDebugReport->Cells[1][7] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[7]);		StringGrid_MPDebugReport->Cells[1][8] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[8]);		StringGrid_MPDebugReport->Cells[1][9] = dstr;
		
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[9]);		StringGrid_MPDebugReport->Cells[1][10] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[10]);		StringGrid_MPDebugReport->Cells[1][11] = dstr;

		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[11]);		StringGrid_MPDebugReport->Cells[1][12] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[12]);		StringGrid_MPDebugReport->Cells[1][13] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[13]);		StringGrid_MPDebugReport->Cells[1][14] = dstr;	

	}
	else
	{

		pBluetoothModule->ActionReport(pBluetoothModule,REPORT_MP_FT_VALUE, &mBT_DEVICE_REPORT);

		dstr.sprintf("0x%.2x%.2x", mBT_DEVICE_REPORT.ReportData[1], mBT_DEVICE_REPORT.ReportData[0]);		StringGrid_MPDebugReport->Cells[1][1] = dstr;
		dstr.sprintf("0x%.2x%.2x", mBT_DEVICE_REPORT.ReportData[3], mBT_DEVICE_REPORT.ReportData[2]);		StringGrid_MPDebugReport->Cells[1][2] = dstr;
		dstr.sprintf("0x%.2x%.2x", mBT_DEVICE_REPORT.ReportData[5], mBT_DEVICE_REPORT.ReportData[4]);		StringGrid_MPDebugReport->Cells[1][3] = dstr;

		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[6]);			StringGrid_MPDebugReport->Cells[1][4] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[7]);			StringGrid_MPDebugReport->Cells[1][5] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[8]);			StringGrid_MPDebugReport->Cells[1][6] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[9]);			StringGrid_MPDebugReport->Cells[1][7] = dstr;
		
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[10]);			StringGrid_MPDebugReport->Cells[1][8] = dstr;
		dstr.sprintf("0x%x", mBT_DEVICE_REPORT.ReportData[11]);			StringGrid_MPDebugReport->Cells[1][9] = dstr;

	}

        return;        
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::Button_ReadBDAddrClick(TObject *Sender)
{
	String dstr,astr;
	unsigned char pData[512];
	unsigned char pEvtBuf[512];

	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, HCI_READ_BD_ADDR, LEN_0_BYTE, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                Memo_msg->Lines->Add(">>Failed to Read BD Address...");
 		goto error;
	}
	else
	{       astr.sprintf("0x%.2x%.2x%.2x%.2x%.2x%.2x", pEvtBuf[11], pEvtBuf[10], pEvtBuf[9], pEvtBuf[8], pEvtBuf[7], pEvtBuf[6]);
		dstr=">>Read BD Address 0x";
		Memo_msg->Lines->Add(dstr+astr.UpperCase());
	}

error:
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Button_SendHciCmdClick(TObject *Sender)
{   
	int i;
	String dstr, astr;
	unsigned char pData[512];
	unsigned char pEvtBuf[512];
	char *pch;	
	unsigned char DataLen;
	unsigned char pDataChar[512];
	
	unsigned int Opcode = StrToInt(Edit_SendHciCmd_Opcode->Text);
	unsigned char Len = StrToInt(Edit_SendHciCmd_Len->Text);
	String strData = Edit_SendHciCmd_Data->Text;

	DataLen = 0;
	strcpy(pDataChar, strData.c_str());
	pch = strtok(pDataChar, ",");

	while(pch != NULL)
	{
		pData[DataLen] = string_to_num(&pch, 0);

		DataLen++;

		if(DataLen > Len)
			break;

		pch = strtok(NULL, ",");
	}
	
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, Opcode, Len, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
		Memo_msg->Lines->Add(">>Failed to Send Hci Cmd...");
 		goto error;
	}
	else
	{
		dstr.sprintf("->Send Hci Cmd : opcode=0x%.4x, len=%d, data = ", Opcode, Len);
		for( i =0; i <Len; i++)
		{
			astr.sprintf("0x%.2x, ", pData[i]);
			dstr+=astr;
		}
		Memo_msg->Lines->Add(dstr);

		dstr.sprintf("<-Recv Hci Event : code=0x%.2x, len=%d, ", pEvtBuf[0], pEvtBuf[1]);

		for( i=0; i <pEvtBuf[1]; i++)
		{
			astr.sprintf("0x%.2x, ", pEvtBuf[i+2]);
			dstr+=astr;
		}
		Memo_msg->Lines->Add(dstr);

			
	}
	
error:

	return; 	
		
}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::BitBtn_ShowTxPowerClick(TObject *Sender)
{
        API_bt_ShowTxDefaultPower();
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_Set_TPM_IQMClick(TObject *Sender)
{

	String dstr;
	unsigned char pData[512];
	unsigned char pEvtBuf[512];
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8763B)
	{
                if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8763C)
                {
                      if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8773B)
		      {
                        dstr.sprintf(">>Not Support Show Tx power Function!!\n");Memo_msg->Lines->Add(dstr);
		        return;
                      }
                }


	}

	if(RadioGroup_BBPro_TPM_IQM->ItemIndex == BBPRO_TPM) //TPM
	{
		pData[0] = 1;
		pData[1] = 1;
	}
	else //IQM
	{
		pData[0] = 1;
		pData[1] = 0;
	}

	pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xfd87, LEN_2_BYTE, pData, 0x0E, pEvtBuf);

	if(pEvtBuf[5] != 0)
	{
		dstr.sprintf("Set Mode : failed !!\n");Memo_msg->Lines->Add(dstr);
	}
	else
	{
		dstr.sprintf("Set Mode : Success !!\n");Memo_msg->Lines->Add(dstr);
	}

        Button_Get_TPM_IQMClick(Sender);

	return;        
}
//---------------------------------------------------------------------------


//modem p3 0x62 [BIT1]，0 : TPM、1 : IQM
//command在B/C cut need patch，D cut ONLY ROM
//vendor command
//opcode: 0xFD87
//param_len: 1
//param[0]: 0 //sub-opcode

//event_param[4]: status
//event_param[5]: sub-opcode
//event_param[6]: current RF mode(0: IQM, 1: TPM)

void __fastcall TForm_Main::Button_Get_TPM_IQMClick(TObject *Sender)
{
	String dstr;
	unsigned long data;
	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        if (mBT_DEVICE_REPORT.pBTInfo == NULL)
	{
		dstr.sprintf(">>pBTInfo is NULL...Unknow device!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        if((pModuleBtReport->pBTInfo->ChipType==RTK_BT_CHIP_ID_RTL8762C)|| (pModuleBtReport->pBTInfo->ChipType==RTK_BT_CHIP_ID_AMEBAZII)||
           (pModuleBtReport->pBTInfo->ChipType==RTK_BT_CHIP_ID_AMEBAD))
        {
		Cbx_PktType->Items->Clear();
		Cbx_PktType->Items->Add("DH1");
		Cbx_PktType->Items->Add("DH3");
		Cbx_PktType->Items->Add("DH5");
		Cbx_PktType->ItemIndex=0;

                isOnly_BLE=1;
                return ;

        }
	else if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8763B)
	{
                if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8763C)
                {
                      if(pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8773B)
		      {
                        return;
                      }
                }
	}

	pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0x03);

	pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, 0x62, 7, 0, &data);

	pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0x00);
	

	if( (data&BIT_1_MASK) == BIT_1_MASK)
	{
		RadioGroup_BBPro_TPM_IQM->ItemIndex = BBPRO_IQM;

	}
	else
	{
		RadioGroup_BBPro_TPM_IQM->ItemIndex = BBPRO_TPM;
	}

	//dstr.sprintf("Get Mode : 0x%x Success !!\n", data);Memo_msg->Lines->Add(dstr);

	if((RadioGroup_BBPro_TPM_IQM->ItemIndex == BBPRO_TPM)  || (isOnly_BLE))
	{
		Cbx_Actionexec->Items->Clear();
		Cbx_Actionexec->Items->Add("Tx (for Certification)");
		Cbx_Actionexec->Items->Add("Pkt-Tx (for MP)");
		Cbx_Actionexec->Items->Add("Pkt-Rx (for MP)");
		Cbx_Actionexec->Items->Add("LE Tx (for Certification)");
		Cbx_Actionexec->ItemIndex=0;

		Cbx_PktType->Items->Clear();
		Cbx_PktType->Items->Add("DH1");
		Cbx_PktType->Items->Add("DH3");
		Cbx_PktType->Items->Add("DH5");
		Cbx_PktType->ItemIndex=0;

		Cbx_Hopping_PktType->Items->Clear();
		Cbx_Hopping_PktType->Items->Add("DH1");
		Cbx_Hopping_PktType->Items->Add("DH3");
		Cbx_Hopping_PktType->Items->Add("DH5");
		Cbx_Hopping_PktType->Items->Add("LE");
		Cbx_Hopping_PktType->ItemIndex=0;
		
		isTPM = 1;
                isOnly_BLE=1;



		Cbx_TxGainIndex->Clear();
		Cbx_TxGainIndex->Items->Add("00");
		Cbx_TxGainIndex->Text="0x0";
		
	}
	else
	{
		Cbx_Actionexec->Items->Clear();
		Cbx_Actionexec->Items->Add("Tx (for Certification)");
		Cbx_Actionexec->Items->Add("Pkt-Tx (for MP)");
		Cbx_Actionexec->Items->Add("Pkt-Rx (for MP)");
		Cbx_Actionexec->Items->Add("LE Tx (for Certification)");
		Cbx_Actionexec->Items->Add("Single Tone (for MP)");
		Cbx_Actionexec->ItemIndex=0;

		Cbx_PktType->Items->Clear();
		Cbx_PktType->Items->Add("DH1");
		Cbx_PktType->Items->Add("DH3");
		Cbx_PktType->Items->Add("DH5");
		Cbx_PktType->Items->Add("2DH1");
		Cbx_PktType->Items->Add("2DH3");
		Cbx_PktType->Items->Add("2DH5");
		Cbx_PktType->Items->Add("3DH1");
		Cbx_PktType->Items->Add("3DH3");
		Cbx_PktType->Items->Add("3DH5");
		Cbx_PktType->ItemIndex=0;

		Cbx_Hopping_PktType->Items->Clear();
		Cbx_Hopping_PktType->Items->Add("DH1");
		Cbx_Hopping_PktType->Items->Add("DH3");
		Cbx_Hopping_PktType->Items->Add("DH5");
		Cbx_Hopping_PktType->Items->Add("2DH1");
		Cbx_Hopping_PktType->Items->Add("2DH3");
		Cbx_Hopping_PktType->Items->Add("2DH5");
		Cbx_Hopping_PktType->Items->Add("3DH1");
		Cbx_Hopping_PktType->Items->Add("3DH3");
		Cbx_Hopping_PktType->Items->Add("3DH5");		
		Cbx_Hopping_PktType->Items->Add("LE");
		Cbx_Hopping_PktType->Items->Add("NULL");
		Cbx_Hopping_PktType->ItemIndex=0;

		isTPM = 0;
	       //	StaticText6->Visible=true;
		Cbx_TxGainIndex->Visible=true;
		
	}
#ifdef BBPro_newRom_Version
                if(mBT_CHIPINFO.Version> 3)
                {
                Button_BBPro_WriteToFlashConfig->Visible=true;
                TabSheet_BBProFlash->TabVisible = false;;
                }
                else
                {
                Button_BBPro_WriteToFlashConfig->Visible=true;
                TabSheet_BBProFlash->TabVisible = true;;
                }
#endif

	Cbx_PktTypeChange(Sender);

        if (EnableControlBTTxPowerIndex1->Checked)
        {
              //	StaticText6->Visible=true;
	     	Cbx_TxGainIndex->Visible=true;
        }
        else
        {
               //	StaticText6->Visible=false;
	     	Cbx_TxGainIndex->Visible=false;
        }

	return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_Dump_RegClick(TObject *Sender)
{
	int i;
	unsigned long Value;
	FILE *p_fp;

        Button_Dump_Reg->Enabled = false;
	p_fp=fopen("dump_reg.txt","w");

	fputs ("------Rf Register-----\n", p_fp);
	
	for(i=0; i<=0xff; i++)
	{
		pBluetoothModule->GetRfRegMaskBits(pBluetoothModule, i, 15, 0, &Value);
		fprintf(p_fp, "0x%x\t0x%x\n", i, Value);
		fflush(p_fp);
	}
	Memo_msg->Lines->Add("Rf Register dump successfully....");

	fputs ("------Md Register Page 0-----\n", p_fp);
	for(i=0; i<=0xff; i++)
	{
		pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, i, 15, 0, &Value);
		fprintf(p_fp, "0x%x\t0x%x\n", i, Value);
		fflush(p_fp);
	}
	Memo_msg->Lines->Add("Md Register dump successfully....");

	fputs ("------BB Register Page 0-----\n", p_fp);
	for(i=0; i<=0x1fff; i++ )
	{
		pBluetoothModule->GetBBRegMaskBits(pBluetoothModule, 0, i, 15, 0, &Value);
		fprintf(p_fp, "0x%x\t0x%x\n", i, Value);
		fflush(p_fp);
	}
	Memo_msg->Lines->Add("BB Register dump successfully....");

	fputs ("------SYS Register-----\n", p_fp);
	for(i=0; i<=0xff; i++ )
	{
		pBluetoothModule->GetSysRegMaskBits(pBluetoothModule, i, 15, 0,&Value);
		fprintf(p_fp, "0x%x\t0x%x\n", i, Value);
		fflush(p_fp);
	}
	Memo_msg->Lines->Add("SYS Register dump successfully....");

	fclose (p_fp);

        Button_Dump_Reg->Enabled = true;

	return;        
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Enable8723dAntInfoClick(TObject *Sender)
{
	if(Enable8723dAntInfo->Checked == false)
	{
		Enable8723dAntInfo->Checked = true;
	}
	else
	{
		Enable8723dAntInfo->Checked = false;
	}

	if(Enable8723dAntInfo->Checked)
	{
		TabSheet_Ant_Info->TabVisible = true;
	}
	else
	{
		TabSheet_Ant_Info->TabVisible = false;
	}
	
	return;        
}

//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_Set_Diff_S0S1Click(TObject *Sender)
{

	String dstr;
	unsigned long data;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
	BT_DEVICE_REPORT *pModuleBtReport=&mBT_DEVICE_REPORT;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	if((pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8723D) && (pModuleBtReport->pBTInfo->ChipType!=RTK_BT_CHIP_ID_RTL8822C))
	{
                dstr.sprintf(">>Only RTL8723D and RTL8822C Support...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex = SET_ANT_DIFF_S0S1;

	pParam->mParamData[0] = RadioGroup_Ant_Info->ItemIndex;
	pParam->mParamData[1] = StrToInt(Edit_Diff_S0S1->Text);

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) != BT_FUNCTION_SUCCESS)
		goto error;

	Memo_msg->Lines->Add("Set Diff S0 S1 successfully....");

        return; 

error:

	Memo_msg->Lines->Add("Set Diff S0 S1 error....");
	return;

}
//---------------------------------------------------------------------------






void __fastcall TForm_Main::BitBtn2Click(TObject *Sender)
{
      //  int rtn=0;
        String dstr;
        unsigned long Value =0;
        if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //PAGE 6 OFFSET = 0X14[7:4]
	if (pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x00,15,0,0x06) != 0)
        {
                        goto error;
        }
        if (pBluetoothModule->GetMdRegMaskBits(pBluetoothModule,0x14,7,4,&Value) !=0)
        {
                        goto error;
        }
	if (pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x00,15,0,0x00)!=0)
        {
                        goto error;
        }

        if (Value == 1)
        {
                dstr.sprintf(">>LBT Mode Modem =1  Not Tx Mode\n" );
                Memo_msg->Lines->Add(dstr);
                R_LBTMode2->Checked = false;
                R_LBTMode1->Checked = true;
        }
        else  if (Value == 2)
        {
                dstr.sprintf(">>LBT Mode Modem =2  Reduce Tx Mode\n" );
                Memo_msg->Lines->Add(dstr);
                R_LBTMode2->Checked = true;
                R_LBTMode1->Checked = false;
        }
        else
        {
                    dstr.sprintf(">>[warning] LBT Mode  = %x\n",Value );
                    Memo_msg->Lines->Add(dstr);

        }

        return ;

error :
                dstr.sprintf(">>Get LBT Mode Fail\n");Memo_msg->Lines->Add(dstr);
		return;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn4Click(TObject *Sender)
{

        String dstr;
        unsigned long Value =0;
        if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //PAGE 6 OFFSET = 0X14[7:4]
	if (pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x00,15,0,0x06) !=0)
        {
                        goto error;
        }
        if (R_LBTMode1->Checked == true)
        {
                 Value =1;
        }
        else
         {
                 Value=2;
         }
        if (pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x14,7,4,Value) !=0)
        {
                        goto error;
        }
	if (pBluetoothModule->SetMdRegMaskBits(pBluetoothModule,0x00,15,0,0x00) !=0)
        {
                        goto error;
        }
        dstr.sprintf(">>Set LBT Mode Modem = %x\n",Value );
        Memo_msg->Lines->Add(dstr);
        return ;

error :
        dstr.sprintf(">>Set LBT Mode Fail\n");Memo_msg->Lines->Add(dstr);
        return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Button_BBPro_WriteToFlashConfigClick(
      TObject *Sender)
{
    	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
      //  int rtn =0;
	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        //write to buffer 
        unsigned char CrystalCapValue = StrToInt(Cbx_RTL8761_XTAL->Text);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x31;
        pParam -> mParamData[1]= CrystalCapValue;
         pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
          goto error;

         //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;
        dstr.sprintf(">>Write Crystal value = 0x%x To Flash Config success....",CrystalCapValue);
        Memo_msg->Lines->Add(dstr);

        return ;
error:

        dstr.sprintf(">>Write Crystal value = 0x%x To Flash Config error....",CrystalCapValue);
        return ;

}
//---------------------------------------------------------------------------






void __fastcall TForm_Main::Button_WriteRFtoFlashConfigClick(
      TObject *Sender)
{
        unsigned char powerlevel[5];
	String text;
	Button_WriteRFtoFlashConfig->Enabled = false;

    	memset(powerlevel, 0xFF, 5);

	if(ComboBox_MaxTxPowerofLegacy1M->Text != "No Used")
	{
                text = ComboBox_MaxTxPowerofLegacy1M->Text.SubString(1,4);
             	powerlevel[0] = StrToInt(text)&0xFF;
	}
	if(ComboBox_MaxTxPowerofLegacy2M->Text != "No Used")
	{
		text = ComboBox_MaxTxPowerofLegacy2M->Text.SubString(1,4);
                powerlevel[1] = StrToInt(text)&0xFF ;

	}
	if(ComboBox_MaxTxPowerofLegacy3M->Text != "No Used")
	{
		text = ComboBox_MaxTxPowerofLegacy3M->Text.SubString(1,4);
                powerlevel[2] = StrToInt(text)&0xFF;
	}
	if(ComboBox_TxPowerofLE1MLR->Text != "No Used")
	{
		//0x3E0
		text = ComboBox_TxPowerofLE1MLR->Text.SubString(1,4);
                powerlevel[3] = StrToInt(text)&0xFF;
	}
	if(ComboBox_TxPowerofLE2M->Text != "No Used")
	{
		//0x3E1
		text = ComboBox_TxPowerofLE2M->Text.SubString(1,4);
                powerlevel[4] = StrToInt(text)&0xFF;
	}
        text.sprintf("Write RF Tx level 1M= 0x%x 2M= 0x%x 3M= 0x%x BLE1M=0x%x BLE2M= 0x%x to Flash Config ....",powerlevel[0],powerlevel[1],powerlevel[2],powerlevel[3],powerlevel[4]);
        Button_WriteRFtoFlashConfig->Enabled = true;
        Memo_msg->Lines->Add(text);

        BT_PARAMETER *pParam=&mBT_PARAMETER;
	if(pBluetoothModule == NULL)
	{
		text.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(text);
		goto error;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);


        pParam->ParameterIndex = CONFIG_EXTEND;
        pParam->mParamData[0] = 0x34;
        pParam->mParamData[1]= powerlevel[0];//1M;
        pParam->mParamData[2]= powerlevel[1];
        pParam->mParamData[3]= powerlevel[2];
        pParam->mParamData[4]= powerlevel[3];
        pParam->mParamData[5]= powerlevel[4];

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!=0)
          goto error;

        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!=0)
          goto error;

        Memo_msg->Lines->Add("Write config flash end");
        return ;
error:

	text.sprintf("Write RF Tx level 1M= 0x%X 2M= 0x%x 3M= 0x%x BLE1M=0x%x BLE2M= 0x%x to Flash Config Fail!!",powerlevel[0],powerlevel[1],powerlevel[2],powerlevel[3],powerlevel[4]);
        Memo_msg->Lines->Add(text);
        Button_WriteRFtoFlashConfig->Enabled = true;

	return;


}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ComboBox_BREDRPowerControlLevelNumberChange(
      TObject *Sender)
{
   /*	int value;
	int i;
	String dstr;

	if(ComboBox_BREDRPowerControlLevelNumber->Text =="No Used")
	{
		ComboBox_DefaultBREDRTxPowerLevel->Text="No Used";
		return;
	}
	
	value = StrToInt(ComboBox_BREDRPowerControlLevelNumber->Text);
	
	ComboBox_DefaultBREDRTxPowerLevel->Items->Clear();
	for (i =0; i<value; i++)
	{
		dstr.sprintf("%d",i);
		ComboBox_DefaultBREDRTxPowerLevel->Items->Add(dstr);
	}
	ComboBox_DefaultBREDRTxPowerLevel->Items->Add("No Used");
	ComboBox_DefaultBREDRTxPowerLevel->ItemIndex = value-1;
    */
	return;        
}
//---------------------------------------------------------------------------
 void HexDump(char *buf,int len,int addr) {
    int i,j,k;
    char binstr[80];
 
    len=(int)(*(WORD *)buf);
    printf("0x%08X bytes:\n",len);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%08x -",i+addr);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j+=2) {
                sprintf(binstr,"%s%C",binstr,(buf[j]<=0x20&&buf[j+1]==0)?L'.':*(wchar_t *)&buf[j]);
            }
            printf("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j+=2) {
            sprintf(binstr,"%s%C",binstr,(buf[j]<=0x20&&buf[j+1]==0)?L'.':*(wchar_t *)&buf[j]);
        }
        printf("%s\n",binstr);
    }
}
int GetDLLVersionInfo(char *filepath ,WORD *pProdVersion) {
    DWORD             dwVerHnd;
    DWORD             dwVerInfoSize;
    VS_FIXEDFILEINFO *pFileInfo;
    LPVOID            lpvMem;
    HANDLE            hMem;
    unsigned int      uInfoSize;
    WORD              m_nProdVersion[4];

    dwVerInfoSize = GetFileVersionInfoSize(filepath, &dwVerHnd);
    if (dwVerInfoSize) {
            hMem = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
            lpvMem = GlobalLock(hMem);
            GetFileVersionInfo(filepath, dwVerHnd, dwVerInfoSize, lpvMem);
            VerQueryValue(lpvMem,"\\",(void**)&pFileInfo, &uInfoSize);
         //   m_nProdVersion[0]=HIWORD(pFileInfo->dwProductVersionMS);
         ////   m_nProdVersion[1]=LOWORD(pFileInfo->dwProductVersionMS);
         //   m_nProdVersion[2]=HIWORD(pFileInfo->dwProductVersionLS);
         //   m_nProdVersion[3]=LOWORD(pFileInfo->dwProductVersionLS);
            m_nProdVersion[0]=HIWORD(pFileInfo->dwFileVersionMS);
            m_nProdVersion[1]=LOWORD(pFileInfo->dwFileVersionMS);
            m_nProdVersion[2]=HIWORD(pFileInfo->dwFileVersionLS);
            m_nProdVersion[3]=LOWORD(pFileInfo->dwFileVersionLS);
            printf("The file [%s]'s version: %d.%d.%d.%d\n",filepath,
                m_nProdVersion[0],
                m_nProdVersion[1],
                m_nProdVersion[2],
                m_nProdVersion[3]);
            pProdVersion[0]=  m_nProdVersion[0];
            pProdVersion[1]=  m_nProdVersion[1];
            pProdVersion[2]=  m_nProdVersion[2];
            pProdVersion[3]=  m_nProdVersion[3];
            GlobalUnlock(hMem);
            GlobalFree(hMem);
    } else {
        printf("Can not GetFileVersionInfoSize(%s,...)!\n","RtlBluetoothMP.dll");
    }
    return 0;
}
void TForm_Main::GetExeDllVersionInfo()
{

      WORD              dll_m_nProdVersion[4]={0};  ;
      WORD              dll_GUI[4]={0} ;
      String            dll_v,gui_v;
      GetDLLVersionInfo("RtlBluetoothMP.dll",dll_m_nProdVersion);
      GetDLLVersionInfo("RTLBTAPP.EXE",dll_GUI);
      dll_v.sprintf("RtlBluetoothMP.dll Version :%d.%d.%d.%d",dll_m_nProdVersion[0],dll_m_nProdVersion[1],dll_m_nProdVersion[2],dll_m_nProdVersion[3]);
      gui_v.sprintf("RTLBTAPP Version :%d.%d.%d.%d",dll_GUI[0],dll_GUI[1],dll_GUI[2],dll_GUI[3]);
      show_versiom = dll_v+"   "+gui_v;

       return ;
}

void __fastcall TForm_Main::About1Click(TObject *Sender)
{
//    MessageB ox(NULL, "Version 5.2.1.21", "About RTLBTAPP", 0);
     ShowMessage(show_versiom);
      return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::EnableReadWriteRegisterPageClick(
      TObject *Sender)
{
        if(EnableReadWriteRegisterPage->Checked == false)
        {
                EnableReadWriteRegisterPage->Checked = true;
        }
        else
        {
                EnableReadWriteRegisterPage->Checked = false;
        }

        if(EnableReadWriteRegisterPage->Checked ==true)
        {
                TabSheet_RW->TabVisible =true;
                Btn_LoadScript->Visible=true;
 
        }
        else
        {
                TabSheet_RW->TabVisible =false;
                Btn_LoadScript->Visible=false;
        }
        return;        
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Button_Show_SNRClick(TObject *Sender)
{

	String dstr;
	unsigned long data;
	double snr;
	
	//set page0 reg18[12:13]=2'b11     //enable mse report reg
	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0)!=BT_FUNCTION_SUCCESS)
		goto error;

	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x18, 13, 12, 3)!=BT_FUNCTION_SUCCESS)
		goto error;

	//set page2 reg62 = 0x15d7           enable mse
	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 2)!=BT_FUNCTION_SUCCESS)
		goto error;

	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x62, 15, 0, 0x15d7)!=BT_FUNCTION_SUCCESS)
		goto error;
	
	//set page3 reg62[0] = 1         // set reg_rpt_latch_rxneg = 1
	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 3)!=BT_FUNCTION_SUCCESS)
		goto error;

	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x62, 0, 0, 1)!=BT_FUNCTION_SUCCESS)
		goto error;
	
	// read page0 reg68  : mse of payload，u(16,16f)
	if(pBluetoothModule->SetMdRegMaskBits(pBluetoothModule, 0x00, 15, 0, 0)!=BT_FUNCTION_SUCCESS)
		goto error;

	if(pBluetoothModule->GetMdRegMaskBits(pBluetoothModule, 0x68, 15, 0, &data)!=BT_FUNCTION_SUCCESS)
		goto error;

	if( (data !=0) )
	{
		snr = ((double)10.0*log10((double)65536.0)) - ((double)10.0*log10((double)data));
	}
	else
	{
		snr = 0.0;
	}

        dstr.sprintf("##### snr= %lf, data= %d #####\n", snr, data );
        Memo_msg->Lines->Add(dstr);

	return;

error:

	return;
        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ComboBox_Hopping_TypeChange(TObject *Sender)
{
	String dstr;
	int i;
	
	if(ComboBox_Hopping_Type->Text=="Fix Channel")
	{
		ComboBox_Hopping_StopCh->Visible = false;
		StaticText28->Visible = false;

		ComboBox_Hopping_StartCh->Items->Clear();
		
		for (i=0; i<=78; i++)
		{
			dstr.sprintf("%d",i);
			ComboBox_Hopping_StartCh->Items->Add(dstr);
		}
		ComboBox_Hopping_StartCh->Text = "0";

		
	}
	else
	{
		if(Cbx_Hopping_PktType->Text == "LE")
		{
			ComboBox_Hopping_StopCh->Visible = true;
			StaticText28->Visible = true;
			
			ComboBox_Hopping_StartCh->Items->Clear();
			
			for (i=0; i<=37; i++)
			{
				dstr.sprintf("%d",i);
				ComboBox_Hopping_StartCh->Items->Add(dstr);
			}
			ComboBox_Hopping_StartCh->Text = "0";

		}
		else
		{
			ComboBox_Hopping_StopCh->Visible = true;
			StaticText28->Visible = true;
			
			ComboBox_Hopping_StartCh->Items->Clear();
			
			for (i=0; i<=59; i++)
			{
				dstr.sprintf("%d",i);
				ComboBox_Hopping_StartCh->Items->Add(dstr);
			}
			ComboBox_Hopping_StartCh->Text = "0";
		}		
	}

	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ComboBox_Hopping_StartChChange(TObject *Sender)
{
	String dstr;
	int i;
	int StartCh = StrToInt(ComboBox_Hopping_StartCh->Text);

	if(ComboBox_Hopping_Type->Text=="Hopping")
	{
		if(Cbx_Hopping_PktType->Text=="LE")
		{
			ComboBox_Hopping_StopCh->Items->Clear();		
			for (i=StartCh+2; i<=39; i++)
			{
				dstr.sprintf("%d",i);
				ComboBox_Hopping_StopCh->Items->Add(dstr);
			}
			ComboBox_Hopping_StopCh->Text = "39";
		}
		else
		{
			ComboBox_Hopping_StopCh->Items->Clear();		
			for (i=StartCh+19; i<=78; i++)
			{
				dstr.sprintf("%d",i);
				ComboBox_Hopping_StopCh->Items->Add(dstr);
			}
			
			ComboBox_Hopping_StopCh->Text = "78";
		}
	}

	return;
}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::BitBtn_TxgainkClick(TObject *Sender)
{
        String dstr;
        BT_PARAMETER *pParam=&mBT_PARAMETER;
        int value= StrToInt("0x"+Edit_Txgaink->Text);

       if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        pParam->ParameterIndex = TX_POWER_GAIN_K;
        pParam->mParamData[0] = 0x01; //set
        pParam->mParamData[1] = value & 0xFF; //set value
   	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0){
		goto error;
 	}
        dstr.sprintf(">>Set TxGain k = 0x%x Succress\n",value);Memo_msg->Lines->Add(dstr);
        return ;
error:
        dstr.sprintf(">>Set TxGain k = 0x%x Fail\n",value);Memo_msg->Lines->Add(dstr);
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_TxflatnessClick(TObject *Sender)
{
        String dstr;
        BT_PARAMETER *pParam=&mBT_PARAMETER;
        int value= StrToInt("0x"+Edit_Txflatness->Text);

       if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        pParam->ParameterIndex = TX_POWER_FLATNESS;
        pParam->mParamData[0] = 0x02; //set
        pParam->mParamData[1] = value & 0xFF; //set value
        pParam->mParamData[2] = (value>>8) & 0xFF; //set value
        pParam->mParamData[3] = (value>>16) & 0xFF; //set value
        pParam->mParamData[4] = (value>>24) & 0xFF; //set value
   	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0){
		goto error;
 	}
        dstr.sprintf(">>Set TxFlatness = 0x%.8x Succress\n",value);Memo_msg->Lines->Add(dstr);
        return ;
error:
        dstr.sprintf(">>Set TxFlatness = 0x%x Fail\n",value);Memo_msg->Lines->Add(dstr);
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_TxpathlossClick(TObject *Sender)
{
        String dstr;
        BT_PARAMETER *pParam=&mBT_PARAMETER;
        int value= StrToInt("0x"+Edit_Txpathloss->Text);

       if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        pParam->ParameterIndex = TX_PATH_LOSS_MODULE;;
        pParam->mParamData[0] = 0x03; //set
        pParam->mParamData[1] = value & 0xFF; //set value
   	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0){
		goto error;
 	}
        dstr.sprintf(">>Set TxPathlossmodule = 0x%x Succress\n",value);Memo_msg->Lines->Add(dstr);
        return ;
error:
        dstr.sprintf(">>Set TxPathlossmodule = 0x%x Fail\n",value);Memo_msg->Lines->Add(dstr);
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_TxGetClick(TObject *Sender)
{
   	String dstr;
    //	BT_PARAMETER *pParam=&mBT_PARAMETER;
     	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pBluetoothModule->ActionReport(pBluetoothModule, REPORT_MP_TXCAL_INFO, &mBT_DEVICE_REPORT);
        dstr.sprintf("%.2x",mBT_DEVICE_REPORT.ReportData[0]);
        Edit_Txgaink->Text=dstr;
        dstr.sprintf("%.2x%.2X%.2x%.2x",mBT_DEVICE_REPORT.ReportData[4],mBT_DEVICE_REPORT.ReportData[3],mBT_DEVICE_REPORT.ReportData[2],mBT_DEVICE_REPORT.ReportData[1]);
        Edit_Txflatness->Text=dstr;
        if (pBTInfo->ChipType == RTK_BT_CHIP_ID_RTL8763C)
        {
                 dstr.sprintf("%.2x",mBT_DEVICE_REPORT.ReportData[5]);
                Edit_Txpathloss->Text=dstr;
  	        dstr.sprintf(">>Get Tx Power Info : Tx Gain K= 0x%.2x , Flatness_k =0x%.2x%.2x%.2x%.2x Modulue_loss=0x%.2x", mBT_DEVICE_REPORT.ReportData[0],mBT_DEVICE_REPORT.ReportData[4],mBT_DEVICE_REPORT.ReportData[3],mBT_DEVICE_REPORT.ReportData[2],mBT_DEVICE_REPORT.ReportData[1],mBT_DEVICE_REPORT.ReportData[5]);
        }
        else
        {
        dstr.sprintf("%.2x",mBT_DEVICE_REPORT.ReportData[3]);
        Edit_Txpathloss->Text=dstr;
  	dstr.sprintf(">>Get Tx Power Info : Tx Gain K= 0x%.2x , Flatness_k =0x%.2x%.2x Modulue_loss=0x%.2x", mBT_DEVICE_REPORT.ReportData[0],mBT_DEVICE_REPORT.ReportData[2],mBT_DEVICE_REPORT.ReportData[1],mBT_DEVICE_REPORT.ReportData[3]);
        }
	Memo_msg->Lines->Add(dstr);
 error:
	return;
}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::EnableDLPatchDLConfigselect1Click(
      TObject *Sender)
{

        if (EnableDLPatchDLConfigselect1->Checked == false)
	{
		EnableDLPatchDLConfigselect1->Checked = true;
                Cb_downloadpatch->Visible=true;
                Cb_ConfigFile->Visible=true;
                 BitBtn_Patch->Visible=true;

	}
	else
	{
		EnableDLPatchDLConfigselect1->Checked = false;
                Cb_downloadpatch->Visible=false;
                Cb_ConfigFile->Visible=false;

	}

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_TxCalSaveClick(TObject *Sender)
{
   	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
       //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write tx gain k to buffer
        unsigned char TxgaincalValue = StrToInt("0x"+Edit_Txgaink->Text);
        dstr.sprintf(">>Write tx gain k = 0x %x .!!\n",TxgaincalValue);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x32;
        pParam -> mParamData[1]= TxgaincalValue;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write Txflatness to buffer
        int Txflatness= StrToInt("0x"+Edit_Txflatness->Text);
        dstr.sprintf(">>Write tx flatness = 0x%x .!!\n",Txflatness);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x33;
        pParam -> mParamData[1]= Txflatness &0xFF;
        pParam -> mParamData[2]= (Txflatness>>8)&0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
  
          //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;

        return ;
error:
        dstr.sprintf(">>Write Tx Gain K = 0x%x ,flatness = 0x%x to device error!!\n",TxgaincalValue,Txflatness);
        Memo_msg->Lines->Add(dstr);
        return ;

}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::TxFlashDLLTestdebug1Click(TObject *Sender)
{
        if (TxFlashDLLTestdebug1->Checked == true)
        {
             TxFlashDLLTestdebug1->Checked = false;

     
             BitBtn_32kDLLTest->Visible = false;
             Edit_BBPro_32k->Visible = false;



            TabSheet_FLASHDLL->TabVisible = false;

        }
        else
        {
            TxFlashDLLTestdebug1->Checked = true;
   

             BitBtn_32kDLLTest->Visible = true;
             Edit_BBPro_32k->Visible = true;

            TabSheet_FLASHDLL->TabVisible = true;
        }


         return ;
}
//---------------------------------------------------------------------------










void __fastcall TForm_Main::BitBtn_32kDLLTestClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
    //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}



        unsigned char CrystalCapValue = StrToInt(Edit_BBPro_32k->Text);
        dstr.sprintf(">>Write 32 xtal = 0x %x.!!\n",CrystalCapValue);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x15;
        pParam -> mParamData[1]= CrystalCapValue;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        return ;
}
//---------------------------------------------------------------------------

/*
void __fastcall TForm_Main::Cbx_TxGainIndexChange(TObject *Sender)
{
	String dstr;
	if(mBT_CHIPINFO.ChipType>=RTK_BT_CHIP_ID_RTL8763B)
	{
		if (CheckBox_FixGain->Checked)
		{
			StaticText_TXLevel->Caption = "Disable Thermal Tracking and Input Gain Value";

			//show default
			int packettype= Cbx_PktType->ItemIndex;
			int rate = (packettype/3)+1;
			dstr.sprintf("%x",TxPowerLevelInfo[rate]);
			dstr=dstr.UpperCase();
			Cbx_TxGainIndex->Text = dstr;
			Cbx_TxGainIndex->Enabled=true;
		}
		else
		{
			Cbx_TxGainIndex->Enabled=false;
			Cbx_TxGainIndex->Text = "Max";
			StaticText_TXLevel->Caption = "Enable Thermal Tracking, default Max Gain";
			
		}
	}	

/*	
               //show default
                int packettype= Cbx_PktType->ItemIndex;;
                int rate = (packettype/3)+1;
                dstr.sprintf("%x",TxPowerLevelInfo[rate]);
                dstr=dstr.UpperCase();
                Cbx_TxGainIndex->Text = dstr;
               // pParam->mTxGainIndex=TxPowerLevelInfo[rate];

               	if ((Cbx_TxGainIndex->Text == "Max" ) || (!CheckBox_FixGain->Checked))
                {
                                unsigned char status=0;
                                if (GetPowerTrackingStatus(&status) !=0 )
                                {
                                        Memo_msg->Lines->Add("Get Power Tracking failed");
		                        return ;
                                }
                                RadioGroup_PowerTracking->ItemIndex = status;
                                if (status )
                                {
                                        StaticText_TXLevel->Caption = "Enable ThermalTracking";
                                }
                                else
                                  StaticText_TXLevel->Caption = "Disable ThermalTracking";
                 }
        }
 exit:
        if (Cbx_TxGainIndex->Text == "Max" )
        {
           dstr.sprintf("+default Max Gain");
        }
        else
        {
                if (CheckBox_FixGain->Checked)
                {
                dstr.sprintf("+Tx Level = 0x%x",StrToInt("0x"+Cbx_TxGainIndex->Text));
                }
                else
                {
                dstr.sprintf("+default Max Gain = 0x%x",StrToInt("0x"+Cbx_TxGainIndex->Text));
                }
         }   
         StaticText_TXLevel->Caption =  StaticText_TXLevel->Caption+  dstr;

       
        return ;

}
*/
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_BatteryResistanceCalClick(
      TObject *Sender)
{
	String dstr;

	if (dwThreadId != 0)
	{
		if (!PostThreadMessage(dwThreadId, MSG_BATTERY_RESISTANCE_CAL, NULL, NULL))
		{
			dstr.sprintf("Button_BatteryResistanceCalClick: PostThreadMessage failed (%d)\n", GetLastError());
			Memo_msg->Lines->Add(dstr);
			goto error;
		}
	}
	else
	{
		Memo_msg->Lines->Add("Button_BatteryResistanceCalClick: Worker thread not created\n");
		goto error;
	}
	
error:

	return;         

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Edit_BatteryResistanceCal_AvgTimesChange(
      TObject *Sender)
{
	if (Edit_BatteryResistanceCal_AvgTimes->Text.IsEmpty() || Edit_BatteryResistanceCal_AvgTimes->Text.ToInt()<20)
	{
		Edit_BatteryResistanceCal_AvgTimes->Text="20";
	}

        return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_ERASECONFIGPAGEClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x16;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        dstr.sprintf(">>Erase flash config page.... !!\n");Memo_msg->Lines->Add(dstr);

        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_LoadFromDeviceClick(TObject *Sender)
{


	unsigned char TotalConfigEntry[1024];
	unsigned char ConfigEntry[10];
	unsigned int TotalConfigEntryLen = 0;
        String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
        BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;	

	String text;
	int value;
	unsigned char isFlatnessSet = 0;
	unsigned int FlatnessVal;
	unsigned int FlatnessMask;

	int blank_pos;
        int version;

        BT_CHIPINFO	        *pBTInfo=&mBT_CHIPINFO;
        Memo_msg->Lines->Add("------------------------------------------------");
	Memo_msg->Lines->Add("Load RF value from Flash Config Begin....");

	if(pBTInfo->Version > 3)
	{
		version = NEW_ROM_VERSION;
	}
	else
	{
		version = OLD_ROM_VERSION;
	}
	
	Button_WriteRFtoFlashConfig->Enabled = false;
	Button_LoadFromDevice->Enabled = false;
	
	memset(TotalConfigEntry, 0, 1024);
	
	if(ComboBox_MaxTxPowerofLegacy1M->Text != "No Used")
	{
		//0x3DD
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x56;
			ConfigEntry[1] = 0x04;
		}
		else{
			ConfigEntry[0] = 0xDD;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;
		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;

		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
		{
 		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("0x%x\n", value);
		        ComboBox_MaxTxPowerofLegacy1M->Text = dstr;
                }
                Memo_msg->Lines->Add(" Legacy1M Power Level: end of search from config...");


	}

	
	if(ComboBox_MaxTxPowerofLegacy2M->Text != "No Used")
	{
		//0x3DE
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x57;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xDE;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;
		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
		{
		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("0x%x\n", value);
		        ComboBox_MaxTxPowerofLegacy2M->Text = dstr;
                 }
                 Memo_msg->Lines->Add(" Legacy2M Power Level: end of search from config...");

	}

	if(ComboBox_MaxTxPowerofLegacy3M->Text != "No Used")
	{
		//0x3DF 
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x58;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xDF;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {
		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("0x%x\n", value);
		        ComboBox_MaxTxPowerofLegacy3M->Text = dstr;
                }
                Memo_msg->Lines->Add(" Legacy3M Power Level: end of search from config...");
	}

	if(ComboBox_TxPowerofLE1MLR->Text != "No Used")
	{
		//0x3E0
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x59;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xE0;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {

		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("0x%x\n", value);
		        ComboBox_TxPowerofLE1MLR->Text = dstr;
                 }
                 Memo_msg->Lines->Add(" LE1MLR Power Level: end of search from config...");
	}

	if(ComboBox_TxPowerofLE2M->Text != "No Used")
	{
		//0x3E1
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x5a;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xE1;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
		{
                		pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);
                		value = pModuleBtReport->ReportData[4];
		                dstr.sprintf("0x%x\n", value);
		                ComboBox_TxPowerofLE2M->Text = dstr;
                 }
                 Memo_msg->Lines->Add(" LE2M Power Level: end of search from config...");

	}

	if(ComboBox_TxPowerofLE2M_2402MHz->Text != "No Used")
	{
		//0x3E2
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x5b;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xE2;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {

		pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		value = pModuleBtReport->ReportData[4];
		dstr.sprintf("0x%x\n", value);
		ComboBox_TxPowerofLE2M_2402MHz->Text = dstr;
                }
                 Memo_msg->Lines->Add(" LE2M 2402M Hz Power Level: end of search from config...");
	} 

	if(ComboBox_TxPowerofLE2M_2480MHz->Text != "No Used")
	{
		//0x3E3
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x5c;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xE3;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {

		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("0x%x\n", value);
		        ComboBox_TxPowerofLE2M_2480MHz->Text = dstr;
                 }
                  Memo_msg->Lines->Add(" LE2M 2480M Hz Power Level: end of search from config...");
	}	

	if(ComboBox_BREDRPowerControlLevelNumber->Text != "No Used")
	{
		//0x3E8
		if (version == NEW_ROM_VERSION ){
			ConfigEntry[0] = 0x63;
			ConfigEntry[1] = 0x04;
		}else{
			ConfigEntry[0] = 0xE8;
			ConfigEntry[1] = 0x03;
		}
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
		{

		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("%x\n", value);
		        ComboBox_BREDRPowerControlLevelNumber->Text = dstr;
                 }
                  Memo_msg->Lines->Add(" BR/EDR PowerControl Level Number: end of search from config...");

	}

	//Flatness
	{

		if (version == NEW_ROM_VERSION ) {
			ConfigEntry[0] = 0x76;
			ConfigEntry[1] = 0x04;
                }else{
			ConfigEntry[0] = 0xFB;
			ConfigEntry[1] = 0x03;
                }
		ConfigEntry[2] = 0x02;
		ConfigEntry[3] = 0xFF;
		ConfigEntry[4] = 0xFF;
		
		memcpy(pParam->mParamData, ConfigEntry, LEN_7_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {
		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);


		        value =  pModuleBtReport->ReportData[5]&0x0F;
		        if(value == 0)
		        {
			        ComboBox_Flatness2402_2423MHz->Text = "0 dB";
		        }
		        else if(value == 2)
		        {
			        ComboBox_Flatness2402_2423MHz->Text = "1 dB";
		        }
		        else if(value == 4)
		        {
			        ComboBox_Flatness2402_2423MHz->Text = "2 dB";
		        }
		        else if(value == 12)
		        {
			        ComboBox_Flatness2402_2423MHz->Text = "-2 dB";
		        }
		        else if(value == 14)
		        {
			        ComboBox_Flatness2402_2423MHz->Text = "-1 dB";
		        }


		        value = (pModuleBtReport->ReportData[5] &0xF0)>>4;
		        if(value == 0)
		        {
			        ComboBox_Flatness2424_2445MHz->Text = "0 dB";
		        }
		        else if(value == 2)
		        {
			        ComboBox_Flatness2424_2445MHz->Text = "1 dB";
		        }
		        else if(value == 4)
		        {
			        ComboBox_Flatness2424_2445MHz->Text = "2 dB";
		        }
		        else if(value == 12)
		        {
			        ComboBox_Flatness2424_2445MHz->Text = "-2 dB";
		        }
		        else if(value == 14)
		        {
			        ComboBox_Flatness2424_2445MHz->Text = "-1 dB";
		        }


		        value = pModuleBtReport->ReportData[6] &0x0F;
		        if(value == 0)
		        {
			        ComboBox_Flatness2446_2463MHz->Text = "0 dB";
		        }
		        else if(value == 2)
		        {
			        ComboBox_Flatness2446_2463MHz->Text = "1 dB";
		        }
		        else if(value == 4)
		        {
			        ComboBox_Flatness2446_2463MHz->Text = "2 dB";
		        }
		        else if(value == 12)
		        {
			        ComboBox_Flatness2446_2463MHz->Text = "-2 dB";
		        }
		        else if(value == 14)
		        {
			        ComboBox_Flatness2446_2463MHz->Text = "-1 dB";
		        }

		
		        value = (pModuleBtReport->ReportData[6] &0xF0)>>4;
		        if(value == 0)
		        {
			        ComboBox_Flatness2464_2480MHz->Text = "0 dB";
		        }
	        	else if(value == 2)
		        {
			        ComboBox_Flatness2464_2480MHz->Text = "1 dB";
		        }
		        else if(value == 4)
		        {
			        ComboBox_Flatness2464_2480MHz->Text = "2 dB";
		        }
		        else if(value == 12)
		        {
			        ComboBox_Flatness2464_2480MHz->Text = "-2 dB";
		        }
		        else if(value == 14)
		        {
			        ComboBox_Flatness2464_2480MHz->Text = "-1 dB";
		        }
		
              }//end  if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
               Memo_msg->Lines->Add(" Flatness: end of search from config...");
	} //Flatness


	if(ComboBox_AdaptivityEnable->Text != "No Used")
	{
		if (version == NEW_ROM_VERSION ) {
			ConfigEntry[0] = 0x96;
			ConfigEntry[1] = 0x04;
			ConfigEntry[2] = 0x01;
			ConfigEntry[3] = 0x80;  // bit7
		}else{
			ConfigEntry[0] = 0x19;
			ConfigEntry[1] = 0x04;
			ConfigEntry[2] = 0x01;
			ConfigEntry[3] = 0x01;
		}

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {
		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];

		        if(value == 0)
		        {
			        ComboBox_AdaptivityEnable->Text = "Disable";
		        }
		        else
		        {
			        ComboBox_AdaptivityEnable->Text = "Enable";
		        }
	        }
                Memo_msg->Lines->Add(" Adaptivity Enable: end of search from config...");
        }

	if(ComboBox_AdaptivityAntennaGain->Text != "No Used")
	{
		//0x41B
                if (version == NEW_ROM_VERSION ) {
			ConfigEntry[0] = 0x98;
			ConfigEntry[1] = 0x04;
                }else{
			ConfigEntry[0] = 0x1B;
			ConfigEntry[1] = 0x04;
                }
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0xFF;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
		{

		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        ComboBox_AdaptivityAntennaGain->ItemIndex = (value -0xEC) & 0xff;
                 }
                 Memo_msg->Lines->Add(" Adaptivity Antenna Gain: end of search from config...");
	}


     /*	if(ComboBox_DefaultBREDRTxPowerLevel->Text != "No Used")
	{
		//0x041C
		if (version == NEW_ROM_VERSION ) {
			ConfigEntry[0] = 0x99;
			ConfigEntry[1] = 0x04;
                }else{
			ConfigEntry[0] = 0x1C;
			ConfigEntry[1] = 0x04;
                }
		ConfigEntry[2] = 0x01;
		ConfigEntry[3] = 0x07;

		memcpy(pParam->mParamData, ConfigEntry, LEN_4_BYTE);

		pParam->ParameterIndex = READ_FLASH_CONFIG;		
		
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
                {

		        pBluetoothModule->ActionReport(pBluetoothModule, REPORT_FLASH_CONFIG, pModuleBtReport);

		        value = pModuleBtReport->ReportData[4];
		        dstr.sprintf("%x\n", value);
		        ComboBox_DefaultBREDRTxPowerLevel->Text = dstr;
                 }
                 Memo_msg->Lines->Add(" Default BR/EDRTx Power Control Level: end of search from config...");
	}
     */

        Memo_msg->Lines->Add("------------------------------------------------");
	Memo_msg->Lines->Add("Load RF value from Flash Config successfully....");

	Button_WriteRFtoFlashConfig->Enabled = true;
	Button_LoadFromDevice->Enabled = true;

	return;
	
error:	
         Memo_msg->Lines->Add("------------------------------------------------");
	Memo_msg->Lines->Add("Load RF value from Flash Config error....");

	Button_WriteRFtoFlashConfig->Enabled = true;
	Button_LoadFromDevice->Enabled = true;
	
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn7Click(TObject *Sender)
{
        String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}



        unsigned char CrystalCapValue = StrToInt(Cbx_RTL8761_XTAL->Text);
         dstr.sprintf(">>Write xtal = 0x %x. to Writing Buffer!!\n",CrystalCapValue);
         Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x31;
        pParam -> mParamData[1]= CrystalCapValue;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn10Click(TObject *Sender)
{
  	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
        unsigned char powerlevel[5];
	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        String text = ComboBox_MaxTxPowerofLegacy1M->Text.SubString(1,4);
	powerlevel[0] = StrToInt(text)&0xFF;

         text = ComboBox_MaxTxPowerofLegacy2M->Text.SubString(1,4);
	powerlevel[1] = StrToInt(text)&0xFF;

         text = ComboBox_MaxTxPowerofLegacy3M->Text.SubString(1,4);
	powerlevel[2] = StrToInt(text)&0xFF;

         text = ComboBox_TxPowerofLE1MLR->Text.SubString(1,4);
	powerlevel[3] = StrToInt(text)&0xFF;

         text = ComboBox_TxPowerofLE2M->Text.SubString(1,4);
	powerlevel[4] = StrToInt(text)&0xFF;

        dstr.sprintf(">>write tx power 1M =%x ,2M =%x ,3M =%x ,BLE1M =%x ,BLE2M =%x to Writting Buffer!!\n",powerlevel[0],
        powerlevel[1],powerlevel[2],powerlevel[3],powerlevel[4]);
        Memo_msg->Lines->Add(dstr);
        pParam->ParameterIndex = CONFIG_EXTEND;
        pParam->mParamData[0] = 0x34;
        pParam->mParamData[1]= powerlevel[0];//1M;
        pParam->mParamData[2]= powerlevel[1];
        pParam->mParamData[3]= powerlevel[2];
        pParam->mParamData[4]= powerlevel[3];
        pParam->mParamData[5]= powerlevel[4];

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        return ;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn9Click(TObject *Sender)
{
   	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}



        unsigned char TxgaincalValue = StrToInt("0x"+Edit_Txgaink->Text);
        dstr.sprintf(">>Write tx gain k = 0x %x  to Writting Buffer.!!\n",TxgaincalValue);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x32;
        pParam -> mParamData[1]= TxgaincalValue;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);


        int Txflatness= StrToInt("0x"+Edit_Txflatness->Text);
        dstr.sprintf(">>Write tx flatness = 0x%x to Writting Buffer!!\n",Txflatness);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x33;
        pParam -> mParamData[1]= Txflatness &0xFF;
        pParam -> mParamData[2]= (Txflatness>>8)&0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);


}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn5Click(TObject *Sender)
{
        String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        dstr.sprintf(">>Clean Writting Buffer...\n");
        Memo_msg->Lines->Add(dstr);

}
//---------------------------------------------------------------------------
/*
#define EXTEND_WRITE_CONFIG_BDADDR  0x10
#define EXTEND_WRITE_CONFIG_XTALCAP 0x11
#define EXTEND_WRITE_CONFIG_TXGAINK 0x12
#define EXTEND_WRITE_CONFIG_TXFLNESS 0x13
#define EXTEND_WRITE_CONFIG_TXPOWER 0x14
#define EXTEND_WRITE_CONFIG_XTAL32k 0x15
#define EXTEND_ERASE_FLASH_CONFIG_PAGE 0x16
#define EXTEND_WRITE_SET_HEADER_SIZE  0X17


#define EXTEND_WRITE_CONFIG_BUF_BDADDR   0x30
#define EXTEND_WRITE_CONFIG_BUF_XTALCAP  0x31
#define EXTEND_WRITE_CONFIG_BUF_TXGAINK  0x32
#define EXTEND_WRITE_CONFIG_BUF_TXFLNESS 0x33
#define EXTEND_WRITE_CONFIG_BUF_TXPOWER  0x34
#define EXTEND_WRITE_CONFIG_BUF_XTAL32k   0x35
#define EXTEND_ERASE_CONFIG_BUF_CLEAN       0x36
#define EXTEND_ERASE_CONFIG_BUF_WriteToDevice       0x39
*/
void __fastcall TForm_Main::BitBtn6Click(TObject *Sender)
{
        String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
       //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        dstr.sprintf(">>Update Writting Buffer to Config flash...\n");
        Memo_msg->Lines->Add(dstr);

        return ;
}
//---------------------------------------------------------------------------
#define stEditArray_TOP_SHIFT 130

int TForm_Main::CreatsXtalCATArray()
{

   int i=0;
   String dstr;
   int count=0;
   int Thermal=-40;
   for (i=0;i<MAX_STXTALCAL_NUMBER;i++)
   {
      if (stEditXtalCalArrary[i] == NULL)
      {
        stEditXtalCalArrary[i]= new TEdit(this);
        stEditXtalCalArrary[i]->Tag=i;
        stEditXtalCalArrary[i]->Parent= TabSheet_TXTALCAL;// GroupBox_TXTALTABLE;
        stEditXtalCalArrary[i]->Width=35;
        stEditXtalCalArrary[i]->Height=25;

        stEditXtalCalArrary[i]->Cursor=crHandPoint;
        if (i <=12)
        {
         stEditXtalCalArrary[i]->Top= 50;//(i/16)*50 + stEditArray_TOP_SHIFT;
         stEditXtalCalArrary[i]->Left= (TabSheet_TXTALCAL->Left)+ 35 *(i%13);// -count *20;// - 100;
        }else if (i==13)    //default 25
        {
         stEditXtalCalArrary[i]->Top= 50+50;//(i/16)*50 + stEditArray_TOP_SHIFT;
         stEditXtalCalArrary[i]->Left= (TabSheet_TXTALCAL->Left)+ 35 *(i%13)+210;// -count *20;// - 100;
        }else
        {
          stEditXtalCalArrary[i]->Top= 50+50+50;//(i/16)*50 + stEditArray_TOP_SHIFT;
          stEditXtalCalArrary[i]->Left= (TabSheet_TXTALCAL->Left)+ 35 *(i%14);// -count *20;// - 100;
        }

      //  stEditXtalCalArrary[i]->Left= (TabSheet_TXTALCAL->Left+TabSheet_TXTALCAL->Width)- 25 *i -count *20 - 100;
     //   if (((i/8)%2) == 0) {
      //  sbtnArray[i]->Left= (GroupBox1->Left+GroupBox1->Width) - (((i%16)+1)*(sbtnArray[i]->Height+5));
     //   }
     //   else{
     //   sbtnArray[i]->Left= (GroupBox1->Left+GroupBox1->Width)-(((i%16)+1)*(sbtnArray[i]->Height+5))-20;
    //    }
        stEditXtalCalArrary[i]->Text="0";//IntToStr(i);
        stEditXtalCalArrary[i]->Font->Color=clBlue;
        stEditXtalCalArrary[i]->Font->Size=12;
    //    stEditXtalCalArrary[i]->OnClick = sButtonOnClick;
        stEditXtalCalArrary[i]->Show();
        //Lable
        stLabelXtalCalArrary[i] = new TLabel(this);
        stLabelXtalCalArrary[i]->Tag=i;
        stLabelXtalCalArrary[i]->Parent= TabSheet_TXTALCAL;
        stLabelXtalCalArrary[i]->Width=25;
        stLabelXtalCalArrary[i]->Height=25;
        if (i==13)
        stLabelXtalCalArrary[i]->Font->Color=clRed;
        else
        stLabelXtalCalArrary[i]->Font->Color=clBlack;
        stLabelXtalCalArrary[i]->Font->Size=8;
        stLabelXtalCalArrary[i]->Top= stEditXtalCalArrary[i]->Top -20;  //(i/16)*50 + 150
        stLabelXtalCalArrary[i]->Left= stEditXtalCalArrary[i]->Left;

        dstr.sprintf("%.2d(%d)",Thermal,i) ;
       //  dstr.sprintf("%.2d",i) ;
        stLabelXtalCalArrary[i]->Caption= dstr   ;//IntToStr(i);
        Thermal = Thermal +5;
       }

   }
  // sButtonOnClick(NULL);
   return 0;

}
//---------------------------------------------------------------------------
#define EXTEND_XTAL_TRACK_EN_GET                       0x50
#define EXTEND_XTAL_TRACK_EN_SET                       0x51
#define EXTEND_XTAL_TRACK_TABLE_SET					   0x52
#define EXTEND_XTAL_TRACK_TABLE_GET					   0x53
#define EXTEND_XTAL_TRACK_EN_WRITE_CONFIG              0x54
#define EXTEND_XTAL_TRACK_EN_WRITE_CONFIG_BUF	       0x55
#define EXTEND_XTAL_TRACK_TABLE_WRITE_CONFIG           0x56
#define EXTEND_XTAL_TRACK_TABLE_WRITE_CONFIG_BUF	   0x57
void __fastcall TForm_Main::CheckBox_XTALTRACKENClick(TObject *Sender)
{
 	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = EXTEND_XTAL_TRACK_EN_SET;    //subIndex
        if (CheckBox_XTALTRACKEN->Checked)
        pParam -> mParamData[1]= 0x01;
        else
        pParam -> mParamData[1]= 0x00;

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        if (CheckBox_XTALTRACKEN->Checked)
        {
            dstr.sprintf(">>Xtal tracking function Enabel!!\n");Memo_msg->Lines->Add(dstr);
        }
        else
        {
             dstr.sprintf(">>Xtal tracking function Disable!!\n");Memo_msg->Lines->Add(dstr);
        }

        return ;


}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_SETXTALTABLE_RAMClick(TObject *Sender)
{

 	String dstr;
        String hexStr;
        int n=0;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
       //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");
                Memo_msg->Lines->Add(dstr);
		return;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = EXTEND_XTAL_TRACK_TABLE_SET;    //subIndex
         dstr = "Set Xtal Tracking Table = ";
        for (n=0;n<26;n++)
        {
             hexStr="0x"+stEditXtalCalArrary[n]->Text;
             pParam->mParamData[1+n]= StrToInt(hexStr);
             dstr= dstr+ hexStr+",";
        }
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        Memo_msg->Lines->Add(dstr);

        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn12Click(TObject *Sender)
{
        String dstr;
        int n=0;
        String hexStr;
        BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

     	BitBtn_GetRtl8761Xtal->Enabled = false;
     	BitBtn_SetRtl8761Xtal->Enabled = false;
     	Button_BBPro_WriteToFlashConfig->Enabled = false;

        if (pBluetoothModule->ActionReport(pBluetoothModule,REPORT_XTAL, &mBT_DEVICE_REPORT) !=0)
          dstr.sprintf(">>Get Crystal table is Fail!!");
        else
       	  dstr.sprintf(">>Get Crystal value = 0x%x",mBT_DEVICE_REPORT.CurrRtl8761Xtal);
        
   	Memo_msg->Lines->Add(dstr);

        if (pModuleBtReport->CurrStage == 0xFF)
        {
                Xtal_tracking_function_Support=0;
        	dstr.sprintf(">>XTAL Tracking function (No Support)....!!",mBT_DEVICE_REPORT.CurrRtl8761Xtal);
   	        Memo_msg->Lines->Add(dstr);
                goto error;
        }
        else if (pModuleBtReport->CurrStage == 0x01)
        {
              CheckBox_XTALTRACKEN->Checked= true;

              Memo_msg->Lines->Add(">>XTAL Tracking Function (Enable)... \n");
        }
        else             //DISBALE 
        {
              CheckBox_XTALTRACKEN->Checked  = false;
               Memo_msg->Lines->Add(">>XTAL Tracking Function (Disable)... \n");
               goto error;
        }
          dstr = ">>Get XTA; Tracking Table[]=";
         for (n=0;n<26;n++)
        {
             hexStr.sprintf("%x",pModuleBtReport->ReportData[n] );
             hexStr= hexStr.UpperCase();

             stEditXtalCalArrary[n]->Text = hexStr;
             dstr = dstr + hexStr + ",";
        }
         Memo_msg->Lines->Add(dstr);
        Xtal_tracking_function_Support=1;
error:
 	BitBtn_GetRtl8761Xtal->Enabled = true;
	BitBtn_SetRtl8761Xtal->Enabled = true;
	Button_BBPro_WriteToFlashConfig->Enabled = true;
 
        return;
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::BitBtn_SETXTALTABLE_WRClick(TObject *Sender)
{
    	String dstr;
        String hexStr;
        int n=0;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");
                Memo_msg->Lines->Add(dstr);
		return;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = EXTEND_XTAL_TRACK_TABLE_WRITE_CONFIG;    //subIndex
        dstr = "Update Xtal Tracking Table to Flash = ";
        for (n=0;n<26;n++)
        {
             hexStr="0x"+stEditXtalCalArrary[n]->Text;
             pParam->mParamData[1+n]= StrToInt(hexStr);
             dstr = dstr+ hexStr+",";
        }
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        Memo_msg->Lines->Add(dstr);
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_XTALTABLE_EN_WRClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = EXTEND_XTAL_TRACK_EN_WRITE_CONFIG;    //subIndex
        if (CheckBox_XTALTRACKEN->Checked)
        pParam -> mParamData[1]= 0x08 ;
        else
        pParam -> mParamData[1]= 0x00;

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        if (CheckBox_XTALTRACKEN->Checked)
        {
            dstr.sprintf(">>Write Xtal tracking Enabel to Device!!\n");Memo_msg->Lines->Add(dstr);
        }
        else
        {
             dstr.sprintf(">>Write Xtal tracking Disable to Device!!\n");Memo_msg->Lines->Add(dstr);
        }

        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::XTALThermalTrackingPageEnable1Click(
      TObject *Sender)
{
       if (XTALThermalTrackingPageEnable1->Checked)
       {
            TabSheet_TXTALCAL->TabVisible= true;
       }
       else
       {
            TabSheet_TXTALCAL->TabVisible= false;
       }
       return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::ReadTmeter1Click(TObject *Sender)
{
        if (ReadTmeter1->Checked)
            ReadTmeter1->Checked = false;
         else
            ReadTmeter1->Checked = true;
           BitBtn_TRXReadThermal->Visible = ReadTmeter1->Checked;

           return ;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn17Click(TObject *Sender)
{
 	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}



        unsigned char Tmeter = StrToInt(Edit_Flash_Tmeter->Text);
        dstr.sprintf(">>Write txgaink Tmeter Value = 0x %x.!!\n",Tmeter);
         Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x17;
        pParam -> mParamData[1]= Tmeter;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn18Click(TObject *Sender)
{
       	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
     //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}



        unsigned char Tmeter = StrToInt(Edit_Flash_Tmeter->Text);
        dstr.sprintf(">>Write txgaink Tmeter Value = 0x %x.!!\n",Tmeter);
         Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x37;
        pParam -> mParamData[1]= Tmeter;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_HoppingRxBeginClick(TObject *Sender)
{
        //0 : hoppint tx  1: fix chanell  2:hopping rx (can to setting start channel and end channel ), 增加 3: stop hopping rx

        Api_HoppingRx(1);
        return ;

}
//--------------------------------------------------------------------------
void TForm_Main::Api_HoppingRx(int Start_1_or_Stop_0)
{
 	BT_PARAMETER    	*pParam=&mBT_PARAMETER;
      //	BT_DEVICE_REPORT	*pModuleBtReport=&mBT_DEVICE_REPORT;

      	unsigned char  PayloadType = ComboBox_Hopping_PayloadType->ItemIndex;
      //	unsigned char  TxGainValue =  StrToInt(Edit_Hopping_TxGainValue->Text);
      //	unsigned char  TxGainIndex = ComboBox_Hopping_TxGainIndex->ItemIndex;
      //	unsigned char  TxDac = StrToInt(ComboBox_Hopping_TxDac->Text);
	String dstr;

	if(Cbx_Hopping_PktType->Text == "LE")
	{
	      //	pParam->mPacketType = BT_PKT_LE;
              Memo_msg->Lines->Add(">>No support BLE Hopping Rx");
              return ;
	}
	else
	{
		pParam->mPacketType = (BT_PKT_TYPE)( Cbx_Hopping_PktType->ItemIndex);
	}


	if (pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return ;
	}

        Btn_HoppingRun->Enabled = false;

	if (Ckb_Whitening->Checked)
	{
		pParam->mWhiteningCoeffValue=0x7f;
	}
	else
	{
		pParam->mWhiteningCoeffValue=0x80;
	}
	
	if (Start_1_or_Stop_0)
	{
		pParam->bHoppingFixChannel= 2;
		pParam->mParamData[0] = StrToInt(ComboBox_Hopping_StartCh->Text);
		pParam->mParamData[1] = StrToInt(ComboBox_Hopping_StopCh->Text);
	}
	else
	{
		pParam->bHoppingFixChannel= 3;
		pParam->mChannelNumber=StrToInt(ComboBox_Hopping_StartCh->Text);
	}

	pParam->mPayloadType = PayloadType;

	//update
	pParam->ParameterIndex = HOPPING_DWELL_TIME;
	//  int siz = sizeof(BT_PARAMETER);
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	//dwell time command

	if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
	{       if (Start_1_or_Stop_0)
                {
		Memo_msg->Lines->Add(">>Run hopping Rx mode begin failed!!");
                }else{
                Memo_msg->Lines->Add(">>Run hopping Rx mode Stop failed!!");
                }
	}
	else
	{
                if (Start_1_or_Stop_0)
		Memo_msg->Lines->Add(">>Run hopping Rx mode Begin....");
                else
                Memo_msg->Lines->Add(">>Run hopping Rx mode Stop....");
	}

	return ;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_HoppingRxStopClick(TObject *Sender)
{
         Api_HoppingRx(0);
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SetAntClick(TObject *Sender)
{
        int ant= ComboBox_SetAnt->ItemIndex;
 
	String dstr;

	BT_PARAMETER *pParam=&mBT_PARAMETER;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

      if((mBT_CHIPINFO.ChipType!=RTK_BT_CHIP_ID_RTL8822C) &&  (mBT_CHIPINFO.ChipType!=RTK_BT_CHIP_ID_RTL8723D))
	{
                dstr.sprintf(">>Only Suppost RTL8723D and RTL8822C Chip...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

	pParam->ParameterIndex = SET_ANT_INFO;

        if (ComboBox_SetAnt->ItemIndex ==0)
	pParam->mParamData[0] = 0;
        else
        pParam->mParamData[0] = 1;

        

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) != BT_FUNCTION_SUCCESS)
		goto error;

        dstr.sprintf("Set Ant S%d successfully....",pParam->mParamData[0]) ;
	Memo_msg->Lines->Add(dstr);

        return;

error:
        dstr.sprintf("Set Ant  S%d error....",pParam->mParamData[0]) ;
	Memo_msg->Lines->Add(dstr);
	return;

}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::SetAntClick(TObject *Sender)
{
        ComboBox_SetAnt->Visible=true;
        BitBtn_SetAnt->Visible=true;
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::ByPassCheckChipID1Click(TObject *Sender)
{
         ByPassCheckChipID1->Checked = !ByPassCheckChipID1->Checked;


}
//---------------------------------------------------------------------------







void __fastcall TForm_Main::MP_debugpageClick(TObject *Sender)
{
                TabSheet_MPDebug->TabVisible= true;

}
//---------------------------------------------------------------------------






void __fastcall TForm_Main::SaveToDeviceClick(TObject *Sender)
{
	String dstr;
	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
        unsigned long long bd_addr= StrToInt64("0x"+Edit_BDaddr_to_Device->Text);

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}

          //write mac bd_addr
        dstr.sprintf(">>write MAC BD_addr 0x%x.!!\n",bd_addr);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x10;
        pParam -> mParamData[1]=bd_addr &0xFF;
        pParam -> mParamData[2]=(bd_addr>>8)&0xFF;
        pParam -> mParamData[3]=(bd_addr>>16)&0xFF;
        pParam -> mParamData[4]=(bd_addr>>24)&0xFF;
        pParam -> mParamData[5]=(bd_addr>>32)&0xFF;
        pParam -> mParamData[6]=(bd_addr>>40)&0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SaveFlatnessClick(TObject *Sender)
{
        TComboBox *ComboBox_Flatness[4];
        unsigned long FlatnessVal = 0;
        int n=0;
        int blank_pos =0;
        String  text;
        int value;
        String dstr;

        ComboBox_Flatness[0]=  ComboBox_Flatness2402_2423MHz;
        ComboBox_Flatness[1]=  ComboBox_Flatness2424_2445MHz;
        ComboBox_Flatness[2]=  ComboBox_Flatness2446_2463MHz;
        ComboBox_Flatness[3]=  ComboBox_Flatness2464_2480MHz;

        for (n=0;n<4;n++)
        {
  	        blank_pos= ComboBox_Flatness[n]->Text.Pos(" ");
       	        text = ComboBox_Flatness[n]->Text.SubString(1, blank_pos-1);
    	        value = StrToInt(text);
                value *=2;
                FlatnessVal |= (((unsigned char)value&0x0F)<<(4*n));
        }
          dstr.sprintf(">>Write Tx Flatness = 0x%x .!!\n",FlatnessVal);    Memo_msg->Lines->Add(dstr);
        /////////////////////////////////////////////////////////////////////

	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write Txflatness to buffer
        dstr.sprintf(">>Write Tx Flatness = 0x%x .!!\n",FlatnessVal);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x33;
        pParam -> mParamData[1]= FlatnessVal &0xFF;
        pParam -> mParamData[2]= (FlatnessVal>>8)&0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);
  
          //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;
         Memo_msg->Lines->Add(">> Write to config flash finish....");
        return ;
error:
        dstr.sprintf(">>Write Tx flatness = 0x%x to device error!!\n",FlatnessVal);
        Memo_msg->Lines->Add(dstr);
        return ;
   


}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SaveLBTClick(TObject *Sender)
{
        unsigned int en=1;
        unsigned int AdaptivityAntennaGain=0xFF;

        if(ComboBox_AdaptivityEnable->Text == "Disable")
        {
            en=0;
        }

        if(ComboBox_AdaptivityAntennaGain->Text != "No Used")
	{
		//0x41B
		AdaptivityAntennaGain = (ComboBox_AdaptivityAntennaGain->ItemIndex+0xEC) & 0xff;

	}
        ////////////////////////////////////////////////////////////////

	BT_PARAMETER *pParam=&mBT_PARAMETER;
      //	BT_CHIPINFO *pBTInfo=&mBT_CHIPINFO;
        String dstr;
	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write LBT Setting to buffer
        dstr.sprintf(">>Write LBT Enable = 0x%x AdaptivityAntennaGain = 0x%x.!!\n",en,AdaptivityAntennaGain);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x41;
        pParam -> mParamData[1]= en &0xFF;
        pParam -> mParamData[2]= AdaptivityAntennaGain & 0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

          //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;
        Memo_msg->Lines->Add(">> Write to config flash finish....");
        return ;
error:
        dstr.sprintf(">>Write LBT Enable = 0x%x AdaptivityAntennaGain = 0x%x. to device error!!\n",en,AdaptivityAntennaGain);
        Memo_msg->Lines->Add(dstr);
        return ;


}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_2402_2480_TXClick(TObject *Sender)
{
        unsigned int BLE2M_2402=0xFF;
        unsigned int BLE2M_2480=0xFF;
        String   text,dstr;
        if(ComboBox_TxPowerofLE2M_2402MHz->Text != "No Used")
	{
		text = ComboBox_TxPowerofLE2M_2402MHz->Text.SubString(1,4);
		BLE2M_2402 = StrToInt(text);
	}

	if(ComboBox_TxPowerofLE2M_2480MHz->Text != "No Used")
	{

		text = ComboBox_TxPowerofLE2M_2480MHz->Text.SubString(1,4);
	        BLE2M_2480 = StrToInt(text);
	}
        ////////////////////////////////////////////////////////////////

        if ((BLE2M_2480 == 0xFF) &&  (BLE2M_2402 ==0xFF))
        {
               dstr.sprintf(">>Bypass setting....\n");Memo_msg->Lines->Add(dstr);
               return ;
        }
	BT_PARAMETER *pParam=&mBT_PARAMETER;
   
	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write LBT Setting to buffer
        dstr.sprintf(">>Write BLE2M 2402M Tx level = 0x%x, 2480M = 0x%x.!!\n",BLE2M_2402,BLE2M_2480);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x40;
        pParam -> mParamData[1]= BLE2M_2402 &0xFF;
        pParam -> mParamData[2]= BLE2M_2480 &0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

          //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;
        Memo_msg->Lines->Add(">> Write to config flash finish....");
        return ;
error:
        dstr.sprintf(">>Write BLE2M 2402M Tx level = 0x%x, 2480M = 0x%x. to config flash error!!",BLE2M_2402,BLE2M_2480);
        Memo_msg->Lines->Add(dstr);
        return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SavePCClick(TObject *Sender)
{
        unsigned int pc_level=0xFF;
        String   text,dstr;
	if(ComboBox_BREDRPowerControlLevelNumber->Text != "No Used")
	{
	      text = ComboBox_BREDRPowerControlLevelNumber->Text.SubString(1,1);
	      pc_level= StrToInt(text);
	}
        else
        {
            dstr.sprintf(">>Bypass setting....\n");Memo_msg->Lines->Add(dstr);
            return ;
        }
	BT_PARAMETER *pParam=&mBT_PARAMETER;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
        //clear buffer
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x36;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

        //Write LBT Setting to buffer
        dstr.sprintf(">>Write Power control level = 0x%x!!\n",pc_level);
        Memo_msg->Lines->Add(dstr);
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x42;
        pParam -> mParamData[1]= pc_level &0xFF;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        pBluetoothModule->ActionControlExcute(pBluetoothModule);

          //write to device
        pParam ->ParameterIndex = CONFIG_EXTEND;
        pParam -> mParamData[0] = 0x39;
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule)!= 0)
            goto error;
        Memo_msg->Lines->Add(">> Write to config flash finish....");
        return ;
error:
        dstr.sprintf(">Write Power control level = 0x%x to config flash error!!",pc_level);
        Memo_msg->Lines->Add(dstr);
        return ;

}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::RTL8763B1Click(TObject *Sender)
{
        if (RTL8763B1->Checked)
            RTL8763B1->Checked = false;
         else
            RTL8763B1->Checked = true;

           GroupBox_LBT->Visible = RTL8763B1->Checked;

           return ;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BLE2M24022480Setting1Click(TObject *Sender)
{
        if (BLE2M24022480Setting1->Checked)
            BLE2M24022480Setting1->Checked = false;
         else
            BLE2M24022480Setting1->Checked = true;

           GroupBox_BLE2M->Visible = BLE2M24022480Setting1->Checked;

           return ;        
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::PowerControlSetting1Click(TObject *Sender)
{
         if (PowerControlSetting1->Checked)
            PowerControlSetting1->Checked = false;
         else
            PowerControlSetting1->Checked = true;

           GroupBox_PowerCtrl->Visible = PowerControlSetting1->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TForm_Main::CheckBox_FixGainClick(TObject *Sender)
{
	String dstr;
	if(mBT_CHIPINFO.ChipType>=RTK_BT_CHIP_ID_RTL8763B)
	{
		if (CheckBox_FixGain->Checked)
		{
			StaticText_TXLevel->Caption = "Disable Thermal Tracking and Input Gain Value";

			//show default
			int packettype= Cbx_PktType->ItemIndex;
			int rate = (packettype/3)+1;
			dstr.sprintf("%x",TxPowerLevelInfo[rate]);
			dstr=dstr.UpperCase();
			Cbx_TxGainIndex->Text = dstr;
			Cbx_TxGainIndex->Enabled=true;
		}
		else
		{
			Cbx_TxGainIndex->Enabled=false;
			Cbx_TxGainIndex->Text = "Max";
			StaticText_TXLevel->Caption = "Enable Thermal Tracking, default Max Gain";
			
		}
	}	
}
//---------------------------------------------------------------------------





void __fastcall TForm_Main::AllFunction1Click(TObject *Sender)
{
       AllFunction1->Checked = !AllFunction1->Checked;

       if (AllFunction1->Checked )
       {
        TabSheet_TXTALCAL->TabVisible = true;
        TabSheet_Efuse->TabVisible=true;
        TabSheet_LETest->TabVisible=true;

        TabSheet_Cal->TabVisible = true;
        TabSheet_DAC->TabVisible = true;
        TabSheet_RW->TabVisible = true;
        TabSheet_Hopping->TabVisible = true;
        TabSheet_Ant_Info->TabVisible = true;
        LBT_TabSheet->TabVisible = true;
        TabSheet_BBPro_BatteryResistanceCal->TabVisible = true;
        TabSheet_MPDebug->TabVisible= true;
        TabSheet_TXTALCAL->TabVisible = true;
        Button_ReadBDAddr->Visible = true;
        Btn_LoadScript->Visible = true;
        TabSheet_ThermalPowerTrackingDebug->TabVisible = true;
       }
    return ;
}
//---------------------------------------------------------------------------



void __fastcall TForm_Main::Button_StartReadLoopClick(TObject *Sender)
{
	String dstr;

	if (dwThreadId != 0)
	{
		if (!PostThreadMessage(dwThreadId, MSG_START_READ_LOOP, NULL, NULL))
		{
			dstr.sprintf("Button_StartReadLoopClick: PostThreadMessage failed (%d)\n", GetLastError());
			Memo_msg->Lines->Add(dstr);
			goto error;
		}
	}
	else
	{
		Memo_msg->Lines->Add("Button_StartReadLoopClick: Worker thread not created\n");
		goto error;
	}
	
error:

	return;      
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_StopReadLoopClick(TObject *Sender)
{
	pWorkerThread->ReadRegLoopFlag = 0;

	return;       
}
//---------------------------------------------------------------------------





//---------------------------------------------------------------------------



void __fastcall TForm_Main::BitBtn11Click(TObject *Sender)
{
             	unsigned char pData[512]={0};;
	        unsigned char pEvtBuf[512] = {0};
                String dstr;
                int channel =   StrToInt(ComboBox_LeTest_Channel->Text);
                //close
                pData[0] =0 ;
                pData[1]= (channel*2) &0xFF;
                pData[2] = 0X30;
                pData[3] =0 ;
                pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFC78, 4, pData, 0x0E, pEvtBuf);
                dstr.sprintf(">>Stop Channel = %d Single Tone Tx ...\n",channel);Memo_msg->Lines->Add(dstr);
                return ;
}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::BitBtn_BLE_SINGLEToneClick(TObject *Sender)
{
String dstr,astr;
	unsigned char pData[512]={0};
	unsigned char pEvtBuf[512] = {0};

        int channel =   StrToInt(ComboBox_LESingleTone_Ch->Text);
        //close
        pData[0] =0 ;
        pData[1]= (channel*2) &0xFF;
        pData[2] = 0X30;
        pData[3] =0 ;
        pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFC78, 4, pData, 0x0E, pEvtBuf);
        //start
        memset(pData,0,512);
        memset(pEvtBuf,0,512);
        pData[0] =1 ;
        pData[1]= (channel*2) &0xFF;
        pData[2] = 0x30;
        pData[3] =0 ;
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFC78, 4, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                dstr.sprintf(">>Channel = %d  Single Tone Tx.. Fail",channel);
 		goto error;
	}
	else
	{
		dstr.sprintf(">>Channel = %d  Single Tone Tx.. Success",channel);
	}
        Memo_msg->Lines->Add(dstr);

error:
        return ;       
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::RadioButton_MDClick(TObject *Sender)
{
	if(RadioButton_MD->Checked == true)
	{
		Edit_RW_Page->Visible = true;
		Label18->Visible = true;
	}
	else
	{
		Edit_RW_Page->Visible = false;
		Label18->Visible = false;
	}
        
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::RadioButton_MACClick(TObject *Sender)
{
	RadioButton_MDClick(Sender);
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::RadioButton_RFClick(TObject *Sender)
{
	RadioButton_MDClick(Sender);
        return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::RadioButton_BTClick(TObject *Sender)
{
	RadioButton_MDClick(Sender);
        return;        
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Button_8822C_SetTxPowerClick(TObject *Sender)
{
	unsigned char powerlevel[512]={0};
	unsigned char pEvtBuf[512] = {0};

	BT_PARAMETER *pParam=&mBT_PARAMETER;
	String dstr;



	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return;
	}
	
	String text = ComboBox_MaxTxPowerofLegacy1M->Text.SubString(1,4);
	powerlevel[0] = StrToInt(text)&0xFF;

	text = ComboBox_MaxTxPowerofLegacy2M->Text.SubString(1,4);
	powerlevel[1] = StrToInt(text)&0xFF;

	text = ComboBox_MaxTxPowerofLegacy3M->Text.SubString(1,4);
	powerlevel[2] = StrToInt(text)&0xFF;

	text = ComboBox_TxPowerofLE1MLR->Text.SubString(1,4);
	powerlevel[3] = StrToInt(text)&0xFF;

	text = ComboBox_TxPowerofLE2M->Text.SubString(1,4);
	powerlevel[4] = StrToInt(text)&0xFF;
	
 	pParam->ParameterIndex = SetTxPower_8822C;
	memcpy(pParam->mParamData, powerlevel, LEN_5_BYTE);
	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) == BT_FUNCTION_SUCCESS)
	{
		dstr.sprintf(">>Set Tx Power successfully!!\n");
	}
	else
	{
		dstr.sprintf(">>Set Tx Power failed...!!\n");
	}

        Memo_msg->Lines->Add(dstr);

	return;        
}
//---------------------------------------------------------------------------




void __fastcall TForm_Main::BitBtn_GetBoundaryClick(TObject *Sender)
{
   /*
        opcode: 0xFD87

        len: 2

        sub-opcode: 9

        operation: 0 (get)
   */
	String dstr,astr;
	unsigned char pData[512] = {0};
	unsigned char pEvtBuf[512] ={0};
        pData[0] = 0x09;
        pData[1] = 0x00;
        int low_b=0;
        int hi_b=0;
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFD87, LEN_2_BYTE, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                Memo_msg->Lines->Add(">>Failed to Get Thermal power tracking boundary...");
 		goto error;
	}
	else
	{
                 if (pEvtBuf[5] == 0x00)
                 {
                    //show
                    if (pEvtBuf[7] > 127)
                    low_b = (-1)*(256-pEvtBuf[7] );
                    else
                    low_b =(int)( pEvtBuf[7]&0xFF);

                    if (pEvtBuf[8] > 127)
                    hi_b= (-1)*(256-pEvtBuf[8] );
                    else
                    hi_b =(int)( pEvtBuf[8]&0xFF);


                    astr.sprintf("%d", low_b);
                    Edit_B0->Text= astr;
                    astr.sprintf("%d",hi_b);
                    Edit_B1->Text= astr;

                    dstr.sprintf("Get track_boundary = %d , %d ",low_b,hi_b);
		    Memo_msg->Lines->Add(dstr);

                 }
                 else
                 {
                   Memo_msg->Lines->Add(">>Failed to Get Thermal power tracking boundary enevt fail...");
 		   goto error;
                 }

	}

error:
	return;
   
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_GetpolicyClick(TObject *Sender)
{
	String dstr,astr;
	unsigned char pData[512] = {0};
	unsigned char pEvtBuf[512] ={0};
        pData[0] = 0x0a;
        pData[1] = 0x00;
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFD87, LEN_2_BYTE, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                Memo_msg->Lines->Add(">>Failed to Get Thermal power tracking policy...");
 		goto error;
	}
	else
	{
                 if (pEvtBuf[5] == 0x00)
                 {
                    //show
                    ComboBox_TP0->ItemIndex =   (int)(pEvtBuf[7]);
                    ComboBox_TP1->ItemIndex =   (int)(pEvtBuf[8]);
                    ComboBox_TP2->ItemIndex =   (int)(pEvtBuf[9]);
                    dstr.sprintf("Policy = %d , %d  , %d ",(int)(pEvtBuf[7]),(int)(pEvtBuf[8]),(int)(pEvtBuf[9])) ;
		    Memo_msg->Lines->Add(dstr);
                 }
                 else
                 {
                   Memo_msg->Lines->Add(">>Failed to Get Thermal power tracking policy enevt fail...");
 		   goto error;
                 }

	}

error:
	return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtn_SetBoundaryClick(TObject *Sender)
{
	String dstr,astr;
	unsigned char pData[512] = {0};
	unsigned char pEvtBuf[512] ={0};
        pData[0] = 0x09;
        pData[1] = 0x01;
        int low_b=StrToInt(Edit_B0->Text);
        int hi_b=StrToInt(Edit_B1->Text);

        pData[2] = (unsigned char )low_b;
        pData[3] = (unsigned char )hi_b;

	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFD87, LEN_4_BYTE, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                Memo_msg->Lines->Add(">>Failed to Set Thermal power tracking boundary...");
 		goto error;
         }
	else
	{
                 if (pEvtBuf[5] == 0x00)
                 {
                   dstr.sprintf("Set track_boundary = %d , %d ",low_b,hi_b);
		   Memo_msg->Lines->Add(dstr);

                 }
                 else
                 {
                   Memo_msg->Lines->Add(">>Failed to Set Thermal power tracking boundary enevt fail...");
 		   goto error;
                 }

	}

error:
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_SetpolicyClick(TObject *Sender)
{
	String dstr,astr;
	unsigned char pData[512] = {0};
	unsigned char pEvtBuf[512] ={0};
        pData[0] = 0x0a;
        pData[1] = 0x01;
        pData[2] = ComboBox_TP0->ItemIndex;
        pData[3] = ComboBox_TP1->ItemIndex;
        pData[4] = ComboBox_TP2->ItemIndex;
	if (pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFD87, LEN_5_BYTE, pData, 0x0E, pEvtBuf)!=BT_FUNCTION_SUCCESS)
	{
                Memo_msg->Lines->Add(">>Failed to Set Thermal power tracking policy...");
 		goto error;
	}
	else
	{
                 if (pEvtBuf[5] == 0x00)
                 {
                    //show


                    ComboBox_TP0->ItemIndex =   (int)(pEvtBuf[6]);
                    ComboBox_TP1->ItemIndex =   (int)(pEvtBuf[7]);
                    ComboBox_TP2->ItemIndex =   (int)(pEvtBuf[8]);
                    dstr.sprintf("Set Policy(0: floor 1:round 2:ceil) => %d , %d  , %d ",(int)(pData[2]),(int)(pData[3]),(int)(pData[4])) ;
		    Memo_msg->Lines->Add(dstr);
                 }
                 else
                 {
                   Memo_msg->Lines->Add(">>Failed to Set Thermal power tracking policy enevt fail...");
 		   goto error;
                 }

	}

error:
	return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_GetTParamClick(TObject *Sender)
{
        BitBtn_GetBoundaryClick(Sender);
        BitBtn_GetpolicyClick(Sender);
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_SetParamClick(TObject *Sender)
{
        BitBtn_SetBoundaryClick(Sender);
        BitBtn_SetpolicyClick(Sender);
        return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_LOOPTESTClick(TObject *Sender)
{
        int i=0;
        int testcount=StrToInt(Edit_LOOPTEST->Text);
        String dstr,astr;

        if (!looptest_flag)
        {
                looptest_flag=1;
        }

        for(i=0;i<testcount;i++)
        {
                if (!looptest_flag)
                {
                        break;
                }
                dstr.sprintf(">>Loop Test %d (%d )\n",i,testcount);Memo_msg->Lines->Add(dstr);
                Btn_Dev_OpenClick(Sender);
                Cbx_Actionexec->ItemIndex=PKT_TX_ACTION;
                Cbx_PktType->ItemIndex = BT_PKT_2DH5 ;
                Btn_ActionExecClick(Sender);
                Sleep(1000);
                Btn_Dev_CloseClick(Sender);
        }
        BitBtn_LOOPTEST->Caption="LoopStop";
        looptest_flag=0;
        return ;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::looptest1Click(TObject *Sender)
{

       // if (looptest1Cl->)

       BitBtn_LOOPTEST->Visible=true;
       Edit_LOOPTEST->Visible=true;
    //   BitBtn_LOOPTESTSTOP->Visible=true;

}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::Unlock_8822CClick(TObject *Sender)
{

	BT_PARAMETER 	*pParam=&mBT_PARAMETER;

	pParam->ParameterIndex = UNLOCK_8822C;

	pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
	if(pBluetoothModule->ActionControlExcute(pBluetoothModule) != BT_FUNCTION_SUCCESS)
		goto error;

	Memo_msg->Lines->Add(">>Unlock 8822C");

	return;
	
error:
	Memo_msg->Lines->Add(">>Failed to Unlock 8822C...");

	return;
}
//---------------------------------------------------------------------------
void TForm_Main::MPBLEFunctionShow(int BLEspec)
{
        int i=0;
        String dstr;
        ComboBox_LeTest_DataLen->Items->Clear();
	if(BLEspec == 50)
	{


		for (i=0; i<=0xFF; i++)
		{
			dstr.sprintf("0x%x",i);
			ComboBox_LeTest_DataLen->Items->Add(dstr);
		}

		ComboBox_LeTest_DataLen->ItemIndex = 0xFF;
			ComboBox_LEE_PHY->Enabled = true;
			ComboBox_LEE_Modulation->Enabled = false;

			ComboBox_LEE_PHY->Items->Clear();
			ComboBox_LEE_PHY->Items->Add("LE 1M PHY");
			ComboBox_LEE_PHY->Items->Add("LE 2M PHY");
		        if(mBT_CHIPINFO.ChipType != RTK_BT_CHIP_ID_RTL8773B)
                        {
                                ComboBox_LEE_PHY->Items->Add("LE Coded PHY with S=8");
			        ComboBox_LEE_PHY->Items->Add("LE Coded PHY with S=2");
                        }
			ComboBox_LEE_PHY->ItemIndex = 0;
		        StaticText12->Visible = true;
	        	ComboBox_LEE_PHY->Visible = true;
		        StaticText14->Visible = true;
		        ComboBox_LEE_Modulation->Visible = true;
	}
	else
	{

		for (i=0; i<=0x25; i++)
		{
			dstr.sprintf("0x%x",i);
			ComboBox_LeTest_DataLen->Items->Add(dstr);
		}

		ComboBox_LeTest_DataLen->ItemIndex = 0x25;

		Edit_LeTest_RxCount->Enabled = true;

		ComboBox_LeTest_DataLen->Enabled = true;
		ComboBox_LeTest_PayloadType->Enabled = true;
		Edit_LeTest_RxCount->Enabled = false;
	     //	StaticText11->Visible = false;
	     //	ComboBox_LEE_ContTx_PHY->Visible = false;
	       	StaticText12->Visible = false;
	      	ComboBox_LEE_PHY->Visible = false;
	      	StaticText14->Visible = false;
	      	ComboBox_LEE_Modulation->Visible = false;

	}
   return ;
}
//---------------------------------------------------------------------------
int TForm_Main::CheckBLE_SPEC()
{	
        int BLEspec = 50;
	unsigned char pData[512];
	unsigned char pEvtBuf[512];
        String dstr;
        int i=0;

	if(pBluetoothModule == NULL)
	{
		dstr.sprintf(">>BluetoothModule is NULL...!!\n");Memo_msg->Lines->Add(dstr);
		return 50;
	}
	pData[0]= 0x00;pData[1]= 0xFF;pData[2]= 0x00;pData[3]= 0x01;
	pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0x2034, LEN_4_BYTE, pData, 0x0E, pEvtBuf);

	if(pEvtBuf[5] != 0)
	{
		dstr.sprintf("BLE Spec is BT4,0 ,Change GUI format is BT4.0\n");Memo_msg->Lines->Add(dstr);
		BLEspec=40;
	}
	else
	{
	       dstr.sprintf("BLE Spec is BT5,0 ,Change GUI format is BT4.0\n");Memo_msg->Lines->Add(dstr);
	       BLEspec=50;		
	}

        pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0x201f, LEN_0_BYTE, pData, 0x0E, pEvtBuf);
        MPBLEFunctionShow(BLEspec);



	return 	BLEspec;
}
//---------------------------------------------------------------------------
 void TForm_Main::SupportFunctionShow()
 {

        //if ()


         return ;
 }
//---------------------------------------------------------------------------


void __fastcall TForm_Main::Enable40MCalPageClick(TObject *Sender)
{
        if(Enable40MCalPage->Checked == false)
	{
		Enable40MCalPage->Checked = true;
	}
	else
	{
		Enable40MCalPage->Checked = false;
	}

	if (Enable40MCalPage->Checked)
	{
		TabSheet_40MCal->TabVisible= true;
	}
	else
	{
		TabSheet_40MCal->TabVisible= false;
	}

        return;

}

//---------------------------------------------------------------------------
void __fastcall TForm_Main::CalClick(TObject *Sender)
{
        if (EditMeasureFreq->Text.Trim() == "" || Editcal_freq->Text.Trim() == "")
        {
                ShowMessage("Please fill all blanks!");
                return;
        }

        String VerStr, dstr;
        VerStr="RtlBluetoothMP.dll";

        if (API_bt_LoadMpDll() !=0)
	{
		//Btn_Dev_Open->Enabled=false;
		//Btn_Dev_Close->Enabled=false;

                dstr.sprintf(">>Load %s Fail!!",VerStr) ;
                Memo_msg->Lines->Add(dstr);
        }

        //Memo_msg->Lines->Add(">>MeasureFreq_MHz = "+EditMeasureFreq->Text);
        //Memo_msg->Lines->Add(">>cal_freq_MHz = "+Editcal_freq->Text);
        unsigned int DIV_int;
        unsigned int DIV_frac;
        
        double MeasureFreq = StrToFloat( EditMeasureFreq->Text );
        int cal_freq_MHz = StrToInt(Editcal_freq->Text);
        unsigned int pData[2] = {0};

        pData[0]=0x7F;
        int rtn;
        rtn = calibration_Excute_XtalBoundary(pBluetoothModule, NULL, cal_freq_MHz, MeasureFreq, pData);
        if(rtn ==0)
	{
		Memo_msg->Lines->Add("Successed!");
	}else if(rtn == 4)
        {
                Memo_msg->Lines->Add("Parameter out of range!");
                goto exit;
        }

        DIV_int  = pData[0];
        DIV_frac = pData[1];
        dstr.sprintf("0x%.2x",DIV_int);
        Memo_msg->Lines->Add(">>DIV_int = "+ dstr);
        dstr.sprintf("0x%.2x",DIV_frac);
        Memo_msg->Lines->Add(">>DIV_frac = "+ dstr);
        return;


        
exit:
        return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::NormalCalClick(TObject *Sender)
{

        if (EditMeasureFreqOffset->Text.Trim() == "" || EditXcalCapIndex->Text.Trim() == "")
        {
                ShowMessage("Please fill all blanks!");
                return;
        }

        String VerStr, dstr;
        VerStr="RtlBluetoothMP.dll";

        if (API_bt_LoadMpDll() !=0)
	{
		//Btn_Dev_Open->Enabled=false;
		//Btn_Dev_Close->Enabled=false;

                dstr.sprintf(">>Load %s Fail!!",VerStr) ;
                Memo_msg->Lines->Add(dstr);
        }

        double MeasureFreqOffset_KHz = StrToFloat( EditMeasureFreqOffset->Text );
        unsigned int xtal_cap_index = StrToInt( EditXcalCapIndex->Text );
        unsigned int NewCFCapValue[1] = {0};
        
        int rtn;
        rtn = calibration_Excute_XtalNormal(pBluetoothModule, NULL, MeasureFreqOffset_KHz, xtal_cap_index, NewCFCapValue);
        if(rtn ==0)
	{
		Memo_msg->Lines->Add("Successed!");
	}else if(rtn == 4)
        {
                Memo_msg->Lines->Add("Parameter out of range!");
                //goto exit;
        }

        dstr.sprintf("0x%.2x",NewCFCapValue[0]);
        Memo_msg->Lines->Add(">>New xtal cap index = "+ dstr);


        return ;
}

//---------------------------------------------------------------------------


void __fastcall TForm_Main::BitBtnSetBQBUARTClick(TObject *Sender)
{
        /*
        unsigned char *pPGRawData;
        unsigned char *pReport;

        String dstr;
        BT_PARAMETER *pParam; // pParam pointer to struct BT_PARAMETER
        pParam=	&mBT_PARAMETER; //BT_PARAMETER mBT_PARAMETER;

        pParam->ParameterIndex = SET_HW_RESET;

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
        {
                dstr.sprintf(">>Failed to Set HW Reset");
                Memo_msg->Lines->Add(dstr);
                dstr.sprintf("Error");
                //return 1;
                //goto error;
        }
        else
        {
                Memo_msg->Lines->Add(">>Set HW Reset successfully...");

        }
        */

        unsigned char *pPGRawData;
        unsigned char *pReport;

        String dstr;
        BT_PARAMETER *pParam; // pParam pointer to struct BT_PARAMETER
        pParam=	&mBT_PARAMETER; //BT_PARAMETER mBT_PARAMETER;

        pParam->ParameterIndex = SET_BQB_UART_MODE;

        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
        {
                dstr.sprintf(">>Failed to Set BQB UART");
                Memo_msg->Lines->Add(dstr);
                dstr.sprintf("Error");
                //return 1;
                //goto error;
        }
        else
        {
                Memo_msg->Lines->Add(">>Set BQB UART successfully...");

        }

        /*
        String dstr,astr;
	unsigned char pData[512]={0};
	unsigned char pEvtBuf[512]={0};

        pBluetoothModule->SendHciCommandWithEvent(pBluetoothModule, 0xFD93, LEN_0_BYTE, pData, 0x0E, pEvtBuf);

        Memo_msg->Lines->Add(">>Please Check BQB UART...");
        return;
        */
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::SetBQBUART1Click(TObject *Sender)
{
        BitBtnSetBQBUART->Visible = true;
        return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::EnableTxSetting1Click(TObject *Sender)
{
        TabSheet_BBProFlash->TabVisible = true;
        return;
}
//---------------------------------------------------------------------------


void __fastcall TForm_Main::R1Click(TObject *Sender)
{
     //   R1->Checked=!R1->Checked;
        Form_BTRD->SetBluetoothModule(pBluetoothModule);
      //  if (R1->Checked)
     //   {
                Form_BTRD->Visible=true;
                Form_BTRD->Show();
      //  }
     //   else
     //   {
     //           Form_BTRD->Visible=false;
     //   }
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------


void __fastcall TForm_Main::RD_MODEClick(TObject *Sender)
{
                Form_BTRD->SetBluetoothModule(pBluetoothModule);
                Form_BTRD->Visible=true;
                Form_BTRD->Show();
                return ;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtnReadSystemEfuseClick(TObject *Sender)
{
         unsigned char *pPGRawData;
        unsigned char *pReport;
        unsigned char sysEfuse[208];

        String dstr;
        BT_PARAMETER *pParam; // pParam pointer to struct BT_PARAMETER
        pParam=	&mBT_PARAMETER; //BT_PARAMETER mBT_PARAMETER;

        pParam->ParameterIndex = READ_EFUSE_DATA;
        pPGRawData = pParam->mPGRawData;
        pReport = mBT_DEVICE_REPORT.ReportData; //BT_DEVICE_REPORT mBT_DEVICE_REPORT;

        pPGRawData[0] = 0x02; // System Efuse
        pPGRawData[1] = 0x00; // Logical Address LSB
        pPGRawData[2] = 0x00; // Logical Address MSB
        pPGRawData[3] = 0xD0; // LSB Len
        pPGRawData[4] = 0x00; // MSB Len
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
        {
                dstr.sprintf(">>Failed to read BDAddr efuse");
                Memo_msg->Lines->Add(dstr);
                dstr.sprintf("Error");
                //return 1;
                //goto error;
        }
        else
        {
                memset(pReport,0x00, MAX_USERAWDATA_SIZE);
                pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
                //dstr.sprintf("0X%.2X%.2X", pReport[6], pReport[5]);
                //Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
                //dstr.sprintf("0X%02X%02X%02X%02X%02X%02X",pReport[9], pReport[8], pReport[7], pReport[6], pReport[5], pReport[4]);
                //Edit_Efuse_BDAddr->Text=dstr;
                Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
                memcpy(sysEfuse, pReport+5, 208);
        }
        Memo_msg->Lines->Add("System Efuse:");

        String tmp;
        int count =0;
        for(int i=0;i<208;i++)
        {
                count++;
                dstr.sprintf("%.2X", sysEfuse[i]);
                tmp= tmp+dstr+" ";
                if(count==16)
                {
                        Memo_msg->Lines->Add(tmp);
                        count =0;
                        tmp="";
                }
        }
        return;                
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtnReadBTEfuseClick(TObject *Sender)
{
        unsigned char *pPGRawData;
        unsigned char *pReport;
        unsigned char btEfuse[1024];

        String dstr;
        BT_PARAMETER *pParam; // pParam pointer to struct BT_PARAMETER
        pParam=	&mBT_PARAMETER; //BT_PARAMETER mBT_PARAMETER;

        pParam->ParameterIndex = READ_EFUSE_DATA;
        pPGRawData = pParam->mPGRawData;
        pReport = mBT_DEVICE_REPORT.ReportData; //BT_DEVICE_REPORT mBT_DEVICE_REPORT;

        pPGRawData[0] = 0x01; // BT Efuse
        pPGRawData[1] = 0x00; // Logical Address LSB
        pPGRawData[2] = 0x00; // Logical Address MSB
        pPGRawData[3] = 0x00; // LSB Len
        pPGRawData[4] = 0x04; // MSB Len
        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
        {
                dstr.sprintf(">>Failed to read BDAddr efuse");
                Memo_msg->Lines->Add(dstr);
                dstr.sprintf("Error");
                //return 1;
                //goto error;
        }
        else
        {
                memset(pReport,0x00, MAX_USERAWDATA_SIZE);
                pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
                //dstr.sprintf("0X%.2X%.2X", pReport[6], pReport[5]);
                //Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
                //dstr.sprintf("0X%02X%02X%02X%02X%02X%02X",pReport[9], pReport[8], pReport[7], pReport[6], pReport[5], pReport[4]);
                //Edit_Efuse_BDAddr->Text=dstr;
                Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
                memcpy(btEfuse, pReport+5, 1024);
        }
        Memo_msg->Lines->Add("BT Efuse:");

        String tmp;
        int count =0;
        for(int i=0;i<1024;i++)
        {
                count++;
                dstr.sprintf("%.2X", btEfuse[i]);
                tmp= tmp+dstr+" ";
                if(count==16)
                {
                        Memo_msg->Lines->Add(tmp);
                        count =0;
                        tmp="";
                }
        }
        return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_Load_MapClick(TObject *Sender)
{

        OpenDialog1->Options.Clear();
	OpenDialog1->Title = "Load"  ;
	OpenDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
        OpenDialog1->Filter = "map files (*.map)|*.map|All files (*.*)|*.*";
	//OpenDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
	OpenDialog1->FileName="";
	OpenDialog1->FilterIndex=0;
	if(OpenDialog1->Execute())
	{

                Memo_msg->Clear();
                TStrings* Str = new TStringList();
                Memo_msg->Lines->LoadFromFile(OpenDialog1->FileName.c_str()); // 載入檔案
                Str->CommaText=Memo_msg->Text;   // 空白及逗點和斷行字串會自動分離

                /*
                for (int i=0;i < Str->Count ; i++  )
                {
                        Memo_msg->Lines->Add(Str->Strings[i]);
                }
                */

                String dstr;
                dstr.sprintf("Are you sure to write? \nPlease Click (N) to check data on Message first.\nIf data is correct on Message, please click (Y)");
                if (Application->MessageBox(dstr.c_str(), "Bluetooth RF Test Tool", MB_YESNO) != IDYES)
	        {
		        return;
	        }


                int count;
                count = Str->Count;
                if(count == 256) // System Efuse Map
                {
                        BT_PARAMETER *pParam = &mBT_PARAMETER;
                        int n=0;
                        unsigned char *pPGRawData;

                        pParam->ParameterIndex = WRITE_EFUSE_DATA;
                        pPGRawData = pParam->mPGRawData;
                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

                        pPGRawData[0] = 0x02; // System Efuse
                        pPGRawData[1] = 0x00; // offset low byte
                        pPGRawData[2] = 0x00; // offset high byte
                        pPGRawData[3] = 0x00; // LSB len
                        pPGRawData[4] = 0x01; // MSB len

                        unsigned char data;
                        AnsiString str;

                        for (n=0; n < 256; n++)
                        {
                                str  = "0x" + Str->Strings[n];
                                data = StrToInt( str ) & 0xFF;
                                pPGRawData[n+5]= data;
                        }

                        if (pBluetoothModule == NULL)
                        {
                                ShowMessage(">>BluetoothModule is NULL...!!\n");
                                //goto error;
                                //return 1;
                        }

                        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);//Write

                        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
                        {
                                ShowMessage(">>Load Efuse Map and Write Fail...\n");
                                //goto error;
                                //return 1;
                        }
                        else
                        {
                                ShowMessage(">>Load Efuse Map and Write Success...\n");
                        }

                }
                else if(count == 1024) // BT Efuse Map
                {
                        BT_PARAMETER *pParam = &mBT_PARAMETER;
                        int n=0;
                        unsigned char *pPGRawData;

                        pParam->ParameterIndex = WRITE_EFUSE_DATA;
                        pPGRawData = pParam->mPGRawData;
                        memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

                        pPGRawData[0] = 0x01; // System Efuse
                        pPGRawData[1] = 0x00; // offset low byte
                        pPGRawData[2] = 0x00; // offset high byte
                        pPGRawData[3] = 0x00; // LSB len
                        pPGRawData[4] = 0x04; // MSB len

                        unsigned char data;
                        AnsiString str;

                        for (n=0; n < 1024; n++)
                        {
                                str  =  "0x" + Str->Strings[n];
                                data = StrToInt( str ) & 0xFF;
                                pPGRawData[n+5]= data;
                        }

                        if (pBluetoothModule == NULL)
                        {
                                ShowMessage(">>BluetoothModule is NULL...!!\n");
                                //goto error;
                                //return 1;
                        }

                        pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);//Write

                        if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
                        {
                                ShowMessage(">>Load Efuse Map and Write Fail...\n");
                                //goto error;
                                //return 1;
                        }
                        else
                        {
                                ShowMessage(">>Load Efuse Map and Write Success...\n");
                        }

                }
                else
                {
                        ShowMessage("Efuse Map Format Error!!");

                }
        }
        return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_Read_EfuseClick(TObject *Sender)
{
        unsigned char *pPGRawData;
	unsigned char *pReport;

	String dstr;
	BT_PARAMETER *pParam;
	pParam=	&mBT_PARAMETER;

	pParam->ParameterIndex = READ_EFUSE_DATA;
	pPGRawData = pParam->mPGRawData;
	pReport = mBT_DEVICE_REPORT.ReportData;

 	//BitBtn_ReadEfuse->Enabled=false;

	if (CheckBox_Efuse_Map_BDAddr->Checked)
	{
		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x30; // Logical Address LSB
                pPGRawData[2] = 0x00; // Logical Address MSB
                pPGRawData[3] = 0x06; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to read BDAddr efuse");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
                        memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0X%02X%02X%02X%02X%02X%02X",pReport[10], pReport[9], pReport[8], pReport[7], pReport[6], pReport[5]);
			Edit_Efuse_Map_BDAddr->Text=dstr;
			Memo_msg->Lines->Add(">>Read BDAddr Efuse Success: "+dstr);
		}
	}


        if(CheckBox_Efuse_Map_Thermal->Checked)
        {
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x8c; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
		     	dstr.sprintf(">>Failed to read Thermal efuse");
		      	Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x",pReport[5]);
			Edit_Efuse_Map_Thermal->Text=dstr;
			Memo_msg->Lines->Add(">>Read Thermal Efuse Success: " + dstr);
		}
        }

        if (CheckBox_Efuse_Map_TX->Checked)
        {
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x78; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
		     	dstr.sprintf(">>Failed to read TX Power");
		      	Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x",pReport[6]);
			Edit_Efuse_Map_TXPower->Text=dstr;
			Memo_msg->Lines->Add(">>Read TX Power Success: " + dstr);
		}



        }

        if (CheckBox_Efuse_Map_Flatness->Checked)
        {
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // BT Efuse
                pPGRawData[1] = 0x7A; // Logical Address LSB
                pPGRawData[2] = 0x02; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
		     	dstr.sprintf(">>Failed to read Flatness Cal");
		      	Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x%02x",pReport[6],pReport[5]);
			Edit_Efuse_Map_Flatness->Text=dstr;
			Memo_msg->Lines->Add(">>Read Flatness Cal Success: " + dstr);
		}



        }

        if (CheckBox_Efuse_Map_Xtal->Checked)
	{
		memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x02; // System Efuse
                pPGRawData[1] = 0x16; // Logical Address LSB
                pPGRawData[2] = 0x00; // Logical Address MSB
                pPGRawData[3] = 0x02; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to Read Xtal Efuse");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x",pReport[5]);
			Edit_Efuse_Map_Xcal->Text=dstr;
			Memo_msg->Lines->Add(">>Read Xtal Efuse Success: " + dstr);
		}
	}

        if(CheckBox_Efuse_Map_40M->Checked)
        {
                memset(pPGRawData,0x00,MAX_USERAWDATA_SIZE);

		pPGRawData[0] = 0x01; // System Efuse
                pPGRawData[1] = 0xE4; // Logical Address LSB
                pPGRawData[2] = 0x01; // Logical Address MSB
                pPGRawData[3] = 0x04; // LSB Len
                pPGRawData[4] = 0x00; // MSB Len
		pBluetoothModule->UpDataParameter(pBluetoothModule,pParam);
		if (pBluetoothModule->ActionControlExcute(pBluetoothModule) !=0)
		{
			dstr.sprintf(">>Failed to Read 40M Bandedge Value ");
			Memo_msg->Lines->Add(dstr);

			dstr.sprintf("Error");
			Edit_Efuse_Map_BDAddr->Text=dstr;
		}
		else
		{
			memset(pReport,0x00, MAX_USERAWDATA_SIZE);
			pBluetoothModule->ActionReport(pBluetoothModule, REPORT_LOGICAL_EFUSE, &mBT_DEVICE_REPORT);
			dstr.sprintf("0x%02x%02x",pReport[6],pReport[5]);
			Edit_Efuse_Map_40M_F->Text=dstr;
			Memo_msg->Lines->Add(">>40M Bandedge Value Success: " + dstr);
                        dstr.sprintf("0x%02x",pReport[8]);
                        Edit_Efuse_Map_40M_I->Text=dstr;
                        Memo_msg->Lines->Add(">>40M Bandedge Value Success: " + dstr);
		}

        }
       return;
}
//---------------------------------------------------------------------------

void __fastcall TForm_Main::BitBtn_Write_EfuseClick(TObject *Sender)
{

	String dstr;
	unsigned long long  BDADDR= StrToInt64(Edit_Efuse_Map_BDAddr->Text) ;
	unsigned char Thermal=StrToInt(Edit_Efuse_Map_Thermal->Text)&0xFF;
        unsigned char TXPower=StrToInt(Edit_Efuse_Map_TXPower->Text)&0xFF;
        unsigned int Flatness=StrToInt(Edit_Efuse_Map_Flatness->Text)&0xFFFF;
	unsigned char Xtal=StrToInt(Edit_Efuse_Map_Xcal->Text)&0xFF;
        //unsigned int Bandedge_F=StrToInt(Edit_Efuse_Map_40M_F->Text)&0xFFFF;
        //unsigned int Bandedge_I=StrToInt(Edit_Efuse_Map_40M_I->Text)&0xFF;

        String str_F, str_I, str;
        str_F=Edit_Efuse_Map_40M_F->Text.SubString(3,4);
        str_I=Edit_Efuse_Map_40M_I->Text.SubString(3,2);
        str =  "0x" + str_F + str_I;
        unsigned int Bandedge=StrToInt(str)&0xFFFFFF;

        BitBtn_Write_Efuse->Enabled=false;
	//BitBtn_PGMPData->Enabled=false;

        dstr.sprintf("Are you sure to write?");
        if (Application->MessageBox(dstr.c_str(), "Bluetooth RF Test Tool", MB_YESNO) != IDYES)
	{
                BitBtn_Write_Efuse->Enabled = true;
		return;
	}


	WriteMpParamterToEfuseMap((unsigned char *)&BDADDR,Thermal,TXPower,(unsigned char *)&Flatness,Xtal,(unsigned char *)&Bandedge);

	//if (CheckBox_Efuse_PowerOn->Checked)
		//WriteMpPowerOnFunctionToEfuse(ComboBox_PowerOnEnable->ItemIndex,ComboBox_PowerOnActive->ItemIndex);

	dstr.sprintf(">>Write Efuse MP Data process end... \n");
	Memo_msg->Lines->Add(dstr);

	//BitBtn_PGMPData->Enabled=true;
        BitBtn_Write_Efuse->Enabled=true;

	return;
}
//---------------------------------------------------------------------------


