티스토리 뷰

반응형

유니티에서 블루투스 read/write 하기

 

기본적으로 유니티에서는 블루투스기능이 제공되지 않는다.

 

궁금한 사항은 메일과 댓글을 통해서 얼마든지 알려주면 공유해드리겠습니다.

 

[에셋 설치 Bluetooth LE for iOS, tvOS and Android]

https://assetstore.unity.com/packages/tools/network/bluetooth-le-for-ios-tvos-and-android-26661

 

Bluetooth LE for iOS, tvOS and Android | 네트워크 | Unity Asset Store

Get the Bluetooth LE for iOS, tvOS and Android package from Shatalmic, llc and speed up your game development process. Find this & other 네트워크 options on the Unity Asset Store.

assetstore.unity.com

 

다음 에셋을 이용하여 진행하였다

 

블루투스 BLE의 구조는

 

Serveice / Characteristic 로 나눠져있다.

 

Service는 디바이스에서 정의한 기능(UUID를 통한 아이디)

Characteristic 는  각 Service의 소 기능(UUID를 통한 아이디)

 

[클래스로 구조 설명]

이런식의 구조를 지닌다고 이해하면된다.

각 Connection / Scan / Read/ Subscribe 등등 기능은 모두 Characteristic 단위로 되기때문에

1개의 디바이스도 연결 및 구독등이 여러 개 등록 가능하다.

    class Service
    {
        string name { get; set; }
        string UUID { get; set; }
        Characteristic characteristics { get; set; }
    }

    class Characteristic
    {
        string UUID { get; set; }
        string name { get; set; }
    }

    class Device
    {
        string UUID { get; set; }
        string name { get; set; }
        Service services { get; set; }
    }

 

[디바이스 스캔]

BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                    // 기기 발견 시 스캔 중지 및 연결
                    if (name.Contains(DeviceName))
                    {
                        DeviceAddress = address;
                        Debug.Log("###################### 디바이스 찾음 ######################:"+name);
                        BluetoothLEHardwareInterface.StopScan();
                        Debug.Log("###################### 스캔 중지 ######################:");
                        ConnectToDevice(address);
                    }
                });

 

[디바이스 연결]

 BluetoothLEHardwareInterface.ConnectToPeripheral(address, null, null, (deviceAddress, serviceUUID, characteristicUUID) => {
                Debug.Log("################# 연결 성공 #################" + characteristicUUID + ": " + serviceUUID);
        }

 

[디바이스 구독]

 BluetoothLEHardwareInterface.SubscribeCharacteristic(DeviceAddress, serviceUUID, characteristicUUID, null, (uuid, data) =>
                    {
                        var msg = Encoding.UTF8.GetString(data);
                        Debug.Log($"######### 메세지 받기 성공:  {msg}  ############");
                    });

 

[디바이스 Write]

  public void Send(string msg= ">D1112")
    {
        var data = Encoding.ASCII.GetBytes(">D1112");
        Debug.Log($"################# 메세지 전송:{msg} #################" + writeServiceUUID + ": " + writeCharacteristicUUID);
        BluetoothLEHardwareInterface.WriteCharacteristic(DeviceAddress, writeServiceUUID, writeCharacteristicUUID, data, data.Length, false, null);
    }

 

[풀소스]

using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class BleManager : MonoBehaviour
{
    
    public string DeviceName = "VH-80A";
    string DeviceAddress = "";

    [SerializeField]
    string readServiceUUID = "00001800-0000-1000-8000-00805f9b34fb";
    [SerializeField]
    string readCharacteristicUUID = "00002a00-0000-1000-8000-00805f9b34fb";

    [SerializeField]
    string writeServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
    [SerializeField]
    string writeCharacteristicUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";

    void Start()
        {
        Debug.Log("###################### 디바이스 이름 ######################:" + DeviceName);
        // BLE 초기화
        BluetoothLEHardwareInterface.Initialize(true, false, () => {
                // 초기화 성공 시, 스캔 시작
                BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                    // 기기 발견 시 스캔 중지 및 연결
                    if (name.Contains(DeviceName))
                    {
                        DeviceAddress = address;
                        Debug.Log("###################### 디바이스 찾음 ######################:"+name);
                        BluetoothLEHardwareInterface.StopScan();
                        Debug.Log("###################### 스캔 중지 ######################:");
                        ConnectToDevice(address);
                    }
                });
            }, (error) => {
                // 초기화 실패 시

                Debug.LogError("BLE Initialization Failed: " + error);
            });
        }

    public void Send(string msg= ">D1112")
    {
        var data = Encoding.ASCII.GetBytes(">D1112");
        Debug.Log($"################# 메세지 전송:{msg} #################" + writeServiceUUID + ": " + writeCharacteristicUUID);
        BluetoothLEHardwareInterface.WriteCharacteristic(DeviceAddress, writeServiceUUID, writeCharacteristicUUID, data, data.Length, false, null);
    }

    private void ConnectToDevice(string address)
        {
            BluetoothLEHardwareInterface.ConnectToPeripheral(address, null, null, (deviceAddress, serviceUUID, characteristicUUID) => {
                Debug.Log("################# 연결 성공 #################" + characteristicUUID + ": " + serviceUUID);
            if (!(serviceUUID == readServiceUUID && characteristicUUID == readCharacteristicUUID))
            {
                Debug.Log("################# read UUID 찾기 성공 -> 구독 진행 #################" + characteristicUUID + ": " + serviceUUID);
                    //// 서비스와 특성 발견 시 데이터 읽기 시도

                    BluetoothLEHardwareInterface.SubscribeCharacteristic(DeviceAddress, serviceUUID, characteristicUUID, null, (uuid, data) =>
                    {
                        var msg = Encoding.UTF8.GetString(data);
                        Debug.Log($"######### 메세지 받기 성공:  {msg}  ############");
                    });
                }
            }, (deviceAddress) => {
                // 연결 해제 시 처리
                BluetoothLEHardwareInterface.DisconnectAll();
                Debug.Log("################ 연결 종료 " + deviceAddress+" ####################");
            });
        }
    }

 

 

# Bluetooth LE for iOS, tvOS and Android #ble #unity #read #write #블루투스 #유니티

반응형
댓글
반응형