在Unity中将BLE与真实的iOS设备和mac编辑器一起使用
我创建了一个本地插件,该插件可在Unity中的实际iOS设备和mac编辑器上使用CoreBluetooth与Bluetooth Low Energy设备进行通信。
我们正在分发Unity软件包。
单击此处以获取存储库→https://github.com/fuziki/UnityCoreBluetooth
我制作了一个可在Unity编辑器和iOS上运行的蓝牙插件#unity pic.twitter.com/EeHz0iqcmL
—藤木(@fzkqi)2019年9月24日
目的
Unity无法通过蓝牙进行通信。
我想在iOS上使用白日梦控制器,所以我做了自己的插件。
它也与Unity Editor兼容,并且可以通过与编辑器实际连接和实现并检查实际机器的运行来进行开发。推出
- 我们正在分发Unity软件包。
合并
获取Daydream控制器的原始数据
关于Daydream控制器
通过连接以下条件的特征,可以获得控制器的原始数据。
BLE设备具有多种服务,并且服务具有多种特征。提供为每个特征确定的功能,这一次特征uuid具有多个具有相同名称的id,因此将使用notify的年龄特征来接收原始数据。|项目|连接端子的条件|
|-|-|
|设备名称| Daydream控制器|
|服务uuid?? | FE55 |
|特征用法|通知|使用UnityCore蓝牙
1.单例实例生成
UnityCore蓝牙用作单例。
蓝牙功能打开后,开始扫描BLE设备。
完成所有回调设置后,致电StartCore蓝牙以启动。
1
2
3
4
5
6
7
8
9 UnityCoreBluetooth.CreateSharedInstance();
UnityCoreBluetooth.Shared.OnUpdateState((string state) =>
{
Debug.Log("state: " + state);
if (state != "poweredOn") return;
UnityCoreBluetooth.Shared.StartScan();
});
//~~中略~~
UnityCoreBluetooth.Shared.StartCoreBluetooth();2.找到具有您要连接的设备名称的设备时,请连接
1
2
3
4
5
6
7
8
9 UnityCoreBluetooth.Shared.OnDiscoverPeripheral((UnityCBPeripheral peripheral) =>
{
if (peripheral.name != "")
Debug.Log("discover peripheral name: " + peripheral.name);
if (peripheral.name != "Daydream controller") return;
UnityCoreBluetooth.Shared.StopScan();
UnityCoreBluetooth.Shared.Connect(peripheral);
});3.连接到设备后,寻找服务。
1
2
3
4
5 UnityCoreBluetooth.Shared.OnConnectPeripheral((UnityCBPeripheral peripheral) =>
{
Debug.Log("connected peripheral name: " + peripheral.name);
peripheral.discoverServices();
});4.找到目标uuid服务后,查找特征。
1
2
3
4
5
6 UnityCoreBluetooth.Shared.OnDiscoverService((UnityCBService service) =>
{
Debug.Log("discover service uuid: " + service.uuid);
if (service.uuid != "FE55") return;
service.discoverCharacteristics();
});5.如果找到通知用途的特征,请启用通知
通过启用
通知,您将能够从白日梦控制器连续接收原始数据。
1
2
3
4
5
6
7
8 UnityCoreBluetooth.Shared.OnDiscoverCharacteristic((UnityCBCharacteristic characteristic) =>
{
string uuid = characteristic.uuid;
string usage = characteristic.propertis[0];
Debug.Log("discover characteristic uuid: " + uuid + ", usage: " + usage);
if (usage != "notify") return;
characteristic.setNotifyValue(true);
});6.在特性
通知时接收数据
*我可以实时接收它,但是主线程无法保证。
1
2
3
4
5 UnityCoreBluetooth.Shared.OnUpdateValue((UnityCBCharacteristic characteristic, byte[] data) =>
{
this.value = data;
this.flag = true;
});7.销毁单例实例
1
2
3
4 void OnDestroy()
{
UnityCoreBluetooth.ReleaseSharedInstance();
}末尾
我创建了一个在统一编辑器和实际iOS设备上运行的BLE插件。
每次检查操作都需要花费时间来启动实际的iOS设备,因此我认为通过使用编辑器进行开发,开发变得容易了几倍。
本文介绍了此插件的结构。