ios蓝牙适配

This commit is contained in:
lishuo 2021-08-30 18:28:26 +08:00
parent d8927ceca5
commit 99540eb1fd
6 changed files with 84 additions and 41 deletions

View File

@ -245,12 +245,12 @@ public class BluetoothDeviceScript : MonoBehaviour
else if (message.Length >= deviceDiscoveredService.Length && message.Substring (0, deviceDiscoveredService.Length) == deviceDiscoveredService) else if (message.Length >= deviceDiscoveredService.Length && message.Substring (0, deviceDiscoveredService.Length) == deviceDiscoveredService)
{ {
if (parts.Length >= 3 && DiscoveredServiceAction != null) if (parts.Length >= 3 && DiscoveredServiceAction != null)
DiscoveredServiceAction (parts[1], parts[2]); DiscoveredServiceAction (parts[1], FullUUID(parts[2]));
} }
else if (message.Length >= deviceDiscoveredCharacteristic.Length && message.Substring (0, deviceDiscoveredCharacteristic.Length) == deviceDiscoveredCharacteristic) else if (message.Length >= deviceDiscoveredCharacteristic.Length && message.Substring (0, deviceDiscoveredCharacteristic.Length) == deviceDiscoveredCharacteristic)
{ {
if (parts.Length >= 4 && DiscoveredCharacteristicAction != null) if (parts.Length >= 4 && DiscoveredCharacteristicAction != null)
DiscoveredCharacteristicAction (parts[1], parts[2], parts[3]); DiscoveredCharacteristicAction (parts[1], FullUUID(parts[2]), FullUUID(parts[3]));
} }
else if (message.Length >= deviceDidWriteCharacteristic.Length && message.Substring (0, deviceDidWriteCharacteristic.Length) == deviceDidWriteCharacteristic) else if (message.Length >= deviceDidWriteCharacteristic.Length && message.Substring (0, deviceDidWriteCharacteristic.Length) == deviceDidWriteCharacteristic)
{ {
@ -264,11 +264,11 @@ public class BluetoothDeviceScript : MonoBehaviour
if (DidUpdateNotificationStateForCharacteristicAction != null && DidUpdateNotificationStateForCharacteristicAction.ContainsKey (parts[1])) if (DidUpdateNotificationStateForCharacteristicAction != null && DidUpdateNotificationStateForCharacteristicAction.ContainsKey (parts[1]))
{ {
var characteristicAction = DidUpdateNotificationStateForCharacteristicAction[parts[1]]; var characteristicAction = DidUpdateNotificationStateForCharacteristicAction[parts[1]];
if (characteristicAction != null && characteristicAction.ContainsKey (parts[2])) if (characteristicAction != null && characteristicAction.ContainsKey (FullUUID(parts[2])))
{ {
var action = characteristicAction[parts[2]]; var action = characteristicAction[FullUUID(parts[2])];
if (action != null) if (action != null)
action (parts[2]); action (FullUUID(parts[2]));
} }
} }
@ -277,9 +277,9 @@ public class BluetoothDeviceScript : MonoBehaviour
var characteristicAction = DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[parts[1]]; var characteristicAction = DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[parts[1]];
if (characteristicAction != null && characteristicAction.ContainsKey (parts[2])) if (characteristicAction != null && characteristicAction.ContainsKey (parts[2]))
{ {
var action = characteristicAction[parts[2]]; var action = characteristicAction[FullUUID(parts[2])];
if (action != null) if (action != null)
action (parts[1], parts[2]); action (parts[1], FullUUID(parts[2]));
} }
} }
} }
@ -287,7 +287,7 @@ public class BluetoothDeviceScript : MonoBehaviour
else if (message.Length >= deviceDidUpdateValueForCharacteristic.Length && message.Substring (0, deviceDidUpdateValueForCharacteristic.Length) == deviceDidUpdateValueForCharacteristic) else if (message.Length >= deviceDidUpdateValueForCharacteristic.Length && message.Substring (0, deviceDidUpdateValueForCharacteristic.Length) == deviceDidUpdateValueForCharacteristic)
{ {
if (parts.Length >= 4) if (parts.Length >= 4)
OnBluetoothData (parts[1], parts[2], parts[3]); OnBluetoothData (parts[1], FullUUID(parts[2]), parts[3]);
} }
else if (message.Length >= deviceRequestMtu.Length && message.Substring(0, deviceRequestMtu.Length) == deviceRequestMtu) else if (message.Length >= deviceRequestMtu.Length && message.Substring(0, deviceRequestMtu.Length) == deviceRequestMtu)
{ {
@ -303,6 +303,12 @@ public class BluetoothDeviceScript : MonoBehaviour
} }
} }
} }
public static string FullUUID(string uuid)
{
if (uuid.Length == 4)
return "0000" + uuid + "-0000-1000-8000-00805F9B34FB";
return uuid;
}
public void OnBluetoothData (string base64Data) public void OnBluetoothData (string base64Data)
{ {

View File

@ -616,7 +616,7 @@ public class BluetoothLEHardwareInterface
bluetoothDeviceScript.ConnectedPeripheralAction = connectAction; bluetoothDeviceScript.ConnectedPeripheralAction = connectAction;
bluetoothDeviceScript.DiscoveredServiceAction = serviceAction; bluetoothDeviceScript.DiscoveredServiceAction = serviceAction;
bluetoothDeviceScript.DiscoveredCharacteristicAction = characteristicAction; bluetoothDeviceScript.DiscoveredCharacteristicAction = characteristicAction;
//bluetoothDeviceScript.ConnectedDisconnectPeripheralAction = disconnectAction; bluetoothDeviceScript.ConnectedDisconnectPeripheralAction = disconnectAction;
bluetoothDeviceScript.DeviceBleStatusDisconnectedAction = disconnectAction; bluetoothDeviceScript.DeviceBleStatusDisconnectedAction = disconnectAction;
} }
@ -1000,3 +1000,4 @@ public class BluetoothLEHardwareInterface
return uuid; return uuid;
} }
} }

View File

@ -816,10 +816,16 @@ extern "C" {
NSString *message = nil; NSString *message = nil;
if (advertisementData != nil && [advertisementData objectForKey:CBAdvertisementDataManufacturerDataKey] != nil) if (advertisementData != nil && [advertisementData objectForKey:@"kCBAdvDataServiceUUIDs"] != nil)
{ {
NSData* bytes = [advertisementData objectForKey:CBAdvertisementDataManufacturerDataKey]; NSArray* bytes = [advertisementData objectForKey:@"kCBAdvDataServiceUUIDs"];
message = [NSString stringWithFormat:@"DiscoveredPeripheral~%@~%@~%@~%@", identifier, name, RSSI, [UnityBluetoothLE base64StringFromData:bytes length:bytes.length]]; NSString* list = @"";
for (CBUUID* sUUID in bytes)
{
list = [list stringByAppendingString: sUUID.UUIDString.length == 4? [NSString stringWithFormat:@"0000%@-0000-1000-8000-00805F9B34FB",sUUID.UUIDString]:sUUID.UUIDString];
list = [list stringByAppendingString: @","];
}
message = [NSString stringWithFormat:@"DiscoveredPeripheral~%@~%@~%@~%@", identifier, name, RSSI, list];
} }
else if (RSSI != 0 && _rssiOnly) else if (RSSI != 0 && _rssiOnly)
{ {
@ -916,7 +922,7 @@ extern "C" {
{ {
for (CBService *service in peripheral.services) for (CBService *service in peripheral.services)
{ {
NSString *message = [NSString stringWithFormat:@"DiscoveredService~%@~%@", foundPeripheral, [service UUID]]; NSString *message = [NSString stringWithFormat:@"DiscoveredService~%@~%@", foundPeripheral,service.UUID.UUIDString];
UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]); UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]);
[peripheral discoverCharacteristics:nil forService:service]; [peripheral discoverCharacteristics:nil forService:service];
@ -939,7 +945,7 @@ extern "C" {
{ {
for (CBCharacteristic *characteristic in service.characteristics) for (CBCharacteristic *characteristic in service.characteristics)
{ {
NSString *message = [NSString stringWithFormat:@"DiscoveredCharacteristic~%@~%@~%@", foundPeripheral, [service UUID], [characteristic UUID]]; NSString *message = [NSString stringWithFormat:@"DiscoveredCharacteristic~%@~%@~%@", foundPeripheral,service.UUID.UUIDString,characteristic.UUID.UUIDString];
UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]); UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]);
} }
} }
@ -960,7 +966,7 @@ extern "C" {
{ {
if (characteristic.value != nil) if (characteristic.value != nil)
{ {
NSString *message = [NSString stringWithFormat:@"DidUpdateValueForCharacteristic~%@~%@~%@", foundPeripheral, [characteristic UUID], [UnityBluetoothLE base64StringFromData:characteristic.value length:characteristic.value.length]]; NSString *message = [NSString stringWithFormat:@"DidUpdateValueForCharacteristic~%@~%@~%@", foundPeripheral, characteristic.UUID.UUIDString, [UnityBluetoothLE base64StringFromData:characteristic.value length:(int)characteristic.value.length]];
UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]); UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]);
//NSString *message = [UnityBluetoothLE base64StringFromData:characteristic.value length:characteristic.value.length]; //NSString *message = [UnityBluetoothLE base64StringFromData:characteristic.value length:characteristic.value.length];
//UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothData", [message UTF8String] ); //UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothData", [message UTF8String] );
@ -1072,7 +1078,7 @@ extern "C" {
NSString *foundPeripheral = [self findPeripheralName:peripheral]; NSString *foundPeripheral = [self findPeripheralName:peripheral];
if (foundPeripheral != nil) if (foundPeripheral != nil)
{ {
NSString *message = [NSString stringWithFormat:@"DidUpdateNotificationStateForCharacteristic~%@~%@", foundPeripheral, characteristic.UUID]; NSString *message = [NSString stringWithFormat:@"DidUpdateNotificationStateForCharacteristic~%@~%@", foundPeripheral, characteristic.UUID.UUIDString];
UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String] ); UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String] );
} }
} }
@ -1166,7 +1172,7 @@ extern "C" {
{ {
characteristic.value = request.value; characteristic.value = request.value;
NSString *message = [NSString stringWithFormat:@"PeripheralReceivedWriteData~%@~%@", [characteristic UUID], [UnityBluetoothLE base64StringFromData:characteristic.value length:characteristic.value.length]]; NSString *message = [NSString stringWithFormat:@"PeripheralReceivedWriteData~%@~%@", [characteristic UUID], [UnityBluetoothLE base64StringFromData:characteristic.value length:(int)characteristic.value.length]];
UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]); UnitySendMessage ("BluetoothLEReceiver", "OnBluetoothMessage", [message UTF8String]);
success = TRUE; success = TRUE;

View File

@ -11,7 +11,7 @@ using Assets.Scripts.Devices;
public static class App public static class App
{ {
public static string Host = "http://192.168.0.101:5084/"; public static string Host = "http://192.168.0.102:5082/";
public static string AppVersion = Application.version; public static string AppVersion = Application.version;

View File

@ -94,7 +94,7 @@ namespace Assets.Scripts.Devices.Ble
{ {
return; return;
} }
#if !(UNITY_ANDROID || UNITY_IOS)
var device111 = discoveredDevices.Last().Value; var device111 = discoveredDevices.Last().Value;
if (device111 != null && device111.State == Ant.DeviceState.Disconnected) if (device111 != null && device111.State == Ant.DeviceState.Disconnected)
{ {
@ -103,10 +103,8 @@ namespace Assets.Scripts.Devices.Ble
//TODO:取消注释,自动连接设备 //TODO:取消注释,自动连接设备
//Debug.Log("自动连接" + device111.Id); //Debug.Log("自动连接" + device111.Id);
device111.Connect(); device111.Connect();
Thread.Sleep(2000);
} }
} }
#endif
//discoveredDevices.Add(device.Peripheral.Address, new BleDevice(device.Peripheral, hwInterface, device.SensorType)); //discoveredDevices.Add(device.Peripheral.Address, new BleDevice(device.Peripheral, hwInterface, device.SensorType));

View File

@ -124,13 +124,13 @@ namespace Assets.Scripts.Ble
if (uuids != null && uuids.Length > 0) if (uuids != null && uuids.Length > 0)
{ {
foreach (var item in uuids) foreach (var item1 in uuids)
{ {
services.Add(new Guid(item)); services.Add(new Guid(item1));
} }
foreach (var item in ServiceUuids.Services) foreach (var item in ServiceUuids.Services)
{ {
if (!uuids.Contains(item.IdGuid.ToString())) if (!services.Contains(item.IdGuid))
{ {
continue; continue;
} }
@ -207,26 +207,41 @@ namespace Assets.Scripts.Ble
List<BleCharacteristicInfo> characteristilist = new List<BleCharacteristicInfo>(); List<BleCharacteristicInfo> characteristilist = new List<BleCharacteristicInfo>();
public void ConnectPeripheral(BlePeripheralInfo info, Action<IBleWinHwInterface, BlePeripheralInfo, BleResponse> callback) public void ConnectPeripheral(BlePeripheralInfo info, Action<IBleWinHwInterface, BlePeripheralInfo, BleResponse> callback)
{ {
BleResponse s = new BleResponse(); if (!this.callbacks.ContainsKey(info))
s.IsSuccess = true;
s.Error = null;
var self = this;
BluetoothLEHardwareInterface.ConnectToPeripheral(info.Address, (address) =>
{ {
callback?.Invoke(self, info, s); this.callbacks.Add(info, callback);
}, (address, service) => { }
ServicesDiscovered(address, service); if (this.callbacks.Count == 1)
}, (address, service, characteristic) =>
{ {
CharacteristicsDiscovered(address, service, characteristic); BleResponse s = new BleResponse();
}, (address)=> { s.IsSuccess = true;
PeripheralDisconnected(address, info); s.Error = null;
}); var self = this;
BluetoothLEHardwareInterface.ConnectToPeripheral(info.Address, (address) =>
{
callback?.Invoke(self, info, s);
this.callbacks.Remove(info);
if (this.callbacks.Any())
{
this.ConnectPeripheral(this.callbacks.First().Key, this.callbacks.First().Value);
}
}, (address, service) =>
{
ServicesDiscovered(address, service);
}, (address, service, characteristic) =>
{
CharacteristicsDiscovered(address, service, characteristic);
}, (address) =>
{
PeripheralDisconnected(address, info);
});
}
} }
#region #region
//服务发现 //服务发现
private void ServicesDiscovered(string address, string service) private void ServicesDiscovered(string address, string service)
{ {
BluetoothLEHardwareInterface.Log(address+"FOUNDFSERVICE" + service);
if (servicesCallbacks.Where(c => c.Key.Address == address).Any()) if (servicesCallbacks.Where(c => c.Key.Address == address).Any())
{ {
@ -245,6 +260,7 @@ namespace Assets.Scripts.Ble
//特征值发现 //特征值发现
private void CharacteristicsDiscovered(string address, string service, string characteristic) private void CharacteristicsDiscovered(string address, string service, string characteristic)
{ {
BluetoothLEHardwareInterface.Log(address + "发现特征值:" + characteristic);
if (characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).Any()) if (characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).Any())
{ {
var characteristicCallback = characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).FirstOrDefault(); var characteristicCallback = characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).FirstOrDefault();
@ -262,6 +278,12 @@ namespace Assets.Scripts.Ble
//设备主动断开处理 //设备主动断开处理
private void PeripheralDisconnected(string address, BlePeripheralInfo info) private void PeripheralDisconnected(string address, BlePeripheralInfo info)
{ {
var currentCallback = this.callbacks.Where(c => c.Key.MatchAddress(address));
if (currentCallback.Any())
{
this.callbacks.Remove(currentCallback.First().Key);
}
var characteristicCallback = characteristicNotificationCallbacks.Where(c => c.Key.MatchAddress(address)); var characteristicCallback = characteristicNotificationCallbacks.Where(c => c.Key.MatchAddress(address));
if (characteristicCallback.Any()) if (characteristicCallback.Any())
{ {
@ -319,17 +341,27 @@ namespace Assets.Scripts.Ble
//发现服务列表 //发现服务列表
public void DiscoverServices(BlePeripheralInfo peripheral, Action<IBleWinHwInterface, BlePeripheralInfo, BleResponse<List<BleServiceInfo>>> callback) public void DiscoverServices(BlePeripheralInfo peripheral, Action<IBleWinHwInterface, BlePeripheralInfo, BleResponse<List<BleServiceInfo>>> callback)
{ {
this.servicesCallbacks.Add(peripheral, callback); if (!this.servicesCallbacks.ContainsKey(peripheral))
{
this.servicesCallbacks.Add(peripheral, callback);
}
} }
//发现特征值 //发现特征值
public void DiscoverCharacteristic(BleServiceInfo service, CharacteristicsDiscoveredCallback callback) public void DiscoverCharacteristic(BleServiceInfo service, CharacteristicsDiscoveredCallback callback)
{ {
this.characteristicsDiscoveredCallbacks.Add(service, callback); if (!this.characteristicsDiscoveredCallbacks.ContainsKey(service))
{
this.characteristicsDiscoveredCallbacks.Add(service, callback);
}
} }
//订阅特征值 //订阅特征值
public void SubscribeCharacteristic(BleCharacteristicInfo characteristic, Action<IBleWinHwInterface, BleCharacteristicInfo, BleResponse> callback) public void SubscribeCharacteristic(BleCharacteristicInfo characteristic, Action<IBleWinHwInterface, BleCharacteristicInfo, BleResponse> callback)
{ {
this.characteristicNotificationCallbacks.Add(characteristic.Peripheral, callback); if (!this.characteristicNotificationCallbacks.ContainsKey(characteristic.Peripheral))
{
this.characteristicNotificationCallbacks.Add(characteristic.Peripheral, callback);
}
BluetoothLEHardwareInterface.Log("SubscribeCharacteristic" + characteristic.Peripheral.Name + characteristic.Service.ToString() + characteristic.Service.ToString());
BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Peripheral.Address, characteristic.Service.ToString(), characteristic.Id.ToString(), null, (deviceAddress, characteristric, bytes) => BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Peripheral.Address, characteristic.Service.ToString(), characteristic.Id.ToString(), null, (deviceAddress, characteristric, bytes) =>
{ {
if (characteristicReadEvent != null) if (characteristicReadEvent != null)