본문 바로가기
프로그래밍/Desktop App

[WinForm] BLE 통신 예제

by YuminK 2023. 12. 11.

데스크탑 환경 테스트앱(C#)과 TOOKTOOk 기기(회사 IOT기기 이름) 연동 테스트 작업을 진행했습니다. PC에 블루투스 동글을 연결하여 IOT기기와 통신합니다. 


프로젝트 참조 패키지
1. C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.22621.0\Windows.winmd
2. Nuget 패키지 System.Runtime.WindowsRuntime 설치

유의사항)
기기와 PC간 거리를 가까이 하지 않으면 스캔/통신 처리가 정상적이지 않았습니다.

BLE 통신 요약
1. BluetoothLEAdvertisementWatcher를 선언하고 BLE 통신 콜백을 등록합니다. 
watcher.Received += OnAdvertisementReceivedAsync;
watcher.Stopped += OnAdvertisementStopped;

2. 스캐닝을 시작하고 OnAdvertisementReceivedAsync에서 디바이스 정보를 얻습니다.
device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

3. 디바이스에 연결합니다.
서비스 UUID 정보에 접근하여 쓰기용 Characteristic 정보를 얻고 구독용 Characteristic 정보를 얻습니다. (콜백 등록)

4. 기기에 메시지를 보내기 위해 WriteCharacteristicAsync 함수를 사용합니다.
async Task WriteCharacteristicAsync(string message)
{
    if (device == null || writeCharacteristic == null)
        return;

    Console.WriteLine("writeCharacteristic message = " + message);
    byte[] bytes = Encoding.UTF8.GetBytes(message);
    var writer = new DataWriter();
    writer.WriteBytes(bytes);

    GattCommunicationStatus result = await writeCharacteristic.WriteValueAsync(writer.DetachBuffer());
    if (result != GattCommunicationStatus.Success)
    {
        await Console.Out.WriteLineAsync("쓰기 실패");
    }
}

5. 기기 인바디 검사에서 구독 정보(callback)를 사용합니다.
private void CharacteristicChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    // notifyCharacteristic 정보가 바뀐 경우, 정보를 읽는다.
    var reader = DataReader.FromBuffer(args.CharacteristicValue);
    byte[] bytes = new byte[args.CharacteristicValue.Length];
    reader.ReadBytes(bytes);

    string value = Encoding.UTF8.GetString(bytes);
   
   // ...
}

 

프로토콜이나 주고 받는 데이터는 구현된 IOT기기마다 다를 것이다. 이 부분은 상황에 맞춰 수정하길 바란다. 

WindowsFormsApp1.zip
3.11MB

댓글