// BleSnifferDlg.cpp : implementation file
//

#include "stdafx.h"
#include "BleSniffer.h"
#include "BleSnifferDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CBleSnifferDlg dialog

CString IntToHex(const int i)
{
	CString s;
	s.Format(_T("%.8X"), i);
	return s;
}

CString IntToHex(const unsigned long i)
{
	CString s;
	s.Format(_T("%.8X"), i);
	return s;
}

CString IntToHex(const __int64 i)
{
	CString s;
	s.Format(_T("%.4X%.8X"), static_cast<INT32>((i >> 32) & 0x00000FFFF),
		static_cast<INT32>(i) & 0xFFFFFFFF);
	return s;
}

CString IntToHex(const unsigned char c)
{
	CString s;
	s.Format(_T("%.2X"), c);
	return s;
}

CString IntToStr(const unsigned long c)
{
	CString s;
	s.Format(_T("%d"), c);
	return s;
}

CString BoolToStr(const bool b)
{
	if (b)
		return _T("true");
	return _T("false");
}

CBleSnifferDlg::CBleSnifferDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CBleSnifferDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CBleSnifferDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_PACKETS, lbPackets);
	DDX_Control(pDX, IDC_COMBO_CHANNEL, cbChannel);
}

BEGIN_MESSAGE_MAP(CBleSnifferDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTON_START, &CBleSnifferDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR, &CBleSnifferDlg::OnBnClickedButtonClear)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CBleSnifferDlg::OnBnClickedButtonStop)
END_MESSAGE_MAP()


// CBleSnifferDlg message handlers

BOOL CBleSnifferDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application"s main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	cbChannel.AddString(_T("37"));
	cbChannel.AddString(_T("38"));
	cbChannel.AddString(_T("39"));
	cbChannel.SetCurSel(0);

	CFont* Font = new CFont();
	Font->CreateFont(16, 0, 0, 0, FW_NORMAL,
		FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
		CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
		DEFAULT_PITCH | FF_SWISS, _T("Courier New"));  
	lbPackets.SetFont(Font);

	__hook(&CwclBleSniffer::OnRawPacketReceived, &FSniffer, &CBleSnifferDlg::RawPacketReceived);
	__hook(&CwclBleSniffer::OnAdvIndReceived, &FSniffer, &CBleSnifferDlg::AdvIndReceived);
	__hook(&CwclBleSniffer::OnAdvDirectIndReceived, &FSniffer, &CBleSnifferDlg::AdvDirectIndReceived);
	__hook(&CwclBleSniffer::OnAdvNonConnIndReceived, &FSniffer, &CBleSnifferDlg::AdvNonConnIndReceived);
	__hook(&CwclBleSniffer::OnAdvScanIndReceived, &FSniffer, &CBleSnifferDlg::AdvScanIndReceived);
	__hook(&CwclBleSniffer::OnScanReqReceived, &FSniffer, &CBleSnifferDlg::ScanReqReceived);
	__hook(&CwclBleSniffer::OnScanRspReceived, &FSniffer, &CBleSnifferDlg::ScanRspReceived);
	__hook(&CwclBleSniffer::OnConnectIndReceived, &FSniffer, &CBleSnifferDlg::ConnectIndReceived);
	__hook(&CwclBleSniffer::OnStarted, &FSniffer, &CBleSnifferDlg::Started);
	__hook(&CwclBleSniffer::OnStopped, &FSniffer, &CBleSnifferDlg::Stopped);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CBleSnifferDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CBleSnifferDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CBleSnifferDlg::RawPacketReceived(void* Sender,
	const wclBluetoothLePacketHeader& Header, const unsigned char* const Payload,
	const unsigned short Size)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("RAW PACKET RECEIVED"));
	DumpHeader(Header);
	DumpPayload(Payload, Size);
}

void CBleSnifferDlg::AdvIndReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 AdvA, const unsigned char* const AdvData,
	const unsigned char AdvDataLen)
{
	UNREFERENCED_PARAMETER(Sender);
	
	lbPackets.AddString(_T("ADV_IND RECEIVED"));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	DumpPduHeader(PduHeader);
	DumpPayload(AdvData, AdvDataLen);
}

void CBleSnifferDlg::OnDestroy()
{
	CDialog::OnDestroy();

	__unhook(&FSniffer);
}

void CBleSnifferDlg::OnBnClickedButtonStart()
{
	int Res = FSniffer.Start((const unsigned char)(cbChannel.GetCurSel() + 37));
	if (Res != WCL_E_SUCCESS)
		AfxMessageBox(_T("Start failed: 0x") + IntToHex(Res));
}

void CBleSnifferDlg::OnBnClickedButtonClear()
{
	lbPackets.ResetContent();
}

void CBleSnifferDlg::OnBnClickedButtonStop()
{
	int Res = FSniffer.Stop();
	if (Res != WCL_E_SUCCESS)
		AfxMessageBox(_T("Stop failed: 0x") + IntToHex(Res));
}

void CBleSnifferDlg::Started(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("Started"));
}

void CBleSnifferDlg::Stopped(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("Stopped"));
}

void CBleSnifferDlg::DumpHeader(const wclBluetoothLePacketHeader& Header)
{
	lbPackets.AddString(_T("   HEADER"));
	lbPackets.AddString(_T("  ========"));
	lbPackets.AddString(_T("    Timestamp: ") + IntToHex(Header.Timestamp));
	lbPackets.AddString(_T("    Access Address: ") + IntToHex(Header.AccessAddress));
	lbPackets.AddString(_T("    Channel: ") + IntToHex(Header.Channel));
	lbPackets.AddString(_T("    Crc: ") + IntToHex(Header.Crc));
	lbPackets.AddString(_T("    Rssi: ") + IntToStr(Header.Rssi));
	if (Header.Valid)
		lbPackets.AddString(_T("    PACKET: OK"));
	else
		lbPackets.AddString(_T("    PACKET: ERROR"));
}

void CBleSnifferDlg::DumpPduHeader(
	const wclBluetoothLeAdvertisingPduHeader& PduHeader)
{
	DumpHeader(PduHeader.Header);

	lbPackets.AddString(_T("   PDU HEADER"));
	lbPackets.AddString(_T("  ============"));
	lbPackets.AddString(_T("    ChSel: ") + BoolToStr(PduHeader.ChSel));
	lbPackets.AddString(_T("    TxAdd: ") + BoolToStr(PduHeader.TxAdd));
	lbPackets.AddString(_T("    RxAdd: ") + BoolToStr(PduHeader.RxAdd));
}

void CBleSnifferDlg::DumpPayload(const unsigned char* const Payload,
	const unsigned short Size)
{
	if (Payload != NULL && Size > 0)
	{
		CString Str = _T("");
		unsigned char Ndx = 1;
		for (unsigned short i = 0; i < Size; i++)
		{
			Str = Str + IntToHex(Payload[i]) + _T(" ");
			Ndx++;
			if (Ndx == 16)
			{
				lbPackets.AddString(_T("    ") + Str);
				Str = _T("");
				Ndx = 1;
			}
		}
		if (Str != _T(""))
			lbPackets.AddString(_T("    ") + Str);
		lbPackets.AddString(_T(""));
	}
}

void CBleSnifferDlg::AdvDirectIndReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 AdvA, const __int64 TargetA)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("ADV_DIRECT_IND RECEIVED"));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	lbPackets.AddString(_T("  TargetA: ") + IntToHex(TargetA));
	DumpPduHeader(PduHeader);
}

void CBleSnifferDlg::AdvNonConnIndReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 AdvA, const unsigned char* const AdvData,
	const unsigned char AdvDataLen)
{
	UNREFERENCED_PARAMETER(Sender);
	
	lbPackets.AddString(_T("ADV_NONCONN_IND RECEIVED"));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	DumpPduHeader(PduHeader);
	DumpPayload(AdvData, AdvDataLen);
}

void CBleSnifferDlg::AdvScanIndReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 AdvA, const unsigned char* const AdvData,
	const unsigned char AdvDataLen)
{
	UNREFERENCED_PARAMETER(Sender);
	
	lbPackets.AddString(_T("ADV_SCAN_IND RECEIVED"));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	DumpPduHeader(PduHeader);
	DumpPayload(AdvData, AdvDataLen);
}

void CBleSnifferDlg::ScanReqReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 ScanA, const __int64 TargetA)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("SCAN_REQ RECEIVED"));
	lbPackets.AddString(_T("  ScanA: ") + IntToHex(ScanA));
	lbPackets.AddString(_T("  TargetA: ") + IntToHex(TargetA));
	DumpPduHeader(PduHeader);
}

void CBleSnifferDlg::ScanRspReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 AdvA, const unsigned char* const ScanRspData,
	const unsigned char ScanRspDataLen)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("SCAN_RSP RECEIVED"));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	DumpPduHeader(PduHeader);
	DumpPayload(ScanRspData, ScanRspDataLen);
}

void CBleSnifferDlg::ConnectIndReceived(void* Sender,
	const wclBluetoothLeAdvertisingPduHeader& PduHeader,
	const __int64 InitA, const __int64 AdvA,
	const wclBleSnifferLlData& LlData)
{
	UNREFERENCED_PARAMETER(Sender);

	lbPackets.AddString(_T("CONNECT_IND RECEIVED"));
	lbPackets.AddString(_T("  InitA: ") + IntToHex(InitA));
	lbPackets.AddString(_T("  AdvA: ") + IntToHex(AdvA));
	lbPackets.AddString(_T("  LLDATA"));
	lbPackets.AddString(_T("    Aa: ") + IntToHex(LlData.Aa));
	lbPackets.AddString(_T("    CrcInit: ") + IntToHex(LlData.CrcInit));
	lbPackets.AddString(_T("    WinSize: ") + IntToStr(LlData.WinSize));
	lbPackets.AddString(_T("    WinOffset: ") + IntToStr(LlData.WinOffset));
	lbPackets.AddString(_T("    Interval: ") + IntToStr(LlData.Interval));
	lbPackets.AddString(_T("    Latency: ") + IntToStr(LlData.Latency));
	lbPackets.AddString(_T("    Timeout: ") + IntToStr(LlData.Timeout));
	lbPackets.AddString(_T("    ChM: ") + IntToHex((unsigned long)(LlData.ChM >> 32)) +
		IntToHex((unsigned long)(LlData.ChM & 0xFFFFFFFF)));
	lbPackets.AddString(_T("    Hop: ") + IntToStr(LlData.Hop));
	lbPackets.AddString(_T("    Sca: ") + IntToStr(LlData.Sca));
	DumpPduHeader(PduHeader);
}