diff --git a/Assets/Plugins/Android/unityandroidbluetoothlelib.jar b/Assets/Plugins/Android/unityandroidbluetoothlelib.jar index 437b1c98..588e1621 100644 Binary files a/Assets/Plugins/Android/unityandroidbluetoothlelib.jar and b/Assets/Plugins/Android/unityandroidbluetoothlelib.jar differ diff --git a/Assets/Plugins/BluetoothDeviceScript.cs b/Assets/Plugins/BluetoothDeviceScript.cs index f056aeed..102148b9 100644 --- a/Assets/Plugins/BluetoothDeviceScript.cs +++ b/Assets/Plugins/BluetoothDeviceScript.cs @@ -10,14 +10,15 @@ public class BluetoothDeviceScript : MonoBehaviour public List DiscoveredDeviceList; - public Action InitializedAction; + public Action InitializedAction { get; set; } public Action DeinitializedAction; public Action ErrorAction; public Action ServiceAddedAction; + public Action BleStatusChangedAction; public Action StartedAdvertisingAction; public Action StoppedAdvertisingAction; public Action DiscoveredPeripheralAction; - public Action DiscoveredPeripheralWithAdvertisingInfoAction; + public Action DiscoveredPeripheralWithAdvertisingInfoAction; public Action DiscoveredBeaconAction; public Action RetrievedConnectedPeripheralAction; public Action PeripheralReceivedWriteDataAction; @@ -71,6 +72,7 @@ public class BluetoothDeviceScript : MonoBehaviour const string deviceDidUpdateValueForCharacteristic = "DidUpdateValueForCharacteristic"; const string deviceLog = "Log"; const string deviceRequestMtu = "MtuChanged"; + const string bleStatusChanged = "BleStatusChanged"; public void OnBluetoothMessage (string message) { @@ -78,7 +80,17 @@ public class BluetoothDeviceScript : MonoBehaviour { char[] delim = new char[] { '~' }; string[] parts = message.Split (delim); - + if (parts[0].Equals("DeviceStateChanged")) + { + //throw new Exception("test"); + } + if (parts[0].Equals(bleStatusChanged)) + { + if (BleStatusChangedAction != null) + { + BleStatusChangedAction(int.Parse(parts[1])); + } + } for (int i = 0; i < parts.Length; ++i) BluetoothLEHardwareInterface.Log(string.Format("Part: {0} - {1}", i, parts[i])); @@ -152,11 +164,22 @@ public class BluetoothDeviceScript : MonoBehaviour int rssi = 0; if (!int.TryParse (parts[3], out rssi)) rssi = 0; + List uuidList = new List(); + if (parts[4].Contains(",")) + { + string[] s = parts[4].Split(','); + foreach (var o in s) + { + if (!string.IsNullOrEmpty(o)) + { + uuidList.Add(o); + } + } + } + //// parse the base 64 encoded data that is the 5th value + //byte[] bytes = System.Convert.FromBase64String (parts[4]); - // parse the base 64 encoded data that is the 5th value - byte[] bytes = System.Convert.FromBase64String (parts[4]); - - DiscoveredPeripheralWithAdvertisingInfoAction (parts[1], parts[2], rssi, bytes); + DiscoveredPeripheralWithAdvertisingInfoAction (parts[1], parts[2], rssi, uuidList.ToArray()); } } } diff --git a/Assets/Plugins/BluetoothHardwareInterface.cs b/Assets/Plugins/BluetoothHardwareInterface.cs index b7c11ed1..4c80d913 100644 --- a/Assets/Plugins/BluetoothHardwareInterface.cs +++ b/Assets/Plugins/BluetoothHardwareInterface.cs @@ -266,7 +266,7 @@ public class BluetoothLEHardwareInterface #endif } - public static BluetoothDeviceScript Initialize (bool asCentral, bool asPeripheral, Action action, Action errorAction) + public static BluetoothDeviceScript Initialize (bool asCentral, bool asPeripheral, Action action, Action errorAction, Action statusAction) { bluetoothDeviceScript = null; @@ -289,6 +289,7 @@ public class BluetoothLEHardwareInterface if (bluetoothDeviceScript != null) { + bluetoothDeviceScript.BleStatusChangedAction = statusAction; bluetoothDeviceScript.InitializedAction = action; bluetoothDeviceScript.ErrorAction = errorAction; } @@ -475,7 +476,7 @@ public class BluetoothLEHardwareInterface #endif } - public static void ScanForPeripheralsWithServices (string[] serviceUUIDs, Action action = null, Action actionAdvertisingInfo = null, bool rssiOnly = false, bool clearPeripheralList = true, int recordType = 0xFF) + public static void ScanForPeripheralsWithServices (string[] serviceUUIDs, Action action = null, Action actionAdvertisingInfo = null, bool rssiOnly = false, bool clearPeripheralList = true, int recordType = 0xFF) { #if !UNITY_EDITOR_OSX || !EXPERIMENTAL_MACOS_EDITOR if (!Application.isEditor) diff --git a/Assets/Scripts/Devices/Ble/BleDevice.cs b/Assets/Scripts/Devices/Ble/BleDevice.cs index 5b799534..beadb367 100644 --- a/Assets/Scripts/Devices/Ble/BleDevice.cs +++ b/Assets/Scripts/Devices/Ble/BleDevice.cs @@ -123,7 +123,7 @@ namespace Assets.Scripts.Devices.Ble Debug.Log("断开设备" + this.Name); //App.MainDeviceAdapter.PrintStatus(); - + this.State = DeviceState.Disconnected; this.hwInterface.DisconnectPeripheral(this.peripheralInfo, () => { //App.MainDeviceAdapter.PrintStatus(); diff --git a/Assets/Scripts/Devices/Ble/mobile/BleMobileInterface.cs b/Assets/Scripts/Devices/Ble/mobile/BleMobileInterface.cs index 2d45a78a..b18fa19f 100644 --- a/Assets/Scripts/Devices/Ble/mobile/BleMobileInterface.cs +++ b/Assets/Scripts/Devices/Ble/mobile/BleMobileInterface.cs @@ -13,7 +13,7 @@ using UnityEngine; namespace Assets.Scripts.Ble { - public sealed class BleMobileInterface: IBleWinHwInterface + public sealed class BleMobileInterface : IBleWinHwInterface { private static BleMobileInterface hwInterface; private BleMobileThread bleMobileThread; @@ -68,7 +68,7 @@ namespace Assets.Scripts.Ble this.bluetoothStateChanged -= value; } } - + private BleState nativeState; public BleState BleState { @@ -78,7 +78,7 @@ namespace Assets.Scripts.Ble } set { - if(this.nativeState != value) + if (this.nativeState != value) { this.nativeState = value; this.bluetoothStateChanged?.Invoke(this, this.nativeState); @@ -102,58 +102,61 @@ namespace Assets.Scripts.Ble private BleMobileInterface() { bleMobileThread = new BleMobileThread(); + bleMobileThread.ManagerInitialized += BleMobileThread_ManagerInitialized; + bleMobileThread.ManagerStatusChanged += ManagerStatusChanged; bleMobileThread.ScanInfoReceived += WatcherScanInfoReceived; } - private void WatcherScanInfoReceived(BleMobileThread sender, string address, string name, int rssi,string type) + private void BleMobileThread_ManagerInitialized(BleMobileThread thread) { - //if (address != 224160707349234) - //{ - // return; - //} + this.BleState = BleState.On; + } + private void ManagerStatusChanged(BleMobileThread sender, WclBleManagerStatus status) + { + this.BleState = BleMobileInterface.StateFromNativeState(status); + } + + private void WatcherScanInfoReceived(BleMobileThread sender, string address, string name, int rssi,string[] uuids) + { SensorType sensor = SensorType.None; List services = new List(); - if (type.Equals("trainer")) + + if (uuids != null && uuids.Length > 0) { - sensor = SensorType.Trainer; - } - else - { - sensor = SensorType.HeartRate; - } - //if (service != null) - //{ - // services = new List { service.Value }; - // foreach (var item in ServiceUuids.Services) - // { - // if (item.IdGuid != service.Value) - // { - // continue; - // } - // if (item.IdByteArray == ServiceUuids.Ftms) - // { - // sensor = SensorType.Trainer; - // } - // else if (item.IdByteArray == ServiceUuids.HeartRate) - // { - // sensor = SensorType.HeartRate; - // } - // else if (item.IdByteArray == ServiceUuids.CyclingPower) - // { - // sensor = SensorType.Power; - // //sensor = SensorType.Trainer; - // } - // else if (item.IdByteArray == ServiceUuids.CyclingSpeedCadence) - // { - // sensor = SensorType.SpeedCadence; - // } - // else if (item.IdByteArray == ServiceUuids.TacxBle) - // { - // sensor = SensorType.Trainer; - // } - // } - //}; + foreach (var item in uuids) + { + services.Add(new Guid(item)); + } + foreach (var item in ServiceUuids.Services) + { + if (!uuids.Contains(item.IdGuid.ToString())) + { + continue; + } + if (item.IdByteArray == ServiceUuids.Ftms) + { + sensor = SensorType.Trainer; + } + else if (item.IdByteArray == ServiceUuids.HeartRate) + { + sensor = SensorType.HeartRate; + } + else if (item.IdByteArray == ServiceUuids.CyclingPower) + { + sensor = SensorType.Power; + //sensor = SensorType.Trainer; + } + else if (item.IdByteArray == ServiceUuids.CyclingSpeedCadence) + { + sensor = SensorType.SpeedCadence; + } + else if (item.IdByteArray == ServiceUuids.TacxBle) + { + sensor = SensorType.Trainer; + } + } + }; var addressStr = address; if (!pCache.ContainsKey(addressStr)) @@ -174,10 +177,10 @@ namespace Assets.Scripts.Ble //Debug.Log(sensor); //pCache[address.ToString()].SensorType = sensor; - //foreach (var item in services) - //{ - // pCache[addressStr].TryAddService(item); - //} + foreach (var item in uuids) + { + pCache[addressStr].TryAddService(new Guid(item)); + } pCache[addressStr].Index++; if (pCache[addressStr].SensorType == SensorType.Power && pCache[addressStr].Services.Any(s => s.Equals(ServiceUuids.Get(ServiceUuids.TacxBle).IdGuid))) @@ -198,7 +201,6 @@ namespace Assets.Scripts.Ble { _discoveredCallback?.Invoke(pCache[addressStr]); } - this.BleState = BleState.On; } //private WclBleGattThread SetUpGattClient(BlePeripheralInfo peripheral) @@ -220,21 +222,6 @@ namespace Assets.Scripts.Ble List characteristilist = new List(); public void ConnectPeripheral(BlePeripheralInfo info, Action callback) { - //this.callbacks.Add(info, callback); - //WclBleGattThread wclBleGattThread = this.wclBleMainThread.GetGattThread(info); - - //if (wclBleGattThread == null) - //{ - - // wclBleGattThread = this.SetUpGattClient(info); - // this.ConnectInternal(wclBleGattThread); - // return; - //} - //else - //{ - // this.ConnectInternal(wclBleGattThread); - //}\ - BleResponse s = new BleResponse(); s.IsSuccess = true; s.Error = null; @@ -243,48 +230,49 @@ namespace Assets.Scripts.Ble { callback?.Invoke(self, info, s); }, (address, service) => { - var l = servicelist.Where(c => c.Id.ToString().Equals(service)).ToList(); - if (l.Count == 0) + if (servicesCallbacks.Where(c => c.Key.Address == address).Any()) { - servicelist.Add(new WinBleServiceInfo(info,new Guid(service))); - } - }, (address, service, characteristic) => - { - var l = characteristilist.Where(c => c.Id.ToString().Equals(characteristic)).ToList(); - if (l.Count == 0) - { - //characteristilist.Add(new BleCharacteristicInfo new WinBleServiceInfo(info, new Guid(characteristic))); + + var serviceCallback = servicesCallbacks.Where(c => c.Key.Address == address).FirstOrDefault(); + List servicelist = new List(); + servicelist.Add(new WinBleServiceInfo(serviceCallback.Key,new Guid(service))); + BleResponse> response = new BleResponse> + { + IsSuccess = true, + Error = null, + Data = servicelist, + }; + serviceCallback.Value?.Invoke(this, serviceCallback.Key, response); } + }, (address, service, characteristic) => + { + if (characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).Any()) + { + var characteristicCallback = characteristicsDiscoveredCallbacks.Where(c => c.Key.Peripheral.Address == address).FirstOrDefault(); + List characteristiclist = new List(); + characteristiclist.Add(new WinBleCharacteristicInfo(new Guid(characteristic), new WinBleServiceInfo(characteristicCallback.Key.Peripheral, new Guid(service)),0)); + BleResponse> response = new BleResponse> + { + IsSuccess = true, + Error = null, + Data = characteristiclist, + }; + characteristicCallback.Value?.Invoke(this, characteristicCallback.Key, response); + } }, null); } - private void ConnectInternal(WclBleGattThread gattClient) - { - //Task.Run(() => - //{ - //int num = gattClient.Connect(); - //Debug.Log("连接设备返回" + num); - - - //}); - } - + //设备断开连接 public void DisconnectPeripheral(BlePeripheralInfo peripheral, Action callback) { - //var gattThread = this.wclBleMainThread.GetGattThread(peripheral); - //if(gattThread != null && gattThread.CanLoadWork) - //{ - // this.callbacks.Remove(peripheral); - // this.servicesCallbacks.Remove(peripheral); - // this.characteristicNotificationCallbacks.Remove(peripheral); - - // this.disconnectedCallback.Add(peripheral, callback); - // gattThread.Discounect(); - //} + BluetoothLEHardwareInterface.DisconnectPeripheral(peripheral.Address, (address) => + { + //peripheralDisconnectedEvent(this, peripheral, null, true); + callback?.Invoke(); + }); } - public static BleMobileInterface GetInterface() { if(hwInterface == null) @@ -294,223 +282,73 @@ namespace Assets.Scripts.Ble return hwInterface; } - + //扫描设备 public void StartScan(Action discoveredCallBack) { pCache.Clear(); _discoveredCallback = discoveredCallBack; bleMobileThread.StartWatcher(); } - - private void ManagerStatusChanged(WclBleMainThread sender, WclBleManagerStatus status) - { - //this.BleState = BleMobileInterface.StateFromNativeState(status); - //Debug.Log("win hw:" + status); - - } - - private void GattConnected(WclBleGattThread gattClient, BleResponse response) - { - //Debug.Log($"gatt connected { response.ToString() }"); - //if (!response.IsSuccess) - //{ - // gattClient.Stop(); - - // this.callbacks[gattClient.Peripheral].Invoke(this, gattClient.Peripheral, response); - // this.callbacks.Remove(gattClient.Peripheral); - // return; - //} - //this.callbacks[gattClient.Peripheral].Invoke(this, gattClient.Peripheral, response); - //this.callbacks.Remove(gattClient.Peripheral); - } - - private void CleanUpPeripheral(BlePeripheralInfo peripheralInfo) - { - //this.callbacks.Clear() - } - - private void GattDisconnected(WclBleGattThread gattClient, BleResponse response) - { - //Debug.Log($"gatt disconnected { gattClient.Peripheral.Name }"); - - //this.callbacks.Remove(gattClient.Peripheral); - //this.servicesCallbacks.Remove(gattClient.Peripheral); - //this.characteristicNotificationCallbacks.Remove(gattClient.Peripheral); - ////App.MainDeviceAdapter.PrintStatus(); - - //var manualDisconnect = disconnectedCallback.ContainsKey(gattClient.Peripheral); - //this.peripheralDisconnectedEvent(this, gattClient.Peripheral, response, manualDisconnect); - - ////App.MainDeviceAdapter.PrintStatus(); - //if (disconnectedCallback.ContainsKey(gattClient.Peripheral)) - //{ - // disconnectedCallback[gattClient.Peripheral].Invoke(); - // disconnectedCallback.Remove(gattClient.Peripheral); - //} - ////this.pCache.Remove(gattClient.Peripheral.Address); - - - - } - private void GattServicesDiscovered(WclBleGattThread gattClient, BleResponse> response) - { - ////Debug.Log("services discovered"); - ////this.callbacks[gattClient.Peripheral].Invoke(this, gattClient.Peripheral, response); - - ////foreach (var item in response.Data) - ////{ - //// Debug.Log(item.ToString()); - ////} - - //if (this.servicesCallbacks.ContainsKey(gattClient.Peripheral)) - //{ - // this.servicesCallbacks[gattClient.Peripheral].Invoke(this, gattClient.Peripheral, response); - //} - } - - private void GattCharacteristicsDiscovered(WclBleGattThread gattClient, BleServiceInfo service, BleResponse> response) - { - //Debug.Log("characteristics discovered"); - - if (this.characteristicsDiscoveredCallbacks.ContainsKey(service)) - { - this.characteristicsDiscoveredCallbacks[service].Invoke(this, service, response); - } - } - - private void GattCharacteristicSubscribed(WclBleGattThread gattClient, BleCharacteristicInfo characteristic, BleResponse response) - { - ////Debug.Log("characteristics subscribed"); - //if (this.characteristicNotificationCallbacks.ContainsKey(gattClient.Peripheral)) - //{ - // this.characteristicNotificationCallbacks[gattClient.Peripheral].Invoke(this, characteristic, response); - //} - } - private void GattCharacteristicRead(WclBleGattThread gattClient, BleCharacteristicInfo characteristic, BleResponse response) - { - //Debug.Log("characteristic read"); - - //if (this.characteristicReadCallbacks.ContainsKey(characteristic)) - //{ - // this.characteristicReadCallbacks[characteristic].Invoke(this, characteristic, response); - // this.characteristicReadCallbacks.Remove(characteristic); - //} - - //this.characteristicReadEvent.Invoke(this, characteristic, response); - } - - private void GattCharacteristicWrote(WclBleGattThread gattClient, BleCharacteristicInfo characteristic, BleResponse response) - { - Debug.Log("characteristic wrote"); - } - private void GattCharacteristicChanged(WclBleGattThread gattClient, BleCharacteristicInfo characteristic, BleResponse response) - { - ////Debug.Log("characteristic changed"); - //if(this.wclBleMainThread.GetGattThread(characteristic.Peripheral) != null) - //{ - // this.characteristicReadEvent.Invoke(this, characteristic, response); - //} - } - + //发现服务列表 public void DiscoverServices(BlePeripheralInfo peripheral, Action>> callback) { this.servicesCallbacks.Add(peripheral, callback); - if (servicelist.Count > 0) - { - BleResponse> response = new BleResponse> - { - IsSuccess = true, - Error = null, - Data = (List)servicelist, - }; - - callback.Invoke(this, peripheral, response); - return; - } } - + //发现特征值 public void DiscoverCharacteristic(BleServiceInfo service, CharacteristicsDiscoveredCallback callback) { - //WclBleGattThread gattThread = this.wclBleMainThread.GetGattThread(service.Peripheral); - //if(gattThread == null) - //{ - // return; - //} - //if (!this.characteristicsDiscoveredCallbacks.ContainsKey(service)) - //{ - // this.characteristicsDiscoveredCallbacks.Add(service, callback); - //} - //int num = gattThread.DiscoverCharacteristics(service); - //if (WclBleErrors.IsSuccessCode(num)) - //{ - // return; - //} - //BleResponse> response = new BleResponse> - //{ - // IsSuccess = false, - // Error = new BleHwInterfaceError(new int?(num), "WclBleGattClientErrorDomain", string.Format("Error discovering characteristics - {0}", num)) - //}; - //this.GattCharacteristicsDiscovered(gattThread, service, response); + this.characteristicsDiscoveredCallbacks.Add(service, callback); } - + //订阅特征值 public void SubscribeCharacteristic(BleCharacteristicInfo characteristic, Action callback) { - //WclBleGattThread gattThread = this.wclBleMainThread.GetGattThread(characteristic.Peripheral); - - //this.characteristicNotificationCallbacks.Add(gattThread.Peripheral, callback); - //int num = gattThread.SubscribeCharacteristic(characteristic); - //if (WclBleErrors.IsSuccessCode(num)) - //{ - // return; - //} - //BleResponse> response = new BleResponse> - //{ - // IsSuccess = false, - // Error = new BleHwInterfaceError(new int?(num), "WclBleGattClientErrorDomain", string.Format("Error subscribing characteristic - {0}", num)) - //}; - //this.GattCharacteristicSubscribed(gattThread, characteristic, response); + this.characteristicNotificationCallbacks.Add(characteristic.Peripheral, callback); + BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Peripheral.Address, characteristic.Service.ToString(), characteristic.Id.ToString(), null, (deviceAddress, characteristric, bytes) => + { + if (characteristicReadEvent != null) + { + BleResponse response = new BleResponse + { + IsSuccess = true, + Error = null, + Data = bytes, + }; + characteristicReadEvent.Invoke(this, characteristic, response); + } + }); } - + //写入特征值 public void WriteCharacteristic(BleCharacteristicInfo characteristic, byte[] data) { - //var gattThread = this.wclBleMainThread.GetGattThread(characteristic.Peripheral); - //if(gattThread == null) - //{ - // return; - //} + BluetoothLEHardwareInterface.WriteCharacteristic(characteristic.Peripheral.Address, characteristic.Service.Id.ToString(), characteristic.Id.ToString(), data, data.Length, false, (characteristicUUID) => { - //int num = gattThread.WriteCharacteristic(characteristic, data); - //if (WclBleErrors.IsSuccessCode(num)) - //{ - // Debug.Log("设置命令成功"); - // return; - //} + BluetoothLEHardwareInterface.Log("Write Succeeded"); + }); } public void Dispose() { - //this.wclBleMainThread.ManagerStatusChanged -= ManagerStatusChanged; - //this.wclBleMainThread.ScanInfoReceived -= WatcherScanInfoReceived; - //this.wclBleMainThread.Stop(); - //this.wclBleMainThread = null; - //hwInterface = null; - //pCache.Clear(); + bleMobileThread.ManagerInitialized -= BleMobileThread_ManagerInitialized; + bleMobileThread.ManagerStatusChanged -= ManagerStatusChanged; + bleMobileThread.ScanInfoReceived -= WatcherScanInfoReceived; + bleMobileThread.Stop(); + bleMobileThread = null; + hwInterface = null; + pCache.Clear(); } public void ReadCharacteristic(BleCharacteristicInfo characteristic, CharacteristicReadCallback callback) { - //WclBleGattThread gattThread = this.wclBleMainThread.GetGattThread(characteristic.Peripheral); - //if(gattThread == null) - //{ - // return; - //} - //this.characteristicReadCallbacks.Add(characteristic, callback); - //int num = gattThread.ReadCharacteristicValue(characteristic); - //if (WclBleErrors.IsSuccessCode(num)) - //{ - // return; - //} + BluetoothLEHardwareInterface.ReadCharacteristic(characteristic.Peripheral.Address, characteristic.Service.Id.ToString(), characteristic.Id.ToString(), (c, bytes) => { + BleResponse response = new BleResponse + { + IsSuccess = true, + Error = null, + Data = bytes, + }; + callback?.Invoke(this, characteristic, response); + }); } private static BleState StateFromNativeState(WclBleManagerStatus status) diff --git a/Assets/Scripts/Devices/Ble/mobile/BleMobileThread.cs b/Assets/Scripts/Devices/Ble/mobile/BleMobileThread.cs index 3274d7a5..a9db13d0 100644 --- a/Assets/Scripts/Devices/Ble/mobile/BleMobileThread.cs +++ b/Assets/Scripts/Devices/Ble/mobile/BleMobileThread.cs @@ -3,64 +3,78 @@ using System.Timers; namespace Assets.Scripts.Devices.Ble { - public class BleMobileThread + internal class BleMobileThread { - public delegate void WclAdvertisementPacketDelegate(BleMobileThread sender, string address, string name, int rssi, string type); - public BleMobileThread.WclAdvertisementPacketDelegate ScanInfoReceived; - private Timer timer { get; set; } - public BleMobileThread() { - //初始蓝牙 - BluetoothLEHardwareInterface.Initialize(true, false, () => { - - }, - (error) => { - - BluetoothLEHardwareInterface.Log("Error: " + error); - - if (error.Contains("Bluetooth LE Not Enabled")) - BluetoothLEHardwareInterface.BluetoothEnable(true); - }); - } - bool startScan = true; - public void StartWatcher() { - //if (timer == null) - //{ - // timer = new Timer(); - // timer.Interval = 500; - // timer.Elapsed += Timer_Elapsed; - //} - //if (!timer.Enabled) - //{ - // timer.Start(); - //} "0000180D-0000-1000-8000-00805F9B34FB" - var ss = new string[] {"00001826-0000-1000-8000-00805F9B34FB","0000180D-0000-1000-8000-00805F9B34FB", "6e40fec1-b5a3-f393-e0a9-e50e24dcca9e" }; - BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ss, (s,a)=> { - BluetoothLEHardwareInterface.Log(s); - }, (address, name, rssi, bytes) => - { - ScanInfoReceived?.Invoke(this, address, name, rssi,"trainer"); - }, true); - } - - public void StopWatcher() + public delegate void WclInitializedDelegate(BleMobileThread sender); + private BleMobileThread.WclInitializedDelegate managerInitialized; + public event BleMobileThread.WclInitializedDelegate ManagerInitialized { - if (timer.Enabled) + add { - timer.Stop(); + this.managerInitialized += value; + } + remove + { + this.managerInitialized -= value; } } - private void Timer_Elapsed(object sender, ElapsedEventArgs e) + public delegate void WclAdvertisementPacketDelegate(BleMobileThread sender, string address, string name, int rssi, string[] uuids); + public BleMobileThread.WclAdvertisementPacketDelegate ScanInfoReceived; + + internal delegate void ManagerStatusChangedCallback(BleMobileThread thread, WclBleManagerStatus status); + private BleMobileThread.ManagerStatusChangedCallback managerStatusChanged; + public event BleMobileThread.ManagerStatusChangedCallback ManagerStatusChanged { - //if (startScan) - //{ - // startScan = false; - // BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null, null,(address, name, rssi, bytes) => - // { + add + { + this.managerStatusChanged += value; + } + remove + { + this.managerStatusChanged -= value; + } + } - // ScanInfoReceived?.Invoke(this, address, name, rssi); - // }, true); - //} - } + internal BleMobileThread() { + var self = this; + //初始蓝牙 + BluetoothLEHardwareInterface.Initialize(true, false, () => { + managerInitialized?.Invoke(self); + }, + (error) => { + BluetoothLEHardwareInterface.Log("Error: " + error); + if (error.Contains("Bluetooth LE Not Enabled")) + BluetoothLEHardwareInterface.BluetoothEnable(true); + }, (status) => { + + var statusEnum = WclBleManagerStatus.RadioOn; + switch (status) + { + case 13: + statusEnum = WclBleManagerStatus.RadioOff; + break; + case 11: + statusEnum = WclBleManagerStatus.RadioOn; + break; + } + if (managerStatusChanged != null) + { + managerStatusChanged.Invoke(self, statusEnum); + } + }); + } + + public void StartWatcher() { + BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null, (address, name, rssi, bytes) => + { + ScanInfoReceived?.Invoke(this, address, name, rssi, bytes); + }, true); + } + + public void Stop() + { + BluetoothLEHardwareInterface.StopScan(); + } } } diff --git a/Assets/Scripts/Scenes/Ride/Scripts/PlayerController.cs b/Assets/Scripts/Scenes/Ride/Scripts/PlayerController.cs index 94388d22..d342a727 100644 --- a/Assets/Scripts/Scenes/Ride/Scripts/PlayerController.cs +++ b/Assets/Scripts/Scenes/Ride/Scripts/PlayerController.cs @@ -56,7 +56,7 @@ namespace Assets.Scenes.Ride.Scripts weight = App.CurrentUser.Weight; bicycleWeight = App.CurrentUser.BicycleWeight; //#if UNITY_EDITOR - power = 500; + //power = 500; //#endif mainController.TrackResistance(currentSlope * App.RideSetting.Sensitivity / 100); }