/// <summary> /// Register the bluetooth device and connects to it /// </summary> /// <param name="device">The device to register</param> /// <returns>True if the registration is successfull. False in any other case</returns> public async Task <bool> RegisterDeviceAsync(Device device) { try { Log.Debug(LOG_TAG, "RegisterDevice: trying to register device " + device.ToString()); InitializeBlueTooth(); // converting our device Id in Guid Guid?deviceGuid = Utils.AsGuid(device.Id, /*this.appSettings.DEVICE_GUID_FORMAT*/ "00000000-0000-0000-0000-{0}"); if (!deviceGuid.HasValue) { Log.Debug(LOG_TAG, "RegisterDeviceAsync: " + nameof(deviceGuid) + " is NULL"); return(false); } // connection this.ConnectedDevice = await this.Adapter.ConnectToKnownDeviceAsync(deviceGuid.Value); if (this.ConnectedDevice == null) { Log.Debug(LOG_TAG, "RegisterDeviceAsync: " + nameof(this.ConnectedDevice) + " is NULL"); return(false); } Log.Debug(LOG_TAG, "RegisterDeviceAsync: Connection successfull"); return(true); } catch (DeviceConnectionException e) { DisposeAll(); Log.Error(LOG_TAG, "RegisterDeviceAsync.DeviceConnectionException: " + e); return(false); } catch (Exception e) { DisposeAll(); Log.Error(LOG_TAG, "RegisterDeviceAsync.Exception: " + e); return(false); } }
/// <summary> /// Initializes a ble service within the device /// </summary> /// <param name="device">The device to initialize</param> /// <param name="serviceUUID">The service to initialize</param> /// <returns>True if the intialization is successfull. False in any other case</returns> public async Task <bool> InitializeBLEServicesAsync(Device device, string serviceUUID) { try { Log.Debug(LOG_TAG, "InitializeBLEServicesAsync : trying to initialize services for device " + device.ToString() + " service=[" + serviceUUID + "]"); InitializeBlueTooth(); // if ConnectedDevice is NULL we try to (re)Register the device if (this.ConnectedDevice == null) { // if it's still not OK, then we return if (!RegisterDeviceAsync(device).Result) { return(false); } } Guid?serviceGuid = Utils.AsGuid(serviceUUID); if (!serviceGuid.HasValue) { Log.Debug(LOG_TAG, "InitializeBLEServicesAsync: " + nameof(serviceGuid) + " is NULL"); return(false); } // Workaround (to let the Bluetooth GATT discover the services) await Task.Delay(1500); // connection this.UARTService = await this.ConnectedDevice.GetServiceAsync(serviceGuid.Value); // Workaround (to let the Bluetooth GATT discover the services) await Task.Delay(1500); if (this.UARTService == null) { Log.Debug(LOG_TAG, "InitializeBLEServicesAsync: " + nameof(this.UARTService) + " is NULL"); return(false); } Log.Debug(LOG_TAG, "InitializeBLEServicesAsync: Service connection successfull"); return(true); } catch (Exception e) { DisposeAll(); Log.Error(LOG_TAG, "InitializeBLEServicesAsync: " + e); return(false); } }