1. 최초 커밋

This commit is contained in:
이형구 2021-05-02 03:47:57 +09:00
commit 8061977c26
24 changed files with 2533 additions and 0 deletions

371
.gitignore vendored Normal file
View File

@ -0,0 +1,371 @@
# Created by https://www.toptal.com/developers/gitignore/api/visualstudio
# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
### VisualStudio Patch ###
# Additional files built by Visual Studio
*.tlog
# End of https://www.toptal.com/developers/gitignore/api/visualstudio

28
MFC_BLUETOOTH_TEST.sln Normal file
View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MFC_BLUETOOTH_TEST", "MFC_BLUETOOTH_TEST\MFC_BLUETOOTH_TEST.vcxproj", "{9679D95A-84E5-4056-AEAC-16F892928DCA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Debug|x64.ActiveCfg = Debug|x64
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Debug|x64.Build.0 = Debug|x64
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Debug|x86.ActiveCfg = Debug|Win32
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Debug|x86.Build.0 = Debug|Win32
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Release|x64.ActiveCfg = Release|x64
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Release|x64.Build.0 = Release|x64
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Release|x86.ActiveCfg = Release|Win32
{9679D95A-84E5-4056-AEAC-16F892928DCA}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,216 @@
// BluetoothDeviceManager.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "MFC_BLUETOOTH_TEST.h"
#include "BluetoothDeviceManager.h"
#include <dbt.h>
CEvent g_callbackevent;
BOOL WINAPI auth_callback_ex(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS authParams)
{
BLUETOOTH_AUTHENTICATE_RESPONSE response = { 0, };
response.bthAddressRemote = authParams->deviceInfo.Address;
response.authMethod = authParams->authenticationMethod;// authParams->authenticationMethod; // == BLUETOOTH_AUTHENTICATION_METHOD_LEGACY
UCHAR pin[] = "123456";
std::copy(pin, pin + sizeof(pin), response.pinInfo.pin);
response.pinInfo.pinLength = 6; //excluding '\0'
response.negativeResponse = false;
HRESULT err = BluetoothSendAuthenticationResponseEx(NULL, &response);
if (err == S_OK)
{
CBluetoothDeviceManager *pCBluetoothDeviceManager = reinterpret_cast<CBluetoothDeviceManager*>(pvParam);
if (pCBluetoothDeviceManager != NULL)
pCBluetoothDeviceManager->SendPairing();
}
if (err)
{
std::wcout << "BluetoothSendAuthenticationResponseEx error = " << err << std::endl;
}
g_callbackevent.PulseEvent();
return true;
}
// CBluetoothDeviceManager
CBluetoothDeviceManager::CBluetoothDeviceManager(const CBluetoothRadioManager &rCBluetoothRadioManager, BLUETOOTH_DEVICE_INFO_STRUCT &rBLUETOOTH_DEVICE_INFO_STRUCT) :
m_rCBluetoothRadioManager(rCBluetoothRadioManager),
m_BLUETOOTH_DEVICE_INFO_STRUCT(rBLUETOOTH_DEVICE_INFO_STRUCT),
m_hHBLUETOOTH_AUTHENTICATION_REGISTRATION(NULL)
{
std::wcout << _T("Device found - Name : ") << m_BLUETOOTH_DEVICE_INFO_STRUCT.szName << std::endl;
std::wcout << _T("Device found - Address : ") << m_BLUETOOTH_DEVICE_INFO_STRUCT.Address.rgBytes << std::endl;
std::wcout << _T("Device found - Device Class : ") << m_BLUETOOTH_DEVICE_INFO_STRUCT.ulClassofDevice << std::endl;
DWORD dwResult = BluetoothRegisterForAuthenticationEx(&m_BLUETOOTH_DEVICE_INFO_STRUCT, &m_hHBLUETOOTH_AUTHENTICATION_REGISTRATION, &auth_callback_ex, this);
if (dwResult == ERROR_OUTOFMEMORY)
{
std::wcerr << _T("BluetoothRegisterForAuthenticationEx ERROR_OUTOFMEMORY") << std::endl;
throw;
}
else if (dwResult != ERROR_SUCCESS)
{
std::wcerr << _T("BluetoothRegisterForAuthenticationEx failed : ") << WSAGetLastError() << std::endl;
throw;
}
}
CBluetoothDeviceManager::~CBluetoothDeviceManager()
{
BluetoothUnregisterAuthentication(m_hHBLUETOOTH_AUTHENTICATION_REGISTRATION);
}
BLUETOOTH_ADDRESS CBluetoothDeviceManager::GetAddress(void)
{
return m_BLUETOOTH_DEVICE_INFO_STRUCT.Address;
}
LPCTSTR CBluetoothDeviceManager::GetName(void)
{
return m_BLUETOOTH_DEVICE_INFO_STRUCT.szName;
}
ULONG CBluetoothDeviceManager::GetClassofDevice(void)
{
return m_BLUETOOTH_DEVICE_INFO_STRUCT.ulClassofDevice;
}
void CBluetoothDeviceManager::SendPairing(void)
{
m_BLUETOOTH_DEVICE_INFO_STRUCT.fAuthenticated = 8;
}
void CBluetoothDeviceManager::StartPairing(void)
{
if (m_BLUETOOTH_DEVICE_INFO_STRUCT.fAuthenticated)
return;
DWORD dwResult = BluetoothAuthenticateDeviceEx(m_rCBluetoothRadioManager.GetSafeHwnd(), m_rCBluetoothRadioManager.m_hRadio, &m_BLUETOOTH_DEVICE_INFO_STRUCT, NULL, MITMProtectionNotRequiredBonding);
if (dwResult == ERROR_SUCCESS)
{
std::wcout << _T("BluetoothAuthenticateDeviceEx : ERROR_SUCCESS") << m_BLUETOOTH_DEVICE_INFO_STRUCT.szName << std::endl;
if (WaitForSingleObject(g_callbackevent, INFINITE) == WAIT_FAILED)
{
std::wcerr << _T("WaitForSingleObject call failed with error : ") << GetLastError() << std::endl;
throw;
}
else
{
std::wcout << _T("WaitForSingleObject call was successful") << std::endl;
}
}
else if (dwResult == ERROR_CANCELLED)
{
std::wcout << _T("BluetoothAuthenticateDeviceEx : The user aborted the operation") << m_BLUETOOTH_DEVICE_INFO_STRUCT.szName << std::endl;
}
else if (dwResult == ERROR_INVALID_PARAMETER)
{
std::wcout << _T("BluetoothAuthenticateDeviceEx : The device structure specified in pbdti is invalid") << m_BLUETOOTH_DEVICE_INFO_STRUCT.szName << std::endl;
}
else if (dwResult == ERROR_NO_MORE_ITEMS)
{
std::wcout << _T("BluetoothAuthenticateDeviceEx : The device in pbtdi is already been marked as authenticated") << m_BLUETOOTH_DEVICE_INFO_STRUCT.szName << std::endl;
}
else
{
std::wcout << _T("BluetoothAuthenticateDeviceEx : ") << WSAGetLastError() << std::endl;
}
}
BOOL CBluetoothDeviceManager::SocketAttach(SOCKET s)
{
return m_Socket.Attach(s);
}
BOOL CBluetoothDeviceManager::Attach(const BTH_DEVICE_INFO &rDeviceInfo)
{
// TRUE == same device
// FALSE == unkonw or different device
// address empty
if ((rDeviceInfo.flags & BDIF_ADDRESS) == FALSE)
return FALSE;
// name empty
if ((rDeviceInfo.flags & BDIF_NAME) == FALSE)
return FALSE;
// different classOfDevice
if (rDeviceInfo.classOfDevice != m_BLUETOOTH_DEVICE_INFO_STRUCT.ulClassofDevice)
return FALSE;
// different mac address
if (rDeviceInfo.address != m_BLUETOOTH_DEVICE_INFO_STRUCT.Address.ullLong)
return FALSE;
// different name
CString strTemp(rDeviceInfo.name);
if (strTemp.Compare(m_BLUETOOTH_DEVICE_INFO_STRUCT.szName) != 0)
return FALSE;
std::wcout << _T("/// after flag start ///") << std::endl;
std::wcout << _T("BDIF_ADDRESS : ") << (rDeviceInfo.flags&BDIF_ADDRESS) << std::endl;
std::wcout << _T("BDIF_COD : ") << (rDeviceInfo.flags&BDIF_COD) << std::endl;
std::wcout << _T("BDIF_NAME : ") << (rDeviceInfo.flags&BDIF_NAME) << std::endl;
std::wcout << _T("BDIF_PAIRED : ") << (rDeviceInfo.flags&BDIF_PAIRED) << std::endl;
std::wcout << _T("BDIF_PERSONAL : ") << (rDeviceInfo.flags&BDIF_PERSONAL) << std::endl;
std::wcout << _T("BDIF_CONNECTED : ") << (rDeviceInfo.flags&BDIF_CONNECTED) << std::endl;
std::wcout << _T("BDIF_SSP_SUPPORTED : ") << (rDeviceInfo.flags&BDIF_SSP_SUPPORTED) << std::endl;
std::wcout << _T("BDIF_SSP_PAIRED : ") << (rDeviceInfo.flags&BDIF_SSP_PAIRED) << std::endl;
std::wcout << _T("BDIF_SSP_MITM_PROTECTED : ") << (rDeviceInfo.flags&BDIF_SSP_MITM_PROTECTED) << std::endl;
std::wcout << _T("/// after flag end ///") << std::endl;
std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << rDeviceInfo.address << std::endl;
std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << rDeviceInfo.classOfDevice << std::endl;
std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << rDeviceInfo.name << std::endl;
m_BLUETOOTH_DEVICE_INFO_STRUCT.fAuthenticated = rDeviceInfo.flags & BDIF_PAIRED;
m_BLUETOOTH_DEVICE_INFO_STRUCT.fConnected = rDeviceInfo.flags & BDIF_CONNECTED;
return TRUE;
}
BOOL CBluetoothDeviceManager::Connect(void)
{
StartPairing();
if (m_BLUETOOTH_DEVICE_INFO_STRUCT.fAuthenticated == FALSE)
return FALSE;
try
{
m_Socket.Connect(m_BLUETOOTH_DEVICE_INFO_STRUCT.Address.ullLong);
}
catch(...)
{
TRACE(_T("try-catch : m_Socket.Connect()"));
return FALSE;
}
return m_Socket.IsConnected();
}
void CBluetoothDeviceManager::Close(void)
{
m_Socket.Close();
}
int CBluetoothDeviceManager::Send(LPVOID pVoid, UINT dLength)
{
return m_Socket.Send(pVoid, dLength);
}

View File

@ -0,0 +1,56 @@
#pragma once
// Link to Bthprops.lib
#include <iostream>
#include <BluetoothAPIs.h>
#include <list>
#include <map>
#include <algorithm>
#pragma comment(lib, "Bthprops.lib")
#include "BluetoothSockets.h"
#include "BluetoothRadioManager.h"
// CBluetoothDeviceManager
class CBluetoothRadioManager;
class CBluetoothDeviceManager
{
public:
CBluetoothDeviceManager(const CBluetoothRadioManager &rCBluetoothRadioManager, BLUETOOTH_DEVICE_INFO_STRUCT &rBLUETOOTH_DEVICE_INFO_STRUCT);
virtual ~CBluetoothDeviceManager();
private:
friend class CBluetoothRadioManager;
CBluetoothSocket m_Socket;
BLUETOOTH_DEVICE_INFO_STRUCT m_BLUETOOTH_DEVICE_INFO_STRUCT;
const CBluetoothRadioManager &m_rCBluetoothRadioManager;
HBLUETOOTH_AUTHENTICATION_REGISTRATION m_hHBLUETOOTH_AUTHENTICATION_REGISTRATION;
protected:
public:
BLUETOOTH_ADDRESS GetAddress(void);
LPCTSTR GetName(void);
ULONG GetClassofDevice(void);
void SendPairing(void);
void StartPairing(void);
BOOL SocketAttach(SOCKET s);
BOOL Attach(const BTH_DEVICE_INFO &pDeviceInfo);
BOOL Connect(void);
void Close(void);
int Send(LPVOID pVoid, UINT dLength);
};
BOOL WINAPI auth_callback_ex(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS authParams);

View File

@ -0,0 +1,62 @@
#include "stdafx.h"
#include "BluetoothManger.h"
CBluetoothManger::CBluetoothManger()
{
FindRadios();
}
CBluetoothManger::~CBluetoothManger()
{
for_each(m_vecRadios.begin(), m_vecRadios.end(), [](CBluetoothRadioManager *pCBluetoothRadioManager) { delete pCBluetoothRadioManager; });
m_vecRadios.clear();
}
void CBluetoothManger::FindRadios(void)
{
BLUETOOTH_FIND_RADIO_PARAMS btfrp = { sizeof(btfrp), };
HANDLE hRadio = NULL;
HBLUETOOTH_RADIO_FIND hFind = BluetoothFindFirstRadio(&btfrp, &hRadio);
if (hFind == NULL)
return;
do
{
try
{
m_vecRadios.push_back(new CBluetoothRadioManager(hRadio));
}
catch (...)
{
TRACE(_T("try-catch : new CBluetoothRadioManager"));
}
} while (BluetoothFindNextRadio(hFind, &hRadio));
BluetoothFindRadioClose(hFind);
}
size_t CBluetoothManger::GetRadioSize(void)
{
return m_vecRadios.size();
}
CBluetoothRadioManager *CBluetoothManger::GetRadio(size_t pos)
{
return m_vecRadios[pos];
}
CBluetoothRadioManager *CBluetoothManger::GetRadio(LPCTSTR pszName)
{
for (auto itor = m_vecRadios.begin(); itor != m_vecRadios.end(); ++itor)
{
if (_tcscmp((*itor)->GetName(), pszName) == 0)
return *itor;
}
return NULL;
}

View File

@ -0,0 +1,27 @@
#pragma once
#include <vector>
#include <algorithm>
#include "BluetoothRadioManager.h"
#include "BluetoothDeviceManager.h"
class CBluetoothManger
{
public:
CBluetoothManger();
~CBluetoothManger();
private:
std::vector<CBluetoothRadioManager*> m_vecRadios;
void FindRadios(void);
protected:
public:
size_t GetRadioSize(void);
CBluetoothRadioManager *GetRadio(size_t pos);
CBluetoothRadioManager *GetRadio(LPCTSTR pszName);
};

View File

@ -0,0 +1,411 @@
// BluetoothRadioManager.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "BluetoothRadioManager.h"
// CBluetoothRadioManager
IMPLEMENT_DYNAMIC(CBluetoothRadioManager, CWnd)
CBluetoothRadioManager::CBluetoothRadioManager(HANDLE hRadioHandle) :
m_hRadio(hRadioHandle),
m_hNotification(NULL),
m_BLUETOOTH_RADIO_INFO({ sizeof(m_BLUETOOTH_RADIO_INFO), }),
m_Socket(std::bind(&CBluetoothRadioManager::OnAccept, this, std::placeholders::_1))
{
if (hRadioHandle == NULL)
throw;
CString strMyClass = AfxRegisterWndClass(CS_VREDRAW | CS_HREDRAW,
::LoadCursor(NULL, IDC_ARROW), (HBRUSH) ::GetStockObject(WHITE_BRUSH),
::LoadIcon(NULL, IDI_APPLICATION));
this->CreateEx(NULL, strMyClass, _T("CBluetoothRadioManager"), NULL, CRect(0, 0, 0, 0), NULL, NULL);
RefreshInfo();
StartNotification();
FindDevice();
}
CBluetoothRadioManager::~CBluetoothRadioManager()
{
ReleaseDevice();
::CloseHandle(m_hRadio);
this->DestroyWindow();
}
BEGIN_MESSAGE_MAP(CBluetoothRadioManager, CWnd)
ON_WM_DEVICECHANGE()
END_MESSAGE_MAP()
// CBluetoothRadioManager 메시지 처리기입니다.
BOOL CBluetoothRadioManager::StartNotification(void)
{
DEV_BROADCAST_HANDLE NotificationFilter = { sizeof(NotificationFilter), };
NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE;
NotificationFilter.dbch_handle = m_hRadio;
//NotificationFilter.dbch_eventguid = GUID_BLUETOOTH_RADIO_IN_RANGE;
NotificationFilter.dbch_eventguid = GUID_BTHPORT_DEVICE_INTERFACE;
m_hNotification = RegisterDeviceNotification(GetSafeHwnd(), &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if (m_hNotification == NULL)
{
std::wcout << _T("failed RegisterDeviceNotification! : ") << WSAGetLastError() << std::endl;
return FALSE;
}
std::wcout << _T("Register Device Notification! : ") << m_hNotification << std::endl;
return TRUE;
}
BOOL CBluetoothRadioManager::OnDeviceChange(UINT nEventType, DWORD_PTR dwData)
{
switch (nEventType)
{
case DBT_CONFIGCHANGECANCELED:
std::wcout << _T("A request to change the current configuration(dock or undock) has been canceled.") << std::endl;
break;
case DBT_CONFIGCHANGED:
std::wcout << _T("The current configuration has changed, due to a dock or undock.") << std::endl;
break;
case DBT_DEVICEARRIVAL:
std::wcout << _T("A device or piece of media has been inserted and is now available.") << std::endl;
break;
case DBT_DEVICEQUERYREMOVE:
std::wcout << _T("Permission is requested to remove a device or piece of media.Any application can deny this request and cancel the removal.") << std::endl;
break;
case DBT_DEVICEQUERYREMOVEFAILED:
std::wcout << _T("A request to remove a device or piece of media has been canceled.") << std::endl;
break;
case DBT_DEVICEREMOVECOMPLETE:
std::wcout << _T("A device or piece of media has been removed.") << std::endl;
break;
case DBT_DEVICEREMOVEPENDING:
std::wcout << _T("A device or piece of media is about to be removed.Cannot be denied.") << std::endl;
break;
case DBT_DEVICETYPESPECIFIC:
std::wcout << _T("A device - specific event has occurred.") << std::endl;
break;
case DBT_DEVNODES_CHANGED:
std::wcout << _T("A device has been added to or removed from the system.") << std::endl;
break;
case DBT_QUERYCHANGECONFIG:
std::wcout << _T("Permission is requested to change the current configuration(dock or undock).") << std::endl;
break;
case DBT_USERDEFINED:
std::wcout << _T("The meaning of this message is user - defined.") << std::endl;
break;
case DBT_CUSTOMEVENT:
{
_DEV_BROADCAST_USERDEFINED *pData = reinterpret_cast<_DEV_BROADCAST_USERDEFINED*>(dwData);
PDEV_BROADCAST_HDR pHeader = reinterpret_cast<PDEV_BROADCAST_HDR>(&pData->dbud_dbh);
if (pHeader->dbch_devicetype != DBT_DEVTYP_HANDLE)
throw;
PDEV_BROADCAST_HANDLE pHandle = reinterpret_cast<PDEV_BROADCAST_HANDLE>(pHeader);
if (pHandle->dbch_eventguid == GUID_BLUETOOTH_RADIO_IN_RANGE)
{
PBTH_RADIO_IN_RANGE pRadioInfo = reinterpret_cast<PBTH_RADIO_IN_RANGE>(pHandle->dbch_data);
BTH_DEVICE_INFO *pDeviceInfo = &pRadioInfo->deviceInfo;
//std::wcout << _T("/// before flag start ///") << std::endl;
//std::wcout << _T("BDIF_ADDRESS : ") << (pRadioInfo->previousDeviceFlags&BDIF_ADDRESS) << std::endl;
//std::wcout << _T("BDIF_COD : ") << (pRadioInfo->previousDeviceFlags&BDIF_COD) << std::endl;
//std::wcout << _T("BDIF_NAME : ") << (pRadioInfo->previousDeviceFlags&BDIF_NAME) << std::endl;
//std::wcout << _T("BDIF_PAIRED : ") << (pRadioInfo->previousDeviceFlags&BDIF_PAIRED) << std::endl;
//std::wcout << _T("BDIF_PERSONAL : ") << (pRadioInfo->previousDeviceFlags&BDIF_PERSONAL) << std::endl;
//std::wcout << _T("BDIF_CONNECTED : ") << (pRadioInfo->previousDeviceFlags&BDIF_CONNECTED) << std::endl;
//std::wcout << _T("BDIF_SSP_SUPPORTED : ") << (pRadioInfo->previousDeviceFlags&BDIF_SSP_SUPPORTED) << std::endl;
//std::wcout << _T("BDIF_SSP_PAIRED : ") << (pRadioInfo->previousDeviceFlags&BDIF_SSP_PAIRED) << std::endl;
//std::wcout << _T("BDIF_SSP_MITM_PROTECTED : ") << (pRadioInfo->previousDeviceFlags&BDIF_SSP_MITM_PROTECTED) << std::endl;
//std::wcout << _T("/// before flag end ///") << std::endl;
//std::wcout << _T("/// after flag start ///") << std::endl;
//std::wcout << _T("BDIF_ADDRESS : ") << (pDeviceInfo->flags&BDIF_ADDRESS) << std::endl;
//std::wcout << _T("BDIF_COD : ") << (pDeviceInfo->flags&BDIF_COD) << std::endl;
//std::wcout << _T("BDIF_NAME : ") << (pDeviceInfo->flags&BDIF_NAME) << std::endl;
//std::wcout << _T("BDIF_PAIRED : ") << (pDeviceInfo->flags&BDIF_PAIRED) << std::endl;
//std::wcout << _T("BDIF_PERSONAL : ") << (pDeviceInfo->flags&BDIF_PERSONAL) << std::endl;
//std::wcout << _T("BDIF_CONNECTED : ") << (pDeviceInfo->flags&BDIF_CONNECTED) << std::endl;
//std::wcout << _T("BDIF_SSP_SUPPORTED : ") << (pDeviceInfo->flags&BDIF_SSP_SUPPORTED) << std::endl;
//std::wcout << _T("BDIF_SSP_PAIRED : ") << (pDeviceInfo->flags&BDIF_SSP_PAIRED) << std::endl;
//std::wcout << _T("BDIF_SSP_MITM_PROTECTED : ") << (pDeviceInfo->flags&BDIF_SSP_MITM_PROTECTED) << std::endl;
//std::wcout << _T("/// after flag end ///") << std::endl;
//std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << pRadioInfo->deviceInfo.address << std::endl;
//std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << pRadioInfo->deviceInfo.classOfDevice << std::endl;
//std::wcout << _T("GUID_BLUETOOTH_RADIO_IN_RANGE : ") << pRadioInfo->deviceInfo.name << std::endl;
BOOL bOldDevice = FALSE;
auto ramda_Attach = [&bOldDevice, &pDeviceInfo](CBluetoothDeviceManager *pCBluetoothDeviceManager)->void
{
bOldDevice |= pCBluetoothDeviceManager->Attach(*pDeviceInfo);
};
for_each(m_vecDevices.begin(), m_vecDevices.end(), ramda_Attach);
if (!bOldDevice && (pDeviceInfo->flags&BDIF_NAME))
{
try
{
BLUETOOTH_DEVICE_INFO_STRUCT DeviceInfo = { sizeof(DeviceInfo), };
_tcscpy_s(DeviceInfo.szName, CA2T(pDeviceInfo->name));
DeviceInfo.Address.ullLong = pDeviceInfo->address;
DeviceInfo.ulClassofDevice = pDeviceInfo->classOfDevice;
CBluetoothDeviceManager *pCBluetoothDeviceManager = new CBluetoothDeviceManager(*this, DeviceInfo);
if (pCBluetoothDeviceManager->Attach(*pDeviceInfo))
m_vecDevices.push_back(pCBluetoothDeviceManager);
}
catch (...)
{
TRACE(_T("try-catch : new CBluetoothDeviceManager"));
}
}
}
else if (pHandle->dbch_eventguid == GUID_BLUETOOTH_L2CAP_EVENT)
{
PBTH_L2CAP_EVENT_INFO pL2CAPEvent = reinterpret_cast<PBTH_L2CAP_EVENT_INFO>(pHandle->dbch_data);
std::wcout << _T("GUID_BLUETOOTH_L2CAP_EVENT bthAddress : ") << pL2CAPEvent->bthAddress << std::endl;
std::wcout << _T("GUID_BLUETOOTH_L2CAP_EVENT psm : ") << pL2CAPEvent->psm << std::endl;
std::wcout << _T("GUID_BLUETOOTH_L2CAP_EVENT connected : ") << pL2CAPEvent->connected << std::endl;
std::wcout << _T("GUID_BLUETOOTH_L2CAP_EVENT initiated : ") << pL2CAPEvent->initiated << std::endl;
// Connect Try
if (pL2CAPEvent->connected)
{
CBluetoothDeviceManager *pCBluetoothDeviceManager = GetDevice(pL2CAPEvent->bthAddress);
// Device -> PC Connect Try
if (pL2CAPEvent->initiated == 0 && pCBluetoothDeviceManager != NULL)
{
}
// PC -> Device Connect Try
else if (pL2CAPEvent->initiated != 0 && pCBluetoothDeviceManager != NULL)
{
}
}
}
else if (pHandle->dbch_eventguid == GUID_BLUETOOTH_RADIO_OUT_OF_RANGE)
{
BLUETOOTH_ADDRESS *pBAdd = reinterpret_cast<BLUETOOTH_ADDRESS*>(pHandle->dbch_data);
std::wcout << _T("GUID_BLUETOOTH_RADIO_OUT_OF_RANGE BLUETOOTH_ADDRESS : ") << pBAdd->ullLong << std::endl;
CBluetoothDeviceManager *pCBluetoothDeviceManager = GetDevice(pBAdd->ullLong);
if (pCBluetoothDeviceManager != NULL)
{
}
}
else if (pHandle->dbch_eventguid == GUID_BLUETOOTH_AUTHENTICATION_REQUEST)
{
std::wcout << _T("GUID_BLUETOOTH_AUTHENTICATION_REQUEST") << std::endl;
}
else if (pHandle->dbch_eventguid == GUID_BLUETOOTH_HCI_EVENT)
{
BTH_HCI_EVENT_INFO *pHCIEvent;
pHCIEvent = (BTH_HCI_EVENT_INFO *)pHandle->dbch_data;
switch (pHCIEvent->connectionType)
{
case HCI_CONNECTION_TYPE_ACL:
break;
case HCI_CONNECTION_TYPE_SCO:
break;
default:
throw;
}
if (pHCIEvent->connected)
std::wcout << _T("GUID_BLUETOOTH_HCI_EVENT : Connected") << std::endl;
else
std::wcout << _T("GUID_BLUETOOTH_HCI_EVENT : Disconnected") << std::endl;
CBluetoothDeviceManager *pCBluetoothDeviceManager = GetDevice(pHCIEvent->bthAddress);
if (pCBluetoothDeviceManager != NULL)
{
if (pHCIEvent->connected == FALSE)
{
}
else if (pHCIEvent->connected)
{
}
}
std::wcout << _T("GUID_BLUETOOTH_HCI_EVENT : ") << pHCIEvent->bthAddress << std::endl;
}
else
{
TCHAR buf[128] = { NULL, };
StringFromGUID2(pHandle->dbch_eventguid, buf, 128);
std::wcout << _T("NOT DEFINED EVENTGUID : ") << buf << std::endl;
}
break;
}
default:
{
std::wcout << _T("NOT DEFINED EVENTTYPE : ") << nEventType << std::endl;
break;
}
}
return FALSE;
}
BOOL CBluetoothRadioManager::OnAccept(SOCKET s)
{
SOCKADDR_BTH SockAddrBthLocal = { 0 };
SockAddrBthLocal.addressFamily = AF_BTH;
SockAddrBthLocal.serviceClassId = SerialPortServiceClass_UUID;
SockAddrBthLocal.port = BT_PORT_ANY;
int len = sizeof(SockAddrBthLocal);
if (getpeername(s, (struct sockaddr *)&SockAddrBthLocal, &len) == SOCKET_ERROR)
{
std::wcout << _T("getpeername is Faile : ") << WSAGetLastError() << std::endl;
return FALSE;
}
CBluetoothDeviceManager *pCBluetoothDeviceManager = GetDevice(SockAddrBthLocal.btAddr);
if (pCBluetoothDeviceManager == NULL)
return FALSE;
return pCBluetoothDeviceManager->SocketAttach(s);
}
BOOL CBluetoothRadioManager::RefreshInfo(void)
{
ZeroMemory(&m_BLUETOOTH_RADIO_INFO, sizeof(m_BLUETOOTH_RADIO_INFO));
m_BLUETOOTH_RADIO_INFO.dwSize = sizeof(m_BLUETOOTH_RADIO_INFO);
DWORD dwResult = BluetoothGetRadioInfo(m_hRadio, &m_BLUETOOTH_RADIO_INFO);
if (dwResult != ERROR_SUCCESS)
{
std::wcerr << _T("BluetoothGetRadioInfo failed with error code : ") << WSAGetLastError() << std::endl;
return FALSE;
}
std::wcout << _T("BluetoothGetRadioInfo is OK!") << std::endl;
return TRUE;
}
void CBluetoothRadioManager::ReleaseDevice(void)
{
for_each(m_vecDevices.begin(), m_vecDevices.end(), [](CBluetoothDeviceManager *pCBluetoothDeviceManager) { delete pCBluetoothDeviceManager; });
m_vecDevices.clear();
}
void CBluetoothRadioManager::FindDevice(void)
{
ReleaseDevice();
BLUETOOTH_DEVICE_INFO_STRUCT deviceInfo = { sizeof(deviceInfo), };
BLUETOOTH_DEVICE_SEARCH_PARAMS deviceSearchParams = { sizeof(deviceSearchParams), };
deviceSearchParams.cTimeoutMultiplier = 5; //5*1.28s search timeout
deviceSearchParams.fIssueInquiry = true; //new inquiry
deviceSearchParams.fReturnAuthenticated = TRUE;
deviceSearchParams.fReturnRemembered = TRUE;
deviceSearchParams.fReturnUnknown = TRUE;
deviceSearchParams.fReturnConnected = TRUE;
deviceSearchParams.hRadio = m_hRadio;
HBLUETOOTH_DEVICE_FIND hDeviceFind = BluetoothFindFirstDevice(&deviceSearchParams, &deviceInfo);
if (hDeviceFind == NULL)
return;
do
{
try
{
m_vecDevices.push_back(new CBluetoothDeviceManager(*this, deviceInfo));
}
catch (...)
{
TRACE(_T("try-catch : new CBluetoothDeviceManager"));
}
} while (BluetoothFindNextDevice(hDeviceFind, &deviceInfo));
BluetoothFindDeviceClose(hDeviceFind);
}
BLUETOOTH_ADDRESS CBluetoothRadioManager::GetAddress(void)
{
RefreshInfo();
return m_BLUETOOTH_RADIO_INFO.address;
}
LPCTSTR CBluetoothRadioManager::GetName(void)
{
RefreshInfo();
return m_BLUETOOTH_RADIO_INFO.szName;
}
ULONG CBluetoothRadioManager::GetClassofDevice(void)
{
RefreshInfo();
return m_BLUETOOTH_RADIO_INFO.ulClassofDevice;
}
size_t CBluetoothRadioManager::GetDeviceSize(void)
{
return m_vecDevices.size();
}
CBluetoothDeviceManager *CBluetoothRadioManager::GetDevice(size_t pos)
{
return m_vecDevices[pos];
}
CBluetoothDeviceManager *CBluetoothRadioManager::GetDevice(LPCTSTR pszName)
{
for (auto itor = m_vecDevices.begin(); itor != m_vecDevices.end(); ++itor)
{
if (_tcscmp((*itor)->GetName(), pszName) == 0)
return *itor;
}
return NULL;
}
CBluetoothDeviceManager *CBluetoothRadioManager::GetDevice(BTH_ADDR &rBTH_ADDR)
{
for (auto itor = m_vecDevices.begin(); itor != m_vecDevices.end(); ++itor)
{
if ((*itor)->GetAddress().ullLong == rBTH_ADDR)
return *itor;
}
return NULL;
}

View File

@ -0,0 +1,60 @@
#pragma once
#include <BluetoothAPIs.h>
#include <dbt.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include "BluetoothDeviceManager.h"
// CBluetoothRadioManager
class CBluetoothDeviceManager;
class CBluetoothRadioManager : public CWnd
{
DECLARE_DYNAMIC(CBluetoothRadioManager)
public:
CBluetoothRadioManager(HANDLE hRadioHandle);
virtual ~CBluetoothRadioManager();
protected:
DECLARE_MESSAGE_MAP()
private:
friend class CBluetoothDeviceManager;
HANDLE m_hRadio;
HDEVNOTIFY m_hNotification;
BLUETOOTH_RADIO_INFO m_BLUETOOTH_RADIO_INFO;
CBluetoothSocketListener m_Socket;
std::vector<CBluetoothDeviceManager*> m_vecDevices;
BOOL StartNotification(void);
BOOL RefreshInfo(void);
void ReleaseDevice(void);
void FindDevice(void);
protected:
afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD_PTR dwData);
virtual BOOL OnAccept(SOCKET s);
public:
BLUETOOTH_ADDRESS GetAddress(void);
LPCTSTR GetName(void);
ULONG GetClassofDevice(void);
size_t GetDeviceSize(void);
CBluetoothDeviceManager *GetDevice(size_t pos);
CBluetoothDeviceManager *GetDevice(LPCTSTR pszName);
CBluetoothDeviceManager *GetDevice(BTH_ADDR &rBTH_ADDR);
};

View File

@ -0,0 +1,323 @@
#include "stdafx.h"
#include "BluetoothSockets.h"
std::shared_ptr<CSocketInitialize> CSocketInitialize::m_pInstance = NULL;
CBluetoothSocketListener::CBluetoothSocketListener(fnc_OnAccept pfnc_OnAccept) :
m_pfnc_OnAccept(std::move(pfnc_OnAccept))
{
Listen();
}
CBluetoothSocketListener::~CBluetoothSocketListener(void)
{
Close();
}
void CBluetoothSocketListener::Init(void)
{
wchar_t szThisComputerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD dwLenComputerName = MAX_COMPUTERNAME_LENGTH + 1;
if (!GetComputerName(szThisComputerName, &dwLenComputerName))
{
std::wcout << _T("GetComputerName is Failed") << std::endl;
throw;
}
m_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (INVALID_SOCKET == m_socket)
{
std::wcout << _T("socket is Failed") << std::endl;
throw;
}
SOCKADDR_BTH SockAddrBthLocal = { 0 };
SockAddrBthLocal.addressFamily = AF_BTH;
SockAddrBthLocal.serviceClassId = SerialPortServiceClass_UUID;
SockAddrBthLocal.port = BT_PORT_ANY;
if (SOCKET_ERROR == bind(m_socket, (struct sockaddr *) &SockAddrBthLocal, sizeof(SOCKADDR_BTH)))
{
std::wcout << _T("bind is Failed") << std::endl;
throw;
}
int iAddrLen = sizeof(SOCKADDR_BTH);
int ulRetCode = getsockname(m_socket, (struct sockaddr *)&SockAddrBthLocal, &iAddrLen);
switch (ulRetCode)
{
case ERROR_SUCCESS:
break;
case WSANOTINITIALISED:
std::wcout << _T("A successful WSAStartup call must occur before using this API.") << std::endl;
break;
case WSAENETDOWN:
std::wcout << _T("The network subsystem has failed.") << std::endl;
break;
case WSAEFAULT:
std::wcout << _T("The name or the namelen parameter is not a valid part of the user address space, or the namelen parameter is too small.") << std::endl;
break;
case WSAEINPROGRESS:
std::wcout << _T("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.") << std::endl;
break;
case WSAENOTSOCK:
std::wcout << _T("The descriptor is not a socket.") << std::endl;
break;
case WSAEINVAL:
std::wcout << _T("The socket has not been bound to an address with bind, or ADDR_ANY is specified in bind but connection has not yet occurred.") << std::endl;
break;
default:
std::wcout << _T("GetSockName is Failed") << std::endl;
break;
}
if (ulRetCode != ERROR_SUCCESS)
throw;
CSADDR_INFO csAddrInfo = { NULL, };
csAddrInfo.LocalAddr.iSockaddrLength = sizeof(SOCKADDR_BTH);
csAddrInfo.LocalAddr.lpSockaddr = (LPSOCKADDR)&SockAddrBthLocal;
csAddrInfo.RemoteAddr.iSockaddrLength = sizeof(SOCKADDR_BTH);
csAddrInfo.RemoteAddr.lpSockaddr = (LPSOCKADDR)&SockAddrBthLocal;
csAddrInfo.iSocketType = SOCK_STREAM;
csAddrInfo.iProtocol = BTHPROTO_RFCOMM;
WSAQUERYSET wsaQuerySet;
ZeroMemory(&wsaQuerySet, sizeof(WSAQUERYSET));
wsaQuerySet.dwSize = sizeof(WSAQUERYSET);
wsaQuerySet.lpServiceClassId = (LPGUID)&SerialPortServiceClass_UUID;
size_t cbInstanceNameSize = 0;
HRESULT res = StringCchLength(szThisComputerName, sizeof(szThisComputerName), &cbInstanceNameSize);
if (FAILED(res))
{
std::wcout << _T("StringCchLength is Failed") << std::endl;
throw;
}
cbInstanceNameSize += sizeof(L"Bluetooth Server") + 1;
wchar_t *pszInstanceName = (LPWSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbInstanceNameSize);
if (NULL == pszInstanceName)
{
std::wcout << _T("HeapAlloc is Failed") << std::endl;
throw;
}
StringCbPrintf(pszInstanceName, cbInstanceNameSize, L"%s %s", szThisComputerName, L"Bluetooth Server");
wsaQuerySet.lpszServiceInstanceName = pszInstanceName;
wsaQuerySet.lpszComment = L"Example Service instance registered in the directory service through RnR";
wsaQuerySet.dwNameSpace = NS_BTH;
wsaQuerySet.dwNumberOfCsAddrs = 1;
wsaQuerySet.lpcsaBuffer = &csAddrInfo;
if (SOCKET_ERROR == WSASetService(&wsaQuerySet, RNRSERVICE_REGISTER, 0))
{
std::wcout << _T("WSASetService is Failed") << std::endl;
HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, pszInstanceName);
throw;
}
else
{
HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, pszInstanceName);
}
Attach(m_socket);
if (SOCKET_ERROR == __super::Listen())
{
std::wcout << _T("Listen is Failed") << std::endl;
throw;
}
}
void CBluetoothSocketListener::OnAccept(int nErrorCode)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Error Report
if (nErrorCode != ERROR_SUCCESS)
{
std::wcout << _T("OnAccept is Failed : ") << WSAGetLastError() << std::endl;
return __super::OnAccept(nErrorCode);
}
SOCKET socket = accept(m_socket, NULL, NULL);
if (socket != INVALID_SOCKET)
{
if (m_pfnc_OnAccept(socket) == FALSE)
{
closesocket(socket);
}
}
__super::OnAccept(nErrorCode);
}
void CBluetoothSocketListener::Listen(void)
{
try
{
Init();
}
catch (...)
{
}
}
void CBluetoothSocketListener::Close(void)
{
if (m_hSocket != INVALID_SOCKET)
m_socket = Detach();
closesocket(m_socket);
}
CBluetoothSocket::CBluetoothSocket(void)
{
}
CBluetoothSocket::~CBluetoothSocket(void)
{
Close();
}
void CBluetoothSocket::OnClose(int nErrorCode)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Error Report
if (nErrorCode != ERROR_SUCCESS)
{
m_bIsConnected = FALSE;
std::wcout << _T("OnClose is Failed : ") << WSAGetLastError() << std::endl;
return __super::OnClose(nErrorCode);
}
m_bIsConnected = FALSE;
__super::OnClose(nErrorCode);
}
void CBluetoothSocket::OnOutOfBandData(int nErrorCode)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Error Report
if (nErrorCode != ERROR_SUCCESS)
{
std::wcout << _T("OnOutOfBandData is Failed : ") << WSAGetLastError() << std::endl;
return __super::OnOutOfBandData(nErrorCode);
}
__super::OnOutOfBandData(nErrorCode);
}
void CBluetoothSocket::OnReceive(int nErrorCode)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Error Report
if (nErrorCode != ERROR_SUCCESS)
{
std::wcout << _T("OnReceive is Failed : ") << WSAGetLastError() << std::endl;
return __super::OnReceive(nErrorCode);
}
BYTE buf[4096] = { 0, };
int cnt = CAsyncSocket::Receive(buf, 4096);
CString str;
str.Format(_T("%s"), CA2W((char*)buf, CP_UTF8));
OutputDebugString(str);
__super::OnReceive(nErrorCode);
}
void CBluetoothSocket::OnSend(int nErrorCode)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Error Report
if (nErrorCode != ERROR_SUCCESS)
{
std::wcout << _T("OnSend is Failed : ") << WSAGetLastError() << std::endl;
return __super::OnSend(nErrorCode);
}
__super::OnSend(nErrorCode);
}
int CBluetoothSocket::Send(LPVOID pVoid, UINT dLength)
{
return __super::Send(pVoid, dLength);
}
void CBluetoothSocket::Connect(BTH_ADDR RemoteAddr)
{
if (m_bIsConnected)
return;
m_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (INVALID_SOCKET == m_socket)
{
std::wcout << _T("socket is Failed") << std::endl;
throw;
}
SOCKADDR_BTH SockAddrBthServer;
SockAddrBthServer.addressFamily = AF_BTH;
SockAddrBthServer.serviceClassId = SerialPortServiceClass_UUID;
SockAddrBthServer.btAddr = RemoteAddr;
SockAddrBthServer.port = BT_PORT_ANY;
int len = sizeof(SockAddrBthServer);
int nResult = connect(m_socket, (struct sockaddr *)&SockAddrBthServer, sizeof(SockAddrBthServer));
if (nResult == 0)
{
// This Line Before Non Async Socket
// This Line After Async Socket
if (Attach(m_socket))
{
return;
}
}
throw;
}
void CBluetoothSocket::Close(void)
{
m_bIsConnected = FALSE;
if (m_hSocket != INVALID_SOCKET)
m_socket = Detach();
closesocket(m_socket);
}
BOOL CBluetoothSocket::IsConnected(void)
{
return m_bIsConnected;
}
BOOL CBluetoothSocket::Attach(SOCKET hSocket)
{
return m_bIsConnected = __super::Attach(hSocket);
}

View File

@ -0,0 +1,110 @@
#pragma once
#include <winsock2.h>
#include <ws2bth.h>
#include <iostream>
#include <strsafe.h>
#include <functional>
#include <memory>
// Server socket
class CSocketInitialize
{
private:
CSocketInitialize(void)
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2, 2), &WSAData);
}
CSocketInitialize(const CSocketInitialize &rCSocketInitialize) {};
public:
virtual ~CSocketInitialize(void)
{
WSACleanup();
}
private:
static std::shared_ptr<CSocketInitialize> m_pInstance;
public:
static const std::shared_ptr<CSocketInitialize> Get(void)
{
if (m_pInstance)
return m_pInstance;
else
return m_pInstance = std::shared_ptr<CSocketInitialize>(new CSocketInitialize());
}
};
template <class _Ty>
class CSocketInitialized : public _Ty
{
public:
CSocketInitialized(void)
{
CSocketInitialize::Get();
}
virtual ~CSocketInitialized(void)
{
}
private:
protected:
public:
};
class CBluetoothSocket;
typedef std::function<BOOL(SOCKET)> fnc_OnAccept;
class CBluetoothSocketListener : private CSocketInitialized<CAsyncSocket>
{
public:
CBluetoothSocketListener(fnc_OnAccept pfnc_OnAccept);
virtual ~CBluetoothSocketListener(void);
private:
SOCKET m_socket;
fnc_OnAccept m_pfnc_OnAccept;
void Init(void);
protected:
virtual void OnAccept(int nErrorCode);
public:
void Listen(void);
void Close(void);
};
class CBluetoothSocket : private CSocketInitialized<CAsyncSocket>
{
public:
CBluetoothSocket(void);
virtual ~CBluetoothSocket(void);
private:
SOCKET m_socket;
BOOL m_bIsConnected;
virtual void OnClose(int nErrorCode);
virtual void OnOutOfBandData(int nErrorCode);
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
protected:
public:
int Send(LPVOID pVoid, UINT dLength);
void Connect(BTH_ADDR RemoteAddr);
void Close(void);
BOOL IsConnected(void);
BOOL Attach(SOCKET hSocket);
};

View File

@ -0,0 +1,112 @@
// MFC_BLUETOOTH_TEST.cpp : 응용 프로그램에 대한 클래스 동작을 정의합니다.
//
#include "stdafx.h"
#include "MFC_BLUETOOTH_TEST.h"
#include "MFC_BLUETOOTH_TESTDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFC_BLUETOOTH_TESTApp
BEGIN_MESSAGE_MAP(CMFC_BLUETOOTH_TESTApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CMFC_BLUETOOTH_TESTApp 생성
CMFC_BLUETOOTH_TESTApp::CMFC_BLUETOOTH_TESTApp()
{
// 다시 시작 관리자 지원
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
// TODO: 여기에 생성 코드를 추가합니다.
// InitInstance에 모든 중요한 초기화 작업을 배치합니다.
}
// 유일한 CMFC_BLUETOOTH_TESTApp 개체입니다.
CMFC_BLUETOOTH_TESTApp theApp;
// CMFC_BLUETOOTH_TESTApp 초기화
BOOL CMFC_BLUETOOTH_TESTApp::InitInstance()
{
// 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을
// 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControlsEx()가 필요합니다.
// InitCommonControlsEx()를 사용하지 않으면 창을 만들 수 없습니다.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 응용 프로그램에서 사용할 모든 공용 컨트롤 클래스를 포함하도록
// 이 항목을 설정하십시오.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
//if (!AfxSocketInit())
//{
// AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
// return FALSE;
//}
AfxEnableControlContainer();
// 대화 상자에 셸 트리 뷰 또는
// 셸 목록 뷰 컨트롤이 포함되어 있는 경우 셸 관리자를 만듭니다.
CShellManager *pShellManager = new CShellManager;
// MFC 컨트롤의 테마를 사용하기 위해 "Windows 원형" 비주얼 관리자 활성화
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
// 표준 초기화
// 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면
// 아래에서 필요 없는 특정 초기화
// 루틴을 제거해야 합니다.
// 해당 설정이 저장된 레지스트리 키를 변경하십시오.
// TODO: 이 문자열을 회사 또는 조직의 이름과 같은
// 적절한 내용으로 수정해야 합니다.
SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성된 응용 프로그램"));
CMFC_BLUETOOTH_TESTDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 여기에 [확인]을 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
else if (nResponse == IDCANCEL)
{
// TODO: 여기에 [취소]를 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
else if (nResponse == -1)
{
TRACE(traceAppMsg, 0, "경고: 대화 상자를 만들지 못했으므로 응용 프로그램이 예기치 않게 종료됩니다.\n");
TRACE(traceAppMsg, 0, "경고: 대화 상자에서 MFC 컨트롤을 사용하는 경우 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS를 수행할 수 없습니다.\n");
}
// 위에서 만든 셸 관리자를 삭제합니다.
if (pShellManager != NULL)
{
delete pShellManager;
}
#ifndef _AFXDLL
ControlBarCleanUp();
#endif
// 대화 상자가 닫혔으므로 응용 프로그램의 메시지 펌프를 시작하지 않고 응용 프로그램을 끝낼 수 있도록 FALSE를
// 반환합니다.
return FALSE;
}

View File

@ -0,0 +1,32 @@
// MFC_BLUETOOTH_TEST.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다.
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다."
#endif
#include "resource.h" // 주 기호입니다.
// CMFC_BLUETOOTH_TESTApp:
// 이 클래스의 구현에 대해서는 MFC_BLUETOOTH_TEST.cpp을 참조하십시오.
//
class CMFC_BLUETOOTH_TESTApp : public CWinApp
{
public:
CMFC_BLUETOOTH_TESTApp();
// 재정의입니다.
public:
virtual BOOL InitInstance();
// 구현입니다.
DECLARE_MESSAGE_MAP()
};
extern CMFC_BLUETOOTH_TESTApp theApp;

Binary file not shown.

View File

@ -0,0 +1,229 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{9679D95A-84E5-4056-AEAC-16F892928DCA}</ProjectGuid>
<RootNamespace>MFC_BLUETOOTH_TEST</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
<Keyword>MFCProj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0412</Culture>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0412</Culture>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0412</Culture>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0412</Culture>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="BluetoothDeviceManager.h" />
<ClInclude Include="BluetoothManger.h" />
<ClInclude Include="BluetoothRadioManager.h" />
<ClInclude Include="MFC_BLUETOOTH_TEST.h" />
<ClInclude Include="MFC_BLUETOOTH_TESTDlg.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="BluetoothSockets.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="BluetoothDeviceManager.cpp" />
<ClCompile Include="BluetoothManger.cpp" />
<ClCompile Include="BluetoothRadioManager.cpp" />
<ClCompile Include="MFC_BLUETOOTH_TEST.cpp" />
<ClCompile Include="MFC_BLUETOOTH_TESTDlg.cpp" />
<ClCompile Include="BluetoothSockets.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="MFC_BLUETOOTH_TEST.rc" />
</ItemGroup>
<ItemGroup>
<None Include="res\MFC_BLUETOOTH_TEST.rc2" />
</ItemGroup>
<ItemGroup>
<Image Include="res\MFC_BLUETOOTH_TEST.ico" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties RESOURCE_FILE="MFC_BLUETOOTH_TEST.rc" />
</VisualStudio>
</ProjectExtensions>
</Project>

View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="소스 파일">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="헤더 파일">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="리소스 파일">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="MFC_BLUETOOTH_TEST.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="MFC_BLUETOOTH_TESTDlg.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="stdafx.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="BluetoothManger.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="BluetoothSockets.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="BluetoothRadioManager.h">
<Filter>헤더 파일</Filter>
</ClInclude>
<ClInclude Include="BluetoothDeviceManager.h">
<Filter>헤더 파일</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="MFC_BLUETOOTH_TEST.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="MFC_BLUETOOTH_TESTDlg.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="BluetoothDeviceManager.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="BluetoothRadioManager.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="BluetoothManger.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
<ClCompile Include="BluetoothSockets.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="MFC_BLUETOOTH_TEST.rc">
<Filter>리소스 파일</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<None Include="res\MFC_BLUETOOTH_TEST.rc2">
<Filter>리소스 파일</Filter>
</None>
</ItemGroup>
<ItemGroup>
<Image Include="res\MFC_BLUETOOTH_TEST.ico">
<Filter>리소스 파일</Filter>
</Image>
</ItemGroup>
</Project>

View File

@ -0,0 +1,219 @@
// MFC_BLUETOOTH_TESTDlg.cpp : 구현 파일
//
#include "stdafx.h"
#include "MFC_BLUETOOTH_TEST.h"
#include "MFC_BLUETOOTH_TESTDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFC_BLUETOOTH_TESTDlg 대화 상자
CMFC_BLUETOOTH_TESTDlg::CMFC_BLUETOOTH_TESTDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_MFC_BLUETOOTH_TEST_DIALOG, pParent),
m_pCBluetoothRadioManager(NULL),
m_pCBluetoothDeviceManager(NULL)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFC_BLUETOOTH_TESTDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMFC_BLUETOOTH_TESTDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, &CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton2)
ON_LBN_SELCHANGE(IDC_LIST1, &CMFC_BLUETOOTH_TESTDlg::OnLbnSelchangeList1)
ON_LBN_SELCHANGE(IDC_LIST2, &CMFC_BLUETOOTH_TESTDlg::OnLbnSelchangeList2)
ON_BN_CLICKED(IDC_BUTTON3, &CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton3)
END_MESSAGE_MAP()
// CMFC_BLUETOOTH_TESTDlg 메시지 처리기
BOOL CMFC_BLUETOOTH_TESTDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는
// 프레임워크가 이 작업을 자동으로 수행합니다.
SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다.
SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다.
// TODO: 여기에 추가 초기화 작업을 추가합니다.
return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다.
}
// 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면
// 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 응용 프로그램의 경우에는
// 프레임워크에서 이 작업을 자동으로 수행합니다.
void CMFC_BLUETOOTH_TESTDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다.
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다.
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;
// 아이콘을 그립니다.
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서
// 이 함수를 호출합니다.
HCURSOR CMFC_BLUETOOTH_TESTDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton1()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_pCBluetoothRadioManager = NULL;
m_pCBluetoothDeviceManager = NULL;
CListBox *pList = (CListBox*)GetDlgItem(IDC_LIST1);
if (!pList->GetSafeHwnd())
return;
while (pList->GetCount())
pList->DeleteString(0);
for (int i = 0; i < bm.GetRadioSize(); ++i)
{
CBluetoothRadioManager *pCBluetoothRadioManager = bm.GetRadio(i);
if (pCBluetoothRadioManager != NULL)
{
pList->InsertString(i, pCBluetoothRadioManager->GetName());
pList->SetItemDataPtr(i, pCBluetoothRadioManager);
}
}
}
void CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton2()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if (m_pCBluetoothDeviceManager == NULL)
return;
if (m_pCBluetoothDeviceManager->Connect())
{
//BYTE buf[4096] = { 0, };
CString strBuf;
static UINT dTryCnt = 0;
strBuf.Format(_T("kknd send : %d\r\n"), ++dTryCnt);
m_pCBluetoothDeviceManager->Send(CT2A(strBuf), strBuf.GetLength());
}
}
void CMFC_BLUETOOTH_TESTDlg::OnBnClickedButton3()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if (m_pCBluetoothDeviceManager == NULL)
return;
m_pCBluetoothDeviceManager->Close();
}
void CMFC_BLUETOOTH_TESTDlg::OnLbnSelchangeList1()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_pCBluetoothRadioManager = NULL;
CListBox *pList = (CListBox*)GetDlgItem(IDC_LIST1);
if (!pList->GetSafeHwnd())
return;
int pos = pList->GetCurSel();
if (pos < 0)
return;
CBluetoothRadioManager *pCBluetoothRadioManager = reinterpret_cast<CBluetoothRadioManager*>(pList->GetItemDataPtr(pos));
if (pCBluetoothRadioManager == NULL)
return;
CListBox *pList2 = (CListBox*)GetDlgItem(IDC_LIST2);
if (!pList2->GetSafeHwnd())
return;
while (pList2->GetCount())
pList2->DeleteString(0);
UINT dIndex = 0;
for (int i = 0; i < pCBluetoothRadioManager->GetDeviceSize(); ++i)
{
CBluetoothDeviceManager *pCBluetoothDeviceManager = pCBluetoothRadioManager->GetDevice(i);
if (pCBluetoothDeviceManager != NULL)
{
pList2->InsertString(dIndex, pCBluetoothDeviceManager->GetName());
pList2->SetItemDataPtr(dIndex, pCBluetoothDeviceManager);
++dIndex;
}
}
m_pCBluetoothRadioManager = pCBluetoothRadioManager;
}
void CMFC_BLUETOOTH_TESTDlg::OnLbnSelchangeList2()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_pCBluetoothDeviceManager = NULL;
CListBox *pList = (CListBox*)GetDlgItem(IDC_LIST2);
if (!pList->GetSafeHwnd())
return;
int pos = pList->GetCurSel();
if (pos < 0)
return;
CBluetoothDeviceManager *pCBluetoothDeviceManager = reinterpret_cast<CBluetoothDeviceManager*>(pList->GetItemDataPtr(pos));
if (pCBluetoothDeviceManager == NULL)
return;
m_pCBluetoothDeviceManager = pCBluetoothDeviceManager;
}

View File

@ -0,0 +1,47 @@
// MFC_BLUETOOTH_TESTDlg.h : 헤더 파일
//
#pragma once
#include "BluetoothManger.h"
// CMFC_BLUETOOTH_TESTDlg 대화 상자
class CMFC_BLUETOOTH_TESTDlg : public CDialogEx
{
// 생성입니다.
public:
CMFC_BLUETOOTH_TESTDlg(CWnd* pParent = NULL); // 표준 생성자입니다.
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_MFC_BLUETOOTH_TEST_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
// 구현입니다.
protected:
HICON m_hIcon;
// 생성된 메시지 맵 함수
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
CBluetoothManger bm;
CBluetoothRadioManager *m_pCBluetoothRadioManager; // TEST
CBluetoothDeviceManager *m_pCBluetoothDeviceManager; // TEST
afx_msg void OnLbnSelchangeList1();
afx_msg void OnLbnSelchangeList2();
afx_msg void OnBnClickedButton3();
};

View File

@ -0,0 +1,71 @@
================================================================================
MFC 라이브러리 : MFC_BLUETOOTH_TEST 프로젝트 개요
===============================================================================
응용 프로그램 마법사에서 이 MFC_BLUETOOTH_TEST 응용 프로그램을 만들었습니다. 이 응용 프로그램은 MFC의 기본 사용법을 보여 줄 뿐만 아니라 응용 프로그램을 작성하기 위한 기본 구조를 제공합니다.
MFC_BLUETOOTH_TEST 응용 프로그램을 구성하는 각 파일에 대한
요약 설명이 포함되어 있습니다.
MFC_BLUETOOTH_TEST.vcxproj
응용 프로그램 마법사를 사용하여 생성한 VC++ 프로젝트의 기본 프로젝트 파일입니다. 파일을 생성한 Visual C++ 버전에 대한 정보와 응용 프로그램 마법사를 사용하여 선택한 플랫폼, 구성 및 프로젝트 기능에 대한 정보가 포함되어 있습니다.
MFC_BLUETOOTH_TEST.vcxproj.filters
응용 프로그램 마법사를 사용하여 생성된 VC++ 프로젝트의 필터 파일입니다. 이 파일에는 프로젝트의 파일과 필터 간의 연결 정보가 들어 있습니다. 이러한 연결은 특정 노드에서 유사한 확장명으로 그룹화된 파일을 표시하기 위해 IDE에서 사용됩니다. 예를 들어 ".cpp" 파일은 "소스 파일" 필터와 연결되어 있습니다.
MFC_BLUETOOTH_TEST.h
해당 응용 프로그램의 기본 헤더 파일입니다.
여기에는 resource.h를 비롯한 다른 프로젝트별 헤더가 포함되어 있으며 CMFC_BLUETOOTH_TESTApp 응용 프로그램 클래스가 선언되어 있습니다.
MFC_BLUETOOTH_TEST.cpp
이는 응용 프로그램 클래스 CMFC_BLUETOOTH_TESTApp가 포함된 기본 응용 프로그램 소스 파일입니다.
MFC_BLUETOOTH_TEST.rc
프로그램에서 사용하는 모든 Microsoft Windows 리소스의 목록입니다. 여기에는 RES 하위 디렉터리에 저장된 아이콘, 비트맵 및 커서가 포함됩니다. 이 파일은 Microsoft Visual C++에서 직접 편집할 수 있습니다. 프로젝트 리소스는 1042에 있습니다.
res\MFC_BLUETOOTH_TEST.ico
아이콘 파일이며, 응용 프로그램의 아이콘으로 사용됩니다. 이 아이콘은 기본 리소스 파일인 MFC_BLUETOOTH_TEST.rc에 의해 포함됩니다.
res\MFC_BLUETOOTH_TEST.rc2
이 파일에는 Microsoft Visual C++ 이외의 다른 도구에서 편집한 리소스가 포함되어 있습니다. 리소스 편집기로 편집할 수 없는 모든 리소스는 이 파일에 넣어야 합니다.
/////////////////////////////////////////////////////////////////////////////
응용 프로그램 마법사에서 대화 상자 클래스 하나를 만듭니다.
MFC_BLUETOOTH_TESTDlg.h, MFC_BLUETOOTH_TESTDlg.cpp - 대화 상자
이 파일에는 CMFC_BLUETOOTH_TESTDlg 클래스가 포함됩니다. 이 클래스는 응용 프로그램의 주 대화 상자에 대한 동작을 정의합니다. 이 대화 상자 템플릿은 MFC_BLUETOOTH_TEST.rc에 있으며, Microsoft Visual C++에서 직접 편집할 수 있습니다.
/////////////////////////////////////////////////////////////////////////////
기타 기능:
ActiveX 컨트롤
응용 프로그램이 Active X 컨트롤을 지원합니다.
Windows 소켓
응용 프로그램에서 TCP/IP 네트워크를 통한 통신을 구축할 수 있습니다.
/////////////////////////////////////////////////////////////////////////////
기타 표준 파일:
StdAfx.h, StdAfx.cpp
이 파일은 미리 컴파일된 헤더(PCH) 파일 MFC_BLUETOOTH_TEST.pch와 미리 컴파일된 형식(PCT) 파일 StdAfx.obj를 빌드하는 데 사용됩니다.
Resource.h
새 리소스 ID를 정의하는 표준 헤더 파일입니다. Microsoft Visual C++에서 이 파일을 읽고 업데이트합니다.
MFC_BLUETOOTH_TEST.manifest
응용 프로그램 매니페스트 파일은 Windows XP에서 특정 버전의 Side-by-Side 어셈블리에 대한 응용 프로그램 종속성을 설명하는 데 사용됩니다. 로더는 이 정보를 통해 어셈블리 캐시 또는 응용 프로그램의 private에서 적절한 어셈블리를 로드합니다. 응용 프로그램 매니페스트는 응용 프로그램 실행 파일과 같은 폴더에 설치된 외부 .manifest 파일 형태로서 재배포용으로 포함되거나, 리소스 형태로 된 실행 파일에 포함될 수 있습니다.
/////////////////////////////////////////////////////////////////////////////
기타 참고:
응용 프로그램 마법사에서 사용하는 "TODO:"는 사용자가 추가하거나 사용자 지정해야 하는 소스 코드 부분을 나타냅니다.
공유된 DLL에서 MFC를 사용하는 응용 프로그램의 경우 MFC DLL을 재배포할 필요가 없습니다. 응용 프로그램에서 운영 체제의 로캘과 다른 언어를 사용하는 경우 이에 해당하는 지역화된 리소스인 mfc110XXX.DLL도 재배포해야 합니다.
이러한 두 항목에 대한 자세한 내용은 MSDN 설명서에 있는 Visual C++ 응용 프로그램 재배포 섹션을 참조하십시오.
/////////////////////////////////////////////////////////////////////////////

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,9 @@
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// MFC_BLUETOOTH_TEST.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")

View File

@ -0,0 +1,55 @@
// stdafx.h : 자주 사용하지만 자주 변경되지는 않는
// 표준 시스템 포함 파일 및 프로젝트 관련 포함 파일이
// 들어 있는 포함 파일입니다.
#pragma once
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // 거의 사용되지 않는 내용은 Windows 헤더에서 제외합니다.
#endif
#include "targetver.h"
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 일부 CString 생성자는 명시적으로 선언됩니다.
// MFC의 공통 부분과 무시 가능한 경고 메시지에 대한 숨기기를 해제합니다.
#define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC 핵심 및 표준 구성 요소입니다.
#include <afxext.h> // MFC 확장입니다.
#include <afxdisp.h> // MFC 자동화 클래스입니다.
#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h> // Internet Explorer 4 공용 컨트롤에 대한 MFC 지원입니다.
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // Windows 공용 컨트롤에 대한 MFC 지원입니다.
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxcontrolbars.h> // MFC의 리본 및 컨트롤 막대 지원
#include <afxsock.h> // MFC 소켓 확장
#define _log(x);
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif

View File

@ -0,0 +1,8 @@
#pragma once
// SDKDDKVer.h를 포함하면 최고 수준의 가용성을 가진 Windows 플랫폼이 정의됩니다.
// 이전 Windows 플랫폼에 대해 응용 프로그램을 빌드하려는 경우에는 SDKDDKVer.h를 포함하기 전에
// WinSDKVer.h를 포함하고 _WIN32_WINNT 매크로를 지원하려는 플랫폼으로 설정하십시오.
#include <SDKDDKVer.h>