private async Task GetBLECharacteristics() { GattDeviceServicesResult getServices; GattCharacteristicsResult getCharacteristics; // Battery level getServices = await device.GetGattServicesForUuidAsync(BTSIG_BatteryService); CheckStatus(getServices.Status, "GetGattServicesForUuidAsync(BTSIG_BatteryService)"); getCharacteristics = await getServices.Services[0].GetCharacteristicsForUuidAsync(BTSIG_BatteryLevel); CheckStatus(getCharacteristics.Status, "GetCharacteristicsForUuidAsync(BTSIG_BatteryLevel)"); batteryLevelCharacteristic = getCharacteristics.Characteristics[0]; // Push notification of measurement change getServices = await device.GetGattServicesForUuidAsync(BTSIG_Unknown_Service); CheckStatus(getServices.Status, "GetGattServicesForUuidAsync(BTSIG_Unknown_Service)"); getCharacteristics = await getServices.Services[0].GetCharacteristicsForUuidAsync(BTSIG_Unknown_Measurement); CheckStatus(getCharacteristics.Status, "GetCharacteristicsForUuidAsync(BTSIG_Unknown_Measurement)"); measurementCharacteristic = getCharacteristics.Characteristics[0]; getCharacteristics = await getServices.Services[0].GetCharacteristicsForUuidAsync(BTSIG_Unknown_Unit); CheckStatus(getCharacteristics.Status, "GetCharacteristicsForUuidAsync(BTSIG_Unknown_Unit)"); unitCharacteristic = getCharacteristics.Characteristics[0]; preMeasurementText = "Waiting..."; await GetBatteryLevel(); await CheckMeasurementPresentation(); await StartNotifications(); }
public async Task EnableNotificationsAsync(Tuple <Guid, Guid> gattChar, Action <byte[]> handler) { charChangedHandler = handler; if (notifyChar == null) { var serviceResult = await device.GetGattServicesForUuidAsync(gattChar.Item1, BluetoothCacheMode.Uncached); if (serviceResult.Services.Count == 0) { throw new InvalidOperationException(string.Format("GATT service '{0}' does not exist", gattChar.Item1)); } var charResult = await serviceResult.Services.FirstOrDefault().GetCharacteristicsForUuidAsync(gattChar.Item2); if (charResult.Characteristics.Count == 0) { throw new InvalidOperationException(string.Format("GATT characteristic '{0}' does not exist", gattChar.Item2)); } notifyChar = charResult.Characteristics.FirstOrDefault(); var notifyResult = await notifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (notifyResult != GattCommunicationStatus.Success) { throw new InvalidOperationException(string.Format("Failed to enable notifications (status = {0:d})", (int)notifyResult)); } notifyChar.ValueChanged += notifyHandler; } }
public async Task InitSensorsAsync() { var services = await ble.GetGattServicesForUuidAsync(model.SensorsServiceID); //TODO: check status service = services.Services[0]; //Enviromental environmentalSource = new DataSource <Environmental>(service, model.EnvironmentalID); //AccGyroMag accGyroMagSource = new DataSource <AccGyroMag>(service, model.AccGyroMagID); //AudioLevel audioLevelSource = new DataSource <AudioLevel>(service, model.AudioLevelID); //LedState ledStateSource = new DataSource <LEDState>(service, model.LEDStateID); //LightSensor lightSensorSource = new DataSource <LightSensor>(service, model.LightSensorID); //BatteryStatus batteryStatusSource = new DataSource <BatterySatus>(service, model.BatteryStatusID); //Orientation orientationSource = new DataSource <Orientation>(service, model.OrientationID); //Compass compassSource = new DataSource <Compass>(service, model.CompassID); //ActivityRecognition activityRecognitionSource = new DataSource <ActivityRecognition>(service, model.ActivityRecognitionID); //CarryPosition carryPositionSource = new DataSource <CarryPosition>(service, model.CarryPositionID); //GestureRecognition gestureRecognitionSource = new DataSource <GestureRecognition>(service, model.GestureRecognitionID); //Proximity proximitySource = new DataSource <Proximity>(service, model.ProximityID); //UltraViolet ultraVioletSource = new DataSource <UltraViolet>(service, model.UltraVioletID); //SmokeSensor smokeSensorSource = new DataSource <SmokeSensor>(service, model.SmokeSensorID); }
async void ConnectDevice(string id) { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id); var srvResultList = await bluetoothLeDevice.GetGattServicesAsync(); var srvResult = await bluetoothLeDevice.GetGattServicesForUuidAsync(new Guid("0000ffb0-0000-1000-8000-00805f9b34fb"), BluetoothCacheMode.Cached); if (srvResult.Status != GattCommunicationStatus.Success || !srvResult.Services.Any()) { Console.WriteLine("Cannot find service for device"); return; } Console.WriteLine("connected"); var service = srvResult.Services.First(); var chrResult = await service.GetCharacteristicsAsync(); if (chrResult.Status != GattCommunicationStatus.Success) { return; } var chrs = from x in chrResult.Characteristics select x; var gattCharacteristics = chrs as GattCharacteristic[] ?? chrs.ToArray(); if (!gattCharacteristics.Any()) { return; } await gattCharacteristics[1].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); gattCharacteristics[1].ValueChanged += gattCharacteristics_1_ValueChanged; sendCommandCharacteristic = gattCharacteristics[1]; }
private async Task <byte[]> ReadBluetoothValue(BluetoothLEDevice device, Guid svcGuid, Guid chrGuid, BluetoothCacheMode cacheMode) { var svc = (await device.GetGattServicesForUuidAsync(svcGuid)).Services[0]; var chr = (await svc.GetCharacteristicsForUuidAsync(chrGuid)).Characteristics[0]; return((await chr.ReadValueAsync(cacheMode)).Value.ToArray()); }
private async Task <Spell> Connect(DeviceInformation args, BluetoothLEDevice device) { string spellName = device.Name.Split(new string[] { ": " }, StringSplitOptions.None)[1]; Spell result; Action <string> markBadDevice = (msg) => { Console.WriteLine(msg); badDeviceIds.Add(args.Id); device.Dispose(); return; }; if (!Enum.TryParse <Spell>(spellName, out result)) { markBadDevice("Spell device: " + device.Name + " has an invalid spell name!"); } var serviceResult = await device.GetGattServicesForUuidAsync(SERVICE_UUID); if (serviceResult.Services.Count != 1) { markBadDevice("Spell device" + device.Name + " does not have a spell service!"); } var characteristicsResult = await serviceResult.Services[0].GetCharacteristicsForUuidAsync(CHARACTERISTIC_UUID); if (characteristicsResult.Characteristics.Count != 1) { markBadDevice("Spell device " + device.Name + " has an invalid number of trigger characteristics!"); } spellDevices[result] = device; spellTriggers[result] = characteristicsResult.Characteristics[0]; return(result); }
static async Task FindSppService() { // ----------------------------------------------------------------------------- // Save the SPP service. // Get all of the services from the device then save the SPP service. GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(sppServiceUuid, BluetoothCacheMode.Uncached); if (serviceResult.Status == GattCommunicationStatus.Success) { // ------------------------------- // Parse all of the services that Windows can see foreach (GattDeviceService service in serviceResult.Services) { if (service.Uuid == sppServiceUuid) { sppServiceHandle = service; } } } // ----------------------------------------------------------------------------- // Could not find service. User needs to restart program. if (sppServiceHandle == null) { throw new Exception("Could not find service on your device. Please make sure your device has the correct gatt UUID."); } }
private static ITargetDevice buildVorzeDevice(BluetoothLEDevice device) { string vorzeServiceUuidStr = "40ee1111-63ec-4b7f-8ce7-712efd55b90e"; string vorzeCharactersticUuidStr = "40ee2222-63ec-4b7f-8ce7-712efd55b90e"; string charactersticDescriptionName = "nls_command"; IDictionary <string, Type> deviceMap = new Dictionary <string, Type>() { { "VorzePiston", typeof(VorzeA10Piston) }, { "CycSA", typeof(VorzeA10Cyclone) }, { "UFOSA", typeof(VorzeUFOSA) }, }; ITargetDevice concreateDevice = null; if (device == null) { return(null); } GattDeviceServicesResult services = device.GetGattServicesForUuidAsync(new Guid(vorzeServiceUuidStr)).GetResults(); var service = services != null && services.Services.Count > 0 ? services.Services[0] : null; if (service == null) { return(null); } Logger.log($"DeviceName: {service.Device.Name}"); var characteristics = service.GetCharacteristicsForUuidAsync(new Guid(vorzeCharactersticUuidStr)).GetResults(); if (characteristics == null || characteristics.Characteristics.Count < 1) { return(null); } var characterstic = characteristics.Characteristics[0]; if (characterstic != null) { foreach (var key in deviceMap.Keys) { if (service.Device.Name.Contains(key)) { concreateDevice = Activator.CreateInstance(deviceMap[key]) as ITargetDevice; concreateDevice.init(characterstic); break; } } } return(concreateDevice); }
public async Task <IButtplugDevice> CreateDeviceAsync([NotNull] BluetoothLEDevice aDevice) { // GetGattServicesForUuidAsync is 15063 only var services = await aDevice.GetGattServicesAsync(BluetoothCacheMode.Cached); foreach (var s in services.Services) { _bpLogger.Debug("Found service UUID: " + s.Uuid + " (" + aDevice.Name + ")"); } var srvResult = await aDevice.GetGattServicesForUuidAsync(_deviceInfo.Services[0], BluetoothCacheMode.Cached); if (srvResult.Status != GattCommunicationStatus.Success || !srvResult.Services.Any()) { _bpLogger.Debug("Cannot find service for device (" + aDevice.Name + ")"); return(null); } var service = srvResult.Services.First(); var chrResult = await service.GetCharacteristicsAsync(); if (chrResult.Status != GattCommunicationStatus.Success) { return(null); } foreach (var s in chrResult.Characteristics) { _bpLogger.Trace("Found characteristics UUID: " + s.Uuid + " (" + aDevice.Name + ")"); } var chrs = from x in chrResult.Characteristics where _deviceInfo.Characteristics.Contains(x.Uuid) select x; var gattCharacteristics = chrs as GattCharacteristic[] ?? chrs.ToArray(); if (!gattCharacteristics.Any()) { return(null); } // TODO This assumes we're always planning on having the UUIDs sorted in the Info classes, which is probably not true. var bleInterface = new UWPBluetoothDeviceInterface(_buttplugLogManager, aDevice, gattCharacteristics.OrderBy((aChr) => aChr.Uuid).ToArray()); var device = _deviceInfo.CreateDevice(_buttplugLogManager, bleInterface); if (await device.Initialize() is Ok) { return(device); } // If initialization fails, don't actually send the message back. Just return null, we'll have the info in the logs. return(null); }
private async void ConnectBLEDevice(BluetoothLEAdvertisementReceivedEventArgs eventArgs, int i) { int index = i; deviceConnected[index] = 1; try { BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress); GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(TimpointerServiceUUID); if (serviceResult.Status == GattCommunicationStatus.Success) { GattCharacteristicsResult serialCharsticsResult = await serviceResult.Services.ElementAt(0).GetCharacteristicsForUuidAsync(TimpointerSerialCharacteristicUUID); if (serialCharsticsResult.Status == GattCommunicationStatus.Success) { characteristics[index] = serialCharsticsResult.Characteristics.ElementAt(0); try { var result = await characteristics[index].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); //ShowStr("Notification resigter " + result + device.Name); if (result == GattCommunicationStatus.Success) { // 처음 연결시 데이터를 보내 아두이노에서 시리얼 개통을함. deviceConnected[index] = 2; //characteristics[index].Service.Session.MaintainConnection = true; connectedDeviceInfo[index] = eventArgs; //Debug.WriteLine(characteristics[index].Service.Session.SessionStatus); return; } } catch (Exception e) { //ShowStr("Notify set error" + e.StackTrace); } } else { //ShowStr("Find charateristic error" + serialCharsticsResult.Status); } } else { //ShowStr("Find service error" + serviceResult.Status); } } catch (Exception e) { } // 재연결 시도 deviceConnected[index] = 0; if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Stopped) { watcher.Start(); } }
private static async Task <GattDeviceService> GetService(BluetoothLEDevice mi_device) { var servicesContainer = await mi_device.GetGattServicesForUuidAsync(_serviceUuid); if (servicesContainer?.Services?.Count == 0) { return(null); } return(servicesContainer.Services.First()); }
public static async Task <GattDeviceService> GetGattServiceForUuidAsync(this BluetoothLEDevice bluetoothLEDevice, Guid uuid) { var serviceResult = await bluetoothLEDevice.GetGattServicesForUuidAsync(uuid); if (serviceResult.Status != GattCommunicationStatus.Success || serviceResult.Services.Count == 0) { throw new Exception("Could not find GATT service with UUID=" + uuid.ToString()); } return(serviceResult.Services.FirstOrDefault()); }
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); } } } } }
public async void Connect(string id) { try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id); if (bluetoothLeDevice == null) { Log.d("Failed to connect to device.", NotifyType.ErrorMessage); return; } bluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChangedHandler; mBluetoothGatt = await GattSession.FromDeviceIdAsync(bluetoothLeDevice.BluetoothDeviceId); mBluetoothGatt.MaintainConnection = true; } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { Log.d("Bluetooth radio is not on.", NotifyType.ErrorMessage); return; } if (bluetoothLeDevice != null) { // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method. // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system). // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event. GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(RX_SERVICE_UUID); if (result.Status == GattCommunicationStatus.Success) { _services.Clear(); _services.AddRange(result.Services); Log.d(String.Format("Found {0} services", _services.Count), NotifyType.StatusMessage); foreach (var service in _services) { Log.d("SERVICE: " + DisplayHelpers.GetServiceName(service)); GetCharachteristics(service); } } else { Log.d("Device unreachable", NotifyType.ErrorMessage); } } }
public async Task subscribeToNotify() { // Service Guid serviceGuid = Guid.Parse(Globals.UUID_SERVICE); GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(serviceGuid); device.ConnectionStatusChanged += OnConnectionChange; // Characteristic (Handle 17 - Sensor Command) Guid charGiud = Guid.Parse(Globals.UUID_CHAR); var characs = await serviceResult.Services.Single(s => s.Uuid == serviceGuid).GetCharacteristicsAsync(); var charac = characs.Characteristics.Single(c => c.Uuid == charGiud); GattCharacteristicProperties properties = charac.CharacteristicProperties; //Write the CCCD in order for server to send notifications. var notifyResult = await charac.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); charac.ValueChanged += Charac_ValueChangedAsync; }
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; } } }
public async Task <IPoweredUpBluetoothService> GetServiceAsync(Guid serviceId) { var gatt = await _device.GetGattServicesForUuidAsync(serviceId); if (gatt.Status == GattCommunicationStatus.Success && gatt.Services.Count > 0) { var service = gatt.Services[0]; return(new WinRTPoweredUpBluetoothService(service)); } else { return(null); } }
public async Task <IBluetoothService> GetServiceAsync(Guid serviceId) { var gatt = await _device.GetGattServicesForUuidAsync(serviceId); if (gatt.Status == GattCommunicationStatus.Success) { var service = gatt.Services.FirstOrDefault(); return(new WinRTBluetoothService(service)); } else { return(null); } }
private async Task <GattCharacteristic[]> ConnectService(BluetoothLEDevice device, Guid serviceUUID, Guid characteristicUUID1, Guid characteristicUUID2) { var service = await device.GetGattServicesForUuidAsync(serviceUUID); LogOutput("サービスの取得を完了"); var characteristics1 = await service.Services[0].GetCharacteristicsForUuidAsync(characteristicUUID1); LogOutput("Characteristic 1 の取得完了"); var characteristics2 = await service.Services[0].GetCharacteristicsForUuidAsync(characteristicUUID2); LogOutput("Characteristic 2 の取得完了"); var characteristics1Data = characteristics1.Characteristics[0]; var characteristics2Data = characteristics2.Characteristics[0]; return(new GattCharacteristic[] { characteristics1Data, characteristics2Data }); }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { lock (lockObj) { if (toioList.Count(t => t.Address == args.BluetoothAddress) > 0) { return; } } var bleServiceUUIDs = args.Advertisement.ServiceUuids; foreach (var uuid in bleServiceUUIDs) { if (uuid == Toio.ServiceUUID) { Task task = Task.Run(async() => { BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(Toio.ServiceUUID); if (result.Status == GattCommunicationStatus.Success) { var service = result.Services[0]; Toio toio = new Toio(args.BluetoothAddress, service); // Test byte battery = toio.ReadBatteryLife(); lock (lockObj) { toioList.Add(toio); } if (newlyFound != null) { newlyFound(toio); } } }); task.Wait(); } } }
async Task <IReadOnlyList <GattService> > _GetGattServicesAsync(Guid uuid) { var result = await device.GetGattServicesForUuidAsync(uuid); switch (result.Status) { case Win.GattCommunicationStatus.Success: return(result.Services.Select(x => new GattService(this, x)).ToList().AsReadOnly()); case Win.GattCommunicationStatus.AccessDenied: throw new AccessViolationException("Access denied."); case Win.GattCommunicationStatus.ProtocolError: case Win.GattCommunicationStatus.Unreachable: default: throw new Exception("Need a better exception here"); } }
private async Task <GattDeviceServicesResult> GetServiceAsync(BluetoothLEDevice dev, Guid my_Guid) { var tcs = new TaskCompletionSource <GattDeviceServicesResult>(); tcs.SetResult(await dev.GetGattServicesForUuidAsync(my_Guid)); var waiter = tcs.Task.GetAwaiter(); tcs.Task.Wait(); if (waiter.IsCompleted) { return(tcs.Task.Result); } else { return(null); } }
/// <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); }
protected async Task <GattDeviceService> GetService(Guid aServiceGuid) { // GetGattServicesForUuidAsync is 15063+ only? var serviceResult = await _bleDevice.GetGattServicesForUuidAsync(aServiceGuid, BluetoothCacheMode.Cached); // Don't log exceptions here, as we may not want to report them at some points. if (serviceResult.Status != GattCommunicationStatus.Success) { throw new ButtplugDeviceException($"Cannot check for service {aServiceGuid} of {_bleDevice.Name}."); } if (serviceResult.Services.Count == 0) { throw new ButtplugDeviceException($"Cannot find service {aServiceGuid} of {_bleDevice.Name}."); } // TODO is there EVER a way we'd get more than one service back? return(serviceResult.Services[0]); }
public bool Open(IDeviceInfo dev) { lock (_lock) { if (_Device != null && _Characteristics != null && _ReadChar != null && _NotifyChar != null && _WriteChar != null) { return(false); //TODO: check connection } BluetoothLEDevice.FromIdAsync(dev.Path) .AsTask() .ContinueWith(r1 => { _Device = r1.Result; if (_Device != null) { BluetoothRadio.StateChanged -= _BluetoothRadio_StateChanged; BluetoothRadio.StateChanged += _BluetoothRadio_StateChanged; _Device.ConnectionStatusChanged += _Device_ConnectionStatusChanged; _Device.GattServicesChanged += _Device_GattServicesChanged; _Device.GetGattServicesForUuidAsync(HIOServiceUuid) .AsTask() .ContinueWith(r2 => { _Service = r2.Result.Services.First(); _Service.OpenAsync(GattSharingMode.SharedReadAndWrite).AsTask().Wait(); if (_Characteristics == null) { _Characteristics = new List <GattCharacteristic>(); } lock (_Characteristics) { GetCharacteristics(); Trace.WriteLine($"Number of chars: {_Characteristics?.Count ?? -1}"); } }) .Wait(); } }) .Wait(); return(true); } }
public async partial Task <IEnumerable <GattService> > GetServicesAsync(IEnumerable <Guid>?uuids) { if (uuids is null || !uuids.Any()) { var result = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached); return(ParseResult(result)); } var services = Enumerable.Empty <GattService>(); foreach (var uuid in uuids) { services = services.Concat(ParseResult( await device.GetGattServicesForUuidAsync(uuid, BluetoothCacheMode.Uncached) )); } return(services); }
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]); }
protected async Task <GattCharacteristic> CreateCharacteristic(BluetoothLEDevice deveice, BluetoothCacheMode mode) { var serviceResult = await deveice.GetGattServicesForUuidAsync(Service); if (serviceResult.Status != GattCommunicationStatus.Success) { //TODO process proper result message return(null); } foreach (var service in serviceResult.Services) { var result = await service.GetCharacteristicsForUuidAsync(Characteristic); if (result.Status == GattCommunicationStatus.Success) { return(result.Characteristics.FirstOrDefault()); } } return(null); }
public async Task <bool> IsFidoDevice(BluetoothLEDevice dev, string key) { try { Logger.Log("IsFidoDevice"); // GetGattServicesForUuidAsyc などはCreaters Update(15063)から追加されたAPI。 Anniversary Edition(14393)まで対応する場合 はGetGattServiceを使う // GetGattServicesForUuidAsyc etc. are APIs added from Creaters Update (15063). Use GetGattService to support up to Anniversary Edition (14393) //var service = dev.GetGattService(GattServiceUuids.DeviceInformation); var services = await dev.GetGattServicesForUuidAsync(GattServiceUuids.DeviceInformation, BluetoothCacheMode.Cached); if (services.Services.Count <= 0) { Logger.Log("サービス無し | No service"); return(false); } foreach (var service in services.Services) { // forlog //await logService(service); ManufacturerNameString = await checkDeviceInformationService_Characteristics(service, GattCharacteristicUuids.ManufacturerNameString); ModelNumberString = await checkDeviceInformationService_Characteristics(service, GattCharacteristicUuids.ModelNumberString); SerialNumberString = await checkDeviceInformationService_Characteristics(service, GattCharacteristicUuids.SerialNumberString); if (ManufacturerNameString == key) { // OK return(true); } } } catch (Exception ex) { Logger.Err(ex); } return(true); }
async void ExecuteConnectCommand() { _device = await BluetoothLEDevice.FromBluetoothAddressAsync(_address); _device.ConnectionStatusChanged += OnConnectionStateChanged; var r1 = await _device.GetGattServicesForUuidAsync(CommunicationId); if (r1.Status != GattCommunicationStatus.Success) { throw new NotImplementedException(); } _communicationService = r1.Services[0]; var r2 = await _communicationService.GetCharacteristicsForUuidAsync(NotifyId); if (r2.Status != GattCommunicationStatus.Success) { throw new NotImplementedException(); } _notifyCharacteristic = r2.Characteristics[0]; _notifyCharacteristic.ValueChanged += OnValueChanged; var r3 = await _communicationService.GetCharacteristicsForUuidAsync(WriteId); if (r3.Status != GattCommunicationStatus.Success) { throw new NotImplementedException(); } _writeCharacteristic = r3.Characteristics[0]; RaisePropertyChanged(nameof(CanWrite)); // 开启通知 var status = await _notifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status != GattCommunicationStatus.Success) { throw new NotImplementedException(); } }