public virtual void WriteTXCharacteristic(byte[] value) { BluetoothGattCharacteristic rxChar; var rxService = Gatt.GetService(RX_SERVICE_UUID2); if (rxService == null) { ShowMessage("mBluetoothGatt null" + Gatt); ShowMessage("Tx service not found!"); BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART); return; } rxChar = rxService.GetCharacteristic(RX_CHAR_UUID2); if (rxChar == null) { ShowMessage("Tx charateristic not found!"); BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART); return; } Debug.WriteLine(TAG, "TxChar = " + RX_CHAR_UUID2.ToString()); rxChar.SetValue(value); bool status = Gatt.WriteCharacteristic(rxChar); Debug.WriteLine(TAG, "write TXchar - status=" + status); }
/// <summary> /// Checks the gatt object to see if we have successfully validated the services. If the gatt object is null, then /// obviously the services are not valid. /// </summary> /// <returns>The services.</returns> private bool ValidateServices() { if (gatt == null) { return(false); } readCharacteristic = null; writeCharacteristic = null; var readService = gatt.GetService(READ_SERVICE); if (readService != null) { readCharacteristic = readService.GetCharacteristic(READ_CHARACTERISTIC); } var writeService = gatt.GetService(WRITE_SERVICE); if (writeService != null) { writeCharacteristic = writeService.GetCharacteristic(WRITE_CHARACTERISTIC); } return(readCharacteristic != null && writeCharacteristic != null); }
public void ConfigureGyroscopePeriod() { var accelerometerPeriod = BluetoothGatt.GetService(BluetoothSensorAttributes.GyroscopeService).GetCharacteristic(BluetoothSensorAttributes.GyroscopePeriod); accelerometerPeriod.SetValue(new byte[] { 10 }); BluetoothGatt.WriteCharacteristic(accelerometerPeriod); }
/// <summary> /// Attempts to find and validate all the characteristic that are present in the controller. /// </summary> /// <returns><c>true</c>, if services was validated, <c>false</c> otherwise.</returns> private bool ValidateServices() { if (gatt == null) { return(false); } foreach (var service in gatt.Services) { Log.D(this, "Service: " + service.Uuid); foreach (var characteristic in service.Characteristics) { Log.D(this, "\tCharacteristic: " + characteristic.Uuid); foreach (var desc in characteristic.Descriptors) { Log.D(this, "\t\tDescriptor: " + desc.Uuid); } } } readCharacteristic = null; writeCharacteristic = null; var baseService = gatt.GetService(SERVICE); if (baseService != null) { readCharacteristic = baseService.GetCharacteristic(READ); writeCharacteristic = baseService.GetCharacteristic(WRITE); } return(readCharacteristic != null && writeCharacteristic != null); }
/// <summary> /// Checks the gatt object to see if we have successfully validated the services. If the gatt object is null, then /// obviously the services are not valid. /// </summary> /// <returns>The services.</returns> private bool ValidateServices() { if (gatt == null) { return(false); } readCharacteristic = null; writeCharacteristic = null; var baseService = gatt.GetService(BASE_SERVICE); if (baseService != null) { readCharacteristic = baseService.GetCharacteristic(READ_CHARACTERISTIC); if (readCharacteristic != null) { readCharacteristicDescriptor = readCharacteristic.GetDescriptor(READ_CHARACTERISTIC_DESCRIPTOR); } writeCharacteristic = baseService.GetCharacteristic(WRITE_CHARACTERISTIC); } return(readCharacteristic != null && readCharacteristicDescriptor != null && writeCharacteristic != null); }
/// <summary> /// Get the UUID's for the device details and sets the list /// </summary> /// <param name="gatt">Gatt.</param> private void getDeviceDetails(BluetoothGatt gatt) { try { UUID deviceInfoUUID = UUID.FromString(BluetoothConstants.DEVICE_INFO_SERVICE); BluetoothGattService deviceInfoSer = gatt.GetService(deviceInfoUUID); deviceChar = new List <BluetoothGattCharacteristic> { deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SERIALNUM)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_MODELNUM)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SOFTWARE_REV)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_FIRMWARE_REV)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_HARDWARE_REV)) }; foreach (BluetoothGattCharacteristic c in deviceChar) { try { gatt.SetCharacteristicNotification(c, false); requestCharacteristic(gatt); } catch (System.Exception e) { string t = ""; // if the char dont exit for thiss } } } catch (System.Exception e) { // stop ourselves sendStateUpdate(gatt.Device.Address, false, "Device could not be read from: " + e.Message); } }
/// <summary> /// Process a callback from the Gatt for changes in the device connection State /// </summary> private void GattCallback_ConnectionStateChange(object sender, ConnectionStateChangeEventArgs e) { Debug.WriteLineIf(sw.TraceInfo, $"++> GattCallback_ConnectionStateChange: {e.NewState}"); switch (e.NewState) { case ProfileState.Connected: _gatt = e.Gatt; _service = _gatt.GetService(uuidService); _gatt.DiscoverServices(); // return without setting State // wait until ServicesDiscovered callback to announce we're actually connected break; case ProfileState.Connecting: State = BlueState.Connecting; break; case ProfileState.Disconnected: State = BlueState.Disconnected; break; case ProfileState.Disconnecting: State = BlueState.Disconnecting; break; default: break; } }
public void ConfigureAccelerometer(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.AccelerometerConfigured; var accelerometer = gatt.GetService(BluetoothSensorAttributes.AccelerometerService).GetCharacteristic(BluetoothSensorAttributes.AccelerometerConfiguration); accelerometer.SetValue(new byte[] { 1 }); gatt.WriteCharacteristic(accelerometer); }
public async Task <List <BluetoothDeviceProximityDatum> > ReadPeripheralCharacteristicValuesAsync(CancellationToken cancellationToken) { List <BluetoothDeviceProximityDatum> bluetoothDeviceProximityData = new List <BluetoothDeviceProximityDatum>(); // copy list of peripherals to read. note that the same device may be reported more than once. read each once. List <ScanResult> scanResults; lock (_scanResults) { scanResults = _scanResults.GroupBy(scanResult => scanResult.Device.Address).Select(group => group.First()).ToList(); } _probe.ReadAttemptCount += scanResults.Count; // read characteristic from each peripheral foreach (ScanResult scanResult in scanResults) { if (cancellationToken.IsCancellationRequested) { break; } AndroidBluetoothClientGattCallback readCallback = null; try { readCallback = new AndroidBluetoothClientGattCallback(_service, _characteristic); BluetoothGatt gatt = scanResult.Device.ConnectGatt(global::Android.App.Application.Context, false, readCallback); BluetoothGattService service = gatt.GetService(_service.Uuid); string characteristicValue = null; bool runningSensus = service != null; if (runningSensus) { characteristicValue = await readCallback.ReadCharacteristicValueAsync(cancellationToken); } if (_probe.DiscoverAll || runningSensus) { long msSinceEpoch = Java.Lang.JavaSystem.CurrentTimeMillis() - SystemClock.ElapsedRealtime() + scanResult.TimestampNanos / 1000000; DateTimeOffset encounterTimestamp = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()).AddMilliseconds(msSinceEpoch); bluetoothDeviceProximityData.Add(new BluetoothDeviceProximityDatum(encounterTimestamp, characteristicValue, scanResult.Device.Address, scanResult.Device.Name, scanResult.Rssi, scanResult.Device.BondState != Bond.None, runningSensus)); _probe.ReadSuccessCount++; } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral: " + ex, LoggingLevel.Normal, GetType()); } finally { readCallback?.DisconnectPeripheral(); } } return(bluetoothDeviceProximityData); }
/// <summary> /// /// </summary> public virtual void EnableTXNotification() { if (m_Gatt == null) { Log.e("BleSerialPort", "No BluetoothGatt to EnableTXNotification!!!"); return; } // Get the service. BluetoothGattService RxService = m_Gatt .GetService(m_UuidServ); if (RxService == null) { Log.e("BleSerialPort", "RxService==null"); return; } // Get the characteristic. BluetoothGattCharacteristic txChar = RxService .GetCharacteristic(m_UuidTx); if (txChar == null) { Log.e("BleSerialPort", "txChar==null"); return; } // Set the characteristic notification. bool result = m_Gatt.SetCharacteristicNotification(txChar, true); if (!result) { Log.e("BleSerialPort", "m_Gatt.SetCharacteristicNotification(txChar,true) failed!!!"); } // (Set the characteristic notification ???). BluetoothGattDescriptor descriptor = txChar .GetDescriptor(m_UuidCCCD); descriptor.SetValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); m_Gatt.WriteDescriptor(descriptor); Log.i("BleSerialPort", "EnableTXNotification successfully."); }
public void ConfigureGyroscope(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.GyroscopeConfigured; var gyroscope = gatt.GetService(BluetoothSensorAttributes.GyroscopeService)?.GetCharacteristic(BluetoothSensorAttributes.GyroscopeConfiguration); gyroscope.SetValue(new byte[] { 7 }); gatt.WriteCharacteristic(gyroscope); }
/// <summary> /// /// </summary> public virtual void OnServicesDiscovered(BluetoothGatt gatt, int status) { Log.i("BluetoothScannerGUI", "OnServicesDiscovered:" + status.ToString()); if (status == BluetoothGatt.GATT_SUCCESS) { BluetoothGattService srv = gatt.GetService(UUID.FromString("0000faea-0000-1000-8000-00805f9b34fb")); BluetoothGattCharacteristic chr = srv.GetCharacteristic(UUID.FromString("0000faeb-0000-1000-8000-00805f9b34fb")); gatt.SetCharacteristicNotification(chr, true); } }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { if (status == GattStatus.Success) { _parent.OnStatusUpdated("Discovering characteristics"); var service = gatt.GetService(UUID.FromString(ServiceUuid)); _characteristic = service.GetCharacteristic(UUID.FromString(CharacteristicUuid)); EnableNotification(); _handler.Connect(_parent._manager.Adapter.Name, _identifier); } }
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(); }
public void ConfigureAccelerometerNotification(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.AccelerometerNotification; var accelerometerData = gatt.GetService(BluetoothSensorAttributes.AccelerometerService).GetCharacteristic(BluetoothSensorAttributes.AccelerometerData); var accelerometerNotification = accelerometerData.GetDescriptor(BluetoothSensorAttributes.AccelerometerNotification); accelerometerNotification.SetValue(new byte[] { 1, 0 }); gatt.SetCharacteristicNotification(accelerometerData, true); gatt.WriteDescriptor(accelerometerNotification); }
public void ConfigureGyroscopeNotification(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.GyroscopeNotification; var gyroscopeData = gatt.GetService(BluetoothSensorAttributes.GyroscopeService).GetCharacteristic(BluetoothSensorAttributes.GyroscopeData); var gyroscopeNotification = gyroscopeData.GetDescriptor(BluetoothSensorAttributes.GyroscopeNotification); gyroscopeNotification.SetValue(new byte[] { 1, 0 }); gatt.SetCharacteristicNotification(gyroscopeData, true); gatt.WriteDescriptor(gyroscopeNotification); }
public void ConfigureGyroscopePeriod(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.GyroscopePeriod; var gyroscopePeriod = gatt.GetService(BluetoothSensorAttributes.GyroscopeService).GetCharacteristic(BluetoothSensorAttributes.GyroscopePeriod); if (gyroscopePeriod.GetValue() != null) { return; } gyroscopePeriod.SetValue(new byte[] { GyroscopePeriod }); gatt.WriteCharacteristic(gyroscopePeriod); }
public void ConfigureAccelerometerPeriod(BluetoothGatt gatt) { ConfigurationStep = ConfigurationStep.AccelerometerPeriod; var accelerometerPeriod = gatt.GetService(BluetoothSensorAttributes.AccelerometerService).GetCharacteristic(BluetoothSensorAttributes.AccelerometerPeriod); if (accelerometerPeriod.GetValue() != null) { return; } accelerometerPeriod.SetValue(new byte[] { AccelerometerPeriod }); gatt.WriteCharacteristic(accelerometerPeriod); }
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 Task <IBLECharacteristic> WriteCharacteristicAsync(string serviceGUID, string characteristicGUID, byte[] valueToWrite) { writeCharacteristicTCS = new TaskCompletionSource <IBLECharacteristic>(); try { if (_gatt == null) { Debug.WriteLine("Connect to Bluetooth Device first"); writeCharacteristicTCS.TrySetException(new Exception("Connect to Bluetooth Device first")); } BluetoothGattCharacteristic characteristic; characteristic = _gatt.GetService(UUID.FromString(serviceGUID)).GetCharacteristic(UUID.FromString(characteristicGUID)); if (characteristic == null) { writeCharacteristicTCS.TrySetException(new Exception("Bluetooth Gatt Characteristic " + characteristicGUID + " Does Not Exist")); } characteristic.SetValue(valueToWrite); if (_gatt.WriteCharacteristic(characteristic) == false) { writeCharacteristicTCS.TrySetException(new Exception("WriteCharacteristic was not initiated successfully")); } } catch (Exception e) { Debug.WriteLine(e.Message); writeCharacteristicTCS.TrySetException(e); } return(writeCharacteristicTCS.Task); }
private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid) { try { BluetoothGattCharacteristic characteristic = gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid); gatt.SetCharacteristicNotification(characteristic, true); BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig); bool indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0; descriptor.SetValue(indication ? BluetoothGattDescriptor.EnableIndicationValue.ToArray() : BluetoothGattDescriptor.EnableNotificationValue.ToArray()); gatt.WriteDescriptor(descriptor); } catch (Exception e) { Log.Error("BloodPressureGattCallbackerror", e.Message); } }
public void ConfigureMovement(BluetoothGatt gatt) { try { var characteristic = gatt.GetService(BluetoothSensorTagAttributes.MovementService).GetCharacteristic(BluetoothSensorTagAttributes.MovementConfiguration); characteristic.SetValue(new byte[] { 0x7F, 0x02 }); gatt.WriteCharacteristic(characteristic); SensorTagConfigurationStep = SensorTagConfigurationStep.Movement; } catch (System.Exception ex) { string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name; BalizaFacil.App.Instance.UnhandledException(title, ex); } }
private void ConfigureMovementData(BluetoothGatt gatt) { try { var characteristic = gatt.GetService(BluetoothSensorTagAttributes.MovementService).GetCharacteristic(BluetoothSensorTagAttributes.MovementData); gatt.SetCharacteristicNotification(characteristic, true); var descriptor = characteristic.GetDescriptor(BluetoothSensorTagAttributes.ClientConfigurationDescriptor); descriptor.SetValue(new byte[] { 1, 0 }); gatt.WriteDescriptor(descriptor); SensorTagConfigurationStep = SensorTagConfigurationStep.MovementData; } catch (System.Exception ex) { string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name; BalizaFacil.App.Instance.UnhandledException(title, ex); } }
private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid) { try { bool indication; BluetoothGattCharacteristic characteristic = gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid); gatt.SetCharacteristicNotification(characteristic, true); BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig); indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0; Log.Error("Indication", indication.ToString()); descriptor.SetValue(indication ? BluetoothGattDescriptor.EnableIndicationValue.ToArray() : BluetoothGattDescriptor.EnableNotificationValue.ToArray()); gatt.WriteDescriptor(descriptor); } catch (Exception e) { e.PrintStackTrace(); } }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { if (status != 0) { return; } if (HasCurrentTimeService(gatt)) { BluetoothGattCharacteristic timeCharacteristic = gatt.GetService(UUID.FromString("00001805-0000-1000-8000-00805f9b34fb")) .GetCharacteristic( UUID.FromString("00002A2B-0000-1000-8000-00805f9b34fb")); timeCharacteristic.SetValue(GetCurrentTimeLocal()); gatt.WriteCharacteristic(timeCharacteristic); } else { ListenToMeasurements(gatt); } }
private async Task <Service> GetServiceNativeAsync(Guid id) { if (_gattCallback == null || _gatt == null) { return(null); } var uuid = UUID.FromString(id.ToString("d")); // _gatt.GetService will directly return if device service discovery was already done var nativeService = _gatt.GetService(uuid); if (nativeService != null) { return(new Service(nativeService, _gatt, _gattCallback, this)); } var services = await DiscoverServicesInternal(); return(services?.FirstOrDefault(service => service.Id == id)); }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { if (status != GattStatus.Success) { _MainActivity.AppendLogText("Failed to discover services"); gatt.Disconnect(); return; } _MainActivity.AppendLogText("Services Discovered"); var configurationService = gatt.GetService(_ConfigurationService); if (configurationService == null) { _MainActivity.AppendLogText("Unable to find configuration service"); gatt.Disconnect(); return; } var configurationKeyCharacteristic = configurationService.GetCharacteristic(_ConfigurationKeyCharacteristic); if (configurationKeyCharacteristic == null) { _MainActivity.AppendLogText("Unable to find characteristic"); gatt.Disconnect(); return; } var configKeyBytes = StringToByteArrayFastest(_ConfigurationValue); configurationKeyCharacteristic.SetValue(configKeyBytes); if (!gatt.WriteCharacteristic(configurationKeyCharacteristic)) { _MainActivity.AppendLogText("Failed to write characteristic"); } else { _MainActivity.AppendLogText("Writing characteristic..."); } }
/// <summary> /// Process a callback from the Gatt for device services discovered while we're connecting /// </summary> private void GattCallback_ServicesDiscovered(object sender, EventArgs e) { Debug.WriteLineIf(sw.TraceInfo, "++> GattCallback_ServicesDiscovered"); _service = _gatt.GetService(uuidService); _TX = _service.GetCharacteristic(uuidTX); _RX = _service.GetCharacteristic(uuidRX); BluetoothGattDescriptor config = _RX.GetDescriptor(uuidCharacteristicConfig); if (config == null) { Debug.WriteLineIf(sw.TraceError, "--> _RX.GetDescriptor failed"); ErrorMessage = "RX.GetDescriptor failed"; Disconnect(); return; } bool b = _gatt.SetCharacteristicNotification(_RX, true); b = config.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()); b = _gatt.WriteDescriptor(config); // now that services are connected, we're ready to go State = BlueState.Connected; }
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 OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { //BTA_GATTC_CONN_MAX //BTA_GATTC_NOTIF_REG_MAX var service = gatt.GetService(OWBoard.ServiceUUID.ToUUID()); if (service == null) { return; } foreach (var characteristic in service.Characteristics) { _characteristics.Add(characteristic.Uuid.ToString().ToLower(), characteristic); } if (_connectTaskCompletionSource.Task.IsCanceled == false) { _connectTaskCompletionSource.SetResult(true); // TODO: Fix this. //BoardConnected?.Invoke(new OWBoard(_board)); } }