// HACK: UNTESTED - this API has only been tested on iOS public Task <ICharacteristic> ReadAsync() { var tcs = new TaskCompletionSource <ICharacteristic>(); if (!CanRead) { throw new InvalidOperationException("Characteristic does not support READ"); } EventHandler <CharacteristicReadEventArgs> updated = null; updated = (sender, e) => { // it may be other characteristics, so we need to test var c = e.Characteristic; tcs.SetResult(c); if (_gattCallback != null) { // wire up the characteristic value updating on the gattcallback _gattCallback.CharacteristicValueUpdated -= updated; } }; if (_gattCallback != null) { // wire up the characteristic value updating on the gattcallback _gattCallback.CharacteristicValueUpdated += updated; } Console.WriteLine(@".....ReadAsync"); _gatt.ReadCharacteristic(_nativeCharacteristic); return(tcs.Task); }
/// <summary> /// Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported /// asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} /// callback. /// </summary> /// <param name="characteristic"> The characteristic to read from. </param> public virtual void ReadCharacteristic(BluetoothGattCharacteristic characteristic) { if (Gatt == null) { Debug.WriteLine(TAG, "mBluetoothGatt not initialized"); return; } Gatt.ReadCharacteristic(characteristic); }
public async Task <byte[]> ReadAsync(IGattCharacteristic characteristic, CancellationToken token) { using (token.Register(() => { lock (_lock) { _readCompletionSource?.TrySetResult(null); } })) { lock (_lock) { var nativeCharacteristic = ((GattCharacteristic)characteristic).BluetoothGattCharacteristic; _readCompletionSource = new TaskCompletionSource <byte[]>(TaskCreationOptions.RunContinuationsAsynchronously); if (!_bluetoothGatt.ReadCharacteristic(nativeCharacteristic)) { _readCompletionSource = null; return(null); } } var result = await _readCompletionSource.Task; lock (_lock) { _readCompletionSource = null; return(result); } } }
public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [GeneratedEnum] GattStatus status) { base.OnCharacteristicRead(gatt, characteristic, status); if (status == GattStatus.Success) { gatt.ReadCharacteristic(characteristic); byte[] valor = characteristic.GetValue(); textCharacteristic = gatt.ReadCharacteristic(characteristic).ToString(); Log.Debug(tag, "CHARACTERISTIC: " + valor); } else { Log.Debug(tag, "characteristic GET VALUE IS NULL"); } }
public Task <IBLECharacteristic> ReadCharacteristicAsync(string serviceGUID, string characteristicGUID) { readCharacteristicTCS = new TaskCompletionSource <IBLECharacteristic>(); try { if (_gatt == null) { Debug.WriteLine("Connect to Bluetooth Device first"); readCharacteristicTCS.TrySetException(new Exception("Connect to Bluetooth Device first")); } BluetoothGattCharacteristic chara = _gatt.GetService(UUID.FromString(serviceGUID)).GetCharacteristic(UUID.FromString(characteristicGUID)); if (null == chara) { readCharacteristicTCS.TrySetException(new Exception("Bluetooth Gatt Characteristic " + characteristicGUID + " Does Not Exist")); } if (false == _gatt.ReadCharacteristic(chara)) { readCharacteristicTCS.TrySetException(new Exception("ReadCharacteristic was not initiated successfully")); } } catch (Exception e) { Debug.WriteLine(e.Message); readCharacteristicTCS.TrySetException(new Exception(e.Message)); } return(readCharacteristicTCS.Task); }
protected override async Task <byte[]> ReadNativeAsync() { var tcs = new TaskCompletionSource <byte[]>(); EventHandler <CharacteristicReadCallbackEventArgs> readHandler = null; readHandler = (sender, args) => { if (args.Characteristic.Uuid != _nativeCharacteristic.Uuid) { return; } if (_gattCallback != null) { _gattCallback.CharacteristicValueUpdated -= readHandler; } tcs.TrySetResult(Value); }; _gattCallback.CharacteristicValueUpdated += readHandler; Trace.Message("ReadAsync: requesting characteristic read"); var ret = _gatt.ReadCharacteristic(_nativeCharacteristic); if (!ret) { _gattCallback.CharacteristicValueUpdated -= readHandler; Trace.Message("ReadAsync: Gatt read characteristic call returned FALSE"); tcs.TrySetException(new CharacteristicReadException("Gatt read characteristic call failed")); } return(await tcs.Task); }
private void PlatformRead() { if (!_gatt.ReadCharacteristic(_characteristic)) { RaiseReadFailed(BLEErrorCode.InternalError); } }
void ReadInternal() { if (!_gatt.ReadCharacteristic(NativeCharacteristic)) { throw new CharacteristicReadException("BluetoothGattCharacteristic.readCharacteristic returned FALSE"); } }
/// <summary> /// Read the characteristic's value /// </summary> public void Read() { if (!CanRead) { throw new InvalidOperationException("Characteristic does not support READ"); } _gatt.ReadCharacteristic(_nativeCharacteristic); }
/** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void ReadCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.Warn(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.ReadCharacteristic(characteristic); }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { if (status != GattStatus.Success) { return; } foreach (BluetoothGattService service in gatt.Services) { if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_GLUCOSE)) { _glucoseMeasurementCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_MEASUREMENT); _glucoseMeasurementContextCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_CONTEXT); _racpCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_RACP); _records.Clear(); } else if (BLEHelpers.BLE_SERVICE_DEVICE_INFO.Equals(service.Uuid)) { _deviceSoftwareRevisionCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_SOFTWARE_REVISION); _deviceManufacturerCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_MANUFACTURE); _deviceSerialCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_SERIALNUM); } else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_MC)) { _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_MC); if (_customTimeCharacteristic != null) { gatt.SetCharacteristicNotification(_customTimeCharacteristic, true); } } else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_TI)) { _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_TI); if (_customTimeCharacteristic != null) { gatt.SetCharacteristicNotification(_customTimeCharacteristic, true); } } else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_TI_NEW)) { _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_TI_NEW); if (_customTimeCharacteristic != null) { gatt.SetCharacteristicNotification(_customTimeCharacteristic, true); } } if (_deviceManufacturerCharacteristic != null) { gatt.ReadCharacteristic(_deviceManufacturerCharacteristic); } } }
/** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void ReadCharacteristic(BluetoothGattCharacteristic characteristic) { if (bluetoothAdapter == null || bluetoothGatt == null) { logger.TraceWarning("BluetoothAdapter not initialized"); return; } bluetoothGatt.ReadCharacteristic(characteristic); logger.TraceInformation("Read Characteristic"); }
protected static Java.Util.UUID CHAR_APPEARANCE = Java.Util.UUID.FromString("00002A01-0000-1000-8000-00805f9b34fb"); //org.bluetooth.characteristic.gap.appearance public GenericAccessService(BluetoothGatt gatt, BluetoothGattService service, GattDevice device) : base(gatt, service, device) { if (service != null) { BluetoothGattCharacteristic characteristic = service.GetCharacteristic(CHAR_DEVICE_NAME); if (characteristic != null) { gatt.ReadCharacteristic(characteristic); } } }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { System.Threading.Tasks.Task.Run(() => { base.OnServicesDiscovered(gatt, status); if (gatt != null) { try { var serviceUuid = ParcelUuid.FromString(_tracingInformation.ServiceId); BluetoothGattService service = gatt.GetService(serviceUuid.Uuid); if (service != null) { _deviceManager.HandleDeviceCommunicationDiscoveredService(_descriptor, (d) => { var characteristicUuid = ParcelUuid.FromString(_tracingInformation.CharacteristicId); BluetoothGattCharacteristic characteristic = service.GetCharacteristic(characteristicUuid.Uuid); if (characteristic != null) { _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristic(_descriptor, (d) => { gatt.ReadCharacteristic(characteristic); }); } else { _deviceManager.HandleIncorrectDevice(_descriptor, (d) => { gatt.Disconnect(); }); } }); } else { _deviceManager.HandleIncorrectDevice(_descriptor, (d) => { gatt.Disconnect(); }); } } catch (Exception ex) { _deviceManager.HandleDeviceCommunicationDiscoveryServiceError(_descriptor, ex.Message, (d) => { gatt.Disconnect(); }); } } }).FireAndForget(); }
void ReadInternal() { if (Configuration.IsForceUI) { using (var h = new Handler(Looper.MainLooper)) { h.Post(() => { if (!_gatt.ReadCharacteristic(_nativeCharacteristic)) { throw new CharacteristicReadException("BluetoothGattCharacteristic.readCharacteristic returned FALSE"); } }); } } else { if (!_gatt.ReadCharacteristic(_nativeCharacteristic)) { throw new CharacteristicReadException("BluetoothGattCharacteristic.readCharacteristic returned FALSE"); } } }
public override void OnServicesDiscovered(BluetoothGatt peripheral, GattStatus status) { BluetoothGattService service = null; try { service = peripheral.GetService(_service.Uuid); if (service == null) { SensusServiceHelper.Get().Logger.Log("Null service returned. The device is not running Senus.", LoggingLevel.Normal, GetType()); _readCompletionSource.SetResult(null); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while getting peripheral service: " + ex, LoggingLevel.Normal, GetType()); } if (service != null) { BluetoothGattCharacteristic characteristic = null; try { characteristic = service.GetCharacteristic(_characteristic.Uuid); if (characteristic == null) { throw new Exception("Null characteristic returned."); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while getting peripheral characteristic: " + ex, LoggingLevel.Normal, GetType()); } if (characteristic != null) { try { peripheral.ReadCharacteristic(characteristic); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral characteristic: " + ex, LoggingLevel.Normal, GetType()); } } } }
public SampleService(BluetoothGatt gatt, BluetoothGattService service, GattDevice device) : base(gatt, service, device) { index = 0; Log.Debug(TAG, "SampleService(0x{0:X})", BlutoothService.GetAssignedNumber(service.Uuid)); if (service != null) { nCharacteristics = service.Characteristics.Count; if (nCharacteristics > 0) { BluetoothGattCharacteristic characteristic = service.Characteristics[0]; Log.Debug(TAG, "ReadCharacteristic(0x{0:X})", BlutoothService.GetAssignedNumber(characteristic.Uuid)); gatt.ReadCharacteristic(characteristic); } } }
// HACK: UNTESTED - this API has only been tested on iOS public Task <ICharacteristic> ReadAsync() { var tcs = new TaskCompletionSource <ICharacteristic>(); if (!CanRead) { throw new InvalidOperationException("Characteristic does not support READ"); } EventHandler <CharacteristicReadEventArgs> updated = null; updated = (object sender, CharacteristicReadEventArgs e) => { // it may be other characteristics, so we need to test if (e.Characteristic.ID == ID) { tcs.TrySetResult(e.Characteristic); if (_gattCallback != null) { _gattCallback.CharacteristicValueUpdated -= updated; } } }; if (_gattCallback != null) { // wire up the characteristic value updating on the gattcallback _gattCallback.CharacteristicValueUpdated += updated; } else { tcs.TrySetException(new MemberAccessException("Gatt callback is null")); return(tcs.Task); } Mvx.TaggedTrace("ReadAsync", "requesting characteristic read"); var ret = _gatt.ReadCharacteristic(_nativeCharacteristic); if (!ret) { _gattCallback.CharacteristicValueUpdated -= updated; Mvx.TaggedWarning("ReadAsync", "Gatt read characteristic call returned {0}", ret); tcs.TrySetException(new InvalidOperationException("Gatt read characteristic call failed")); } return(tcs.Task); }
//public void StartUpdates() //{ // Task.Run(() => // { // while (true) // { // if (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, true)) // { // // In order to subscribe to notifications on a given characteristic, you must first set the Notifications Enabled bit // // in its Client Characteristic Configuration Descriptor. See https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorsHomePage.aspx and // // https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml // // for details. // if (_nativeCharacteristic.Descriptors.Count > 0) // { // var descriptors = _nativeCharacteristic.Descriptors; // var descriptor = descriptors[0]; // if (descriptor != null && Properties.HasFlag(CharacteristicPropertyType.Indicate)) // { // if (!descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray())) // { // } // if (!_gatt.WriteDescriptor(descriptor)) // { // } // } // if (descriptor != null && Properties.HasFlag(CharacteristicPropertyType.Notify)) // { // if (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray())) // { // } // if (!_gatt.WriteDescriptor(descriptor)) // { // } // } // break; // } // else // { // } // } // else // { // } // Thread.Sleep(1000); // } // }); //} public void StartUpdates() { Task.Run(() => {//on andorid this NEEDS to be in a different thread. when you await each command it stops it from responding and unblocking. while (!_gatt.ReadCharacteristic(_nativeCharacteristic)) { Thread.Sleep(100); } while (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, true)) { Thread.Sleep(100); } // [TO20131211@1634] It seems that setting the notification above isn't enough. You have to set the NOTIFY // descriptor as well, otherwise the receiver will never get the updates. I just grabbed the first (and only) // descriptor that is associated with the characteristic, which is the NOTIFY descriptor. This seems like a really // odd way to do things to me, but I'm a Bluetooth newbie. Google has a example here (but no real explaination as // to what is going on): if (_nativeCharacteristic.Descriptors.Count > 0) { Thread.Sleep(100); BluetoothGattDescriptor descriptor = _nativeCharacteristic.Descriptors[0]; while (!descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray())) { Console.WriteLine("Descriptor Setvalue loop"); Thread.Sleep(100); } while (!_gatt.WriteDescriptor(descriptor)) { Console.WriteLine(" Write Descriptor loop"); Thread.Sleep(100); } Thread.Sleep(100); while (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray())) { Console.WriteLine("Descriptor Setvalue loop"); Thread.Sleep(100); } while (!_gatt.WriteDescriptor(descriptor)) { Console.WriteLine(" Write Descriptor loop"); Thread.Sleep(100); } } }); }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { BluetoothGattService deviceIdService; try { deviceIdService = gatt.GetService(_probe.DeviceIdService.Uuid); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while getting device ID service: " + ex, LoggingLevel.Normal, GetType()); DisconnectPeripheral(gatt); return; } BluetoothGattCharacteristic deviceIdCharacteristic; try { deviceIdCharacteristic = deviceIdService.GetCharacteristic(_probe.DeviceIdCharacteristic.Uuid); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while getting device ID characteristic: " + ex, LoggingLevel.Normal, GetType()); DisconnectPeripheral(gatt); return; } try { gatt.ReadCharacteristic(deviceIdCharacteristic); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading device ID characteristic: " + ex, LoggingLevel.Normal, GetType()); DisconnectPeripheral(gatt); } }
private void ProcessQueue() { var queueNumber = _queueNumber; ++_queueNumber; Debug.WriteLine($"ProcessQueue {queueNumber}: {_gattOperationQueue.Count}"); if (_gattOperationQueue.Count == 0) { return; } if (_gattOperationQueueProcessing) { return; } _gattOperationQueueProcessing = true; var item = _gattOperationQueue.Dequeue(); switch (item.OperationType) { case OWBLE_QueueItemOperationType.Read: bool didRead = _bluetoothGatt.ReadCharacteristic(item.Characteristic); if (didRead == false) { Debug.WriteLine($"ERROR {queueNumber}: Unable to read {item.Characteristic.Uuid}"); } break; case OWBLE_QueueItemOperationType.Write: bool didSetValue = item.Characteristic.SetValue(item.Data); bool didWrite = _bluetoothGatt.WriteCharacteristic(item.Characteristic); if (didWrite == false) { Debug.WriteLine($"ERROR {queueNumber}: Unable to write {item.Characteristic.Uuid}"); } break; case OWBLE_QueueItemOperationType.Subscribe: bool didSubscribe = _bluetoothGatt.SetCharacteristicNotification(item.Characteristic, true); if (didSubscribe == false) { Debug.WriteLine($"ERROR {queueNumber}: Unable to subscribe {item.Characteristic.Uuid}"); } var subscribeDescriptor = item.Characteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805f9b34fb")); bool didSetSubscribeDescriptor = subscribeDescriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()); bool didWriteSubscribeDescriptor = _bluetoothGatt.WriteDescriptor(subscribeDescriptor); break; case OWBLE_QueueItemOperationType.Unsubscribe: bool didUnsubscribe = _bluetoothGatt.SetCharacteristicNotification(item.Characteristic, false); if (didUnsubscribe == false) { Debug.WriteLine($"ERROR {queueNumber}: Unable to unsubscribe {item.Characteristic.Uuid}"); } var unsubscribeDescriptor = item.Characteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805f9b34fb")); var didSetUnsubscribeDescriptor = unsubscribeDescriptor.SetValue(BluetoothGattDescriptor.DisableNotificationValue.ToArray()); var didWriteUnsubscribeDescriptor = _bluetoothGatt.WriteDescriptor(unsubscribeDescriptor); break; } }
/// <summary> /// Used to read from the list of characteristics /// </summary> /// <param name="gatt">Gatt.</param> private void requestCharacteristic(BluetoothGatt gatt) { gatt.ReadCharacteristic(deviceChar.Last()); }
private void StepintoCharacteristic() { BluetoothGattCharacteristic c = characteristics[adapter.GetChooseItem()]; gatt.ReadCharacteristic(c); }
public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [GeneratedEnum] GattStatus status) { switch (status) { case GattStatus.Success: DisplayMessageToUi("Se preiau date..."); if (BLEHelpers.BLE_CHAR_GLUCOSE_MANUFACTURE.Equals(characteristic.Uuid)) { string manufacturer = characteristic.GetStringValue(0); _isIsensMeter = manufacturer.Equals("i-SENS"); if (!manufacturer.Equals("i-SENS")) { Log.Error("Manfacture Error", "Device not supported"); gatt.Disconnect(); } else if (_deviceSoftwareRevisionCharacteristic != null) { gatt.ReadCharacteristic(_deviceSoftwareRevisionCharacteristic); } else if (_deviceSerialCharacteristic != null) { gatt.ReadCharacteristic(_deviceSerialCharacteristic); } } else if (BLEHelpers.BLE_CHAR_SOFTWARE_REVISION.Equals(characteristic.Uuid)) { if (_isIsensMeter) { Log.Error("Revision", characteristic.GetStringValue(0)); _bleSwRevision = characteristic.GetStringValue(0).Split("."); int parseInt = int.Parse(_bleSwRevision[0]); if (parseInt > 1 || _customTimeCharacteristic == null) { Log.Error("Error Revision", "Revision greater or equal with 1 and mCustomTimeCharacteristic is null. Disconecting..."); gatt.Disconnect(); return; } } if (_deviceSerialCharacteristic != null) { gatt.ReadCharacteristic(_deviceSerialCharacteristic); } } else if (BLEHelpers.BLE_CHAR_GLUCOSE_SERIALNUM.Equals(characteristic.Uuid)) { _serial = characteristic.GetStringValue(0); Log.Error("Serial", _serial); EnableRecordAccessControlPointIndication(gatt); } break; case GattStatus.ConnectionCongested: break; case GattStatus.Failure: break; case GattStatus.InsufficientAuthentication: break; case GattStatus.InsufficientEncryption: break; case GattStatus.InvalidAttributeLength: break; case GattStatus.InvalidOffset: break; case GattStatus.ReadNotPermitted: break; case GattStatus.RequestNotSupported: break; case GattStatus.WriteNotPermitted: break; default: Log.Error("OnCharacteristicRead", "Unrecognized Status " + status); break; } }
public void Read(BluetoothGattCharacteristic characteristic, Action <byte[], GattStatus> onRead) { _onRead = onRead; _gatt.ReadCharacteristic(characteristic); }