public async void InitializeServiceAsync(string deviceId, Guid characteristicUuid) { try { Deinitialize(); _service = await GattDeviceService.FromIdAsync(deviceId); if (_service != null) { _characteristic = _service.GetCharacteristics(characteristicUuid)[0]; if (DeviceConnectionUpdated != null && (_service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected)) { DeviceConnectionUpdated(true, null); } _service.Device.ConnectionStatusChanged += OnConnectionStatusChanged; } else if (DeviceConnectionUpdated != null) { DeviceConnectionUpdated(false, "No services found from the selected device"); } } catch (Exception e) { if (DeviceConnectionUpdated != null) { DeviceConnectionUpdated(false, "Accessing device failed: " + e.Message); } } }
private void OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { var data = DataReader.FromBuffer(args.CharacteristicValue).ReadString(args.CharacteristicValue.Length); SendMessageToServer(data); }
/// <summary> /// Enables data notifications from the sensor by setting the configurationDescriptorvalue to Notify. /// </summary> /// <returns></returns> /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception> /// <exception cref="DeviceNotInitializedException">Thrown if the object has not been successfully initialized using the initialize() method.</exception> public async Task EnableService() { Validator.Requires<DeviceNotInitializedException>(deviceService != null); configCharacteristic = deviceService.GetCharacteristics(new Guid(this.SensorConfigUuid))[0]; }
public TourTheStairs(GattCharacteristic motorChar, GattCharacteristic datetimeChar, GattCharacteristic initCount1To20Char, GattCharacteristic emergencyStopChar) { _motorChar = motorChar; _datetimeChar = datetimeChar; _initCount1To20Char = initCount1To20Char; _emergencyStopChar = emergencyStopChar; }
public virtual async Task<InitResult> Init() { // On recherche un device supportant le service du sensor // Si le device trouvé est un SensorTag on retourne le service // Sinon on retourne null var deviceService = await GetDeviceService(pServiceUUID); if (deviceService == null) { // Aucun SensorTag ne supporte ce service return InitResult.DeviceNotFound; } #if WINDOWS_PHONE_APP if (deviceService.Device.ConnectionStatus == Windows.Devices.Bluetooth.BluetoothConnectionStatus.Disconnected) { // SensorTag déconnecté return InitResult.DeviceDisconnected; } #endif // On stocke le DeviceService pDeviceService = deviceService; // On a le DeviceService, on peut maintenant se brancher sur les caractéristiques // Configuration et Data var configCharacteristic = GetCharacteristic(pDeviceService, pConfigurationUUID); if (configCharacteristic == null) { return InitResult.DeviceNotFound; } var dataCharacteristic = GetCharacteristic(pDeviceService, pDataUUID); if (dataCharacteristic == null) { return InitResult.DeviceNotFound; } // On peut stocker les caractéristiques trouvées pConfigurationCharacteristic = configCharacteristic; pDataCharacteristic = dataCharacteristic; // On peut se brancher sur l'événement de changement de valeur des données await pDataCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); pDataCharacteristic.ValueChanged += pDataCharacteristic_ValueChanged; return InitResult.Ok; }
public void Deinitialize() { _characteristic = null; if (_service != null) { _service.Device.ConnectionStatusChanged -= OnConnectionStatusChanged; _service = null; } }
//値の取得 static private void TemperatureMeasurementChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs) { byte[] temperatureData = new byte[eventArgs.CharacteristicValue.Length]; Windows.Storage.Streams.DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(temperatureData); float calx = BitConverter.ToSingle(temperatureData, 0); float caly = BitConverter.ToSingle(temperatureData, 4); float calz = BitConverter.ToSingle(temperatureData, 8); pitch = calx; roll = caly; yaw = calz; Console.WriteLine("count:" + temperatureData.Length.ToString() + " " + calx.ToString("0.00") + " " + caly.ToString("0.00") + " " + calz.ToString("0.00")); }
public async Task DisableRemote() { Validator.Requires<DeviceNotInitializedException>(deviceService != null); configCharacteristic = deviceService.GetCharacteristics(new Guid(this.SensorConfigUuid))[0]; dataCharacteristic = deviceService.GetCharacteristics(new Guid(this.SensorDataUuid))[0]; byte[] sensorData = new byte[] { 0 }; GattCommunicationStatus status = await configCharacteristic.WriteValueAsync(sensorData.AsBuffer()); }
// Read data change handler async void incomingData_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs) { byte[] bArray = new byte[eventArgs.CharacteristicValue.Length]; DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray); string message = System.Text.Encoding.UTF8.GetString(bArray); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { receiveTextBox.Text = message; }); }
private async Task WriteConfigurationInChar(GattCharacteristic characteristic, GattClientCharacteristicConfigurationDescriptorValue charConfigValue) { try { DevicesInformation += $" {charConfigValue} {Environment.NewLine}"; await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(charConfigValue); DevicesInformation += $" - Ok{Environment.NewLine}"; } catch (Exception exception) { DevicesInformation += $" - Exception {exception.Message}{Environment.NewLine}"; } }
public void Deinitialize() { if (_characteristic != null) { _characteristic.ValueChanged -= Oncharacteristic_ValueChanged; _characteristic = null; } if (_service != null) { _service.Device.ConnectionStatusChanged -= OnConnectionStatusChanged; //_service.Dispose();// appears that we should not call this here!! _service = null; } }
public async void SetupBLE() { txtProgress.Text = "Obtaining BTLE Info..."; var query = BluetoothLEDevice.GetDeviceSelector(); var deviceList = await DeviceInformation.FindAllAsync(query); int count = deviceList.Count(); if(count > 0) { //Assumes default name of the Adafruit Bluefruit LE var deviceInfo = deviceList.Where(x => x.Name == "Adafruit Bluefruit LE").FirstOrDefault(); if(deviceInfo!=null) { var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var deviceServices = bleDevice.GattServices; txtProgress.Text = "Retrieving service and GATT characteristics..."; var deviceSvc = deviceServices.Where(svc => svc.AttributeHandle == 0x003a).FirstOrDefault(); if (deviceSvc != null) { var characteristics = deviceSvc.GetAllCharacteristics(); _notifyCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x003b).FirstOrDefault(); _writeCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x003e).FirstOrDefault(); _readCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x0040).FirstOrDefault(); _notifyCharacteristic.ValueChanged += NotifyCharacteristic_ValueChanged; await _notifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); txtProgress.Text = "Bluetooth LE Device service and characteristics initialized"; txtBTLEStatus.Text = "Initialized"; txtBTLEStatus.Foreground = new SolidColorBrush(Colors.Green); btnBlue.IsEnabled = true; btnGreen.IsEnabled = true; btnYellow.IsEnabled = true; btnOrange.IsEnabled = true; btnPurple.IsEnabled = true; btnRead.IsEnabled = true; } else { txtInfo.Text = "Custom GATT Service Not Found on the Bluefruit"; } } else { txtInfo.Text = "Adafruit Bluefruit LE not found, is it paired ??"; } } }
private void NotifyCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { //notification that the NeoPixel color has changed, update the UI with the new value byte[] bArray = new byte[args.CharacteristicValue.Length]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(bArray); var color = Color.FromArgb(0,bArray[0], bArray[1], bArray[2]); string result = color.ToString(); //remove alpha channel from string (only rgb was returned) result = result.Remove(1, 2); Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { txtLastNotificationHex.Text = result; }); }
public async void InitializeServiceAsync(string deviceId) { try { Deinitialize(); _service = await GattDeviceService.FromIdAsync(deviceId); if (_service != null) { //we could be already connected, thus lets check that before we start monitoring for changes if (DeviceConnectionUpdated != null && (_service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected)) { DeviceConnectionUpdated(true, null); } _service.Device.ConnectionStatusChanged += OnConnectionStatusChanged; _characteristic = _service.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement)[0]; _characteristic.ValueChanged += Oncharacteristic_ValueChanged; var currentDescriptorValue = await _characteristic.ReadClientCharacteristicConfigurationDescriptorAsync(); if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) || (currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != GattClientCharacteristicConfigurationDescriptorValue.Notify)) { // most likely we never get here, though if for any reason this value is not Notify, then we should really set it to be await _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("ERROR: Accessing your device failed." + Environment.NewLine + e.Message); if(DeviceConnectionUpdated != null) { DeviceConnectionUpdated(false, "Accessing device failed: " + e.Message); } } }
private async void DevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { RunButton.IsEnabled = false; var device = DevicesListBox.SelectedItem as DeviceInformation; DevicesListBox.Visibility = Visibility.Collapsed; nrfService = await GattDeviceService.FromIdAsync(device.Id); writeCharacteristic = nrfService.GetCharacteristics(new Guid("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"))[0]; readCharacteristic = nrfService.GetCharacteristics(new Guid("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"))[0]; if (nrfService != null) { bleInfoTextBlock.Text = "Using service Id: " + nrfService.DeviceId; readCharacteristic.ValueChanged += incomingData_ValueChanged; await readCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } else { bleInfoTextBlock.Text = "Error: gattService is null"; } }
private async Task Initialize() { var query = BluetoothLEDevice.GetDeviceSelector(); var deviceList = await DeviceInformation.FindAllAsync(query); var deviceInfo = deviceList.Where(x => x.Name == "UART").FirstOrDefault(); var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var deviceServices = bleDevice.GattServices; var deviceSvc = deviceServices.Where(svc => svc.AttributeHandle == 0x0024).FirstOrDefault(); var characteristics = deviceSvc.GetAllCharacteristics(); _notifyCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x0025).FirstOrDefault(); _writeCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x0028).FirstOrDefault(); _readCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x002a).FirstOrDefault(); _notifyCharacteristic.ValueChanged += OnValueChanged; await _notifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); }
void recordAccessControlPoint_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { this.IRecordAccessControlPointCharacteristic.ProcessData(args.CharacteristicValue); }
private void glucoseMeasurementNotification(GattCharacteristic sender, GattValueChangedEventArgs args) { var measurementObject = (GlucoseMeasurementValue)this.IGlucoseMeasurementCharacteristic.ProcessData(args.CharacteristicValue); if (MeasurementNotification != null) MeasurementNotification(measurementObject); }
private async void NotificationSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { //Received 8 bytes about some kind of notification var valueBytes = args.CharacteristicValue.ToArray(); var dat = ByteArrayToNotificationSourceData(valueBytes); if (dat.EventFlags.HasFlag(EventFlags.EventFlagPreExisting)) { //We dont care about old notifications return; } FlagCache[dat.NotificationUID] = dat.EventFlags; //Ask for more data through the control point characteristic var attributes = new GetNotificationAttributesData { CommandId = 0x0, NotificationUID = dat.NotificationUID, AttributeId1 = (byte) NotificationAttribute.Title, AttributeId1MaxLen = 16, AttributeId2 = (byte) NotificationAttribute.Message, AttributeId2MaxLen = 32 }; var bytes = StructureToByteArray(attributes); try { var status = await this.ControlPointCharacteristic.WriteValueAsync(bytes.AsBuffer(), GattWriteOption.WriteWithResponse); } catch (Exception) { } }
private async void DataSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { var stream = args.CharacteristicValue.AsStream(); var br = new BinaryReader(stream); var cmdId = br.ReadByte(); var notUid = br.ReadUInt32(); var attr1 = (NotificationAttribute)br.ReadByte(); var attr1len = br.ReadUInt16(); var attr1val = br.ReadChars(attr1len); var attr2 = (NotificationAttribute) br.ReadByte(); var attr2len = br.ReadUInt16(); var attr2val = br.ReadChars(attr2len); EventFlags? flags = null; if(FlagCache.ContainsKey(notUid)) { flags = FlagCache[notUid]; } var not = new PlainNotification() { EventFlags = flags, Uid = notUid, Title = new string(attr1val), Message = new string(attr2val) }; OnNotification?.Invoke(not); }
private void ClearSelectedCharacteristic() { if (selectedCharacteristic != null) { if (isValueChangedHandlerRegistered) { selectedCharacteristic.ValueChanged -= Characteristic_ValueChanged; isValueChangedHandlerRegistered = false; } selectedCharacteristic = null; } }
public BluetoothLEAttributeDisplay(GattCharacteristic characteristic) { this.characteristic = characteristic; AttributeDisplayType = AttributeType.Characteristic; }
/** * \fn connectDeviceAsync */ public async Task <uint> ConnectDeviceAsync(String macAddress) { uint uiErrorCode = ErrorServiceHandlerBase.ERR_ELA_BLE_COMMUNICATION_NOT_CONNECTED; try { ulong ulMacAddress = MacAddress.macAdressHexaToLong(macAddress); // try to get data m_ConnectedDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(ulMacAddress); if (null != m_ConnectedDevice) { m_Gatt = await m_ConnectedDevice.GetGattServicesAsync(BluetoothCacheMode.Cached); if (null != m_Gatt) { foreach (GattDeviceService service in m_Gatt.Services) { if (service.Uuid.ToString().Equals(NORDIC_UART_SERVICE)) { bool bFoundRx = false; bool bFoundTx = false; m_Characteristics = await service.GetCharacteristicsAsync(); foreach (var charac in m_Characteristics.Characteristics) { if (charac.Uuid.ToString().Equals(NORDIC_UART_TX_CHAR)) { m_TxNordicCharacteristic = charac; bFoundTx = true; } if (charac.Uuid.ToString().Equals(NORDIC_UART_RX_CHAR)) { m_RxNordicCharacteristic = charac; var result = await m_RxNordicCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (result == GattCommunicationStatus.Success) { m_RxNordicCharacteristic.ValueChanged += AssociatedCharacteristic_ValueChanged; } bFoundRx = true; } // if (true == bFoundRx && true == bFoundTx) { m_IsConnected = true; uiErrorCode = ErrorServiceHandlerBase.ERR_OK; } } } } } } } catch (Exception ex) { m_IsConnected = false; //return ErrorServiceHandlerBase.ERR_CONNECT_ERROR; throw new ElaBleException($"Exception while trying to connect to device {macAddress}.", ex); } // return(uiErrorCode); }
private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { // BT_Code: An Indicate or Notify reported that the value has changed. // Display the new value with a timestamp. var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat); var message = $"Value at {DateTime.Now:hh:mm:ss.FFF}: {newValue}"; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => CharacteristicLatestValue.Text = message); }
//public event Action<ApplicationAttributeCollection> ApplicationAttributesReceived; public DataSource(GattCharacteristic c) { this.Characteristic = c; }
// Handle the recieved data from the notification event. void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { string result = string.Empty; const byte HEART_RATE_VALUE_FORMAT = 0x01; var data = new byte[args.CharacteristicValue.Length]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data); ushort heartRate; if (data.Length >= 2) { byte flags = data[0]; bool isHeartRateValueSizeLong = ((flags & HEART_RATE_VALUE_FORMAT) != 0); int currentOffset = 1; if (isHeartRateValueSizeLong) { heartRate = (ushort)((data[currentOffset + 1] << 8) + data[currentOffset]); currentOffset += 2; } else { heartRate = data[currentOffset]; currentOffset++; } result =string.Format("{0} bpm", heartRate); } this.ReturnResult(result); }
private void GattCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { if (args == null) return; if (args.CharacteristicValue.Length == 0) return; var arrayLenght = (int)args.CharacteristicValue.Length; var hrData = new byte[arrayLenght]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(hrData); //Convert to string var hrValue = ProcessData(hrData); Debug.WriteLine(hrValue); HeartRateValue = hrValue.ToString(); HrCollection.Add(new HrModel { HeartRate = hrValue }); DisplayHrData(); }
private async void ScanDevice(BLEDevice b) { StatusUpdate.Text = "Using device " + b.Name; log("Using device " + b.Name + ", " + b.id); log("Enumerating Services and Characteristics..."); var dev = await BluetoothLEDevice.FromIdAsync(b.id); if (dev == null) { log("... Couldn't get Device from ID"); return; } var services = await dev.GetGattServicesAsync(); if (services == null || services.Services == null) { log("... Couldn't get services from device"); return; } bool found = false; foreach (GattDeviceService gds in services.Services) { log(b.Name + ": s" + gds.Uuid); if (gds.Uuid.ToString().Equals("6e400001-b5a3-f393-e0a9-e50e24dcca9e")) // nordic serial { found = true; } var characts = await gds.GetCharacteristicsAsync(); if (characts == null || characts.Characteristics == null) { log(b.Name + ": s" + gds.Uuid + ", couldn't enumerate characteristics"); continue; } foreach (GattCharacteristic gc in characts.Characteristics) { log(b.Name + ": s" + gds.Uuid + ", c" + gc.Uuid); if (found && gc.Uuid.ToString().Equals("6e400003-b5a3-f393-e0a9-e50e24dcca9e")) // rx { read = gc; var res = await read.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (res == GattCommunicationStatus.Success) { log("Registered for notifications"); read.ValueChanged += RX; } } if (found && gc.Uuid.ToString().Equals("6e400002-b5a3-f393-e0a9-e50e24dcca9e")) // tx { write = gc; } } } if (!found) { log("Compatable service not found"); Open.IsEnabled = false; Upload.IsEnabled = false; } else { Open.IsEnabled = true; } }
private void batterLevelCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { try { BatteryLevelCharacteristics result; var batteryLevelData = new byte[args.CharacteristicValue.Length]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(batteryLevelData); result = BatteryLevelCharacteristicsHandler.ProcessDataBatteryLevel(batteryLevelData); if(ValueChangeCompleted != null) { ValueChangeCompleted(result); } } catch (Exception ex) { var error = ex.StackTrace; } }
public async Task<byte[]> ReadValue() { if (dataCharacteristic == null) dataCharacteristic = deviceService.GetCharacteristics(new Guid(sensorDataUuid))[0]; GattReadResult readResult = await dataCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached); if (readResult.Status == GattCommunicationStatus.Unreachable) throw new ArgumentOutOfRangeException(); var sensorData = new byte[readResult.Value.Length]; DataReader.FromBuffer(readResult.Value).ReadBytes(sensorData); return sensorData; }
private void CharacteristicList_SelectionChanged() { ClearSelectedCharacteristic(); var attributeInfoDisp = (BluetoothLEAttributeDisplay)CharacteristicList.SelectedItem; if (attributeInfoDisp == null) { EnableCharacteristicPanels(GattCharacteristicProperties.None); return; } selectedCharacteristic = attributeInfoDisp.characteristic; isValueChangedHandlerRegistered = false; // BT_Code: There's no need to get presentation format unless there's at least one descriptor. presentationFormat = null; var descriptors = selectedCharacteristic.GetAllDescriptors(); if (descriptors.Count > 0) { if (selectedCharacteristic.PresentationFormats.Count > 1) { // It's difficult to figure out how to split up a characteristic and encode its different parts propertly. // In this case, we'll just encode the whole thing to a string to make it easy to print out. } else { // Get the presentation format since there's only one way of presenting it presentationFormat = selectedCharacteristic.PresentationFormats[0]; } } // Enable/disable operations based on the GattCharacteristicProperties. EnableCharacteristicPanels(selectedCharacteristic.CharacteristicProperties); }
private void dataCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { var data = new byte[args.CharacteristicValue.Length]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data); OnSensorValueChanged(data, args.Timestamp); }
public void characteristics_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs EventArgs) { string base64String = null; string JsonString=null; byte[] forceData = new byte[EventArgs.CharacteristicValue.Length]; DataReader.FromBuffer(EventArgs.CharacteristicValue).ReadBytes(forceData); Thread.Sleep(waiting_time); base64String = System.Convert.ToBase64String(forceData, 0, forceData.Length); //currentDeviceCharacteristic[NotifyCharaIndex].Value = currentDeviceCharacteristic[NotifyCharaIndex].Value + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length); //JsonString = "\"" + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length)+ "\""; JsonString = "\"" + base64String + "\""; //JsonString = Regex.Replace(JsonString, "\n", "\\n"); //JsonString = Regex.Replace(JsonString, "\r", "\\r"); PluginResult result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"subscribedResult\",\"value\":" + JsonString + "}"); result.KeepCallback = true; DispatchCommandResult(result, callbackId_sub); }
public virtual async Task DisableSensor() { GattCharacteristic configCharacteristic = deviceService.GetCharacteristics(new Guid(sensorConfigUuid))[0]; GattCommunicationStatus status = await configCharacteristic.WriteValueAsync((new byte[] { 0 }).AsBuffer()); }