commit 8061977c26ed433b40080960ce75e03aee11b24d Author: chodadoo Date: Sun May 2 03:47:57 2021 +0900 1. 최초 커밋 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5f95e29 --- /dev/null +++ b/.gitignore @@ -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 \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST.sln b/MFC_BLUETOOTH_TEST.sln new file mode 100644 index 0000000..75a2652 --- /dev/null +++ b/MFC_BLUETOOTH_TEST.sln @@ -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 diff --git a/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.cpp b/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.cpp new file mode 100644 index 0000000..50067a3 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.cpp @@ -0,0 +1,216 @@ +// BluetoothDeviceManager.cpp : 구현 파일입니다. +// + +#include "stdafx.h" +#include "MFC_BLUETOOTH_TEST.h" +#include "BluetoothDeviceManager.h" + +#include + +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(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); +} \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.h b/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.h new file mode 100644 index 0000000..2a0abe1 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothDeviceManager.h @@ -0,0 +1,56 @@ +#pragma once + +// Link to Bthprops.lib +#include +#include + +#include +#include +#include + +#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); diff --git a/MFC_BLUETOOTH_TEST/BluetoothManger.cpp b/MFC_BLUETOOTH_TEST/BluetoothManger.cpp new file mode 100644 index 0000000..e7e39ab --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothManger.cpp @@ -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; +} diff --git a/MFC_BLUETOOTH_TEST/BluetoothManger.h b/MFC_BLUETOOTH_TEST/BluetoothManger.h new file mode 100644 index 0000000..a8af7d8 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothManger.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include "BluetoothRadioManager.h" +#include "BluetoothDeviceManager.h" + +class CBluetoothManger +{ +public: + CBluetoothManger(); + ~CBluetoothManger(); + +private: + std::vector m_vecRadios; + + void FindRadios(void); + +protected: + +public: + size_t GetRadioSize(void); + CBluetoothRadioManager *GetRadio(size_t pos); + CBluetoothRadioManager *GetRadio(LPCTSTR pszName); +}; + diff --git a/MFC_BLUETOOTH_TEST/BluetoothRadioManager.cpp b/MFC_BLUETOOTH_TEST/BluetoothRadioManager.cpp new file mode 100644 index 0000000..d7d4d7e --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothRadioManager.cpp @@ -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(&pData->dbud_dbh); + if (pHeader->dbch_devicetype != DBT_DEVTYP_HANDLE) + throw; + + PDEV_BROADCAST_HANDLE pHandle = reinterpret_cast(pHeader); + + if (pHandle->dbch_eventguid == GUID_BLUETOOTH_RADIO_IN_RANGE) + { + PBTH_RADIO_IN_RANGE pRadioInfo = reinterpret_cast(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(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(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; +} \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/BluetoothRadioManager.h b/MFC_BLUETOOTH_TEST/BluetoothRadioManager.h new file mode 100644 index 0000000..de31ece --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothRadioManager.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include + +#include + +#include +#include + +#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 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); +}; + + diff --git a/MFC_BLUETOOTH_TEST/BluetoothSockets.cpp b/MFC_BLUETOOTH_TEST/BluetoothSockets.cpp new file mode 100644 index 0000000..9c70ef2 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothSockets.cpp @@ -0,0 +1,323 @@ +#include "stdafx.h" + +#include "BluetoothSockets.h" + +std::shared_ptr 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); +} \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/BluetoothSockets.h b/MFC_BLUETOOTH_TEST/BluetoothSockets.h new file mode 100644 index 0000000..981c012 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/BluetoothSockets.h @@ -0,0 +1,110 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// 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 m_pInstance; + +public: + static const std::shared_ptr Get(void) + { + if (m_pInstance) + return m_pInstance; + else + return m_pInstance = std::shared_ptr(new CSocketInitialize()); + } +}; + +template +class CSocketInitialized : public _Ty +{ +public: + CSocketInitialized(void) + { + CSocketInitialize::Get(); + } + virtual ~CSocketInitialized(void) + { + + } + +private: +protected: +public: +}; + +class CBluetoothSocket; + +typedef std::function fnc_OnAccept; +class CBluetoothSocketListener : private CSocketInitialized +{ +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 +{ +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); +}; \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.cpp b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.cpp new file mode 100644 index 0000000..0c29ed3 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.cpp @@ -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; +} + diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.h b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.h new file mode 100644 index 0000000..a13331a --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.h @@ -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; \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.rc b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.rc new file mode 100644 index 0000000..deaad33 Binary files /dev/null and b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.rc differ diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj new file mode 100644 index 0000000..510ca42 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj @@ -0,0 +1,229 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {9679D95A-84E5-4056-AEAC-16F892928DCA} + MFC_BLUETOOTH_TEST + 8.1 + MFCProj + + + + Application + true + v140 + Unicode + Dynamic + + + Application + false + v140 + true + Unicode + Dynamic + + + Application + true + v140 + Unicode + Dynamic + + + Application + false + v140 + true + Unicode + Dynamic + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) + true + + + Windows + + + false + true + _DEBUG;%(PreprocessorDefinitions) + + + 0x0412 + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + _WINDOWS;_DEBUG;%(PreprocessorDefinitions) + true + + + Windows + + + false + true + _DEBUG;%(PreprocessorDefinitions) + + + 0x0412 + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) + true + + + Windows + true + true + + + false + true + NDEBUG;%(PreprocessorDefinitions) + + + 0x0412 + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + _WINDOWS;NDEBUG;%(PreprocessorDefinitions) + true + + + Windows + true + true + + + false + true + NDEBUG;%(PreprocessorDefinitions) + + + 0x0412 + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj.filters b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj.filters new file mode 100644 index 0000000..e59eb53 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TEST.vcxproj.filters @@ -0,0 +1,87 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + 헤더 파일 + + + + + 소스 파일 + + + 소스 파일 + + + 소스 파일 + + + 소스 파일 + + + 소스 파일 + + + 소스 파일 + + + 소스 파일 + + + + + 리소스 파일 + + + + + 리소스 파일 + + + + + 리소스 파일 + + + \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.cpp b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.cpp new file mode 100644 index 0000000..04a1a94 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.cpp @@ -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(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(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(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(pList->GetItemDataPtr(pos)); + + if (pCBluetoothDeviceManager == NULL) + return; + + m_pCBluetoothDeviceManager = pCBluetoothDeviceManager; +} diff --git a/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.h b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.h new file mode 100644 index 0000000..ef035fe --- /dev/null +++ b/MFC_BLUETOOTH_TEST/MFC_BLUETOOTH_TESTDlg.h @@ -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(); +}; + diff --git a/MFC_BLUETOOTH_TEST/ReadMe.txt b/MFC_BLUETOOTH_TEST/ReadMe.txt new file mode 100644 index 0000000..071a106 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/ReadMe.txt @@ -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++ 응용 프로그램 재배포 섹션을 참조하십시오. + +///////////////////////////////////////////////////////////////////////////// diff --git a/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.ico b/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.ico new file mode 100644 index 0000000..d56fbcd Binary files /dev/null and b/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.ico differ diff --git a/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.rc2 b/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.rc2 new file mode 100644 index 0000000..6511fae Binary files /dev/null and b/MFC_BLUETOOTH_TEST/res/MFC_BLUETOOTH_TEST.rc2 differ diff --git a/MFC_BLUETOOTH_TEST/resource.h b/MFC_BLUETOOTH_TEST/resource.h new file mode 100644 index 0000000..98fc2f6 Binary files /dev/null and b/MFC_BLUETOOTH_TEST/resource.h differ diff --git a/MFC_BLUETOOTH_TEST/stdafx.cpp b/MFC_BLUETOOTH_TEST/stdafx.cpp new file mode 100644 index 0000000..9be2fce --- /dev/null +++ b/MFC_BLUETOOTH_TEST/stdafx.cpp @@ -0,0 +1,9 @@ + +// stdafx.cpp : ǥ ϸ ִ ҽ Դϴ. +// MFC_BLUETOOTH_TEST.pch ̸ ϵ ˴ϴ. +// stdafx.obj ̸ ϵ Ե˴ϴ. + +#include "stdafx.h" + + +#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console") \ No newline at end of file diff --git a/MFC_BLUETOOTH_TEST/stdafx.h b/MFC_BLUETOOTH_TEST/stdafx.h new file mode 100644 index 0000000..a618a0d --- /dev/null +++ b/MFC_BLUETOOTH_TEST/stdafx.h @@ -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 // MFC ٽ ǥ Դϴ. +#include // MFC ȮԴϴ. + + +#include // MFC ڵȭ ŬԴϴ. + + + +#ifndef _AFX_NO_OLE_SUPPORT +#include // Internet Explorer 4 Ʈѿ MFC Դϴ. +#endif +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // Windows Ʈѿ MFC Դϴ. +#endif // _AFX_NO_AFXCMN_SUPPORT + +#include // MFC Ʈ + + +#include // 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 + + diff --git a/MFC_BLUETOOTH_TEST/targetver.h b/MFC_BLUETOOTH_TEST/targetver.h new file mode 100644 index 0000000..3142091 --- /dev/null +++ b/MFC_BLUETOOTH_TEST/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// SDKDDKVer.h ϸ ְ 뼺 Windows ÷ ǵ˴ϴ. + +// Windows ÷ α׷ Ϸ 쿡 SDKDDKVer.h ϱ +// WinSDKVer.h ϰ _WIN32_WINNT ũθ Ϸ ÷ Ͻʽÿ. + +#include