public virtual IObservable <BleWriteSegment> BlobWrite(Stream stream, bool reliableWrite) => Observable.Create <BleWriteSegment>(async ob => { var cts = new CancellationTokenSource(); var trans = reliableWrite ? this.Service.Device.BeginReliableWriteTransaction() : new VoidGattReliableWriteTransaction(); using (trans) { var mtu = this.Service.Device.MtuSize; var buffer = new byte[mtu]; var read = stream.Read(buffer, 0, buffer.Length); var pos = read; var len = Convert.ToInt32(stream.Length); while (!cts.IsCancellationRequested && read > 0) { await trans .Write(this, buffer) .ToTask(cts.Token) .ConfigureAwait(false); //if (this.Value != buffer) //{ // trans.Abort(); // throw new GattReliableWriteTransactionException("There was a mismatch response"); //} var seg = new BleWriteSegment(buffer, pos, len); ob.OnNext(seg); read = stream.Read(buffer, 0, buffer.Length); if (read > 0 && read < buffer.Length) { for (var index = read; index < buffer.Length; index++) { buffer[index] = 0; } } pos += read; } await trans.Commit(); } ob.OnCompleted(); return(() => { cts.Cancel(); trans.Dispose(); }); });
public virtual IObservable <BleWriteSegment> BlobWrite(Stream stream, bool reliableWrite) { return(Observable.Create <BleWriteSegment>(async ob => { var cts = new CancellationTokenSource(); var trans = reliableWrite ? this.Service.Device.BeginReliableWriteTransaction() : new VoidGattReliableWriteTransaction(); using (trans) { var mtu = this.Service.Device.GetCurrentMtuSize(); var buffer = new byte[mtu]; var read = stream.Read(buffer, 0, buffer.Length); var pos = read; var len = Convert.ToInt32(stream.Length); while (!cts.IsCancellationRequested && read > 0) { await trans.Write(this, buffer).RunAsync(cts.Token); //await this.Write(buffer).RunAsync(cts.Token); if (this.Value != buffer) { trans.Abort(); throw new GattReliableWriteTransactionException("There was a mismatch response"); } var seg = new BleWriteSegment(buffer, pos, len); ob.OnNext(seg); read = stream.Read(buffer, 0, buffer.Length); pos += read; } await trans.Commit(); } ob.OnCompleted(); return () => { cts.Cancel(); trans.Dispose(); }; })); }