Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제
; https://www.sysnet.pe.kr/2/0/11106

.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET Framework: 715. C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

.NET Framework: 722. C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11420

.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11799

.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법
; https://www.sysnet.pe.kr/2/0/12001

.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출
; https://www.sysnet.pe.kr/2/0/12470

닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
; https://www.sysnet.pe.kr/2/0/13438




WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법

UWP의 도움을 받으면 일반 데스크톱 프로그램에서 Bluetooth 관련 기능을 쉽게 사용할 수 있습니다. 예를 들어, Windows Forms 프로젝트를 생성 후 다음의 어셈블리 2개를 참조 추가하면,

C:\Program Files (x86)\Windows Kits\10\UnionMetadata\...[version]...\Windows.winmd
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

UWP 관련 유틸리티 클래스들을 데스크톱 프로그램에서도 사용할 수 있습니다. 블루투스 페어링 관련해서는 도움말에 따라,

Pair devices
; https://learn.microsoft.com/en-us/windows/uwp/devices-sensors/pair-devices

다음과 같이 (예를 들어 Winform 프로젝트에서) 코드로 작성할 수 있습니다.

using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Enumeration;

namespace DevicePickerWinFormAppSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Button1_Click(object sender, EventArgs e)
        {
            var picker = new DevicePicker();
            picker.DeviceSelected += Picker_DeviceSelected;
            picker.Filter.SupportedDeviceSelectors.Add(
                BluetoothDevice.GetDeviceSelectorFromPairingState(false));

            DeviceInformation di = await picker.PickSingleDeviceAsync(new Windows.Foundation.Rect(0, 0, 0, 0), Windows.UI.Popups.Placement.Default);
            if (di == null)
            {
                return;
            }

            if (di.Pairing.IsPaired == false)
            {
                di.Pairing.Custom.PairingRequested += Custom_PairingRequested;

                if (di.Pairing.CanPair == true)
                {
                    var pairResult = await di.Pairing.PairAsync();
                    if (pairResult.Status == DevicePairingResultStatus.Paired)
                    {
                        // do something
                    }
                }
                else
                {
                    var pairResult = await di.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin);
                    if (pairResult.Status == DevicePairingResultStatus.Paired)
                    {
                        // do something
                    }
                }
            }
        }

        private void Custom_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            if (args.PairingKind == DevicePairingKinds.ProvidePin)
            {
                // Microsoft.VisualBasic.dll 참조 필요
                string result = Microsoft.VisualBasic.Interaction.InputBox("Pin?", "Pairing...", "");
                if (string.IsNullOrEmpty(result) == false)
                {
                    args.Accept(result);
                }
            }
            else
            {
                args.Accept();
            }
        }

        private void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            var di = args.SelectedDevice;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(di.Name);
            sb.AppendLine(di.Id);
            sb.AppendLine(di.Kind.ToString());
            sb.AppendLine(di.Pairing.IsPaired.ToString());
            sb.AppendLine(di.Pairing.CanPair.ToString());
            sb.AppendLine("");
            foreach (var item in di.Properties.Keys)
            {
                sb.Append(item);

                string[] props = di.Properties[item] as string[];
                if (props != null)
                {
                    sb.AppendLine(":");
                    foreach (var prop in props)
                    {
                        sb.AppendLine("    " + prop);
                    }
                }
                else
                {
                    sb.AppendLine(": " + di.Properties[item]);
                }
            }

            Trace.WriteLine(sb.ToString());
        }
    }
}

실제로 실행해 보면 블루투스 기기를 찾는 대화창이 뜹니다.

device_picker_sample_1.png

Make sure the device is turned on and is discoverable.

이 상태에서, 테스트를 위해 다른 블루투스 기기를(여기서는 페어링되지 않은 제 갤럭시 폰) 켜 블루투스 메뉴로 들어가면 다음과 같이 대화창 목록에 폰이 나옵니다.

device_picker_sample_2.png

해당 항목을 선택하면 Picker_DeviceSelected 이벤트 핸들러가 실행되고 갤럭시 노트 9의 경우 DeviceInformation 타입을 이용해 아래와 같은 정보를 구할 수 있습니다.

Galaxy Note9
Bluetooth#Bluetooth7c:6d:e5:da:19:0c-58:af:e9:b2:e3:5e
AssociationEndpoint
False
False

System.ItemNameDisplay: Galaxy Note9
System.Devices.DeviceInstanceId: 
System.Devices.Icon: C:\Windows\System32\DDORes.dll,-2035
System.Devices.GlyphIcon: C:\Windows\System32\DDORes.dll,-3022
System.Devices.InterfaceEnabled: 
System.Devices.IsDefault: 
System.Devices.PhysicalDeviceLocation: 
System.Devices.ContainerId: 
System.Devices.DevObjectType: 5
System.Devices.CategoryIds: 
System.Devices.Aep.ContainerId: 3984f580-ceb2-5030-9e71-10027efe5b76
System.Devices.Aep.Category:
    Communication.Phone
System.Devices.Aep.ProtocolId: e0cbf06c-cd8b-4647-bb8a-263b43f0f974
System.Devices.AepContainer.ContainerId: 
System.Devices.AepContainer.Categories: 
System.Devices.AepContainer.Children: 
System.Devices.AepContainer.ProtocolIds: 
System.Devices.AepContainer.SupportsAudio: 
System.Devices.AepContainer.SupportsVideo: 
System.Devices.AepContainer.SupportsImages: 
System.Devices.AepContainer.SupportedUriSchemes: 
System.Devices.AepService.ContainerId: 
{C192D624-035A-4EA7-BD44-2A820C0D09FF} 3: 
System.Devices.AepService.AepId: 
System.Devices.AepService.ProtocolId: e0cbf06c-cd8b-4647-bb8a-263b43f0f974

위에서 강조된 "58:af:e9:b2:e3:5e" 값은 블루투스 기기의 MAC 주소입니다. 이후, DeviceInformation.Pairing 속성을 이용해 페어링되지 않은 기기를 PairAsync 메서드를 이용해 페어를 시도할 수 있습니다.

여기서 제가 한 가지 이해하지 못하고 있는 것이 있는데, DeviceInformation.Pairing.CanPair가 (적어도 제가 가지고 있는 블루투스 기기들은) 모두 false 값이 나온다는 점입니다.

if (di.Pairing.CanPair == true)
{
    // 이 코드로 진입하는 블루투스 기기는 거의 없고,
    var pairResult = await di.Pairing.PairAsync();
    if (pairResult.Status == DevicePairingResultStatus.Paired)
    {
        // do something
    }
}
else
{
    // 대개의 경우 이 코드로 진입하게 됨.
    var pairResult = await di.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin);
    if (pairResult.Status == DevicePairingResultStatus.Paired)
    {
        // do something
    }
}

그래서 위의 코드에서 di.Pairing.CanPair == true인 상황은 테스트되지 않은 코드입니다. (혹시 어떤 블루투스 기기가 CanPair == true 인지 아시는 분은 덧글 부탁드립니다. ^^)

어쨌든 저렇게 해서 PairAsync를 호출하면 대상 블루투스 기기에 신호가 전달되고 (이런 경우에는 폰이 생성한) PIN 번호를 PairAsync를 호출한 기기에서 입력하라는 메시지가 뜹니다. 따라서 해당 값을, DeviceInformation.Pairing.Custom.PairingRequested 이벤트 핸들러에서 다음과 같은 식으로 처리해 주면 됩니다.

static private void Custom_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
{
    if (args.PairingKind == DevicePairingKinds.ProvidePin)
    {
        // Microsoft.VisualBasic.dll 참조 필요
        string result = Microsoft.VisualBasic.Interaction.InputBox("Pin?", "Pairing...", "");
        if (string.IsNullOrEmpty(result) == false)
        {
            args.Accept(result);
        }
    }
    else
    {
        args.Accept();
    }
}

사실, 블루투스 페어링을 이런 식으로 프로그래밍할 필요는 없습니다. 왜냐하면 이미 윈도우나 여타 블루투스 기기에서 별도의 페어링 방법을 제공하기 때문에 그걸로 미리 해두면 되기 때문입니다.

(이 글의 예제 코드는 github - DevicePickerWinFormAppSample에서 제공합니다.)




참고로, 이 코드를 Console 프로젝트 유형에서 사용하는 경우에는 PickSingleDeviceAsync 메서드 호출 시에 "Invalid window handle" 예외가 발생합니다.

System.Exception
  HResult=0x80070578
  Message=Invalid window handle. (Exception from HRESULT: 0x80070578)
  Source=mscorlib
  StackTrace:
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() in f:\dd\ndp\clr\src\BCL\system\runtime\exceptionservices\exceptionservicescommon.cs:line 133
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 352
   at Program.<Main>d__0.MoveNext() in F:\test\ConsoleApp1\ConsoleApp1\Program.cs:line 23
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() in f:\dd\ndp\clr\src\BCL\system\runtime\exceptionservices\exceptionservicescommon.cs:line 133
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult() in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 114
   at Program.<Main>(String[] args)

어쩔 수 없습니다. 동일하게 Window 하나 만들어 주고 그 안에서 코드 실행을 해야 하는데, 그럴 거면 애당초 WinForm/WPF 프로젝트로 시작하는 것이 더 좋을 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/19/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-03-20 10시29분
파이썬으로 블루투스 통신 하는 방법 (Ubuntu)
; https://blog.naver.com/cjinnnn/223047209187
정성태

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13373정성태6/19/20234399오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233113개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233132개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233297개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233096개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233225개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233333오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233132.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232897오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233682.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233245스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233165.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233639오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233354오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233664.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233690.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233958.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233569.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234074VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233325오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233665.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233570.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233936.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...