public async Task PrintAllCharacteristicsAsync() { Logger.Info("======================================================="); Logger.Info("Status: " + BOARD.ConnectionStatus); if (BOARD.ConnectionStatus == BluetoothConnectionStatus.Connected) { GattDeviceServicesResult sResult = await BOARD.GetGattServicesAsync(); if (sResult.Status == GattCommunicationStatus.Success) { foreach (GattDeviceService s in sResult.Services) { Logger.Info("UUID: " + s.Uuid + ", Handle: " + s.AttributeHandle); GattCharacteristicsResult cResult = await s.GetCharacteristicsAsync(); if (cResult.Status == GattCommunicationStatus.Success) { foreach (GattCharacteristic c in cResult.Characteristics) { await Utils.PrintAsync(c); } } } } } Logger.Info("======================================================="); }
private async Task FillServices() { var result = await m_Device.GetGattServicesAsync(BluetoothCacheMode.Cached); Console.WriteLine($"GetGattServicesAsync result status {result.Status} "); //if (result.Status == GattCommunicationStatus.Success) { foreach (var service in result.Services) { var res = await service.GetCharacteristicsAsync(BluetoothCacheMode.Cached); //if (res.Status == GattCommunicationStatus.Success) { res.Characteristics.ToList().ForEach(c => { if (!Characteristics.ContainsKey(c.Uuid)) { Characteristics.Add(c.Uuid, c); } }); //Characteristics.AddRange(res.Characteristics); } } Console.WriteLine($"filled chars - {Characteristics.Count}"); } if (Characteristics.Count < 1) { Console.WriteLine("could not fill chars - "); } }
public async void ListCurrentDeviceServicesToLog() { //CheckBluetoothStatus(true); BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(ChosenDevice.Id); if (device == null) { return; } DeviceAccessStatus accessStatus = await device.RequestAccessAsync(); var deviceServicesResult = await device.GetGattServicesAsync(); // build the string to add in the log string services = "[Services list of " + device.Name + "]"; int i = 0; foreach (GattDeviceService service in deviceServicesResult.Services) { services += "\n -- Handle: \t" + service.AttributeHandle.ToString(); services += "\n --> UUID: \t" + service.Uuid.ToString(); services += "\n --> Access Info: \t" + service.DeviceAccessInformation.CurrentStatus.ToString(); i++; if (i < deviceServicesResult.Services.Count) { services += "\n----------------------------------------------------------------"; } } services += "\n\nFor info on Bluetooth Standard codes and identifiers, please visit https://www.bluetooth.com/specifications/assigned-numbers" + "\n"; // add log AddLog(services, AppLog.LogCategory.Debug); }
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 void StartDevice() { //To get your blueToothAddress add: ulong blueToothAddress = device.BluetoothAddress to your old code. ulong blueToothAddress = 88396936323791; //fill in your device address!! device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress); if (device != null) { string deviceName = device.DeviceInformation.Name; Debug.WriteLine(deviceName); int servicesCount = 3;//Fill in the amount of services from your device!! int tryCount = 0; bool connected = false; while (!connected)//This is to make sure all services are found. { tryCount++; serviceResult = await device.GetGattServicesAsync(); if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount) { connected = true; Debug.WriteLine("Connected in " + tryCount + " tries"); } if (tryCount > 5)//make this larger if faild { Debug.WriteLine("Failed to connect to device "); return; } } } }
public async Task DiscoverServicesAsync() { ResetCharacteristics(); int retry = 3; while (retry >= 0) { var servicesResult = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached); foreach (var service in servicesResult.Services) { var charsresult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); foreach (var characteristic in charsresult.Characteristics) { characteristics.Add(characteristic.Uuid, characteristic); } } if (characteristics.Count == 0) { retry--; } else { retry = -1; } } if (characteristics.Count == 0) { throw new InvalidOperationException("No GATT characteristics were discovered"); } }
/// <summary> /// Handle the client's request to connect to a particular peripheral. /// Valid in the discovery state; transitions to connected state on success. /// </summary> /// <param name="parameters"> /// A JSON object containing the UUID of a peripheral found by the most recent discovery request /// </param> private async Task Connect(JObject parameters) { if (_services != null) { throw JsonRpcException.InvalidRequest("already connected to peripheral"); } var peripheralId = parameters["peripheralId"].ToObject <ulong>(); if (!_reportedPeripherals.Contains(peripheralId)) { // the client may only connect to devices that were returned by the current discovery request throw JsonRpcException.InvalidParams($"invalid peripheral ID: {peripheralId}"); } _peripheral = await BluetoothLEDevice.FromBluetoothAddressAsync(peripheralId); var servicesResult = await _peripheral.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (servicesResult.Status != GattCommunicationStatus.Success) { throw JsonRpcException.ApplicationError($"failed to enumerate GATT services: {servicesResult.Status}"); } _peripheral.ConnectionStatusChanged += OnPeripheralStatusChanged; _services = servicesResult.Services; // cache all characteristics in all services foreach (var service in _services) { var characteristicsResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); if (characteristicsResult.Status != GattCommunicationStatus.Success) { continue; } foreach (var characteristic in characteristicsResult.Characteristics) { _cachedCharacteristics.Add(characteristic.Uuid, characteristic); } } // collect optional services plus all services from all filters // Note: this modifies _optionalServices for convenience since we know it'll go away soon. _allowedServices = _optionalServices ?? new HashSet <Guid>(); _allowedServices = _filters .Where(filter => filter.RequiredServices?.Count > 0) .Aggregate(_allowedServices, (result, filter) => { result.UnionWith(filter.RequiredServices); return(result); }); // clean up resources used by discovery _watcher.Stop(); _watcher = null; _reportedPeripherals.Clear(); _optionalServices = null; }
public async Task <int> Connect(String ID) { Debug.WriteLine("Initializing device..."); 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) { var dialog = new MessageDialog("Failed to connect to device."); await dialog.ShowAsync(); } else { GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { Debug.WriteLine("Connected & Found services"); return(1); } } } catch (Exception ex) { Debug.WriteLine("Retrieving device properties failed with message: " + ex.Message); } return(0); }
private async Task StartCacheAsync() { // Get all services: GattDeviceServicesResult sResult = await DEVICE.GetGattServicesAsync(); if (sResult.Status == GattCommunicationStatus.Success) { 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) { CHARACTERISTICS.Add(c.Uuid, c); await LoadCharacteristicValueAsync(c); } } } Logger.Debug("Finished requesting characteristics."); await SubscribeToCharacteristicsAsync(CharacteristicsCache.SUBSCRIBE_TO_CHARACTERISTICS); } else { Logger.Warn("Failed to request GetGattServicesAsync() - " + sResult.Status.ToString()); } }
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args) { device = args; BLEdevice = await BluetoothLEDevice.FromIdAsync(device.Id); GattDeviceServicesResult result = await BLEdevice.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { if (service.Uuid.ToString() == UUID_UART_SERV) { characteristics = await service.GetCharacteristicsAsync(); foreach (var characteristic in characteristics.Characteristics) { if (characteristic.Uuid.ToString() == UUID_UART_RX) { character = characteristic; } } } } } Debug.WriteLine("Device Added"); }
private async void ConnDevice_Button_Click(object sender, RoutedEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { try { bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ConnDevice_Id.Text); if (bluetoothLeDevice == null) { FindDevice_List.Text += String.Format("\r\nwarning1"); } } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { FindDevice_List.Text += String.Format("\r\nwarning2"); } if (bluetoothLeDevice != null) { GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { FindDevice_List.Text += String.Format("{0} : {1}\r\n", bluetoothLeDevice.Name, service.Uuid); } } } else { FindDevice_List.Text += String.Format("\r\nwarning3"); } }); }
private async Task DiscoverServices() { var gatt = await _myoBle.GetGattServicesAsync(); if (gatt.Services.Count >= 1) { foreach (var service in gatt.Services) { if (service.Uuid == ControlServiceUUID) { _controlService = service; } else if (service.Uuid == ImuDataServiceUUID) { _imuDataService = service; } else if (service.Uuid == ClassifierServiceUUID) { _classifierService = service; } else if (service.Uuid == RawEmgDataServiceUUID) { _emgDataService = service; } } } }
public async void StartReceivingData() { leDevice = await BluetoothLEDevice.FromIdAsync(device.Id); var services = await leDevice.GetGattServicesAsync(); foreach (var service in services.Services) { switch (service.Uuid.ToString()) { case SensorUUIDs.UUID_ENV_SERV: InitializeTemperatureSensor(service); InitializePressureSensor(service); break; case SensorUUIDs.UUID_ACC_SERV: InitializeAccelerationSensor(service); break; } } timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += Timer_Tick; timer.Start(); }
private async void Button_Click(object sender, RoutedEventArgs e) { if (myDevice == null) { return; } if (myCharacteristic == null) { GattDeviceServicesResult result = await myDevice.GetGattServicesAsync(); foreach (var service in result.Services) { if (service.Uuid.ToString() == RSL10_Motion_BLE_SERVICE_UIID) { GattCharacteristicsResult CharResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); foreach (var characteristic in CharResult.Characteristics) { if (characteristic.Uuid.ToString() == RSL10_Motion_BLE_CHARACTERISTIC_UIID) { myCharacteristic = characteristic; dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += dispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);//100 ms dispatcherTimer.Start(); } } } } } }
public async void Connect() { bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(this.BluetoothLEid); if (bluetoothLeDevice != null) { GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { if (service.Uuid == HEALTH_THERMOMETER_UUID) { selectedService = service; tempCharacteristic = await selectedService.GetCharacteristicsForUuidAsync(MagUUID); magCharacteristic = tempCharacteristic.Characteristics[0]; tempCharacteristic = await selectedService.GetCharacteristicsForUuidAsync(WriteUUID); writeCharacteristic = tempCharacteristic.Characteristics[0]; } } } else { Debug.WriteLine("Connect Fail"); } } }//end method connect
public static async Task <string> GuessModelNameAsync(BluetoothLEDevice bluetoothLEDevice) { GattDeviceServicesResult servicesResult = await bluetoothLEDevice.GetGattServicesAsync(); if (servicesResult.Status != GattCommunicationStatus.Success) { return(string.Empty); } foreach (var service in servicesResult.Services) { switch (service.Uuid.ToString()) { case "a2220000-f92a-ad93-dc47-9c4df7aa5e9e": return(SupportedSensors.FerrisSensorV1); case "6a800001-b5a3-f393-e0a9-e50e24dcca9e": return(SupportedSensors.InfoLinkNRF51SensorTag); default: break; } } return("Unknown sensor"); }
public async Task <bool> InitializeService() { /// 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 BLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status != GattCommunicationStatus.Success) { return(false); } IReadOnlyList <GattDeviceService> services = result.Services; if (!await DeviceInfo.Initialize(result.Services, ValueChanged)) { return(false); } if (!await Battery.Initialize(result.Services, ValueChanged)) { return(false); } if (!await Sensors.Initialize(result.Services, ValueChanged)) { return(false); } if (!await Config.Initialize(result.Services, ValueChanged)) { return(false); } return(true); }
public async void Connect() { DeviceType dv = MainPage.TestresultModel.GetDeviceType(3); BLEDeviceInfo device = null; foreach (var dev in MainPage.TestresultModel.BLEDevices) { if (dev.DeviceType == DeviceTypesenums.THERMOMETER && dev.IsPaired) { device = dev; break; } else if (dev.DeviceType == DeviceTypesenums.THERMOMETER && !dev.IsPaired) { MainPage.mainPage.commChannel.SendMessageToMCC( string.Format(CommunicationCommands.THERMORCONNECTIONSTATUS, "Device is not paried.")); MainPage.TestresultModel.NotifyStatusMessage?.Invoke("Device is not paried. ", 1); return; } } GTTServicelist.Clear(); if (device == null) { MainPage.mainPage.commChannel.SendMessageToMCC( string.Format(CommunicationCommands.THERMORCONNECTIONSTATUS, "Device not found with id:")); MainPage.TestresultModel.NotifyStatusMessage?.Invoke(" Device not found with id: " + MainPage.TestresultModel.ThermoMeterId, 1); return; } bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.DeviceInfo.Id); if (bluetoothLeDevice == null) { MainPage.mainPage.commChannel.SendMessageToMCC( string.Format(CommunicationCommands.THERMORCONNECTIONSTATUS, "Device Unreachable.")); MainPage.TestresultModel.NotifyStatusMessage?.Invoke(" Device Unreachable.", 1); return; } GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var svc in services) { GTTServicelist.Add(svc.Uuid.ToString().ToLower(), svc); } SelectService(device); //MainPage.TestresultModel.ThermoServiceID } else { MainPage.mainPage.commChannel.SendMessageToMCC( string.Format(CommunicationCommands.THERMORCONNECTIONSTATUS, "Failed to connect. " + result.Status.ToString())); MainPage.TestresultModel.NotifyStatusMessage?.Invoke("Failed to connect. " + result.Status.ToString(), 1); } }
private async void Build() { await mDevice.GetGattServicesAsync().AsTask().ContinueWith((obj) => { Debug.WriteLine("Found Services."); ServicesAquired(obj.Result); }); }
public async Task <BluetoothLEDevice> FromBluetoothAddressAsync(UInt64 address) { BluetoothLEDevice ble = await BluetoothLEDevice.FromBluetoothAddressAsync(address); GattDeviceServicesResult results = await ble.GetGattServicesAsync(); return(ble); }
public bool DiscoverServices() { var t = Task.Run(async() => await bleDevice.GetGattServicesAsync()); services = WaitTask(t, 10) == t ? t.Result : null; stage = 3; return(services != null); }
public async Task <BluetoothLEDevice> BluetoothLEDeviceFromIdAsync(string id) { BluetoothLEDevice ble = await BluetoothLEDevice.FromIdAsync(id); GattDeviceServicesResult results = await ble.GetGattServicesAsync(); return(ble); }
// Get all the GATT services from the Sensortag public async Task GetGATTServicesDataAsync(BluetoothLEDevice device) { deviceSerivceResult = await device.GetGattServicesAsync(); deviceService = deviceSerivceResult.Services[irsensorservice]; await GetGATTCharacteristicsDataAsync(deviceService); }
public async Task <IButtplugDevice> CreateDeviceAsync([NotNull] BluetoothLEDevice aDevice) { // GetGattServicesForUuidAsync is 15063 only var services = await aDevice.GetGattServicesAsync(BluetoothCacheMode.Cached); List <Guid> uuids = new List <Guid>(); foreach (var s in services.Services) { _bpLogger.Trace($"Found service UUID: {s.Uuid} ({aDevice.Name})"); uuids.Add(s.Uuid); } var srvs = (from x in services.Services from y in _deviceInfo.Services where x.Uuid == y select x).ToArray(); if (srvs.Length != 1) { // Somehow we've gotten multiple services back, something we don't currently support. _bpLogger.Error($"Found {srvs.Length} services for {aDevice.Name}, which is more/less than 1. Please fix this in the bluetooth definition."); return(null); } var service = srvs[0]; var chrResult = await service.GetCharacteristicsAsync(); if (chrResult.Status != GattCommunicationStatus.Success) { _bpLogger.Error($"Cannot connect to service {service.Uuid} of {aDevice.Name}."); return(null); } foreach (var s in chrResult.Characteristics) { _bpLogger.Trace($"Found characteristics UUID: {s.Uuid} ({aDevice.Name})"); } var chrs = chrResult.Characteristics.ToArray(); // If there aren't any characteristics by this point, something has gone wrong. if (!chrs.Any()) { _bpLogger.Error($"Cannot find characteristics for service {service.Uuid} of {aDevice.Name}."); return(null); } var bleInterface = new UWPBluetoothDeviceInterface(_buttplugLogManager, _deviceInfo, aDevice, chrs); var device = _deviceInfo.CreateDevice(_buttplugLogManager, bleInterface); // If initialization fails, don't actually send the message back. Just return null, we'll // have the info in the logs. return(await device.InitializeAsync().ConfigureAwait(false) is Ok ? device : null); }
public async void Connect() { BLEDeviceInfo device = null; foreach (var dev in MainPage.TestresultModel.BLEDevices) { if (dev.DeviceType == DeviceTypesenums.BPMONITOR && dev.IsPaired) { device = dev; break; } else if (dev.DeviceType == DeviceTypesenums.BPMONITOR && !dev.IsPaired) { SendConnectionStatusmessageToMCC("BP Monitor is not Paired."); NotifyStatusMessage?.Invoke("BP Monitor is not Paired.", 3); return; } } GTTServicelist.Clear(); if (device == null) { SendConnectionStatusmessageToMCC("BP Monitor is not foud."); NotifyStatusMessage?.Invoke("BP Monitor is not foud.", 3); return; } bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.DeviceInfo.Id); if (bluetoothLeDevice == null) { SendConnectionStatusmessageToMCC("Device Unreachable."); NotifyStatusMessage?.Invoke("Device Unreachable.", 1); return; } // 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.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var svc in services) { GTTServicelist.Add(svc.Uuid.ToString().ToLower(), svc); } SelectBPMeasureServicesAsync(device);//MainPage.TestresultModel.BPServiceID); } else { SendConnectionStatusmessageToMCC("Failed to connect. " + result.Status.ToString()); NotifyStatusMessage?.Invoke("Failed to connect. " + result.Status.ToString(), 1); } }
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); }
public async void UpdateAllData() { leDevice = await BluetoothLEDevice.FromIdAsync(device.Id); string selector = "(System.DeviceInterface.Bluetooth.DeviceAddress:=\"" + leDevice.BluetoothAddress.ToString("X") + "\")"; var services = await leDevice.GetGattServicesAsync(); foreach (var service in services.Services) { switch (service.Uuid.ToString()) { case SensorUUIDs.UUID_UART_SERV: { var characteristics = await service.GetCharacteristicsAsync(); foreach (var character in characteristics.Characteristics) { switch (character.Uuid.ToString()) { case SensorUUIDs.UUID_UART_RX: { var writer = new DataWriter(); // DATA:SET command not yet working //string message = "DATA:SET #22046524f4d205741544348\n"; //writer.WriteString(message); //await character.WriteValueAsync(writer.DetachBuffer()); // Reading and displaying heartrate from BioSensor RateSensor bs = new RateSensor(); bs.RateSensorInit(); // await Task.Delay(1000); bs.RateMonitorON(); hrmHeartRate = bs.GetHeartRate(); Debug.WriteLine($"Current heartrate: {hrmHeartRate}"); // hrmHeartRate = bs.I2C_ReadRegData(HrmSensor, AS7000_REG_HRM_HEARTRATE); //await Task.Delay(1); //writing TRIGGER to the AdafruitBT writer.WriteString("TRIGGER\n"); //writing current HeartRate to the Adafruit bluetooth //writer.WriteString(hrmHeartRate); await character.WriteValueAsync(writer.DetachBuffer()); } break; } } } break; } } }
/// <summary> /// Connect to the device, check if there's the DFU Service and start the firmware update /// </summary> /// <param name="device">The device discovered</param> /// <returns></returns> public async void connectToDeviceAsync2(DeviceInformation device) { try { var deviceAddress = "N/A"; if (device.Id.Contains("-")) { deviceAddress = device.Id.Split('-')[1]; } Console.WriteLine("Connecting to:" + deviceAddress + "..."); BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id); Console.WriteLine("Name:" + bluetoothLeDevice); //Perform the connection to the device var result = await bluetoothLeDevice.GetGattServicesAsync(); if (result.Status == GattCommunicationStatus.Success) { Console.WriteLine("Device " + deviceAddress + " connected. Updating firmware..."); //Scan the available services var services = result.Services; foreach (var service_ in services) { Console.WriteLine("Service " + service_.Uuid); //If DFUService found... if (service_.Uuid == new Guid(UARTService.UARTService_UUID)) { //NRF52 DFU Service Console.WriteLine("UART Service found"); var stCharacteristic = service_.GetCharacteristics(new Guid(UARTService.UARTCharacteristics_UUID_TX))[0]; await stCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); stCharacteristic.ValueChanged += Characteristic_ValueChangedTest; this.startReaderAsync(this.txCharacteristic); this.startReaderAsync(this.rxCharacteristic); break; } } } else { Console.WriteLine("Status error: " + result.Status.ToString() + " need to restarte the device"); } } catch (Exception e) { Console.WriteLine("ERROR: Accessing2 your device failed." + Environment.NewLine + e.Message + "\n" + e.StackTrace); } }
private async Task <bool> GetAllPrimaryServices(BluetoothCacheMode cacheMode) { var succeeded = false; string debugMsg = String.Format("GetAllPrimaryServices: "); Debug.WriteLine(debugMsg + "Entering"); // Get all the services for this device var result = await BluetoothLEDevice.GetGattServicesAsync(cacheMode); if (result.Status == GattCommunicationStatus.Success) { System.Diagnostics.Debug.WriteLine(debugMsg + "GetGattServiceAsync SUCCESS"); lock (Services) { foreach (var serv in result.Services) { if (!GattServiceUuidHelper.IsReserved(serv.Uuid)) { var temp = new ObservableGattDeviceService(serv); // This isn't awaited so that the user can disconnect while the services are still being enumerated temp.Initialize(); Services.Add(temp); } else { serv.Dispose(); } } ServiceCount = Services.Count(); } succeeded = true; } else if (result.Status == GattCommunicationStatus.ProtocolError) { ErrorText = debugMsg + "GetGattServiceAsync Error: Protocol Error - " + result.ProtocolError.Value; System.Diagnostics.Debug.WriteLine(ErrorText); string msg = "Connection protocol error: " + result.ProtocolError.Value.ToString(); var messageDialog = new MessageDialog(msg, "Connection failures"); await messageDialog.ShowAsync(); } else if (result.Status == GattCommunicationStatus.Unreachable) { ErrorText = debugMsg + "GetGattServiceAsync Error: Unreachable"; System.Diagnostics.Debug.WriteLine(ErrorText); string msg = "Device unreachable"; var messageDialog = new MessageDialog(msg, "Connection failures"); await messageDialog.ShowAsync(); } return(succeeded); }
private async Task <bool> ConnectImpl() { if (!ClearBluetoothLEDeviceAsync()) { Console.WriteLine("Error: Unable to reset state, try again."); //Debug.Assert(false, "Error: Unable to reset state, try again."); return(false); } try { var device = KnownDevices[0]; // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id); if (bluetoothLeDevice == null) { Console.WriteLine("Failed to connect to device."); return(false); } } catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE) { Console.WriteLine("Bluetooth radio is not on."); } 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.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; Console.WriteLine(String.Format("Found {0} services", services.Count)); foreach (var service in services) { ServiceCollection.Add(new BluetoothLEAttributeDisplay(service)); } return(true); } else { Console.WriteLine("Device unreachable"); //Debug.Assert(false, "Device unreachable"); return(false); } } return(false); }