private async Task WriteAttributeAsync(byte connection, ushort handle, byte[] value) { var writeTCS = new TaskCompletionSource <bool>(); var onProcedureCompleted = new EventHandler <ProcedureCompletedEventArgs>((s, e) => { if (e.Connection != connection || e.ChrHandle != handle) { return; } if (e.ErrorCode == 0) { writeTCS.TrySetResult(true); } else { var error = new SDK.ErrorException(e.ErrorCode); writeTCS.TrySetException(error); } }); _messageHub.AttributeClient.ProcedureCompleted += onProcedureCompleted; try { await _messageHub.AttributeClient.AttributeWriteAsync(connection, handle, value); await writeTCS.Task; } finally { _messageHub.AttributeClient.ProcedureCompleted += onProcedureCompleted; } }
public async Task ConfigAsync(GattCharacteristic characteristic, GattCharacteristicSettings settings) { var connection = characteristic.Connection; var itemsTCS = new TaskCompletionSource <IList <FindInformationFoundEventArgs> >(); var items = new List <FindInformationFoundEventArgs>(); var onFindInformationFound = new EventHandler <FindInformationFoundEventArgs>((s, e) => { if (e.Connection != connection) { return; } items.Add(e); }); var onProcedureCompleted = new EventHandler <ProcedureCompletedEventArgs>((s, e) => { if (e.Connection != connection) { return; } if (e.ErrorCode == 0) { itemsTCS.TrySetResult(items); } else { var error = new SDK.ErrorException(e.ErrorCode); itemsTCS.TrySetException(error); } }); _messageHub.AttributeClient.FindInformationFound += onFindInformationFound; _messageHub.AttributeClient.ProcedureCompleted += onProcedureCompleted; try { var start = characteristic.Start; var end = characteristic.End; await _messageHub.AttributeClient.FindInformationAsync(connection, start, end); await itemsTCS.Task; } finally { _messageHub.AttributeClient.FindInformationFound -= onFindInformationFound; _messageHub.AttributeClient.ProcedureCompleted -= onProcedureCompleted; } var item = items.First(i => { var uuid = BitConverter.ToUInt16(i.UUID, 0); return(uuid == 0x2902); }); var handle = item.ChrHandle; var settingsValue = (ushort)settings; var value = BitConverter.GetBytes(settingsValue); await _messageHub.AttributeClient.WriteCommandAsync(connection, handle, value); }