public override void DiscoveredService(CBPeripheral peripheral, NSError error) { var descriptor = peripheral.ToDeviceDescriptor(); if (error != null) { _deviceManager.HandleDeviceCommunicationDiscoveryServiceError(descriptor, error.LocalizedFailureReason, (d) => { _centralManager.CancelPeripheralConnection(peripheral); }); return; } CBUUID uuidCharacteristic = CBUUID.FromString(_tracingInformation.CharacteristicId); CBUUID uuidService = CBUUID.FromString(_tracingInformation.ServiceId); var service = peripheral.Services.FirstOrDefault(x => x.UUID == uuidService); if (service != null) { _deviceManager.HandleDeviceCommunicationDiscoveredService(descriptor, (d) => { peripheral.DiscoverCharacteristics(new[] { uuidCharacteristic }, service); }); } else { _deviceManager.HandleIncorrectDevice(descriptor); _centralManager.CancelPeripheralConnection(peripheral); } }
protected override Task <IEnumerable <ICharacteristic> > GetCharacteristicsNativeAsync() { //TODO: review: is this correct? Event was not used, yet var tcs = new TaskCompletionSource <IEnumerable <ICharacteristic> >(); EventHandler <CBServiceEventArgs> handler = null; handler = (sender, args) => { _device.DiscoveredCharacteristic -= handler; if (args.Error == null) { var characteristics = _service.Characteristics.Select(characteristic => new Characteristic(characteristic, _device)); tcs.TrySetResult(characteristics); } else { Trace.Message("Could not discover characteristics: {0}", args.Error.Description); // TODO: use proper exception tcs.TrySetException(new Exception()); } }; _device.DiscoveredCharacteristic += handler; _device.DiscoverCharacteristics(_service); return(tcs.Task); }
public async Task <CBCharacteristic[]> GetCharacteristics(CBPeripheral peripheral, CBService service, int scanTime) { peripheral.DiscoverCharacteristics(service); await Task.Delay(scanTime); return(service.Characteristics); }
private void HandleDiscoveredService(object sender, NSErrorEventArgs e) { CBPeripheral peripheral = sender as CBPeripheral; if (peripheral == null || peripheral != Peripheral) return; int servicesCount = peripheral.Services.Length; peripheral.DiscoveredCharacteristic += (o, es) => { servicesCount--; if (servicesCount == 0) { IsServiceDiscovered = true; if (e.Error == null) { OnServicesDiscovered(this, new BleServicesDiscoveredEventArgs(BleGattOperationState.Success)); ConnectionState = BleConnectionState.ConnectedWithServices; } else { OnServicesDiscovered(this, new BleServicesDiscoveredEventArgs(BleGattOperationState.Failure)); } } }; foreach (CBService service in peripheral.Services) { peripheral.DiscoverCharacteristics(service); } }
protected override Task <IList <ICharacteristic> > GetCharacteristicsNativeAsync() { return(TaskBuilder.FromEvent <IList <ICharacteristic>, EventHandler <CBServiceEventArgs> >( execute: () => _device.DiscoverCharacteristics(_service), getCompleteHandler: (complete, reject) => (sender, args) => { if (args.Error != null) { reject(new Exception($"Discover characteristics error: {args.Error.Description}")); } else if (args.Service?.Characteristics == null) { reject(new Exception($"Discover characteristics error: returned list is null")); } else { var characteristics = args.Service.Characteristics .Select(characteristic => new Characteristic(characteristic, _device, this)) .Cast <ICharacteristic>().ToList(); complete(characteristics); } }, subscribeComplete: handler => _device.DiscoveredCharacteristic += handler, unsubscribeComplete: handler => _device.DiscoveredCharacteristic -= handler)); }
Task <IReadOnlyList <GattCharacteristic> > PlatformGetCharacteristics() { TaskCompletionSource <IReadOnlyList <GattCharacteristic> > tcs = new TaskCompletionSource <IReadOnlyList <GattCharacteristic> >(); CBPeripheral peripheral = Device; void handler(object sender, CBServiceEventArgs args) { peripheral.DiscoveredCharacteristic -= handler; if (args.Error != null) { tcs.SetException(new Exception(args.Error.ToString())); } List <GattCharacteristic> characteristics = new List <GattCharacteristic>(); foreach (CBCharacteristic cbcharacteristic in _service.Characteristics) { characteristics.Add(new GattCharacteristic(this, cbcharacteristic)); } tcs.SetResult(characteristics.AsReadOnly()); } peripheral.DiscoveredCharacteristic += handler; peripheral.DiscoverCharacteristics(_service); return(tcs.Task); }
public override async void DiscoveredService(CBPeripheral peripheral, NSError error) { try { if (error == null) { var services = new List <GattService>(); if (_peripheral.Services != null) { foreach (var service in _peripheral.Services) { _discoverCompletionSource = new TaskCompletionSource <IEnumerable <IGattCharacteristic> >(TaskCreationOptions.RunContinuationsAsynchronously); _peripheral.DiscoverCharacteristics(service); var result = await _discoverCompletionSource.Task; _discoverCompletionSource = null; if (result != null) { services.Add(new GattService(service, result)); } else { lock (_lock) { DisconnectInternal(); _connectCompletionSource?.SetResult(null); } return; } } } lock (_lock) { State = BluetoothLEDeviceState.Connected; _connectCompletionSource?.SetResult(services); return; } } else { lock (_lock) { DisconnectInternal(); _connectCompletionSource?.SetResult(null); } } } catch (Exception) { lock (_lock) { DisconnectInternal(); _connectCompletionSource?.SetResult(null); } } }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { System.Console.WriteLine ("Discovered a service"); foreach (var service in peripheral.Services) { Console.WriteLine (service.ToString ()); peripheral.DiscoverCharacteristics (service); } }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { _parent.OnStatusUpdated("Discovering characteristics"); _peripheral = peripheral; var service = peripheral.GetService(ServiceUuid); peripheral.DiscoverCharacteristics(service); }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { // Discover all the characteristics of the services contained in peripheral.Services foreach (var service in peripheral.Services) { peripheral.DiscoverCharacteristics(service); } }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { System.Console.WriteLine("Discovered a service"); foreach (var service in peripheral.Services) { Console.WriteLine(service.ToString()); peripheral.DiscoverCharacteristics(service); } }
public void DiscoverCharacteristicsFor(Service service) { // The event should probably have been called "DiscoveredCharacteristics" // instead of "DiscoveredCharacteristic" - at least it seems like it // will only be called once per service. connectedCbPeripheral.DiscoveredCharacteristic += DiscoveredCharacteristicsForService; var cbService = FindService(service); connectedCbPeripheral.DiscoverCharacteristics(cbService); }
public void SetPeripheralAndService(CBPeripheral peripheral, CBService service) { connectedPeripheral = peripheral; connectedPeripheral.DiscoveredCharacteristic += (sender, e) => { HandleDiscoveredCharacteristic((CBPeripheral)sender, service); }; // when a descriptor is dicovered, reload the table. connectedPeripheral.DiscoveredDescriptor += HandleDiscoveredDescriptor; // discover the charactersistics connectedPeripheral.DiscoverCharacteristics(service); }
public void SetPeripheralAndService (CBPeripheral peripheral, CBService service) { connectedPeripheral = peripheral; connectedPeripheral.DiscoveredCharacteristic += (sender, e) => { HandleDiscoveredCharacteristic((CBPeripheral)sender, service); }; // when a descriptor is dicovered, reload the table. connectedPeripheral.DiscoveredDescriptor += HandleDiscoveredDescriptor; // discover the charactersistics connectedPeripheral.DiscoverCharacteristics(service); }
public override void DiscoveredIncludedService(CBPeripheral peripheral, CBService service, NSError error) { client.completedInc += 1; peripheral.Delegate = this; if (service.IncludedServices != null) { client.serviceObjects.AddRange(service.IncludedServices); client.charCallCount += service.IncludedServices.Count(); foreach (var s in service.IncludedServices) { peripheral.DiscoverCharacteristics(null, s); } } client.allDiscovered(); }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { if (disposed) { return; } foreach (var service in peripheral.Services) { if (service.UUID == PeripheralUUID) { peripheral.DiscoverCharacteristics(service); } } }
public async partial Task <IEnumerable <GattCharacteristic> > GetCharacteristicsAsync(IEnumerable <Guid>?uuids) { var cbUuids = uuids?.Select(x => CBUUID.FromString(x.ToString())).ToArray(); var errorAwaiter = @delegate.DiscoveredCharacteristicObservable.FirstAsync(x => x.service == service).GetAwaiter(); peripheral.DiscoverCharacteristics(cbUuids, service); var(_, error) = await errorAwaiter; if (error is not null) { throw new NSErrorException(error); } return(service.Characteristics?.Select(x => new GattCharacteristic(peripheral, @delegate, this, x)) ?? Enumerable.Empty <GattCharacteristic>()); }
public override void DiscoveredService(CBPeripheral peripheral, NSError error) { peripheral.Delegate = this; if (peripheral.Services != null) { client.serviceObjects.AddRange(peripheral.Services); client.charCallCount = client.serviceObjects.Count; client.incCallCount = client.serviceObjects.Count; client.descCallCount = 0; foreach (var service in peripheral.Services) { peripheral.DiscoverIncludedServices(null, service); peripheral.DiscoverCharacteristics(null, service); } } }
protected override Task <IList <ICharacteristic> > GetCharacteristicsNativeAsync() { var exception = new Exception($"Device '{Device.Id}' disconnected while fetching characteristics for service with {Id}."); return(TaskBuilder.FromEvent <IList <ICharacteristic>, EventHandler <CBServiceEventArgs>, EventHandler <CBPeripheralErrorEventArgs> >( execute: () => { if (_device.State != CBPeripheralState.Connected) { throw exception; } _device.DiscoverCharacteristics(_service); }, getCompleteHandler: (complete, reject) => (sender, args) => { if (args.Error != null) { reject(new Exception($"Discover characteristics error: {args.Error.Description}")); } else if (args.Service?.Characteristics == null) { reject(new Exception($"Discover characteristics error: returned list is null")); } else { var characteristics = args.Service.Characteristics .Select(characteristic => new Characteristic(characteristic, _device, this, _bleCentralManagerDelegate)) .Cast <ICharacteristic>().ToList(); complete(characteristics); } }, subscribeComplete: handler => _device.DiscoveredCharacteristic += handler, unsubscribeComplete: handler => _device.DiscoveredCharacteristic -= handler, getRejectHandler: reject => ((sender, args) => { if (args.Peripheral.Identifier == _device.Identifier) { reject(exception); } }), subscribeReject: handler => _bleCentralManagerDelegate.DisconnectedPeripheral += handler, unsubscribeReject: handler => _bleCentralManagerDelegate.DisconnectedPeripheral -= handler)); }
static void OnPeripheralDiscoveredService(object sender, NSErrorEventArgs e) { if (e.Error != null) { Console.WriteLine(e.Error); peripheral.DiscoverServices(); return; } foreach (CBService s in (sender as CBPeripheral).Services) { Console.WriteLine("Discovered service {0}", s); peripheral.DiscoverCharacteristics(s); } }
/// <summary> /// Occurs when a new service is discovered for the peripheral /// </summary> /// <param name="peripheral">Peripheral.</param> /// <param name="error">Error.</param> public override void DiscoveredService(CBPeripheral peripheral, NSError error) { if (monitor.disposed) { return; } foreach (var service in peripheral.Services) { // Right now limited to POC and Zephyr services if (service.UUID == BluetoothIdentifiers.POCServiceUUID || service.UUID == BluetoothIdentifiers.ZephyrServiceUUID) //GetCBUUID(S_PERIPHERAL_UUID)) { peripheral.DiscoverCharacteristics(service); } Console.WriteLine($"discovered service: {service.UUID}"); } }
public void DiscoveredService(CBPeripheral peripheral, NSError error) { Debug.WriteLine($"Peripheral_DiscoveredService: {peripheral.Name}"); CBService foundService = null; foreach (var service in peripheral.Services) { if (service.UUID == OWBoard.ServiceUUID.ToCBUUID()) { foundService = service; break; } } if (foundService != null) { _service = foundService; _peripheral.DiscoverCharacteristics(_service); } }
private async Task MapDevice(Device device, CBPeripheral nativeDevice) { nativeDevice.DiscoveredService += nativeDevice_DiscoveredService; nativeDevice.DiscoverServices(); await Task.Run(() => _servicesDiscovered.WaitOne(TimeSpan.FromSeconds(10))); nativeDevice.DiscoveredService -= nativeDevice_DiscoveredService; _servicesDiscovered.Reset(); foreach (var cbService in nativeDevice.Services) { nativeDevice.DiscoveredCharacteristic += nativeDevice_DiscoveredCharacteristic; nativeDevice.DiscoverCharacteristics(cbService); await Task.Run(() => _characteristicsDiscovered.WaitOne(TimeSpan.FromSeconds(10))); nativeDevice.DiscoveredCharacteristic -= nativeDevice_DiscoveredCharacteristic; _characteristicsDiscovered.Reset(); var service = new Service() { Id = BluetoothConverter.ConvertBluetoothLeUuid(cbService.UUID.Uuid), Device = device, Characteristics = new List <Characteristic>() }; foreach (var cbCharacteristic in cbService.Characteristics) { var characteristic = await ConvertCharacteristic(cbCharacteristic); characteristic.Service = service; service.Characteristics.Add(characteristic); } service.Device = device; device.Services.Add(service); } }
public void DiscoverCharacteristics(IBLEService service) { nativePeripheral.DiscoverCharacteristics(service.NativeService as CBService); }
internal Task <List <IBLECharacteristic> > GetCharacteristicsAsync(CBPeripheral peripheral, TaskCompletionSource <List <IBLECharacteristic> > characteristicDiscoveryTCS) { characteristicDiscoveryTCS = new TaskCompletionSource <List <IBLECharacteristic> >(); peripheral.DiscoverCharacteristics(_nativeService); return(characteristicDiscoveryTCS.Task); }
/// <summary> /// Discovers the characteristics for the services. /// </summary> public void DiscoverCharacteristics() { _peripheral.DiscoverCharacteristics(NativeService); }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { peripheral.DiscoveredService += (sender, e) => { try { if (e.Error == null) { // discover characteristics for newly discovered services foreach (CBService service in peripheral.Services) { if (service.UUID.Equals(_probe.DeviceIdService.UUID)) { peripheral.DiscoverCharacteristics(new CBUUID[] { _probe.DeviceIdCharacteristic.UUID }, service); } } } else { throw new Exception("Error while discovering service: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while discovering characteristics: " + ex.Message, LoggingLevel.Normal, GetType()); DisconnectPeripheral(central, peripheral); } }; peripheral.DiscoveredCharacteristic += (sender, e) => { try { if (e.Error == null) { // read device ID for newly discovered characteristics foreach (CBCharacteristic characteristic in e.Service.Characteristics) { if (characteristic.UUID.Equals(_probe.DeviceIdCharacteristic.UUID)) { peripheral.ReadValue(characteristic); } } } else { throw new Exception("Error while discovering characteristic: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading device ID value from peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); DisconnectPeripheral(central, peripheral); } }; peripheral.UpdatedCharacterteristicValue += (sender, e) => { try { if (e.Error == null) { // characteristic should have a non-null value if (e.Characteristic.Value == null) { throw new Exception("Null updated value for characteristic."); } else { string encounteredDeviceId = Encoding.UTF8.GetString(e.Characteristic.Value.ToArray()); DeviceIdEncountered?.Invoke(this, new BluetoothDeviceProximityDatum(DateTime.UtcNow, encounteredDeviceId)); } } else { throw new Exception("Error while updating characteristic value: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reporting encountered device ID: " + ex.Message, LoggingLevel.Normal, GetType()); } finally { DisconnectPeripheral(central, peripheral); } }; try { central.ConnectPeripheral(peripheral); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while connecting to peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); } }
// TODO: decide how to Interface this, right now it's only in the iOS implementation public void DiscoverCharacteristics() { // TODO: need to raise the event and listen for it. ParentDevice.DiscoverCharacteristics(NativeService); }
public override void DiscoveredService (CBPeripheral peripheral, NSError error) { if (disposed) { return; } foreach (var service in peripheral.Services) { if (service.UUID == PeripheralUUID) { peripheral.DiscoverCharacteristics (service); } } }
public async Task <List <Tuple <string, DateTimeOffset> > > ReadPeripheralCharacteristicValuesAsync(CancellationToken cancellationToken) { List <Tuple <string, DateTimeOffset> > characteristicValueTimestamps = new List <Tuple <string, DateTimeOffset> >(); // copy list of peripherals to read. note that the same device may be reported more than once. read each once. List <Tuple <CBPeripheral, CBCentralManager, DateTimeOffset> > peripheralCentralTimestamps; lock (_peripheralCentralTimestamps) { peripheralCentralTimestamps = _peripheralCentralTimestamps.GroupBy(peripheralCentralTimestamp => peripheralCentralTimestamp.Item1.Identifier).Select(group => group.First()).ToList(); } _probe.ReadAttemptCount += peripheralCentralTimestamps.Count; // read characteristic from each peripheral foreach (Tuple <CBPeripheral, CBCentralManager, DateTimeOffset> peripheralCentralTimestamp in peripheralCentralTimestamps) { if (cancellationToken.IsCancellationRequested) { break; } TaskCompletionSource <string> readCompletionSource = new TaskCompletionSource <string>(); CBPeripheral peripheral = peripheralCentralTimestamp.Item1; CBCentralManager central = peripheralCentralTimestamp.Item2; DateTimeOffset timestamp = peripheralCentralTimestamp.Item3; #region discover services peripheral.DiscoveredService += (sender, e) => { try { if (e.Error == null) { SensusServiceHelper.Get().Logger.Log("Discovered services. Discovering characteristics...", LoggingLevel.Normal, GetType()); // discover characteristics for newly discovered services that match the one we're looking for foreach (CBService service in peripheral.Services) { if (service.UUID.Equals(_service.UUID)) { peripheral.DiscoverCharacteristics(new CBUUID[] { _characteristic.UUID }, service); } } } else { throw new Exception("Error while discovering services: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while discovering characteristics: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion #region discover characteristics peripheral.DiscoveredCharacteristic += (sender, e) => { try { if (e.Error == null) { SensusServiceHelper.Get().Logger.Log("Discovered characteristics. Reading value...", LoggingLevel.Normal, GetType()); // read characteristic value for newly discovered characteristics that match the one we're looking for foreach (CBCharacteristic characteristic in e.Service.Characteristics) { if (characteristic.UUID.Equals(_characteristic.UUID)) { peripheral.ReadValue(characteristic); } } } else { throw new Exception("Error while discovering characteristics: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading characteristic values from peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion #region update characteristic value peripheral.UpdatedCharacterteristicValue += (sender, e) => { try { if (e.Error == null) { // characteristic should have a non-null value if (e.Characteristic.Value == null) { throw new Exception("Null updated value for characteristic."); } else { SensusServiceHelper.Get().Logger.Log("Value read.", LoggingLevel.Normal, GetType()); string characteristicValue = Encoding.UTF8.GetString(e.Characteristic.Value.ToArray()); readCompletionSource.SetResult(characteristicValue); } } else { throw new Exception("Error while updating characteristic value: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reporting characteristic value: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion try { SensusServiceHelper.Get().Logger.Log("Connecting to peripheral...", LoggingLevel.Normal, GetType()); central.ConnectPeripheral(peripheral); string characteristicValue = await BluetoothDeviceProximityProbe.CompleteReadAsync(readCompletionSource, cancellationToken); if (characteristicValue != null) { characteristicValueTimestamps.Add(new Tuple <string, DateTimeOffset>(characteristicValue, timestamp)); _probe.ReadSuccessCount++; } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral: " + ex, LoggingLevel.Normal, GetType()); } finally { DisconnectPeripheral(central, peripheral); } } return(characteristicValueTimestamps); }