private async Task disableSensor(int sensor) { Debug.WriteLine("Begin disable of sensor: " + sensor.ToString()); GattDeviceService gattService = serviceList[sensor]; if (gattService != null) { // Disable notifications IReadOnlyList <GattCharacteristic> characteristicList; if (sensor >= 0 && sensor <= 2) { characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX)); } else { characteristicList = gattService.GetCharacteristics(LUXOMETER_CONFIGURATION_GUID); } if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); } } } activeCharacteristics[sensor] = null; Debug.WriteLine("End disable for sensor: " + sensor.ToString()); }
// // Summary: // Initializes all the CRTP service and characteristic objects // Uses the first of each that's found public async Task <Boolean> InitCrtpService() { var bthServices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync( GattDeviceService.GetDeviceSelectorFromUuid( crtpServiceGuid), null); // Use the first instance of this guid if (bthServices.Count >= 1) { crtpService = await GattDeviceService.FromIdAsync(bthServices[0].Id); if (crtpService != null) { var chars = crtpService.GetCharacteristics(crtpCharacteristicGuid); if (chars.Count >= 1) { crtpChar = chars[0]; } var upChars = crtpService.GetCharacteristics(crtpUpCharacteristicGuid); if (upChars.Count >= 1) { crtpUpChar = upChars[0]; } var downChars = crtpService.GetCharacteristics(crtpDownCharacteristicGuid); if (downChars.Count >= 1) { crtpDownChar = downChars[0]; } } } return((crtpService != null) && (crtpChar != null) && (crtpUpChar != null) && (crtpDownChar != null)); }
public async void StarDfu(GattDeviceService deviceFirmwareUpdate) { if (!IsServiceChanged || !IsServiceInitialized) { throw new Exception(); } deviceFirmwareUpdateControlPointCharacteristics.StartBootLoaderCommand(this.firmwareType); controlPoint = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUControlPoint).FirstOrDefault(); packet = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUPacket).FirstOrDefault(); dFUVersion = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUVersion).FirstOrDefault(); try { if (controlPoint != null) { controlPoint.ValueChanged += controlPoint_ValueChanged; await controlPoint.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); var buffer = deviceFirmwareUpdateControlPointCharacteristics.StartBootLoaderCommand(this.firmwareType); await controlPoint.WriteValueAsync(buffer); } if (packet != null) { var buffer = deviceFirmwareUpdatePacketCharacteristics.ImageSizeCommand(initialSizes); await packet.WriteValueAsync(buffer, GattWriteOption.WriteWithoutResponse); } } catch (Exception) { } }
// --------------------------------------------------- // Hardware Configuration Helper Functions // --------------------------------------------------- // Retrieve Barometer Calibration data private async void calibrateBarometer() { GattDeviceService gattService = serviceList[BAROMETRIC_PRESSURE]; if (gattService != null) { // Set Barometer configuration to 2, so that calibration data is saved var characteristicList = gattService.GetCharacteristics(BAROMETER_CONFIGURATION_GUID); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte((Byte)0x02); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } // Save Barometer calibration data characteristicList = gattService.GetCharacteristics(BAROMETER_CALIBRATION_GUID); if (characteristicList != null) { GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached); baroCalibrationData = new byte[result.Value.Length]; DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData); } } }
/// <summary> /// Finds connected Bluetooth device with the service GUID. /// </summary> /// <exception cref="System.TimeoutException"> /// Could not find connected IrDA bridge within timeout. /// </exception> /// <returns></returns> public async void InitializeTranciever() { device = (await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(serviceGuid)))[0]; if (device != null) { GattCommunicationStatus status; service = await GattDeviceService.FromIdAsync(device.Id); commandData = service.GetCharacteristics(new Guid("d40c53c0-4462-4714-99cc-f90772bd7f61"))[0]; respData = service.GetCharacteristics(new Guid("54d8deac-1c1d-4841-947f-ac4406f3034e"))[0]; error = service.GetCharacteristics(new Guid("c29a164e-9406-4d81-800b-29efcb447933"))[0]; respData.ValueChanged += Characteristic_ValueChanged; error.ValueChanged += Characteristic_ValueChanged; status = await respData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); status = await error.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { DeviceInitialized(); } else { DeviceNotInitialied(); } } }
public async void Connect() { ClearBluetoothLEDevice(); try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(BluetoothLEDeviceId); bluetoothLeDevice.ConnectionStatusChanged += BluetoothLeDevice_ConnectionStatusChanged; } catch (Exception ex) when((uint)ex.HResult == 0x800710df) { // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on. } if (bluetoothLeDevice != null) { Guid ancsUuid = new Guid("7905F431-B5CE-4E99-A40F-4B1E122D00D0"); try { GattService = bluetoothLeDevice.GetGattService(ancsUuid); } catch (Exception ex) { throw new Exception("Apple Notification Center Service not found."); } if (GattService == null) { throw new Exception("Apple Notification Center Service not found."); } else { Guid notificationSourceUuid = new Guid("9FBF120D-6301-42D9-8C58-25E699A21DBD"); Guid controlPointUuid = new Guid("69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9"); Guid dataSourceUuid = new Guid("22EAC6E9-24D6-4BB5-BE44-B36ACE7C7BFB"); try { ControlPoint = new ControlPoint(GattService.GetCharacteristics(controlPointUuid).First()); DataSource = new DataSource(GattService.GetCharacteristics(dataSourceUuid).First()); NotificationSource = new NotificationSource(GattService.GetCharacteristics(notificationSourceUuid).First()); } catch (Exception ex) { throw new Exception(ex.Message); } } } else { ClearBluetoothLEDevice(); throw new Exception("Failed to connect to device."); } }
/// <summary> /// Disables the sensor by writing a 0 to the config characteristic. /// </summary> /// <returns></returns> /// <exception cref="DeviceNotInitializedException">Thrown if sensor has not been initialized successfully.</exception> /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception> public virtual async Task DisableSensor() { GattCharacteristic configCharacteristic = deviceService.GetCharacteristics(new Guid(sensorConfigUuid))[0]; GattCommunicationStatus status = await configCharacteristic.WriteValueAsync((new byte[] { 0 }).AsBuffer()); if (status == GattCommunicationStatus.Unreachable) { throw new ArgumentOutOfRangeException(); } }
public bool CanNotify(Guid characteristicGuid) { try { GattCharacteristic characteristic = _service.GetCharacteristics(characteristicGuid).FirstOrDefault(); return(characteristic != null && characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)); } catch { } return(false); }
/// <summary> /// Disables the sensor by writing a 0 to the config characteristic. /// </summary> /// <returns></returns> /// <exception cref="DeviceNotInitializedException">Thrown if sensor has not been initialized successfully.</exception> /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception> public virtual async Task DisableSensor() { Validator.Requires <DeviceNotInitializedException>(deviceService != null); GattCharacteristic configCharacteristic = deviceService.GetCharacteristics(new Guid(sensorConfigUuid))[0]; GattCommunicationStatus status = await configCharacteristic.WriteValueAsync((new byte[] { 0 }).AsBuffer()); if (status == GattCommunicationStatus.Unreachable) { throw new DeviceUnreachableException(DeviceUnreachableException.DEFAULT_UNREACHABLE_MESSAGE); } }
public async void SendMotorCommand(Boolean on, int tilt, int forward, int turn, int up, float scale) { var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors); var characteristic = characteristics[0]; var writer = new DataWriter(); try { writer.WriteByte(2); writer.WriteByte((byte)_motorCounter); writer.WriteByte(2); writer.WriteByte(0); writer.WriteByte(2); writer.WriteByte(0); if (on) { writer.WriteByte(1); } else { writer.WriteByte(0); } // is byte casting necessary??? writer.WriteByte((byte)(tilt & 0xFF)); writer.WriteByte((byte)(forward & 0xFF)); writer.WriteByte((byte)(turn & 0xFF)); writer.WriteByte((byte)(up & 0xFF)); //writer.WriteDouble(scale); // well, but I need different endian :( await characteristic.WriteValueAsync(writer.DetachBuffer()); } catch (IOException e) { Debug.WriteLine(e); } //var gattTransaction = new GattReliableWriteTransaction(); //gattTransaction.WriteValue(characteristic, writer.DetachBuffer()); //var status = await gattTransaction.CommitAsync(); //switch (status) //{ // case GattCommunicationStatus.Success: // AddLogAction("Writing to your device OK !"); // break; // case GattCommunicationStatus.Unreachable: // AddLogAction("Writing to your device Failed !"); // break; //} }
public bool Initialiser() { try { _gattCaracteristiqueConfig = _gattService.GetCharacteristics(_ConfCaracGuid).First(); _gattCaracteristiqueData = _gattService.GetCharacteristics(_DataCaracGuid).First(); return(true); } catch { _gattCaracteristiqueConfig = null; _gattCaracteristiqueData = null; } return(false); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { selectedBtleDevice = (BluetoothLEDevice)e.Parameter; mwGattService = selectedBtleDevice.GetGattService(GUID_METAWEAR_SERVICE); foreach (var characteristic in selectedBtleDevice.GetGattService(GUID_DEVICE_INFO_SERVICE).GetAllCharacteristics()) { var result = await characteristic.ReadValueAsync(); string value = result.Status == GattCommunicationStatus.Success ? System.Text.Encoding.UTF8.GetString(result.Value.ToArray(), 0, (int)result.Value.Length) : "N/A"; mwDeviceInfoChars.Add(characteristic.Uuid, value); outputListView.Items.Add(new ConsoleLine(ConsoleEntryType.INFO, DEVICE_INFO_NAMES[characteristic.Uuid] + ": " + value)); } mwNotifyChar = mwGattService.GetCharacteristics(METAWEAR_NOTIFY_CHARACTERISTIC).First(); await mwNotifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); mwNotifyChar.ValueChanged += new TypedEventHandler <Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic, GattValueChangedEventArgs>((Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic sender, GattValueChangedEventArgs obj) => { byte[] response = obj.CharacteristicValue.ToArray(); mbl_mw_connection_notify_char_changed(mwBoard, response, (byte)response.Length); }); }
/// <summary> /// Register a ValueChanged callback on a device Characteristic. /// The Characteristic must be readable and send Notifications. /// </summary> /// <param name="service">The Service containing the Characteristic</param> /// <param name="readCharacteristicUUID">The UUID of the Characteristic</param> /// <param name="valueChangedHandler">The event handler callback</param> /// <returns>A GattCharacteristic for the which the event handler was /// registered or null if the Characteristic wasn’t found</returns> private async Task <GattCharacteristic> registerCharacteristicChangedCallback(GattDeviceService service, string readCharacteristicUUID, TypedEventHandler <GattCharacteristic, GattValueChangedEventArgs> valueChangedHandler) { Debug.Assert(service != null, "Null service passed as argument."); Debug.Assert(readCharacteristicUUID != null, "Null Characteristic UUID pass as argument."); //Obtain the characteristic we want to interact with var characteristics = service.GetCharacteristics(new Guid(readCharacteristicUUID)); if (characteristics.Count == 0) { return(null); } var characteristic = characteristics[0]; //Subscribe to value changed event characteristic.ValueChanged += valueChangedHandler; //Set configuration to notify await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); return(characteristic); }
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); } } }
/// <summary> /// Returns a GATT characteristic for a sensor's data service. /// </summary> /// <param name="sensor">the sensor you want to read</param> /// <returns>the GATT characteristic</returns> public static async Task <GattCharacteristic> GetCharacteristic(Sensor sensor, Attribute attribute) { //Get a query for devices with this service string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensor.GetUUID(Attribute.Service))); //seek devices using the query var deviceCollection = await DeviceInformation.FindAllAsync(deviceSelector); //return info for the first device you find DeviceInformation device = deviceCollection.FirstOrDefault(); if (device == null) { throw new Exception("Device not found."); } // use the id to get the service GattDeviceService service = await GattDeviceService.FromIdAsync(device.Id); //get matching characteristic IReadOnlyList <GattCharacteristic> characteristics = service.GetCharacteristics(new Guid(sensor.GetUUID(attribute))); if (characteristics.Count == 0) { throw new Exception("characteristic not found."); } //Return first characteristic in the list. return(characteristics[0]); }
/// <summary> /// Reads a value from from a service of a device /// </summary> /// <param name="gattDeviceService">GattDeviceService of a connected bluetooth device</param> /// <param name="valueServiceUuid">Uuid of the characteristic you want to read from</param> /// <returns>Raw data read from the sensor</returns> /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception> /// <exception cref="Exception">Thrown on purpose if the GattDeviceService doesn't provide the specified characteristic.</exception> public async static Task <byte[]> ReadValue(GattDeviceService gattDeviceService, string valueServiceUuid) { Validator.RequiresNotNull(gattDeviceService, "gattDeviceService"); Validator.RequiresNotNullOrEmpty(valueServiceUuid, "valueServiceUuid"); IReadOnlyList <GattCharacteristic> characteristics = gattDeviceService.GetCharacteristics(new Guid(valueServiceUuid)); if (characteristics.Count == 0) { throw new Exception("Could not find specified characteristic."); } GattCharacteristic sidCharacteristic = characteristics[0]; GattReadResult res = await sidCharacteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached); if (res.Status == GattCommunicationStatus.Unreachable) { throw new DeviceUnreachableException(DeviceUnreachableException.DEFAULT_UNREACHABLE_MESSAGE); } var data = new byte[res.Value.Length]; DataReader.FromBuffer(res.Value).ReadBytes(data); return(data); }
/* Method */ public async void InitializeDevice() { /*** Get a list of devices that match desired service UUID ***/ Guid selectedService = new Guid("0000AA10-0000-1000-8000-00805F9B34FB"); var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(selectedService)); /*** Create an instance of the eTDS device ***/ DeviceInformation eTdsDevice = devices[0]; // Only one device should be matching the eTDS-specific service UUID Console.WriteLine("Device Name: {0}", eTdsDevice.Name); // Display the name of the device /*** Create an instance of the specified eTDS service ***/ GattDeviceService myService = await GattDeviceService.FromIdAsync(eTdsDevice.Id); Console.WriteLine("Service UUID: {0}", myService.Uuid.ToString()); /*** Create an instance of the characteristic of the specified service ***/ Guid selectedCharacteristic = new Guid("0000AA11-0000-1000-8000-00805F9B34FB"); const int CHARACTERISTIC_INDEX = 0; GattCharacteristic myCharacteristic = myService.GetCharacteristics(selectedCharacteristic)[CHARACTERISTIC_INDEX]; myCharacteristic.ProtectionLevel = GattProtectionLevel.Plain; // Set security level to "No encryption" /*** Create an event handler when the characteristic value changes ***/ myCharacteristic.ValueChanged -= myCharacteristic_ValueChanged; GattCommunicationStatus disableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); Console.WriteLine("Disable Notification Status: {0}", disableNotifStatus); myCharacteristic.ValueChanged += myCharacteristic_ValueChanged; GattCommunicationStatus enableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); Console.WriteLine("Enable Notification Status: {0}", disableNotifStatus); }//end method InitializeDevice
public async Task <byte[]> ReadValueAsync(Guid serviceId, Guid featureId) { try { GattDeviceService service = _device.GetGattService(serviceId); if (service == null) { Debug.WriteLine($"Unable to find service {serviceId}"); return(null); } GattCharacteristic feature = service.GetCharacteristics(featureId).SingleOrDefault(); if (feature == null) { Debug.WriteLine($"Unable to find feature {featureId}"); return(null); } GattReadResult readResult = await feature.ReadValueAsync(); if (readResult.Status == GattCommunicationStatus.Unreachable) { Debug.WriteLine("Unable to read"); return(null); } return(readResult.Value.ToArray()); } catch (Exception e) { Debug.WriteLine($"Exception : {e.Message} {e.StackTrace}"); } return(null); }
/// <summary> /// Returns a GATT characteristic for a sensor's data service. /// </summary> /// <param name="sensor">the sensor you want to read</param> /// <returns>the GATT characteristic</returns> static async Task <GattCharacteristic> GetCharacteristic(Sensor sensor) { //Get a query for devices with this service string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensor.GetServiceUUID())); //seek devices using the query var deviceCollection = await DeviceInformation.FindAllAsync(deviceSelector); //return info for the first device you find DeviceInformation device = deviceCollection.FirstOrDefault(); if (device == null) { throw new Exception("Device not found."); } // using the id get the service GattDeviceService service = await GattDeviceService.FromIdAsync(device.Id); //get all characteristics IReadOnlyList <GattCharacteristic> characteristics = service.GetCharacteristics(new Guid(sensor.GetDataUUID())); if (characteristics.Count == 0) { throw new Exception("characteristic not found."); } //Reaturn event handler for first characteristic return(characteristics[0]); }
public async Task <bool> WriteValueAsync(Guid serviceId, Guid featureId, byte[] data) { try { GattDeviceService service = _device.GetGattService(serviceId); if (service == null) { Debug.WriteLine($"Unable to find service {serviceId}"); return(false); } GattCharacteristic feature = service.GetCharacteristics(featureId).SingleOrDefault(); if (feature == null) { Debug.WriteLine($"Unable to find feature {featureId}"); return(false); } await feature.WriteValueAsync(data.AsBuffer()); return(true); } catch (Exception e) { Debug.WriteLine($"Exception : {e.Message} {e.StackTrace}"); } return(false); }
//~HRGATTConnect() //{ // Dispose(false); //} public async void Initialize() { try { var heartrateServices = await Windows.Devices.Enumeration .DeviceInformation.FindAllAsync(GattDeviceService .GetDeviceSelectorFromUuid( GattServiceUuids.HeartRate), null); firstHeartRateMonitorService = await GattDeviceService.FromIdAsync(heartrateServices[0].Id); Debug.WriteLine("serviceName: " + heartrateServices[0].Name); hrMonitorCharacteristics = firstHeartRateMonitorService.GetCharacteristics( GattCharacteristicUuids.HeartRateMeasurement)[0]; hrMonitorCharacteristics.ValueChanged += hrMeasurementChanged; await hrMonitorCharacteristics .WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); disposed = false; } catch (Exception e) { } }
public async void Unsubscribe() { characteristics = service.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement)[0]; try { // BT_Code: Must write the CCCD in order for server to send notifications. // We receive them in the ValueChanged event handler. // Note that this sample configures either Indicate or Notify, but not both. var result = await characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); if (result == GattCommunicationStatus.Success) { subscribedForNotifications = false; if (subscribedForNotifications) { characteristics.ValueChanged -= Characteristic_ValueChanged; characteristics = null; subscribedForNotifications = false; } Debug.WriteLine("Successfully un-registered for notifications"); } else { Debug.WriteLine($"Error un-registering for notifications: {result}"); } } catch (UnauthorizedAccessException ex) { // This usually happens when a device reports that it support notify, but it actually doesn't. Debug.WriteLine(ex.Message); } }
private async Task ConfigureServiceForNotificationsAsync() { try { _characteristic = _service.GetCharacteristics(CHARACTERISTIC_UUID)[CHARACTERISTIC_INDEX]; _characteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired; _characteristic.ValueChanged += Characteristic_ValueChanged; var currentDescriptorValue = await _characteristic.ReadClientCharacteristicConfigurationDescriptorAsync(); if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) || (currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != CHARACTERISTIC_NOTIFICATION_TYPE)) { GattCommunicationStatus status = await _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE); if (status == GattCommunicationStatus.Unreachable) { StartDeviceConnectionWatcher(); } } } catch (Exception e) { LoggerWrapper.Instance.WriteToLogFile(e); } }
private async void StartGattServiceWatcher(DeviceInformation deviceInfoDisp) { //Get the Bluetooth address for filtering the watcher var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfoDisp.Id); var selector = "(" + GattDeviceService.GetDeviceSelectorFromUuid(IoServiceUuid) + ")" + " AND (System.DeviceInterface.Bluetooth.DeviceAddress:=\"" + bleDevice.BluetoothAddress.ToString("X") + "\")"; gattServiceWatcher = DeviceInformation.CreateWatcher(selector); // Hook up handlers for the watcher events before starting the watcher gattServiceWatcher.Added += async(watcher, deviceInfo) => { weDoIoService = await GattDeviceService.FromIdAsync(deviceInfo.Id); outputCommandCharacteristic = weDoIoService.GetCharacteristics(OutputCommandCharacteristicGuid)[0]; }; //gattServiceWatcher.Updated += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => ); //gattServiceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => ); //gattServiceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => ); //gattServiceWatcher.Stopped += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => ); gattServiceWatcher.Start(); }
private async void StartGattServiceWatcher() { //Get the Bluetooth address for filtering the watcher BluetoothLEDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as BluetoothLEDeviceDisplay; BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfoDisp.Id); string selector = "(" + GattDeviceService.GetDeviceSelectorFromUuid(IoServiceUuid) + ")" + " AND (System.DeviceInterface.Bluetooth.DeviceAddress:=\"" + bleDevice.BluetoothAddress.ToString("X") + "\")"; gattServiceWatcher = DeviceInformation.CreateWatcher(selector); // Hook up handlers for the watcher events before starting the watcher gattServiceWatcher.Added += new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) => { // If the selected device is a WeDo device, enable the controls await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { weDoIoService = await GattDeviceService.FromIdAsync(deviceInfo.Id); outputCommandCharacteristic = weDoIoService.GetCharacteristics(OutputCommandCharacteristicGuid)[0]; ForwardButton.IsEnabled = true; StopButton.IsEnabled = true; BackwardButton.IsEnabled = true; }); }); gattServiceWatcher.Updated += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { //Do nothing }); }); gattServiceWatcher.EnumerationCompleted += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { //Do nothing }); }); gattServiceWatcher.Removed += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { //Do nothing }); }); gattServiceWatcher.Stopped += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { //Do nothing }); }); gattServiceWatcher.Start(); }
public void Land() { var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_DateTime); byte[] commandToWrite = { 4, (byte)_settingsCounter, 2, 0, 3, 0 }; SendCommandTo1StChar(characteristics, commandToWrite); _settingsCounter++; }
private static async Task <string> ReadStringCharacteristicAsync(GattDeviceService service, Guid guid, CancellationToken cancellationToken) { var characteristic = service.GetCharacteristics(guid).SingleOrDefault(); if (characteristic != null) { return(await characteristic.ReadValueAsync().AsStringOrDefault(cancellationToken) ?? ""); } return(null); }
private void ConfigureServices(IAsyncOperation <GattDeviceService> AsyncInfo, AsyncStatus AsyncStatus) { mService = AsyncInfo.GetResults(); mCharacteristic = mService.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement)[CHARACTERISTIC_INDEX]; mCharacteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired; mCharacteristic.ValueChanged += CharacteristicValueChanged; IAsyncOperation <GattReadClientCharacteristicConfigurationDescriptorResult> characteristicConfiguration = mCharacteristic.ReadClientCharacteristicConfigurationDescriptorAsync(); characteristicConfiguration.Completed = CharacteristicConfiguration; }
private async Task <byte[]> ReadValue(string Uuid) { GattCharacteristic sidCharacteristic = deviceService.GetCharacteristics(new Guid(Uuid))[0]; GattReadResult res = await sidCharacteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached); byte[] data = new byte[res.Value.Length]; DataReader.FromBuffer(res.Value).ReadBytes(data); return(data); }
public async Task<bool> Start(GattDeviceService linkLossDeviceService) { if (linkLossDeviceService != null && linkLossDeviceService.Uuid != GattServiceUuids.LinkLoss) return IsServiceStarted = false; this.linkLossDeviceService = linkLossDeviceService; var result = await RegisterDeviceServiceAsBackgroundTask(linkLossDeviceService); alertLevel = linkLossDeviceService.GetCharacteristics(GattCharacteristicUuids.AlertLevel).FirstOrDefault(); if (result != null) return IsServiceStarted = true; else return IsServiceStarted = false; }
public async Task <List <string> > getDevices() { Debug.WriteLine("C"); foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("00002220-0000-1000-8000-00805f9b34fb")))) { Debug.WriteLine("D"); Debug.WriteLine(di.Name); GattDeviceService bleService = await GattDeviceService.FromIdAsync(di.Id); Debug.WriteLine(bleService.Device.ConnectionStatus.ToString()); accConfig = bleService.GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(0x2222))[0]; Debug.WriteLine("E:Write_char"); accData = bleService.GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(0x2221))[0]; accData.ValueChanged += accData_ValueChanged; // I have no idea what the next line does await accData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); Debug.WriteLine("F:Read_char"); } return(deviceList); }
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"; } }
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); } } }
public async void StarDfu(GattDeviceService deviceFirmwareUpdate) { if (!IsServiceChanged || !IsServiceInitialized) throw new Exception(); deviceFirmwareUpdateControlPointCharacteristics.StartBootLoaderCommand(this.firmwareType); controlPoint = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUControlPoint).FirstOrDefault(); packet = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUPacket).FirstOrDefault(); dFUVersion = deviceFirmwareUpdate.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.DFUVersion).FirstOrDefault(); try { if (controlPoint != null) { controlPoint.ValueChanged += controlPoint_ValueChanged; await controlPoint.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); var buffer = deviceFirmwareUpdateControlPointCharacteristics.StartBootLoaderCommand(this.firmwareType); await controlPoint.WriteValueAsync(buffer); } if(packet != null) { var buffer = deviceFirmwareUpdatePacketCharacteristics.ImageSizeCommand(initialSizes); await packet.WriteValueAsync(buffer, GattWriteOption.WriteWithoutResponse); } } catch(Exception) { } }
public async void InitializeServiceAsync(string deviceId, Guid characteristicsGuid) { 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; var characteristic = _service.GetCharacteristics(characteristicsGuid); _characteristic = characteristic[0]; _characteristic.ValueChanged += Oncharacteristic_ValueChanged; //this appears to be problematic with my simulator, thus commenting out the checking, writing always works just fine with all ways tested so far /* 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) { if (DeviceConnectionUpdated != null) { DeviceConnectionUpdated(false, "Accessing device failed: " + e.Message); } } }
private static void ValidateChars(string deviceId, GattDeviceService service, Guid charsUuid) { var chars = service.GetCharacteristics(charsUuid); if (chars == null || chars.Count == 0) return; var charsName = CharacteristicUuidsResolver.GetNameFromUuid(charsUuid); Debug.WriteLine($" {chars.Count} found for {charsName}"); foreach (GattCharacteristic characteristic in chars) { var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid); var friendlyDesc = characteristic.UserDescription; Debug.WriteLine($" {charName} - {friendlyDesc} - {characteristic.ProtectionLevel}"); } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { selectedBtleDevice = (BluetoothLEDevice) e.Parameter; mwGattService = selectedBtleDevice.GetGattService(Gatt.METAWEAR_SERVICE); foreach(var characteristic in selectedBtleDevice.GetGattService(DEVICE_INFO_SERVICE).GetAllCharacteristics()) { var result = await characteristic.ReadValueAsync(); string value = result.Status == GattCommunicationStatus.Success ? System.Text.Encoding.UTF8.GetString(result.Value.ToArray(), 0, (int)result.Value.Length) : "N/A"; mwDeviceInfoChars.Add(characteristic.Uuid, value); outputListView.Items.Add(new ConsoleLine(ConsoleEntryType.INFO, DEVICE_INFO_NAMES[characteristic.Uuid] + ": " + value)); } mwNotifyChar = mwGattService.GetCharacteristics(Gatt.METAWEAR_NOTIFY_CHARACTERISTIC).First(); await mwNotifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); mwNotifyChar.ValueChanged += new TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs>((GattCharacteristic sender, GattValueChangedEventArgs obj) => { byte[] response = obj.CharacteristicValue.ToArray(); MetaWearBoard.HandleResponse(mwBoard, response, (byte)response.Length); }); }
protected GattCharacteristic GetCharacteristic(GattDeviceService deviceService, Guid characteristicUUID) { var characteristics = deviceService.GetCharacteristics(characteristicUUID); if (characteristics.Count > 0) { return characteristics[0]; } else { return null; } }
/// <summary> /// Register a ValueChanged callback on a device Characteristic. /// The Characteristic must be readable and send Notifications. /// </summary> /// <param name="service">The Service containing the Characteristic</param> /// <param name="readCharacteristicUUID">The UUID of the Characteristic</param> /// <param name="valueChangedHandler">The event handler callback</param> /// <returns>A GattCharacteristic for the which the event handler was /// registered or null if the Characteristic wasn’t found</returns> private async Task<GattCharacteristic> registerCharacteristicChangedCallback(GattDeviceService service, string readCharacteristicUUID, TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> valueChangedHandler) { Debug.Assert(service != null, "Null service passed as argument."); Debug.Assert(readCharacteristicUUID != null, "Null Characteristic UUID pass as argument."); //Obtain the characteristic we want to interact with var characteristics = service.GetCharacteristics(new Guid(readCharacteristicUUID)); if (characteristics.Count == 0) return null; var characteristic = characteristics[0]; //Subscribe to value changed event characteristic.ValueChanged += valueChangedHandler; //Set configuration to notify await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); return characteristic; }
/// <summary> /// Reads a value from from a service of a device /// </summary> /// <param name="gattDeviceService">GattDeviceService of a connected bluetooth device</param> /// <param name="valueServiceUuid">Uuid of the characteristic you want to read from</param> /// <returns>Raw data read from the sensor</returns> /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception> /// <exception cref="Exception">Thrown on purpose if the GattDeviceService doesn't provide the specified characteristic.</exception> public async static Task<byte[]> ReadValue(GattDeviceService gattDeviceService, string valueServiceUuid) { Validator.RequiresNotNull(gattDeviceService, "gattDeviceService"); Validator.RequiresNotNullOrEmpty(valueServiceUuid, "valueServiceUuid"); IReadOnlyList<GattCharacteristic> characteristics = gattDeviceService.GetCharacteristics(new Guid(valueServiceUuid)); if (characteristics.Count == 0) throw new Exception("Could not find specified characteristic."); GattCharacteristic sidCharacteristic = characteristics[0]; GattReadResult res = await sidCharacteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached); if (res.Status == GattCommunicationStatus.Unreachable) throw new DeviceUnreachableException(DeviceUnreachableException.DEFAULT_UNREACHABLE_MESSAGE); var data = new byte[res.Value.Length]; DataReader.FromBuffer(res.Value).ReadBytes(data); return data; }
public async Task InitializeServiceAsync(DeviceInformation deviceInformation) { try { service_ = await GattDeviceService.FromIdAsync(deviceInformation.Id); if (service_ == null) { //rootPage.NotifyUser("Access to the device is denied, because the application was not granted access, " + // "or the device is currently in use by another application.", // NotifyType.StatusMessage); } else { start_ = DateTime.Now; // The Heart Rate Profile specifies that the Heart Rate Service will contain a single // Heart Rate Measurement Characteristic. var characteristics = service_.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement); var characteristic = characteristics[0]; // Register the event handler for receiving device notification data characteristic.ValueChanged += (sender, e) => { var dataReader = DataReader.FromBuffer(e.CharacteristicValue); var data = new byte[e.CharacteristicValue.Length]; dataReader.ReadBytes(data); // Process the raw data received from the device. var value = ProcessData(data); value.Timestamp = e.Timestamp - start_; context_.Post(nl => { datapoints_.Add(value); while (datapoints_.Count > this.StackingCount) { datapoints_.RemoveAt(0); } }, null); }; // Set the Client Characteristic Configuration descriptor on the device, // registering for Characteristic Value Changed notifications var status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Unreachable) { //rootPage.NotifyUser("Your device is unreachable, most likely the device is out of range, " + // "or is running low on battery, please make sure your device is working and try again.", // NotifyType.StatusMessage); } else { this.IsServiceInitialized = true; this.OnPropertyChanged("IsServiceInitialized"); } } } catch (Exception) { //rootPage.NotifyUser("ERROR: Accessing your device failed." + Environment.NewLine + e.Message, // NotifyType.ErrorMessage); } }