Xamarin

자마린에서 블루투스 연결하기

봄가을1 2021. 10. 14. 12:39

1. Nuget 에서 Plugin.BLE 설치하기.

 

 

2. 블루투스 연결 가능인지 확인하기.

        public bluetooth()
        {
            IBluetoothLE ble;
            ble = CrossBluetoothLE.Current;

            var state = ble.State;  //state 는 여러가지가 있으니 확인.
            if (state.ToString() != "On")
            {
                displayNotice();
            }

            ble.StateChanged += (s, e) =>
            {
                if(e.NewState.ToString() != "On")
                {
                    displayNotice();
                }
            };
        }

        private async void displayNotice()
        {
            await DisplayAlert("알림", "블루투스가 꺼져 있습니다. 블루투스를 켜주세요.", "확인");
        }

 

3. Scan

                IAdapter adapter = CrossBluetoothLE.Current.Adapter;

                adapter.DeviceDiscovered += (s, a) =>
                {
                    IDevice fdev = deviceList.Find(x => x.Id == a.Device.Id);
                    if (fdev == null)
                    {
                        // 중복된 ID가 아니라면, 리스트에 추가.
                        deviceList.Add(a.Device);
                    }
                };

                adapter.ScanTimeout = 5000;
                await adapter.StartScanningForDevicesAsync();

4. Connect

                public IDevice devToCon; //connect 하려고 하는 device 값을 넣어준다.

                try
                {
                    await adapter.ConnectToDeviceAsync(devToCon);
                }
                catch (DeviceConnectionException err)
                {
                    //specific
                    await DisplayAlert("연결 실패 !", err.Message, "확인");
                }
                catch (Exception err)
                {
                    await DisplayAlert("Error!", err.Message, "확인");
                }

5. UUID 얻어오기.

  UUID 에 대한 자세한 정보는 여기서. https://www.bluetooth.com/specifications/assigned-numbers/

public IDevice curDev; //연결된 device.
public static ICharacteristic sendCharacteristic = null;
public static ICharacteristic receiveCharacteristic = null;
.....
{
    var services = await curDev.GetServicesAsync();
    if (services != null)
    {
        for (int i = 0; i < services.Count; i++)
        {
            var service = await curDev.GetServiceAsync(services[i].Id);  //service 정보를 확인하고, 필요한 것만 사용
            if (service != null)
            {
                var characteristics = await service.GetCharacteristicsAsync();
                if (characteristics != null)
                {
                    for (int j = 0; j < characteristics.Count; j++)
                    {
                        var characteristic = await service.GetCharacteristicAsync(characteristics[j].Id);
                        if (characteristic != null)
                        {
                            var cid = characteristic.Id.ToString().Substring(0, 8);
                            if (cid == "0000fff1")  // ID "0000fff1" 이 receive ID로 사용될 경우.
                            {
                                if (receiveCharacteristic == null)
                                {
                                    receiveCharacteristic = characteristic;
                                }
                            }
                            if (cid == "0000fff2") // ID "0000fff2" 가 send ID로 사용될 경우.
                            {
                                if (sendCharacteristic == null)
                                {
                                    sendCharacteristic = characteristic; // send 
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

6. Recieve data

receiveCharacteristic.ValueUpdated += async (o, args) =>
{
    var receivedBytes = args.Characteristic.Value;
    XamarinEssentials.MainThread.BeginInvokeOnMainThread(() =>
    {
        // receivedBytes 값 처리.
        for (int r = 0; r < receivedBytes.Length; r++)
        {
            message2.Text += receivedBytes[r].ToString("X2");
        }
    });
};
await receiveCharacteristic.StartUpdatesAsync();

7. Send data

Byte[] sendBytes = new Byte[5];
.....
var bytes = await sendCharacteristic.WriteAsync(sendBytes);