public void ConnectToArmband(Guid armbandGuid) { // identify myo MyoArmband myo = connectedMyos.Where(g => (g.Id == armbandGuid)).FirstOrDefault(); int myoIndex = connectedMyos.IndexOf(myo); if (myo == null) { Console.WriteLine("myo object was null"); return; } // hook control service, establishing a connection Task <GattDeviceServicesResult> grabIt = Task.Run(() => GetServiceAsync(myo.Device, myoGuids["MYO_SERVICE_GCS"])); grabIt.Wait(); var controlserv = grabIt.Result; myo.controlService = controlserv.Services.FirstOrDefault(); // ensure the control service is ready if (myo.controlService != null) { GattCharacteristicsResult fwCh = GetCharac(myo.controlService, myoGuids["MYO_FIRMWARE_CH"]).Result; myo.FW_charac = fwCh.Characteristics.FirstOrDefault(); GattCharacteristicsResult cmdCharac = GetCharac(myo.controlService, myoGuids["COMMAND_CHARACT"]).Result; myo.cmdCharac = cmdCharac.Characteristics.FirstOrDefault(); // read firmware characteristic to establish a connection if (myo.FW_charac != null) { GattReadResult readData = Read(myo.FW_charac).Result; if (readData != null) { ushort[] fwData = new UInt16[readData.Value.Length / 2]; System.Buffer.BlockCopy(readData.Value.ToArray(), 0, fwData, 0, (int)(readData.Value.Length)); myo.myFirmwareVersion = ($"{fwData[0]}.{fwData[1]}.{fwData[2]} rev.{fwData[3]}"); vibrate_armband(myo); // update data object connectedMyos[myoIndex] = myo; int errCode = SetupMyo(myo.Name); Console.WriteLine("Setup of " + myo.Name + "(" + myo.myFirmwareVersion + ") returned code: " + errCode); } } } }
private static async void GetCharacteristics(GattDeviceService service) { IReadOnlyList <GattCharacteristic> characteristics = null; string device = service.Device.DeviceInformation.Id.Substring(41); try { DeviceAccessStatus accessStatus = await service.RequestAccessAsync(); if (accessStatus == DeviceAccessStatus.Allowed) { GattCharacteristicsResult result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { characteristics = result.Characteristics; Console.WriteLine("Found Characteristics"); } else { blePowermates[device].isSubscribing = false; Console.WriteLine("Error accessing service."); characteristics = new List <GattCharacteristic>(); } } else { blePowermates[device].isSubscribing = false; Console.WriteLine("Error accessing service."); } } catch (Exception ex) { blePowermates[device].isSubscribing = false; Console.WriteLine("Error: Restricted service. Can't read characteristics: " + ex.ToString()); } if (characteristics != null) { foreach (GattCharacteristic characteristic in characteristics) { Console.WriteLine("└Characteristic uuid: " + characteristic.Uuid.ToString()); if (UuidEquals(uuidRead, characteristic.Uuid)) { SubscribeToValueChange(characteristic); Console.WriteLine(" └Subscribing to Read Characteristic"); } } } }
public override async Task ConnectAsync() { if (ConnectionStatus.DISCONNECTED == ConnectionStatus) { ConnectionStatus = ConnectionStatus.CONNECTING; BluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(BluetoothAddress); BluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChanged; var gattDeviceServicesResult = await BluetoothLeDevice.GetGattServicesForUuidAsync(SERVICE_UUID); Services = gattDeviceServicesResult.Services; var foundService = gattDeviceServicesResult.Services.Single(s => s.Uuid == SERVICE_UUID); GattCharacteristicsResult gattCharacteristicsResult = await foundService.GetCharacteristicsAsync(); ReadData = gattCharacteristicsResult.Characteristics.Single(x => x.Uuid == CHARACTERISTIC_READ_UUID); Debug.WriteLine("Found Read Char"); WriteData = gattCharacteristicsResult.Characteristics.Single(x => x.Uuid == CHARACTERISTIC_WRITE_UUID); Debug.WriteLine("Found Write Char"); GattCommunicationStatus status = GattCommunicationStatus.Unreachable; int count = 0; do { try { status = await ReadData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); Debug.WriteLine("Notify status: " + status); } catch (Exception e) { Debug.WriteLine("Error during notify" + e.Message); } } while (status != GattCommunicationStatus.Success && ++count < 5); if (status == GattCommunicationStatus.Success) { ReadData.ValueChanged += HandleRealTimeData; await WriteValue(); ConnectionStatus = ConnectionStatus.CONNECTED; } else { ConnectionStatus = ConnectionStatus.DISCONNECTED; } } }
/// <summary> /// Obtain a new Characteristic /// </summary> /// <param name="device"></param> /// <returns></returns> internal virtual async System.Threading.Tasks.Task RenewCharacteristic() { if (Device != null) { Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress); Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached); AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("00001623-1212-efde-1623-785feabcd123")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached); Characteristic = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("00001624-1212-efde-1623-785feabcd123")); MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green); } }
/// <summary> /// Starts a new Task and tries to load all characteristics. /// Can only be called once! /// </summary> internal void RequestCharacteristics() { if (characteristicsLoaded) { Logger.Warn("Requesting characteristics failed - already loaded!"); return; } characteristicsLoaded = true; Logger.Debug("Requesting characteristics for: " + BOARD.DeviceId); Task.Run(async() => { try { // Get all services: GattDeviceServicesResult sResult = await BOARD.GetGattServicesAsync(); if (sResult.Status == GattCommunicationStatus.Success) { ONEWHEEL_CHARACTERISTICS.Clear(); foreach (GattDeviceService s in sResult.Services) { // Get all characteristics: GattCharacteristicsResult cResult = await s.GetCharacteristicsAsync(); if (cResult.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in cResult.Characteristics) { ONEWHEEL_CHARACTERISTICS.Add(c.Uuid, c); } } } Logger.Debug("Finished requesting characteristics for: " + BOARD.DeviceId); // Run unlock: UNLOCK_HELPER.Start(); } else { Logger.Warn("Failed to request GetGattServicesAsync() for " + BOARD.DeviceId + " - " + sResult.Status.ToString()); } } catch (Exception e) { Logger.Error("Error during requesting characteristics for: " + BOARD.DeviceId, e); } Logger.Debug("Finished requesting characteristics for: " + BOARD.DeviceId); }, REQUEST_SUBS_CANCEL_TOKEN.Token); }
public void GetSteps() { Task task = Task.Run(async() => { GattDeviceServicesResult sensorServiceResult = await bluetoothDevice.GetGattServicesForUuidAsync(SensorSRVID); GattCharacteristicsResult characteristicsResult = await sensorServiceResult.Services[0].GetCharacteristicsForUuidAsync(new Guid("00000007-0000-3512-2118-0009af100700")); GattReadResult readResult = await characteristicsResult.Characteristics[0].ReadValueAsync(); using DataReader reader = DataReader.FromBuffer(readResult.Value); byte[] vs = new byte[10]; reader.ReadBytes(vs); uint steps = reader.ReadUInt32(); Console.WriteLine(steps.ToString().Substring(1, 3)); Console.WriteLine(steps); Console.WriteLine(steps.ToString().Substring(2, 4)); }); }
public async Task ConnectDevice(string id) { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id); if (bluetoothLeDevice != null) { GattDeviceServicesResult gattDeviceServicesResult = await bluetoothLeDevice.GetGattServicesAsync(); Log.Debug($"{bluetoothLeDevice.Name} Services: {gattDeviceServicesResult.Services.Count}, {gattDeviceServicesResult.Status}, {gattDeviceServicesResult.ProtocolError}"); if (gattDeviceServicesResult.Status == GattCommunicationStatus.Success) { _selectedDeviceServices = gattDeviceServicesResult.Services.FirstOrDefault(x => x.Uuid.ToString() == ServiceUUID); foreach (var service in gattDeviceServicesResult.Services) { Log.Debug("service: " + service.Uuid); } if (_selectedDeviceServices != null) { GattCharacteristicsResult gattCharacteristicsResult = await _selectedDeviceServices.GetCharacteristicsAsync(); if (gattCharacteristicsResult.Status == GattCommunicationStatus.Success) { var characteristics = gattCharacteristicsResult.Characteristics.Where(x => x.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)); _commandCharacteristic = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == CommandUUID); _serialCharacteristic = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == SerialPortUUID); GattCharacteristicProperties properties = _serialCharacteristic.CharacteristicProperties; if (_serialCharacteristic != null) { if (properties.HasFlag(GattCharacteristicProperties.Read)) { ReadBLESerial(); } if (properties.HasFlag(GattCharacteristicProperties.Write)) { WriteBlunoSettings(); } if (properties.HasFlag(GattCharacteristicProperties.Notify)) { // This characteristic supports subscribing to notifications. } } } } } } }
private async Task <GattCharacteristic> GetCharacteristicAsync(Guid guid, GattDeviceService service) { GattCharacteristicsResult result = await service.GetCharacteristicsAsync(); if (result.Status == GattCommunicationStatus.Success) { var characteristics = result.Characteristics; foreach (var characteristic in characteristics) { if (characteristic.Uuid.Equals(guid)) { return(characteristic); } } } throw (new Exception("GetCharacteristic: Couldnt find Characteristic " + guid + " Result:" + result.Status)); }
private async Task MapCharacteristics() { Characteristics.Clear(); GattCharacteristicsResult res = await Service.GetCharacteristicsAsync(); if (res.Status == GattCommunicationStatus.Success) { var characteristics = res.Characteristics; foreach (var characteristic in characteristics) { Characteristics.Add( new BleCharacteristic { Characteristic = characteristic }); } } }
public async Task <bool> SendBuffer(byte [] bufferSource, bool stringChannel = false) { try { double currentCompletion = 0, lastCompletion = 0; int completionDelta = bufferSource.Length / 10; if (!iSServiceStarted || bufferSource == null) { return(false); } GattCharacteristicsResult result = await this.UARTGattService.GetCharacteristicsForUuidAsync(stringChannel?GattCharacteristicsUuid.ATX : GattCharacteristicsUuid.TX); var txCharacteristic = result.Characteristics.FirstOrDefault(); int bufferOffset = 0; while (bufferOffset < bufferSource.Length) { int chunkSize = Math.Min(BLEPAYLOADSIZE, bufferSource.Length - bufferOffset); var ibuffer = ToIBuffer(bufferSource, bufferOffset, chunkSize); await txCharacteristic.WriteValueAsync(ibuffer, GattWriteOption.WriteWithoutResponse); bufferOffset += chunkSize; currentCompletion = (double)((int)bufferOffset / (int)completionDelta) / 10; if (currentCompletion > lastCompletion) { Debug.WriteLine("BLEUartService::SendBuffer SENT " + bufferOffset); lastCompletion = currentCompletion; if (TransmitCompletion != null) { TransmitCompletion(currentCompletion); } } } return(true); } catch (Exception e) { Debug.WriteLine("BLEUartService::SendBuffer EXCEPTION " + e.ToString()); return(false); } }
private bool BluetoothSetup() { BluetoothLEDevice device = this.Waitfor( "connection to Bluetooth device", BluetoothLEDevice.FromBluetoothAddressAsync(System.Convert.ToUInt64("001580912553", 16))); if (device == null) { this.logEol("Device wasn't found"); return(false); } GattDeviceServicesResult deviceServices = this.Waitfor( "device services", device.GetGattServicesAsync()); DeviceAccessStatus deviceAccessStatus = this.Waitfor( "device access", device.RequestAccessAsync()); this.logEol($"Device access status: {deviceAccessStatus}"); System.Guid gyroServiceGuid = System.Guid.Parse("0000ffe0-0000-1000-8000-00805f9b34fb"); GattDeviceService gyroService = deviceServices.Services.Single(x => x.Uuid.Equals(gyroServiceGuid)); var gyroServiceAccessStatus = this.Waitfor( "gro data service access", gyroService.RequestAccessAsync()); this.logEol($"Gyro service access status: {gyroServiceAccessStatus}"); GattCharacteristicsResult characteristics = this.Waitfor( "gyro data service", gyroService.GetCharacteristicsAsync()); this.txRxChannel = characteristics .Characteristics .SingleOrDefault(x => x.UserDescription.Replace(" ", "") == "TX&RX"); if (this.txRxChannel == default(GattCharacteristic)) { this.logEol("Couldn't find TXRX channel...disconnected?"); return(false); } this.txRxChannel.ValueChanged += this.TxRx_ValueChanged; return(true); }
/// <summary> /// Connect BLE device via ID /// </summary> /// <param name="Id"></param> async void ConnectDevice(string Id) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. HaveData?.Invoke(this, "Connecting..."); BluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(Id); HaveData?.Invoke(this, "Reading service"); var res = await BluetoothLeDevice.GetGattServicesForUuidAsync(UARTServiceId); if (res.Status == GattCommunicationStatus.Success) { Service = res.Services.FirstOrDefault(); } else { HaveData?.Invoke(this, "service denied."); return; } HaveData?.Invoke(this, "Connecting to characteristic"); GattCharacteristicsResult cres = await Service.GetCharacteristicsForUuidAsync(RXCharacteristicsId); if (cres.Status == GattCommunicationStatus.Success) { Characteristic = cres.Characteristics.FirstOrDefault(); } else { HaveData?.Invoke(this, "Reading characteristic failed"); } Characteristic.ValueChanged += Characteristic_ValueChanged; HaveData?.Invoke(this, "Subscribing for notification"); GattCommunicationStatus status = await Characteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { // Server has been informed of clients interest. HaveData?.Invoke(this, "Subscribed."); } else { HaveData?.Invoke(this, "Subsrcription failed"); } }
//------------------------------------------------------------------------------------ private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args) { try { //get added device end search it in target devices btdev = await BluetoothLEDevice.FromIdAsync(args.Id); TBleDevice dev = findInTargetList(btdev.Name); //if found deal with its services/characteristics if (dev != null) { //get SERVICES GattDeviceServicesResult result = await btdev.GetGattServicesAsync(); //explore SERVICES foreach (GattDeviceService service in result.Services) { //if custom SERVICE found explore characteristics //if (customGuid == service.Uuid) //{ // GattCharacteristicsResult cresult = await service.GetCharacteristicsAsync(); foreach (GattCharacteristic ccc in cresult.Characteristics) { if (dev.targetCharacteristics.Exists(x => ccc.Uuid == new Guid(x))) { await ccc.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); ccc.ValueChanged += Characteristic_ValueChanged; } } //} } } } catch (Exception e) { } }
// Not used but can be usefull for debugging public async void EnumeratingUsages() { if (!HasDeviceConnected()) { return; } GattDeviceServicesResult services = await connectedDevice.GetGattServicesAsync(); if (services.Status == GattCommunicationStatus.Success) { foreach (GattDeviceService s in services.Services) { await s.RequestAccessAsync(); GattCharacteristicsResult characteristicsResult = await s.GetCharacteristicsAsync(); Console.WriteLine("Service : " + s.Uuid); if (characteristicsResult.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in characteristicsResult.Characteristics) { GattCharacteristicProperties props = c.CharacteristicProperties; Console.WriteLine("\t characteristics : " + c.Uuid + " / " + c.UserDescription); if (props.HasFlag(GattCharacteristicProperties.Read)) { Console.WriteLine("\t\tRead"); } if (props.HasFlag(GattCharacteristicProperties.Write)) { Console.WriteLine("\t\tWrite"); } if (props.HasFlag(GattCharacteristicProperties.Notify)) { Console.WriteLine("\t\tNotify"); } } } s.Dispose(); } } }
public async Task <bool> Start(GattDeviceService uARTService, bool stringChannel = false) { if (uARTService == null || uARTService.Uuid != GattServiceUuids.UART) { iSServiceStarted = false; return(iSServiceStarted); } else { UARTGattService = uARTService; GattCharacteristicsResult result = await this.UARTGattService.GetCharacteristicsForUuidAsync(stringChannel?GattCharacteristicsUuid.ARX : GattCharacteristicsUuid.RX); rxCharacteristic = result.Characteristics.FirstOrDefault(); iSServiceStarted = await EnableRXNotification(); return(iSServiceStarted); } }
/// <summary> /// Gets characteristic for uuid /// </summary> /// <param name="uuid">Uuid for characteristic</param> /// <returns></returns> private async Task <GattCharacteristic> GetCharacteristic(Guid uuid) { GattCharacteristic characteristic = null; GattDeviceServicesResult servicesResult = await mBluetoothLEDevice.GetGattServicesForUuidAsync(uuid); if (servicesResult.Status == GattCommunicationStatus.Success) { GattCharacteristicsResult characteristicsResult = await servicesResult.Services[0].GetCharacteristicsForUuidAsync(uuid); if (characteristicsResult.Status == GattCommunicationStatus.Success) { if (characteristicsResult.Characteristics.Count == 1) { characteristic = characteristicsResult.Characteristics[0]; } } } return(characteristic); }
public void Dispose() { Disconnect(); Gatt = null; AllCharacteristic = null; Characteristic = null; if (Device != null) { Device.Dispose(); } Device = null; IsConnected = false; // Finally, we clear this device to welcome new Advertisements MainBoard.registeredBluetoothDevices.RemoveAll(s => s == BluetoothAddress); }
private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args) { GattDeviceService service = await GattDeviceService.FromIdAsync(args.Id); if (service != null) { GattCharacteristicsResult cResult = await service.GetCharacteristicsAsync(); if (cResult.Status == GattCommunicationStatus.Success) { IReadOnlyList <GattCharacteristic> characteristics = cResult.Characteristics; foreach (GattCharacteristic characteristic in characteristics) { AddCharacteristic(characteristic); } } } }
public async Task <bool> Initialize(IReadOnlyList <GattDeviceService> services, TypedEventHandler <GattCharacteristic, GattValueChangedEventArgs> eventHandler) { service = services.FirstOrDefault(item => item.Uuid == serviceUuid); valueChanged = eventHandler; if (service == null) { return(false); } if (await service.RequestAccessAsync() != DeviceAccessStatus.Allowed) { return(false); } GattCharacteristicsResult result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (result.Status != GattCommunicationStatus.Success) { return(false); } foreach (var item in result.Characteristics) { GattReadResult readResult = await item.ReadValueAsync(); if (readResult.Status != GattCommunicationStatus.Success) { return(false); } if (item.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { await item.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); item.ValueChanged += valueChanged; item.ValueChanged += localValueChanged; } characteristics.Add(item); values.Add(item.Uuid, FormatToString(readResult.Value)); } return(true); }
/// <summary> /// Gets all the characteristics of this service /// </summary> /// <returns>The status of the communication with the GATT device.</returns> private async Task <GattCommunicationStatus> GetAllCharacteristics() { var tokenSource = new CancellationTokenSource(5000); var getCharacteristicsTask = await Task.Run( () => Service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached), tokenSource.Token); GattCharacteristicsResult result = null; result = await getCharacteristicsTask; if (result.Status == GattCommunicationStatus.Success) { foreach (var gattCharacteristic in result.Characteristics) { Characteristics.Add(new ObservableGattCharacteristics(gattCharacteristic, this)); } } return(result.Status); }
private async void InitializeHRMRead() { // TODO: Make example of a write to the BLE device // Example of READING Noric_HRM values: Check hrm_ValueChanged() method below for more foreach (GattDeviceService service in _nordicServices.Services) { _nordicChars = await service.GetCharacteristicsAsync(); foreach (GattCharacteristic characteristic in _nordicChars.Characteristics) { if (characteristic.Uuid.Equals(new Guid("00002a37-0000-1000-8000-00805f9b34fb"))) { Debug.WriteLine("\nHeart Rate Measurement Characteristic:"); // Enable Notifications for this HRM Characteristic await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); characteristic.ValueChanged += hrm_ValueChanged; } } } }
private static async Task <(GattDeviceService, GattCharacteristic)> GetCustomHm1xCharacteristic(BluetoothLEDevice device) { const string bluetoothBaseGuidSuffix = "0000-1000-8000-00805F9B34FB"; GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(new Guid($"{Hm1xShortUuids.CustomService}-{bluetoothBaseGuidSuffix}")); if (serviceResult.Status != GattCommunicationStatus.Success) { Debug.WriteLine($"No GATT service {Hm1xShortUuids.CustomService} found on device {device.DeviceId} {device.Name}: status {serviceResult.Status} {serviceResult.ProtocolError:x}."); return(null, null); } GattDeviceService service = serviceResult.Services[0]; GattCharacteristicsResult characteristicResult = await service.GetCharacteristicsForUuidAsync(new Guid($"{Hm1xShortUuids.CustomCharacteristic}-{bluetoothBaseGuidSuffix}")); if (characteristicResult.Status != GattCommunicationStatus.Success) { Debug.WriteLine($"No GATT characteristic {Hm1xShortUuids.CustomCharacteristic} found on device {device.DeviceId} {device.Name}: status {characteristicResult.Status} {characteristicResult.ProtocolError:x}."); return(service, null); } return(service, characteristicResult.Characteristics[0]); }
static async Task PrintGattdb() { GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(otaServiceUuid, BluetoothCacheMode.Uncached); if (serviceResult.Status == GattCommunicationStatus.Success) { foreach (var service in serviceResult.Services) { Console.Out.WriteLine("Service: " + service.Uuid); GattCharacteristicsResult charResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (charResult.Status == GattCommunicationStatus.Success) { foreach (var characteristic in charResult.Characteristics) { Console.Out.WriteLine("Characteristic: " + characteristic.Uuid); } } } } }
async void prepareGuitar() { device.ConnectionStatusChanged += Device_ConnectionStatusChanged; GattDeviceServicesResult services = await device.GetGattServicesAsync(); foreach (GattDeviceService service in services.Services) { GattCharacteristicsResult characteristics = await service.GetCharacteristicsAsync(); foreach (GattCharacteristic characteristic in characteristics.Characteristics) { if (characteristic.Uuid.ToString().Equals("533e1524-3abe-f33f-cd00-594e8b0a8ea3")) { controller.Connect(); optionCharacteristic = characteristic; GattCommunicationStatus status = await optionCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); optionCharacteristic.ValueChanged += Characteristic_ValueChanged; } } } }
private async void BLEWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { _nordic = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); Debug.WriteLine($"\nBLE Device Found\n\tName: {_nordic.Name}\n\tID: {_nordic.DeviceId}\n\tAddress: {_nordic.BluetoothAddress}\n"); if (_nordic == null) { Debug.WriteLine("Error: BLE Device can't connect!"); return; } _nordic.ConnectionStatusChanged += NordicDevice_ConnectionChange; _nordicServices = await _nordic.GetGattServicesAsync(); var services = _nordicServices.Services; if (services == null) { Debug.WriteLine("Error: Services from BLE Device can not be ascertained!"); } else { Debug.WriteLine($"\nThe BLE Device named {_nordic.Name} has the following {services.Count()} services:"); } foreach (GattDeviceService service in services) { Debug.WriteLine($"\tService: {service.Uuid}"); _nordicChars = await service.GetCharacteristicsAsync(); var characteristics = _nordicChars.Characteristics; foreach (GattCharacteristic character in characteristics) { Debug.WriteLine($"\t\t- Characteristic: {character.Uuid}"); } } }
internal static async Task <GattCharacteristicsResult> GetCharacteristicsAsync(GattDeviceService ser, int tryAgainCount, int tryAgainDelay) { GattCharacteristicsResult charResult = await ser.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (tryAgainCount <= 0) { return(charResult); } else { if (charResult.Status == GattCommunicationStatus.AccessDenied) { await Task.Delay(tryAgainDelay < 0? 0 : tryAgainDelay); return(await GetCharacteristicsAsync(ser, tryAgainCount - 1, tryAgainDelay)); } else { return(charResult); } } }
/// <summary> /// 设置写特征对象。 /// </summary> /// <returns></returns> public async Task GetCurrentWriteCharacteristic() { Guid guid = new Guid(WriteCharacteristicGuid); CurrentService.GetCharacteristicsForUuidAsync(guid).Completed = async(asyncInfo, asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { GattCharacteristicsResult result = asyncInfo.GetResults(); if (result.Characteristics.Count > 0) { CurrentWriteCharacteristic = result.Characteristics[CHARACTERISTIC_INDEX]; } else { //没有发现写特征对象,自动重试中 await GetCurrentWriteCharacteristic(); } } }; }
static async Task SubscribeToDeviceSPP() { // ----------------------------------------------------------------------------- // Find the spp_data characteristic in the service. // Get all of the characteristics in the selected service. GattCharacteristicsResult result = await sppServiceHandle.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { // ------------------------------- // Get the spp_data characteristic. Parse through the list. foreach (var charateristic in result.Characteristics) { if (charateristic.Uuid == sppCharacteristicUuid) { sppCharacteristicHandle = charateristic; // save the characteristic for later use // ------------------------------- // Write to descriptor. Even though the descriptor does not exist in the BLE device's GATT database, // this needs to be called to get notifications to work. (Do not know why...) GattCommunicationStatus status = await sppCharacteristicHandle.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { sppCharacteristicHandle.ValueChanged += CharactisticUpdated; // Add callback whenever BLE device notifies windows } } } } // ----------------------------------------------------------------------------- // Could not find service. User needs to restart program. if (sppCharacteristicHandle == null) { throw new Exception("Could not find characteristic on your device. Please make sure your device has the correct gatt UUID."); } }
async void ConnectDevice(DeviceInformation deviceInfo) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); GattDeviceServicesResult sr = await bluetoothLeDevice.GetGattServicesAsync(); if (sr.Status == GattCommunicationStatus.Success) { var services = sr.Services; foreach (var s in services) { if (s.Uuid.ToString() == "e95d0753-251d-470a-a062-fa1922dfa9a8") { GattCharacteristicsResult cr = await s.GetCharacteristicsAsync(); if (cr.Status == GattCommunicationStatus.Success) { var characteristics = cr.Characteristics; foreach (var c in characteristics) { if (c.Uuid.ToString() == "e95dca4b-251d-470a-a062-fa1922dfa9a8") { Characteristic = c; GattCommunicationStatus status = await c.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { // Server has been informed of clients interest. c.ValueChanged += Characteristic_ValueChanged; } } } } } } } }
private async void ConnectDevice(ulong bluetoothAddress) { GattDeviceService midiService = null; GattCharacteristic midiCharacteristic = null; bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress); GattDeviceServicesResult serviceResult = await bluetoothLeDevice.GetGattServicesAsync(); if (serviceResult.Status == GattCommunicationStatus.Success) { devices.Text = "Connected"; List <GattDeviceService> services = new List <GattDeviceService>(serviceResult.Services); foreach (GattDeviceService service in services) { if (service.Uuid == midiServiceUuid) { midiService = service; } } GattCharacteristicsResult characteristicResult = await midiService.GetCharacteristicsAsync(); List <GattCharacteristic> characteristics = new List <GattCharacteristic>(characteristicResult.Characteristics); foreach (GattCharacteristic characteristic in characteristics) { if (characteristic.Uuid == midiCharacteristicUuid) { midiCharacteristic = characteristic; } } GattCommunicationStatus status = await midiCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { midiCharacteristic.ValueChanged += Characteristic_ValueChanged; } } }