public override IObservable <GattCharacteristicResult> Read() => Observable.Create <GattCharacteristicResult>(ob => { this.AssertRead(); var handler = new EventHandler <CBCharacteristicEventArgs>((sender, args) => { if (!this.Equals(args.Characteristic)) { return; } if (args.Error != null) { ob.OnError(new BleException(args.Error.Description)); } else { var value = this.NativeCharacteristic.Value?.ToArray(); var result = new GattCharacteristicResult(this, value, GattCharacteristicResultType.Read); ob.Respond(result); } }); this.Peripheral.UpdatedCharacterteristicValue += handler; this.Peripheral.ReadValue(this.NativeCharacteristic); return(() => this.Peripheral.UpdatedCharacterteristicValue -= handler); });
public override IObservable <GattCharacteristicResult> Read() => this.context.Invoke(Observable.Create <GattCharacteristicResult>((Func <IObserver <GattCharacteristicResult>, IDisposable>)(ob => { this.AssertRead(); var sub = this.context .Callbacks .CharacteristicRead .Where(this.NativeEquals) .Subscribe(args => { if (!args.IsSuccessful) { ob.OnError(new BleException($"Failed to read characteristic - {args.Status}")); } else { var value = args.Characteristic.GetValue(); var result = new GattCharacteristicResult(this, value, GattCharacteristicResultType.Read); ob.Respond(result); } }); this.context.InvokeOnMainThread(() => { try { if (!this.context.Gatt?.ReadCharacteristic(this.native) ?? false) { throw new BleException("Failed to read characteristic"); } } catch (Exception ex) { ob.OnError(ex); } }); return(sub); })));
public override IObservable <GattCharacteristicResult> WhenNotificationReceived() => Observable.Create <GattCharacteristicResult>(async ob => { var handler = new TypedEventHandler <Native, GattValueChangedEventArgs>((sender, args) => { if (sender.Equals(this.Native)) { var bytes = args.CharacteristicValue.ToArray(); var result = new GattCharacteristicResult(this, bytes, GattCharacteristicResultType.Notification); ob.OnNext(result); } }); this.Native.ValueChanged += handler; this.handlers.Add(handler); this.context.SetNotifyCharacteristic(this); this.IsNotifying = true; return(() => { this.Native.ValueChanged -= handler; this.handlers.Remove(handler); }); });