protected async override void OnNavigatedTo(NavigationEventArgs e) { _progressbar = StatusBar.GetForCurrentView().ProgressIndicator; await _progressbar.ShowAsync(); if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(DeviceInformation))) { try { _idDevice=((DeviceInformation)e.Parameter).Id; _device = await BluetoothLEDevice.FromIdAsync(((DeviceInformation)e.Parameter).Id); this.lblDeviceName.Text = ((DeviceInformation)e.Parameter).Name+" " + BLEHelper.AddressToString(_device.BluetoothAddress); if (_device == null) new MessageDialog("Could not connect to the selected device!", "Error").ShowAsync(); _services = _device.GattServices; lstServices.ItemsSource = _services; } catch (Exception ex) { new MessageDialog("Device enumeration error: " + ex.Message, "Error").ShowAsync(); } } this.navigationHelper.OnNavigatedTo(e); await _progressbar.HideAsync(); _dataTransferManager = DataTransferManager.GetForCurrentView(); _dataTransferManager.DataRequested += OnDataRequested; }
private void OnConnectionStatusChanged(BluetoothLEDevice sender, object args) { if (DeviceConnectionUpdated != null) { DeviceConnectionUpdated(sender.ConnectionStatus == BluetoothConnectionStatus.Connected, null); } }
void Device_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) { ChangeScanToStopButton(); } }
private async void ConnectButton_Click() { ConnectButton.IsEnabled = false; ClearBluetoothLEDevice(); try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId); } catch (Exception ex) when ((uint)ex.HResult == 0x800710df) { // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on. } if (bluetoothLeDevice != null) { // BT_Code: GattServices returns a list of all the supported services of the device. // If the services supported by the device are expected to change // during BT usage, subscribe to the GattServicesChanged event. foreach (var service in bluetoothLeDevice.GattServices) { ServiceCollection.Add(new BluetoothLEAttributeDisplay(service)); } ConnectButton.Visibility = Visibility.Collapsed; ServiceList.Visibility = Visibility.Visible; } else { ClearBluetoothLEDevice(); rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage); } ConnectButton.IsEnabled = true; }
public async void startScan(string options) { bleDevice = await BluetoothLEDevice.FromIdAsync(bleDevices[0].Id); currentDevice = bleDevice; string CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString(); string CurrentDeviceName = currentDevice.Name.ToString(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"scanResult\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}")); }
public void AddBLEDevice(BluetoothLEDevice device) { //var exist = this.items.FirstOrDefault(obj => obj.DeviceID == device.DeviceId); //if (exist != null) // this.items.Remove(exist); this.items.Clear(); var addedDevice = new DeviceInformationItem(device); this.items.Add(addedDevice); }
public MiBand(BluetoothLEDevice device) { _device = device; _io = new BluetoothIO(device); Debug.WriteLine($"Name : {device.Name}"); Debug.WriteLine($"Device connection status : {device.ConnectionStatus}"); _device.ConnectionStatusChanged += OnConnectionStatusChanged; _device.GattServicesChanged += OnGattServicesChanged; _device.NameChanged += OnNameChanged; }
/// <summary> /// Executes when the connection state changes /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void BluetoothLEDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { IsPaired = DeviceInfo.Pairing.IsPaired; IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected; UpdateSecureConnectionStatus(); }
protected virtual void Dispose(bool disposing) { _device?.Dispose(); _device = null; }
/// <summary> /// Connect to this bluetooth device /// </summary> /// <returns>Connection task</returns> public async Task <bool> Connect() { bool ret = false; string debugMsg = String.Format("Connect: "); Debug.WriteLine(debugMsg + "Entering"); try { if (BluetoothLEDevice == null) { Debug.WriteLine(debugMsg + "Calling BluetoothLEDevice.FromIdAsync"); BluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(DeviceInfo.Id); } else { Debug.WriteLine(debugMsg + "Previously connected, not calling BluetoothLEDevice.FromIdAsync"); } if (BluetoothLEDevice == null) { ret = false; Debug.WriteLine(debugMsg + "BluetoothLEDevice is null"); MessageDialog dialog = new MessageDialog("No permission to access device", "Connection error"); await dialog.ShowAsync(); } else { Debug.WriteLine(debugMsg + "BluetoothLEDevice is " + BluetoothLEDevice.Name); // Setup our event handlers and view model properties BluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged; BluetoothLEDevice.NameChanged += BluetoothLEDevice_NameChanged; IsPaired = DeviceInfo.Pairing.IsPaired; IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected; UpdateSecureConnectionStatus(); Name = BluetoothLEDevice.Name; // Get all the services for this device CancellationTokenSource GetGattServicesAsyncTokenSource = new CancellationTokenSource(5000); BluetoothCacheMode cacheMode; if (IsConnectable == true) { cacheMode = BluetoothCacheMode.Uncached; } else { cacheMode = BluetoothCacheMode.Cached; } var GetGattServicesAsyncTask = Task.Run(() => BluetoothLEDevice.GetGattServicesAsync(cacheMode), GetGattServicesAsyncTokenSource.Token); result = await GetGattServicesAsyncTask.Result; if (result.Status == GattCommunicationStatus.Success) { // In case we connected before, clear the service list and recreate it Services.Clear(); System.Diagnostics.Debug.WriteLine(debugMsg + "GetGattServiceAsync SUCCESS"); foreach (var serv in result.Services) { Services.Add(new ObservableGattDeviceService(serv, cacheMode)); } ServiceCount = Services.Count(); ret = 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(); } } } catch (Exception ex) { Debug.WriteLine(debugMsg + "Exception - " + ex.Message); string msg = String.Format("Message:\n{0}\n\nInnerException:\n{1}\n\nStack:\n{2}", ex.Message, ex.InnerException, ex.StackTrace); var messageDialog = new MessageDialog(msg, "Exception"); await messageDialog.ShowAsync(); // Debugger break here so we can catch unknown exceptions Debugger.Break(); } if (ret) { Debug.WriteLine(debugMsg + "Exiting (0)"); } else { Debug.WriteLine(debugMsg + "Exiting (-1)"); } return(ret); }
/// <summary> /// Executes when the name of this devices changes /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The arguments.</param> private async void BluetoothLEDevice_NameChanged(BluetoothLEDevice sender, object args) { await DispatcherQueue.EnqueueAsync(() => { Name = BluetoothLEDevice.Name; }, DispatcherQueuePriority.Normal); }
public static async Task Main(string[] args) { var tokenSource = new CancellationTokenSource(); Console.CancelKeyPress += (sender, ev) => { tokenSource.Cancel(); ev.Cancel = true; }; var token = tokenSource.Token; try { var blackmagicCameraService = new Guid("291d567a-6d75-11e6-8b77-86f30ca893d3"); var outgoingCameraControlCharacter = new Guid("5DD3465F-1AEE-4299-8493-D2ECA2F8E1BB"); var address = await new BleAdvertisementFinder(blackmagicCameraService).GetBluetoothAddressAsync(token); Console.WriteLine(address.ToString()); // 229589057331041 using (var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address)) { var services = await device.GetGattServicesForUuidAsync(blackmagicCameraService); if (services.Status != GattCommunicationStatus.Success) { throw new Exception($"Can't get service. {services.Status}"); } var service = services.Services[0]; var characters = await service.GetCharacteristicsForUuidAsync(outgoingCameraControlCharacter); if (characters.Status != GattCommunicationStatus.Success) { throw new Exception($"Can't get characteristics. {characters.Status}"); } var character = characters.Characteristics[0]; if (!character.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { throw new Exception("Can't write."); } var gamepad = XInput.Wrapper.X.Gamepad_1; while (true) { await Task.Delay(TimeSpan.FromSeconds(1.0 / 30.0), token); if (token.IsCancellationRequested) { break; } gamepad.Update(); try { var messageQueue = new Queue <CameraControlProtocolMessage>(); // focus var diff = gamepad.LStick_N.X; if (Math.Abs(diff) > 0.01f) { messageQueue.Enqueue(CameraControlProtocolMessage.ManualLensFocusRelative( DestinationDeviceType.One, diff * 0.02f)); } if (gamepad.LStick_down) { messageQueue.Enqueue(CameraControlProtocolMessage.AutoFocus(DestinationDeviceType.One)); } if (gamepad.Back_down) { messageQueue.Enqueue(CameraControlProtocolMessage.StartRecording(DestinationDeviceType.One)); } while (messageQueue.Count > 0) { var message = messageQueue.Dequeue(); Console.WriteLine($"Sending... {message}"); var result = await character.WriteValueAsync(message.Message.AsBuffer()); if (result != GattCommunicationStatus.Success) { Console.WriteLine($"Send Error: {result}"); } } } catch (OperationCanceledException) { throw; } catch (Exception e) { Console.WriteLine($"Catch Exception: {e}"); } } } Console.WriteLine("Done"); } catch (Exception e) { Console.WriteLine($"Catch Exception: {e}"); } }
public static async Task<ImbleDevice> ConnectAsync(BluetoothLEDevice device, CancellationToken cancellationToken) { var imble = new ImbleDevice(); await imble.Initialize(device.DeviceInformation, device.BluetoothAddress, cancellationToken); return imble; }
public BluetoothIO(BluetoothLEDevice device) { _device = device; }
public async Task <DeviceInformationCollection> GetSensors() { var collection = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); return(collection); }
static async Task <BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options) { DevicePicker picker = new DevicePicker(); Rect bounds = Rect.Empty; #if !UAP uint len = 64; byte[] buffer = new byte[len]; IntPtr hwnd = IntPtr.Zero; try { // a console app will return a non-null string for title if (!string.IsNullOrEmpty(Console.Title)) { bounds = new Rect(0, 0, 480, 480); hwnd = GetConsoleWindow(); // set console host window as parent for picker ((IInitializeWithWindow)(object)picker).Initialize(hwnd); } } catch { } int hasPackage = GetCurrentPackageId(ref len, buffer); if (hasPackage == 0x3d54) { foreach (var attr in System.Reflection.Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute))) { picker.Appearance.Title = ((AssemblyProductAttribute)attr).Product + " wants to pair"; break; } } else { picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; } #else picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; bounds = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds; picker.Appearance.SelectedAccentColor = (Color)Windows.UI.Xaml.Application.Current.Resources["SystemAccentColor"]; #endif if (options != null && !options.AcceptAllDevices) { foreach (var filter in options.Filters) { if (!string.IsNullOrEmpty(filter.Name)) { picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name)); } foreach (var service in filter.Services) { picker.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid(service)); } } } if (picker.Filter.SupportedDeviceSelectors.Count == 0) { //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelector()); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); } try { var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDevice(device)); } catch (Exception ex) { if (ex.HResult == -2147023496) { throw new PlatformNotSupportedException("RequestDevice cannot be called from a Console application."); } return(null); } }
private async Task <BluetoothLEDevice> getDevice(ulong btAddr) { return(await BluetoothLEDevice.FromBluetoothAddressAsync(btAddr)); }
public int SetupMyo(string myoName) { MyoArmband myo = connectedMyos.Where(g => (g.Name == myoName)).FirstOrDefault(); int myoIndex = connectedMyos.IndexOf(myo); if (myo.Device == null) { return(1); } try { // Establishing an IMU data connection var myServices = Task.Run(() => GetServiceAsync(myo.Device, myoGuids["IMU_DATA_SERVIC"])).Result; myo.imuService = myServices.Services.FirstOrDefault(); if (myo.imuService == null) { return(2); } GattCharacteristicsResult imuDataChar = Task.Run(() => GetCharac(myo.imuService, myoGuids["IMU_DATA_CHARAC"])).Result; myo.imuCharac = imuDataChar.Characteristics.FirstOrDefault(); if (myo.imuCharac == null) { return(3); } Notify(myo.imuCharac, charDesVal_notify); // Establishing an EMG data connection var myservs = Task.Run(() => GetServiceAsync(myo.Device, myoGuids["MYO_EMG_SERVICE"])).Result; myo.emgService = myservs.Services.FirstOrDefault(); if (myo.emgService == null) { return(4); } Task <GattCommunicationStatus>[] EmgNotificationTasks = new Task <GattCommunicationStatus> [4]; for (int t = 0; t < 4; t++) { string currEMGChar = "EMG_DATA_CHAR_" + t.ToString(); var tempCharac = Task.Run(() => GetCharac(myo.emgService, myoGuids[currEMGChar])).Result; myo.emgCharacs[t] = tempCharac.Characteristics.FirstOrDefault(); EmgNotificationTasks[t] = Notify(myo.emgCharacs[t], charDesVal_notify); myo.EmgConnStat[t] = EmgNotificationTasks[t].Result; } Task.WaitAll(EmgNotificationTasks); int errhandCode = myo.TryConnectEventHandlers(); if (errhandCode > 0) { Console.WriteLine("error attached event handlers, code " + errhandCode); } int emgErrCode = (int)myo.EmgConnStat[0] + (int)myo.EmgConnStat[1] + (int)myo.EmgConnStat[2] + (int)myo.EmgConnStat[3]; if (emgErrCode != 0) { return(5); } // signify readiness vibrate_armband(myo); myo.IsReady = true; myo.DevConnStat = BluetoothConnectionStatus.Connected; // prepare files for data collection myo.myDataHandler.Prep_EMG_Datastream(myo.Name, SessionId); myo.myDataHandler.Prep_IMU_Datastream(myo.Name, SessionId); if (!bondedMyos.Contains(myo.Name)) { bondedMyos.Add(myo.Name); } // update data objects connectedMyos[myoIndex] = myo; currentDevice = null; isConnecting = false; } catch { return(9); } return(0); }
public Peripheral(CentralContext adapterContext, BluetoothLEDevice native) { this.context = new DeviceContext(adapterContext, this, native); this.Name = native.Name; this.Uuid = native.GetDeviceId(); }
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher aObj, BluetoothLEAdvertisementReceivedEventArgs aEvent) { // BpLogger.Trace($"Got BLE Advertisement for device: {aEvent.Advertisement.LocalName} / {aEvent.BluetoothAddress}"); if (_currentlyConnecting.Contains(aEvent.BluetoothAddress)) { // BpLogger.Trace($"Ignoring advertisement for already connecting device: {aEvent.Advertisement.LocalName} / {aEvent.BluetoothAddress}"); return; } BpLogger.Trace("BLE device found: " + aEvent.Advertisement.LocalName); var factories = from x in _deviceFactories where x.MayBeDevice(aEvent.Advertisement) select x; // We should always have either 0 or 1 factories. var buttplugBluetoothDeviceFactories = factories as UWPBluetoothDeviceFactory[] ?? factories.ToArray(); if (buttplugBluetoothDeviceFactories.Length != 1) { if (buttplugBluetoothDeviceFactories.Any()) { BpLogger.Warn($"Found multiple BLE factories for {aEvent.Advertisement.LocalName} {aEvent.BluetoothAddress}:"); buttplugBluetoothDeviceFactories.ToList().ForEach(x => BpLogger.Warn(x.GetType().Name)); } else { // BpLogger.Trace("No BLE factories found for device."); } return; } _currentlyConnecting.Add(aEvent.BluetoothAddress); var factory = buttplugBluetoothDeviceFactories.First(); BpLogger.Debug($"Found BLE factory: {factory.GetType().Name}"); // If we actually have a factory for this device, go ahead and create the device var fromBluetoothAddressAsync = BluetoothLEDevice.FromBluetoothAddressAsync(aEvent.BluetoothAddress); if (fromBluetoothAddressAsync != null) { var dev = await fromBluetoothAddressAsync; // If a device is turned on after scanning has started, windows seems to lose the // device handle the first couple of times it tries to deal with the advertisement. // Just log the error and hope it reconnects on a later retry. try { var d = await factory.CreateDeviceAsync(dev); InvokeDeviceAdded(new DeviceAddedEventArgs(d)); } catch (Exception ex) { BpLogger.Error( $"Cannot connect to device {aEvent.Advertisement.LocalName} {aEvent.BluetoothAddress}: {ex.Message}"); _currentlyConnecting.Remove(aEvent.BluetoothAddress); return; } } _currentlyConnecting.Remove(aEvent.BluetoothAddress); }
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args) { try { // Filter out Muses. A name filter is the best method currently, since wildcards are not supported in AQS string. // A more robust method may be to query for a Muse specific GATT service, however this requires devices to be powered on, and even if the device was previously paired with the machine, the service won't be cached. if (Constants.DeviceNameFilter.Any(x => args.Name.Contains(x))) { var device = await BluetoothLEDevice.FromIdAsync(args.Id); Debug.WriteLine("Device Name: " + device.Name); Debug.WriteLine("Current Connection Status: " + device.ConnectionStatus); // For debugging - list all services and characteristics. //var services = await device.GetGattServicesAsync(); //foreach(var service in services.Services) //{ // var characteristics = await service.GetCharacteristicsAsync(); // Debug.WriteLine("Service: " + service.Uuid + " Handle: " + service.AttributeHandle); // foreach(var characteristic in characteristics.Characteristics) // { // Debug.WriteLine("Characteristic: " + characteristic.Uuid + " Handle: " + characteristic.AttributeHandle + " Description: " + characteristic.UserDescription); // } //} var muse = Muses.FirstOrDefault(x => x.Id == args.Id); // Don't try to pair an actively streaming Muse. if (muse == null || (muse != null && !muse.IsStreaming)) { var di = await DeviceInformation.CreateFromIdAsync(args.Id); if (di.Pairing.IsPaired) { // Always unpair the device. await di.Pairing.UnpairAsync(); } // Always repair device via BlueMuse if AlwaysPair is "on". if (AlwaysPair) { await di.Pairing.PairAsync(); } } // Retreive an arbitrary service. This will allow the device to auto connect. await device.GetGattServicesForUuidAsync(Constants.MUSE_TOGGLE_STREAM_UUID); lock (Muses) { muse = Muses.FirstOrDefault(x => x.Id == args.Id); if (muse != null) { muse.Id = device.DeviceId; muse.Name = device.Name; muse.Status = device.ConnectionStatus == BluetoothConnectionStatus.Connected ? MuseConnectionStatus.Online : MuseConnectionStatus.Offline; } else { muse = new Muse(device, device.Name, device.DeviceId, device.ConnectionStatus == BluetoothConnectionStatus.Connected ? MuseConnectionStatus.Online : MuseConnectionStatus.Offline); Muses.Add(muse); } ResolveAutoStream(muse); } // Must watch for status changed because Added and Updated are not always called upon connecting or disconnecting. device.ConnectionStatusChanged -= Device_ConnectionStatusChanged; device.ConnectionStatusChanged += Device_ConnectionStatusChanged; } } catch (Exception ex) { Log.Error($"Exception during find device (DeviceWatcher_Added) (device ID={args.Id}).", ex); } }
//connect to bluetooth device public bool Connect() { try { var device = AsyncHelpers.RunSync(() => BluetoothLEDevice.FromBluetoothAddressAsync(ConnectionConstants.AdreessLEGO).AsTask()); if (device != null) { if (device.DeviceInformation.Pairing.IsPaired == false) { /* Optional Below - Some examples say use FromIdAsync * to get the device. I don't think that it matters. */ var did = device.DeviceInformation.Id; //I reuse did to reload later. device.Dispose(); device = null; device = AsyncHelpers.RunSync(() => BluetoothLEDevice.FromIdAsync(did).AsTask()); /* end optional */ var handlerPairingRequested = new TypedEventHandler <DeviceInformationCustomPairing, DevicePairingRequestedEventArgs>(handlerPairingReq); device.DeviceInformation.Pairing.Custom.PairingRequested += handlerPairingRequested; LoggerHelper.Instance.Debug("Paired to device"); var prslt = AsyncHelpers.RunSync(() => device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None).AsTask()); LoggerHelper.Instance.Debug($"Custom PAIR complete status: {prslt.Status}, Connection Status: {device.ConnectionStatus}"); device.DeviceInformation.Pairing.Custom.PairingRequested -= handlerPairingRequested; //Don't need it anymore once paired. if (prslt.Status != DevicePairingResultStatus.Paired) { //This should not happen. If so we exit to try again. LoggerHelper.Instance.Debug("prslt exiting. prslt.status=" + prslt.Status); // so the status may have updated. lets drop out of here and get the device again. should be paired the 2nd time around? return(false); } } _bluetoothLEDevice = device; //get the Lego Boost service var services = AsyncHelpers.RunSync(() => device.GetGattServicesForUuidAsync(Guid.Parse(ConnectionConstants.ServiceUUID)).AsTask()); if (services.Services.Count > 0) { //there is should be only one service with such UUID _deviceService = services.Services[0]; //get the characteristic var characteristics = AsyncHelpers.RunSync(() => _deviceService.GetCharacteristicsForUuidAsync(Guid.Parse(ConnectionConstants.CharacteristicUUID)).AsTask()); if (characteristics.Characteristics.Count > 0) { //there is should be only one characteristic with such UUID _characteristic = characteristics.Characteristics[0]; GattCharacteristicProperties properties = _characteristic.CharacteristicProperties; LoggerHelper.Instance.Debug("Characteristic properties:"); foreach (GattCharacteristicProperties property in Enum.GetValues(typeof(GattCharacteristicProperties))) { if (properties.HasFlag(property)) { LoggerHelper.Instance.Debug($"{property} "); } } LoggerHelper.Instance.Debug("Connector::Connect characteristic created"); //subscribe to the GATT characteristic notification var status = AsyncHelpers.RunSync(() => _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify).AsTask()); if (status == GattCommunicationStatus.Success) { LoggerHelper.Instance.Debug("Subscribing to the Indication/Notification"); _characteristic.ValueChanged += DataCharacteristic_ValueChanged; } else { LoggerHelper.Instance.Debug($"Connetor::Connect set notification failed: {status}"); throw new Exception("Connetor::Connect set notification failed"); } return(true); } LoggerHelper.Instance.Debug("Connector::Connect characteristic not found"); return(false); } LoggerHelper.Instance.Debug("Connector::Connect service not found"); return(false); } LoggerHelper.Instance.Debug("Connector::Connect device not found"); return(false); } catch (Exception e) { //0x800710df - ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on if ((uint)e.HResult == 0x800710df) { var s = "ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on"; LoggerHelper.Instance.Error(s); throw (new Exception(s, e)); } throw; } }
private async void BleReceived(BluetoothLEAdvertisementWatcher w, BluetoothLEAdvertisementReceivedEventArgs btAdv) { if (w == null) { return; } if (btAdv == null) { return; } TimeSpan minTimeBetweenChecks = TimeSpan.FromSeconds(10); lock (_discoverylocker) { if (!_discover) { return; } //Stop(); if (_nonLaunchDevices.Contains(btAdv.BluetoothAddress)) { return; } if (!_lastChecked.ContainsKey(btAdv.BluetoothAddress)) { _lastChecked.Add(btAdv.BluetoothAddress, DateTime.Now); } else if (DateTime.Now - _lastChecked[btAdv.BluetoothAddress] < minTimeBetweenChecks) { return; } _lastChecked[btAdv.BluetoothAddress] = DateTime.Now; } Debug.WriteLine($"BLE advertisement received, aquiring device ..."); var deviceAwaiting = BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress); if (deviceAwaiting == null) { return; } BluetoothLEDevice device = await deviceAwaiting; if (device == null) { return; } Debug.WriteLine($"BLE Device: {device.Name} ({device.DeviceId})"); if (device.Name != "Launch") { Debug.WriteLine("Not a Launch"); _nonLaunchDevices.Add(device.BluetoothAddress); device.Dispose(); return; } bool foundAndConnected = false; try { Thread.Sleep(1000); // SERVICES!! GattDeviceService service = (await device.GetGattServicesForUuidAsync(Launch.Uids.MainService)) .Services.FirstOrDefault(); if (service == null) { return; } Debug.WriteLine($"{device.Name} Main Services found!"); Debug.WriteLine("Service UUID found!"); GattCharacteristic writeCharacteristics = (await service.GetCharacteristicsForUuidAsync(Launch.Uids.WriteCharacteristics)).Characteristics .FirstOrDefault(); GattCharacteristic notifyCharacteristics = (await service.GetCharacteristicsForUuidAsync(Launch.Uids.StatusNotificationCharacteristics)) .Characteristics.FirstOrDefault(); GattCharacteristic commandCharacteristics = (await service.GetCharacteristicsForUuidAsync(Launch.Uids.CommandCharacteristics)) .Characteristics.FirstOrDefault(); if (writeCharacteristics == null || commandCharacteristics == null || notifyCharacteristics == null) { return; } Debug.WriteLine("Characteristics found!"); Launch launch = new Launch(device, writeCharacteristics, notifyCharacteristics, commandCharacteristics); bool init = await launch.Initialize(); Debug.WriteLine("Launch Initialized: " + init.ToString().ToUpper() + "!"); foundAndConnected = true; OnDeviceFound(launch); Stop(); } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message); device.Dispose(); } finally { if (!foundAndConnected) { Debug.WriteLine("Connect failed, try again ..."); Start(); } } }
/// <summary> /// Initialize the device. /// </summary> /// <param name="deviceInformation">An instance of DeviceInformation class corresponding to the BluetoothLEDevice.</param> /// <param name="bluetoothAddress">The bluetooth address of the device.</param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task Initialize(DeviceInformation deviceInformation, ulong bluetoothAddress, CancellationToken cancellationToken) { if (deviceInformation.Pairing.IsPaired) { // If the device is paired, all we have to do is just getting BluetoothLEDevice object by its ID. this.bleDevice = (await BluetoothLEDevice.FromIdAsync(deviceInformation.Id)).AddTo(this.disposables); this.service = this.bleDevice.GetGattService(ServiceUuid).AddTo(this.disposables); } else { // If the device is not paired, pair with the device. var result = await deviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None); switch(result.Status) { case DevicePairingResultStatus.Paired: // The device has been paired successfully. break; default: throw new ImbleOperationException("Failed to pair with the device."); } // After the PairAsync method returns, we have to wait until the device paired is registered to the system. var selector = BluetoothLEDevice.GetDeviceSelectorFromBluetoothAddress(bluetoothAddress); var watcher = DeviceInformation.CreateWatcher(selector); var deviceAddedTask = EventSubscription.ReceiveFirst<DeviceWatcher, DeviceInformation>(handler => watcher.Added += handler, handler => watcher.Added -= handler, cancellationToken); watcher.Start(); var bleDeviceInformation = await deviceAddedTask; // Wait until the target device is added. watcher.Stop(); this.bleDevice = (await BluetoothLEDevice.FromIdAsync(bleDeviceInformation.Id)).AddTo(this.disposables); var gattServiceChangedTask = EventSubscription.ReceiveFirst<BluetoothLEDevice, object>(handler => this.bleDevice.GattServicesChanged += handler, handler => this.bleDevice.GattServicesChanged -= handler, cancellationToken); this.service = this.bleDevice.GetGattService(ServiceUuid); if(this.service == null) { // If the GATT services have not been enumerated yet, wait until the enumeration completes. await gattServiceChangedTask; this.service = this.bleDevice.GetGattService(ServiceUuid); } } // Get the READ characteristic in the IMBLE service. this.readCharacteristic = this.service.GetCharacteristics(ReadCharacteristicUuid).Single(); EventSubscription.Subscribe<GattCharacteristic, GattValueChangedEventArgs>( handler => this.readCharacteristic.ValueChanged += handler, handler => this.readCharacteristic.ValueChanged -= handler, (sender, args) => { if (args.CharacteristicValue.Length < 4) return; // The length of data is too short. var data = args.CharacteristicValue.ToArray(); var length = data[0] + 1; if (data.Length < length) return; // The length field is invalid. Ignore this data. var body = new byte[length - 4]; Array.Copy(data, 4, body, 0, body.Length); this.DataArrived?.Invoke(this, new DataArrivedEventArgs(body, args.Timestamp)); }) .AddTo(this.disposables); // Enable notification of the READ characteristic. var readCccdResult = await this.readCharacteristic.ReadClientCharacteristicConfigurationDescriptorAsync().AsTask(cancellationToken); var readCccd = readCccdResult.ClientCharacteristicConfigurationDescriptor | GattClientCharacteristicConfigurationDescriptorValue.Notify; for (var retryCount = 0;; retryCount++) { try { using (var timeoutCancel = new CancellationTokenSource(TimeSpan.FromSeconds(5))) using(var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancel.Token)) { await this.readCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(readCccd).AsTask(linkedTokenSource.Token); } break; } catch (Exception ex) { if (retryCount > 3) throw new ImbleOperationException("Failed to configure the device.", ex); } } this.writeCharacteristic = this.service.GetCharacteristics(WriteCharacteristicUuid).Single(); EventSubscription.Subscribe<TypedEventHandler<BluetoothLEDevice, object>>( handler => this.bleDevice.ConnectionStatusChanged += handler, handler => this.bleDevice.ConnectionStatusChanged -= handler, (device, _) => { this.ConnectionStatus = device.ConnectionStatus; }) .AddTo(this.disposables); this.ConnectionStatus = this.service.Device.ConnectionStatus; this.Status = ImbleDeviceStatus.Running; }
public BluetoothLEConnection(BluetoothLEDevice device) { Device = device; }
public DeviceInformationItem(BluetoothLEDevice device) : base() { this.Device = device; this.DeviceAddress = GattServiceHelper.ToStringAddress(device.BluetoothAddress); try { foreach (var service in device.GattServices) { switch (service.Uuid.ToString()) { case "00001811-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.ALERT_NOTIFICATION, service); break; case "0000180f-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.BATTERY, service); break; case "00001810-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.BLOOD_PRESSURE, service); break; case "00001805-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.CURRENT_TIME, service); break; case "00001818-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.CYCLING_POWER, service); break; case "00001816-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.CYCLING_SPEED_AND_CADENCE, service); break; case "0000180a-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.DEVICE_INFORMATION, service); break; case "00001800-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.GENERIC_ACCESS, service); break; case "00001801-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.GENERIC_ATTRIBUTES, service); break; case "00001808-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.GLUCOSE, service); break; case "00001809-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.HEALTH_THERMOMETER, service); break; case "0000180d-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.HEART_RATE, service); break; case "00001812-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.HUMAN_INTERFACE_DEVICE, service); break; case "00001802-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.IMMEDIATE_ALERT, service); break; case "00001803-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.LINK_LOSS, service); break; case "00001819-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.LOCATION_AND_NAVIGATION, service); break; case "00001807-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.NEXT_DST_CHANGE, service); break; case "0000180e-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.PHONE_ALERT_STATUS, service); break; case "00001806-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.REFERENCE_TIME_UPDATE, service); break; case "00001814-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.RUNNING_SPEED_AND_CADENCE, service); break; case "00001813-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.SCAN_PARAMETERS, service); break; case "00001804-0000-1000-8000-00805f9b34fb": Services.Add(ToolboxIdentifications.GattServiceNames.TX_POWER, service); break; case "00001530-1212-efde-1523-785feabcd123": Services.Add(ToolboxIdentifications.GattServiceNames.DEVICE_FIRMWARE_UPDATE, service); break; case "6e400001-b5a3-f393-e0a9-e50e24dcca9e": Services.Add(ToolboxIdentifications.GattServiceNames.NORDIC_UART, service); break; default: break; } } } catch (Exception e) { //Catch any exceptions and make alert to phone or user } if (LocalSettings.Values.ContainsKey(DeviceAddress)) { string[] values = ((string)LocalSettings.Values[DeviceAddress]).Split(','); AlertOnPhone = bool.Parse(values[0]); AlertOnDevice = bool.Parse(values[1]); //alertLevel = (AlertLevel)Enum.Parse(typeof(AlertLevel), values[2]); } this.CompleteDeviceName = device.Name; this.DeviceID = device.DeviceId; this.ConnectionStatus = device.ConnectionStatus; }
public async Task <Boolean> TryLocateServices(BluetoothLEDevice bluetoothLeDevice) { // Only one init if (GattDeviceServiceTemperature != null || GattDeviceServiceLuminosity != null || GattDeviceServiceBattery != null) { return(true); } // Try get access to device Windows.Devices.Enumeration.DeviceAccessStatus result; try { result = await bluetoothLeDevice.RequestAccessAsync(); } catch (Exception) { result = Windows.Devices.Enumeration.DeviceAccessStatus.DeniedBySystem; } // Access denied if (result != DeviceAccessStatus.Allowed) { return(false); } // Get services of device in loop with timeout of 100 ms GattDeviceServicesResult gattDeviceServicesResult = null; for (int i = 0; i < 5; i++) { // Try get list of services gattDeviceServicesResult = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); // Any services in list if (gattDeviceServicesResult?.Services.Count > 0) { break; } // Wait 100 ms await Task.Delay(100).ConfigureAwait(false); } // No services available if (gattDeviceServicesResult == null || gattDeviceServicesResult?.Services.Count == 0) { return(false); } // Iterate services foreach (var service in gattDeviceServicesResult.Services) { // 9dc84838-7619-4f09-a1ce-ddcf63225b20 is the luminosity service if (String.Compare(LuminosityGattServiceUuuid, service.Uuid.ToString(), StringComparison.OrdinalIgnoreCase) == 0) { GattDeviceServiceLuminosity = service; } if (String.Compare(BatteryGattServiceUuuid, service.Uuid.ToString(), StringComparison.OrdinalIgnoreCase) == 0) { GattDeviceServiceBattery = service; } if (String.Compare(TemperatureGattServiceUuid, service.Uuid.ToString(), StringComparison.OrdinalIgnoreCase) == 0) { GattDeviceServiceTemperature = service; } } double batteryLevel = await ReadBatteryValue().ConfigureAwait(true); double lux = await ReadLuminosityValue().ConfigureAwait(true); Debug.WriteLine($"SensorBug Lux {lux} lx battery level {batteryLevel} %"); await ReadValues().ConfigureAwait(true); // we can read values => start imer ThreadHelper.RunOnMainThread(() => { Timer?.Start(); }); return(true); }
async void Device_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { await ConnectionStatusChangedUI(); }
private async void Bleaw_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (sender == null) { return; } bool OK = false; if (System.Threading.Interlocked.Increment(ref barrier) == 1) { BLEAdvWatcher.Stop(); Guid guidNotification; ulong blAdress = args.BluetoothAddress;; BluetoothLEDevice blDevice = await Windows.Devices.Bluetooth.BluetoothLEDevice.FromBluetoothAddressAsync(blAdress); if (!(blDevice == null)) { var name = blDevice.Name; System.Diagnostics.Debug.WriteLine("Device Name=:", name); if ((blDevice.DeviceInformation.Kind == Windows.Devices.Enumeration.DeviceInformationKind.AssociationEndpoint) && (NameFilter == ""?true:name.ToLower().Contains(NameFilter.ToLower()))) { System.Diagnostics.Debug.WriteLine("Bluetooth Address: {0}", blAdress); await CC2650SensorTag.PrependTextStatic(string.Format("Bluetooth Address: {0}", blAdress)); byte[] bytes = BitConverter.GetBytes(blAdress); string res = System.Text.Encoding.UTF8.GetString(bytes); string addrStr = bytes[bytes.Length - 3].ToString("X2"); for (int i = bytes.Length - 4; i > -1; i--) { addrStr += ":" + bytes[i].ToString("X2"); } System.Diagnostics.Debug.WriteLine("Bluetooth Address: {0}", addrStr); await CC2650SensorTag.PrependTextStatic(string.Format("Bluetooth Address: {0}", addrStr)); var scanresp = args.AdvertisementType; Windows.Devices.Enumeration.DeviceAccessStatus result; try { result = await blDevice.RequestAccessAsync(); } catch (Exception ex) { result = Windows.Devices.Enumeration.DeviceAccessStatus.DeniedBySystem; } if (result == Windows.Devices.Enumeration.DeviceAccessStatus.Allowed) { name = blDevice.Name; System.Diagnostics.Debug.WriteLine("Endpoint Device Name: {0}", name); await CC2650SensorTag.PrependTextStatic(string.Format("Endpoint Device Name: {0}", name)); var services = await blDevice.GetGattServicesAsync(); var svcs = services.Services; System.Diagnostics.Debug.WriteLine("Endpoint Device Id: {0}", blDevice.DeviceId); await CC2650SensorTag.PrependTextStatic(string.Format("Endpoint Device Id: {0}", blDevice.DeviceId)); System.Diagnostics.Debug.WriteLine("Start"); string nm = blDevice.Name; string did = blDevice.DeviceId; string info = blDevice.DeviceInformation.Name; if (svcs != null) { int num = svcs.Count; if (num != 0) { foreach (var x in svcs) { string sdf = x.Uuid.ToString(); string asdcb = x.DeviceId; System.Diagnostics.Debug.WriteLine("{0} = {1}", sdf, asdcb); } await TagServices.InterogateServices(svcs); OK = true; } else { System.Diagnostics.Debug.WriteLine("No Services."); OK = false; } } else { System.Diagnostics.Debug.WriteLine("ull Services."); OK = false; } } } } } if (!OK) { System.Threading.Interlocked.Decrement(ref barrier); BLEAdvWatcher.Start(); } }
private async void ProcessManufacturerData(BluetoothLEAdvertisementReceivedEventArgs e, MData m) { int idx = m.FindManufacturerId(BMRecordBase.MANUFACTURER_ID); if (idx < 0) { return; } if (!_blueMaestroDevices.ContainsKey(e.BluetoothAddress)) { BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(e.BluetoothAddress); lock (_blueMaestroDevices) { if (device != null) { _blueMaestroDevices[e.BluetoothAddress] = device; _stopperBM = 0; } } } if (_blueMaestroDevices.ContainsKey(e.BluetoothAddress)) { BluetoothLEDeviceDisplay display = new BluetoothLEDeviceDisplay(_blueMaestroDevices[e.BluetoothAddress].DeviceInformation); Log.d("*BT* " + display.ToString()); } if (m.ManufacturerData.Count > 0) { lock (_blueMaestroDevices) { foreach (MData.Section section in m.ManufacturerData) { if (BMRecordCurrent.IsManufacturerID(section.CompanyId)) { DateTime date = DateTime.Now; // eventArgs.Timestamp.DateTime; BluetoothDevice dev = new BluetoothDevice( e.Advertisement.LocalName, e.BluetoothAddress, e.AdvertisementType.ToString()); if (_averages == null) { _averages = new BMRecordAverages(dev, e.RawSignalStrengthInDBm, date, null); } if (_current == null) { _current = new BMRecordCurrent(dev, e.RawSignalStrengthInDBm, date, null); } if (section.Buffer.Length == 14) { if (BMDatabaseMap.INSTANCE.Contains(dev.Address)) { int count = BMDatabaseMap.INSTANCE[dev.Address].Records.Count; if (count > 0) { //time between readings TimeSpan tsElapsed = DateTime.Now - BMDatabaseMap.INSTANCE[dev.Address].Records.Last().Date; _lastCurrent = ", Curr Updated: " + tsElapsed.TotalSeconds.ToString("0s"); } } _current = BMDatabaseMap.INSTANCE.AddRecord(dev, e.RawSignalStrengthInDBm, date, section.Buffer); } else if (section.Buffer.Length == 25) { //just update time TimeSpan tsElapsed = DateTime.Now - _averages.Date; _lastAverage = ", Avg Updated: " + tsElapsed.TotalSeconds.ToString("0s"); _averages.Set_sData(section.Buffer); } else { Log.e(" --- Unknown Length: " + section.Buffer.Length); } string recordsCount = ""; if (BMDatabaseMap.INSTANCE.Contains(dev.Address)) { int count = BMDatabaseMap.INSTANCE[dev.Address].Records.Count; recordsCount = "Records: " + count + " \n"; } string message = recordsCount; message += "Total: " + CommonTools.TimeSpanToString(TimeSpan.FromSeconds(_stopperBM)) + _lastAverage + _lastCurrent + " \n"; message += "Timestamp: " + date.ToString("MMM dd, HH:mm:ss") + " \n"; message += _current.ToString() + _averages.ToString(); OnBMDeviceMsgReceivedAction(message); } } } } }
private async void ConnectToKeyboard(DeviceInformation device) { try { if (this.KeyboardDeviceInformation != null) { return; } var keyboard = await BluetoothLEDevice.FromIdAsync(device.Id); if (keyboard == null) { return; } if (keyboard.ConnectionStatus != BluetoothConnectionStatus.Connected) { return; } var services = await keyboard.GetGattServicesAsync(); if (services == null) { return; } GattDeviceService oadService = null; foreach (GattDeviceService service in services.Services) { if (service.Uuid == OAD_GUID) { oadService = service; break; } } GattCharacteristicsResult characteristics = await oadService.GetCharacteristicsAsync(); GattCharacteristic writeGatt = null; GattCharacteristic readGatt = null; foreach (GattCharacteristic characteristic in characteristics.Characteristics) { if (characteristic.Uuid == WRITE_GATT_GUID) { writeGatt = characteristic; } else if (characteristic.Uuid == READ_GATT_GUID) { readGatt = characteristic; } } this.WriteGatt = writeGatt; this.ReadGatt = readGatt; this.KeyboardDeviceInformation = device; this.KeyboardDeviceInformation = device; await this.ReadGatt.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); this.ReadGatt.ValueChanged += ReadGatt_ValueChanged; // Sync up the profile data this.RequestKeyboardSync(); } // We should actually catch errors here... catch (Exception ex) { Debug.WriteLine(ex); } }
public WinRTPoweredUpBluetoothDevice(BluetoothLEDevice device) { _device = device ?? throw new ArgumentNullException(nameof(device)); }
private void ClearBluetoothLEDevice() { bluetoothLeDevice?.Dispose(); bluetoothLeDevice = null; }
private void OnConnectionStatusChanged(BluetoothLEDevice sender, object args) { Debug.WriteLine("Connection status changed : " + _device.ConnectionStatus); }
public static string IdentifierFromBluetoothLEDevice(BluetoothLEDevice bleDevice) { return(bleDevice.DeviceId); }
/// <summary> /// Executes when the name of this devices changes /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void BluetoothLEDevice_NameChanged(BluetoothLEDevice sender, object args) { Name = BluetoothLEDevice.Name; }
internal static async Task <TAPProperties> GetTAPPropertiesAsync(BluetoothLEDevice d) { GattCharacteristic tapData = null; GattCharacteristic tapMouse = null; GattCharacteristic nusRx = null; int fwVersion = 0; GattDeviceServicesResult tapServicesResult = await GetServicesAsync(d, 10, 800); foreach (GattDeviceService ser in tapServicesResult.Services) { if (ser.Uuid == TAPGuids.service_tap) { GattCharacteristicsResult tapCharacteristicsResult = await GetCharacteristicsAsync(ser, 10, 800); foreach (GattCharacteristic ch in tapCharacteristicsResult.Characteristics) { if (ch.Uuid == TAPGuids.characteristic_tapdata) { tapData = ch; } else if (ch.Uuid == TAPGuids.characteristic_mousedata) { tapMouse = ch; } } } if (ser.Uuid == TAPGuids.service_nus) { GattCharacteristicsResult nusCharacteristicsResult = await GetCharacteristicsAsync(ser, 10, 800); foreach (GattCharacteristic ch in nusCharacteristicsResult.Characteristics) { if (ch.Uuid == TAPGuids.characteristic_rx) { nusRx = ch; } } } if (ser.Uuid == TAPGuids.service_device_information) { GattCharacteristicsResult fwCharacteristicsResult = await GetCharacteristicsAsync(ser, 10, 800); foreach (GattCharacteristic ch in fwCharacteristicsResult.Characteristics) { if (ch.Uuid == TAPGuids.characteristic_fw_version) { GattReadResult fwRead = await ch.ReadValueAsync(); if (fwRead.Status == GattCommunicationStatus.Success) { DataReader reader = DataReader.FromBuffer(fwRead.Value); string str = reader.ReadString(fwRead.Value.Length); fwVersion = VersionNumber.FromString(str); } } } } } return(new TAPProperties(tapData, tapMouse, nusRx, fwVersion)); }
static async Task <BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options) { DevicePicker picker = new DevicePicker(); Rect bounds = Rect.Empty; //picker.Appearance.AccentColor = Windows.UI.Colors.Green; //picker.Appearance.ForegroundColor = Windows.UI.Colors.White; //picker.Appearance.BackgroundColor = Windows.UI.Colors.DarkGray; #if !UAP uint len = 64; byte[] buffer = new byte[len]; int hasPackage = GetCurrentPackageId(ref len, buffer); if (hasPackage == 0x3d54) { foreach (var attr in System.Reflection.Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute))) { picker.Appearance.Title = ((AssemblyProductAttribute)attr).Product + " wants to pair"; break; } } else { picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; } #else picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; bounds = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds; picker.Appearance.SelectedAccentColor = (Color)Windows.UI.Xaml.Application.Current.Resources["SystemAccentColor"]; #endif if (!options.AcceptAllDevices) { foreach (var filter in options.Filters) { if (!string.IsNullOrEmpty(filter.Name)) { picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name)); } foreach (var service in filter.Services) { picker.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid(service)); } } } if (picker.Filter.SupportedDeviceSelectors.Count == 0) { //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelector()); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); } var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDevice(device)); }
private async void DeviceOnConnectionStatusChanged(BluetoothLEDevice device, object args) { if (device.ConnectionStatus == BluetoothConnectionStatus.Connected) { //Get stuff up and running OnStatusChange?.Invoke("Connected"); if ( this.NotificationSourceCharacteristic.CharacteristicProperties.HasFlag( GattCharacteristicProperties.Notify)) { this.NotificationSourceCharacteristic.ValueChanged += NotificationSourceCharacteristicOnValueChanged; // Set the notify enable flag try { await this.NotificationSourceCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); } catch (Exception ex) { } } this.DataSourceCharacteristic.ValueChanged += DataSourceCharacteristicOnValueChanged; await this.DataSourceCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); } if (device.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { //Stop doing stuff this.DataSourceCharacteristic.ValueChanged -= DataSourceCharacteristicOnValueChanged; this.NotificationSourceCharacteristic.ValueChanged -= NotificationSourceCharacteristicOnValueChanged; OnStatusChange?.Invoke("Disconnected"); } }
private void OnNameChanged(BluetoothLEDevice sender, object args) { Debug.WriteLine("Name changed : " + _device.Name); }
public void Dispose() { this.disposables.Dispose(); this.bleDevice = null; this.service = null; this.readCharacteristic = null; this.writeCharacteristic = null; }
public async void disconnect(string options) { string[] args = null; try { args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options); } catch (FormatException) { } string status; PluginResult result; await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute)); if (currentDevice.ConnectionStatus.ToString() == "Connected") { status = "disconnecting"; callbackId_sub = args[args.Length - 1]; result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\"}"); result.KeepCallback = true; DispatchCommandResult(result, callbackId_sub); } while (currentDevice.ConnectionStatus.ToString() != "Disconnected") { } currentDevice = null; status = "disconnected"; result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\"}"); result.KeepCallback = false; DispatchCommandResult(result, callbackId_sub); }
/// <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); }); }
private void OnGattServicesChanged(BluetoothLEDevice sender, object args) { Debug.WriteLine("Gatt services changed"); }
void Device_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { if(sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { this.nordicUartControlButtonViewModel.StopUartService(); StopUartModelUI(); } }
public BluetoothLEDeviceEvents(BluetoothLEDevice This) { this.This = This; }
async void ConnectDevice(ulong add) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(add); //System.Threading.Thread.Sleep(5000); isConnected = true; // BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ble.DeviceId); //Console.WriteLine("Device Added"); //Console.ReadLine(); //GattDeviceServicesResult result = await bluetoothLeDevice; //var prslt = await bluetoothLeDevice.DeviceInformation.Pairing.PairAsync(); //System.Threading.Thread.Sleep(7000); //try 5 second lay. Guid serUuid = new Guid("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); Guid charUuid = new Guid("beb5483e-36e1-4688-b7f5-ea07361b26a8"); //IReadOnlyList<GattDeviceService> svc = bluetoothLeDevice.GattServices; GattDeviceService service = bluetoothLeDevice.GetGattService(serUuid); //Console.ReadLine(); //Console.WriteLine(String.Format(" Device Name: {0}", bluetoothLeDevice.DeviceInformation.Name)); //Console.WriteLine("Getting Characterstics"); //IReadOnlyList<GattCharacteristic> chars = service.GetAllCharacteristics(); GattCharacteristic selectedCharacteristic = service.GetCharacteristics(charUuid).FirstOrDefault(); //Console.WriteLine(chars.FirstOrDefault().Uuid); // Console.WriteLine(svc.FirstOrDefault().Uuid); // //IReadOnlyList<GattCharacteristic> chrs = svc.GetAllCharacteristics(); /* * if (result.Status == GattCommunicationStatus.Success) * { * var services = result.Services; * * // ... * }*/ //***** WRITE DATA ******* var writer = new DataWriter(); // WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle writer.WriteByte(0x78); GattCommunicationStatus result1 = await selectedCharacteristic.WriteValueAsync(writer.DetachBuffer()); if (result1 == GattCommunicationStatus.Success) { Console.WriteLine("Written Successfully"); } //***** READING DATA ******** GattReadResult result = await selectedCharacteristic.ReadValueAsync(); if (result.Status == GattCommunicationStatus.Success) { var reader = DataReader.FromBuffer(result.Value); byte[] input = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(input); Console.WriteLine(Encoding.UTF8.GetString(input)); // Utilize the data as needed } // ... }
private void OnConnectionStatusChanged(BluetoothLEDevice sender, object args) { if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) { System.Diagnostics.Debug.WriteLine("Connected"); } else { System.Diagnostics.Debug.WriteLine("Disconnected"); } if (DeviceConnectionUpdated != null) { DeviceConnectionUpdated(sender.ConnectionStatus == BluetoothConnectionStatus.Connected,null); } }
public async Task ConnectDisconnect() { var tcs = new TaskCompletionSource <ulong>(); var adWatcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active }; var handler = new TypedEventHandler <BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs> ((sender, args) => { if (args.Advertisement.LocalName.StartsWith("bean", StringComparison.InvariantCultureIgnoreCase)) { tcs.TrySetResult(args.BluetoothAddress); } } ); adWatcher.Received += handler; adWatcher.Start(); var bluetoothAddress = await tcs.Task; adWatcher.Stop(); var device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress); this.output.WriteLine($"Bluetooth DeviceId: {device.BluetoothDeviceId.Id} - {device.DeviceId} / {device.Name}"); var serviceResult = await device.GetGattServicesForUuidAsync(Guid.Parse("A495FF20-C5B1-4B44-B512-1370F02D74DE")); var service = serviceResult.Services.First(); await service.OpenAsync(GattSharingMode.Exclusive); var characteristicResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached); var characteristic = characteristicResult.Characteristics.First(); var chtcs = new TaskCompletionSource <byte[]>(); var handler2 = new TypedEventHandler <GC, GattValueChangedEventArgs>((sender, args) => chtcs.TrySetResult(args.CharacteristicValue.ToArray()) ); characteristic.ValueChanged += handler2; await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); var data = await chtcs.Task; // start cleanup await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); characteristic.ValueChanged -= handler2; //BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected) //service.Session.SessionStatusChanged += (sender, args) => //{ // //args.Status == GattSessionStatus.Active //}; //service.Session.MaintainConnection = true; //foreach (var c in characteristicResult.Characteristics) //{ // c.Service.Session.Dispose(); //} foreach (var s in serviceResult.Services) { s.Session.Dispose(); } //service = null; //var list = device.GetType().GetTypeInfo().GetRuntimeMethods().OrderBy(x => x.Name); ////var releasers = list.Where(x => x.Name.StartsWith("Release")); ////foreach (var releaser in releasers) //foreach (var method in list) //{ // this.output.WriteLine($"Name: {method.Name}, Static: {method.IsStatic}, Public: {method.IsPublic}, Private: {method.IsPrivate}, Parameters: {method.GetParameters().Length}"); //} service.Dispose(); service = null; characteristic = null; device.Dispose(); device = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); }
private async void Device_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.scanButton.Visibility = Visibility.Collapsed; this.disconnectButton.Visibility = Visibility.Visible; }); } }
internal BluetoothDevice(BluetoothLEDevice device) { NativeDevice = device; }
public void close(string options) { bleDevices = null; currentDevice = null; currentDeviceServices = null; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"closed\"}")); }
private async void WathcerReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { // アドバタイズパケット受信→HeartRateサービスを検索 bool find = false; var bleServiceUUIDs = args.Advertisement.ServiceUuids; BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); if (dev == null) { return; } // 発見 GattDeviceServicesResult result = await dev.GetGattServicesAsync(/*GattServiceUuids.HeartRate*/); if (result.Status == GattCommunicationStatus.Success) { var services = result.Services; foreach (var service in services) { if (service.Uuid == GattServiceUuids.HeartRate) { this.Service = service; find = true; this.advWatcher.Stop(); break; } } } //発見したデバイスがHeartRateサービスを持っていたら if (find) { { var characteristics = await Service.GetCharacteristicsForUuidAsync(GattCharacteristicUuids.HeartRateMeasurement); if (characteristics.Status == GattCommunicationStatus.Success) { foreach (var chr in characteristics.Characteristics) { if (chr.Uuid == GattCharacteristicUuids.HeartRateMeasurement) { this.Characteristic_HeartRate_Measurement = chr; //データの送り方が二種類あるので場合分け。OH1はNotifyなのでそちら側しか動作確認をしていない if (this.Characteristic_HeartRate_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate)) { this.Characteristic_HeartRate_Measurement.ValueChanged += characteristicChanged_HeartRate_Measurement; await this.Characteristic_HeartRate_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate); } if (this.Characteristic_HeartRate_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { this.Characteristic_HeartRate_Measurement.ValueChanged += characteristicChanged_HeartRate_Measurement; await this.Characteristic_HeartRate_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } OnConnectBLE(EventArgs.Empty); break; } } } else { this.advWatcher.Start(); } } } }
public async void connect(string options) { string[] args = null; try { args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options); } catch (FormatException) { } bleDevice = await BluetoothLEDevice.FromIdAsync(bleDevices[0].Id); currentDevice = bleDevice; string status; string CurrentDeviceName=null; string CurrentDeviceAddress = null; PluginResult result; if (currentDevice.ConnectionStatus.ToString() == "Disconnected") { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute)); status = "connecting"; CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString(); CurrentDeviceName = currentDevice.Name.ToString(); callbackId_sub = args[args.Length-1]; result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}"); result.KeepCallback = true; DispatchCommandResult(result, callbackId_sub); } while(currentDevice.ConnectionStatus.ToString() != "Connected") {} status = "connected"; CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString(); CurrentDeviceName = currentDevice.Name.ToString(); result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}"); result.KeepCallback = false; DispatchCommandResult(result, callbackId_sub); }
public DeviceInformationItem(BluetoothLEDevice device) { this.Device = device; this.DeviceAddress = ConvertingTools.GetBLEMacAddress(device.BluetoothAddress); try { foreach (var service in device.GattServices) { switch (service.Uuid.ToString()) { case "00001811-0000-1000-8000-00805f9b34fb": Services.Add("AlertNotification", service); break; case "0000180f-0000-1000-8000-00805f9b34fb": Services.Add("Battery", service); break; case "00001810-0000-1000-8000-00805f9b34fb": Services.Add("BloodPressure", service); break; case "00001805-0000-1000-8000-00805f9b34fb": Services.Add("CurrentTime", service); break; case "00001818-0000-1000-8000-00805f9b34fb": Services.Add("CyclingPower", service); break; case "00001816-0000-1000-8000-00805f9b34fb": Services.Add("CyclingSpeedAndCadence", service); break; case "0000180a-0000-1000-8000-00805f9b34fb": Services.Add("DeviceInformation", service); break; case "00001800-0000-1000-8000-00805f9b34fb": Services.Add("GenericAccess", service); break; case "00001801-0000-1000-8000-00805f9b34fb": Services.Add("GenericAttribute", service); break; case "00001808-0000-1000-8000-00805f9b34fb": Services.Add("Glucose", service); break; case "00001809-0000-1000-8000-00805f9b34fb": Services.Add("HealthThermometer", service); break; case "0000180d-0000-1000-8000-00805f9b34fb": Services.Add("HeartRate", service); break; case "00001812-0000-1000-8000-00805f9b34fb": Services.Add("HumanInterfaceDevice", service); break; case "00001802-0000-1000-8000-00805f9b34fb": Services.Add("ImmediateAlert", service); break; case "00001803-0000-1000-8000-00805f9b34fb": Services.Add("LinkLoss", service); break; case "00001819-0000-1000-8000-00805f9b34fb": Services.Add("LocationAndNavigation", service); break; case "00001807-0000-1000-8000-00805f9b34fb": Services.Add("NextDstChange", service); break; case "0000180e-0000-1000-8000-00805f9b34fb": Services.Add("PhoneAlertStatus", service); break; case "00001806-0000-1000-8000-00805f9b34fb": Services.Add("ReferenceTimeUpdate", service); break; case "00001814-0000-1000-8000-00805f9b34fb": Services.Add("RunningSpeedAndCadence", service); break; case "00001813-0000-1000-8000-00805f9b34fb": Services.Add("ScanParameters", service); break; case "00001804-0000-1000-8000-00805f9b34fb": Services.Add("TxPower", service); break; case "00001530-1212-efde-1523-785feabcd123": Services.Add(GATTServiceIdentification.DEVICE_FIRMWARE_UPDATE, service); break; //case "00001531-1212-efde-1523-785feabcd123": // Services.Add("Packet", service); // break; //case "00001532-1212-efde-1523-785feabcd123": // Services.Add("ControlPoint", service); // break; //case "00001534-1212-efde-1523-785feabcd123": // Services.Add("DFUVersion", service); // break; default: break; } } } catch (Exception e) { //Catch any exceptions and make alert to phone or user } if (LocalSettings.Values.ContainsKey(DeviceAddress)) { string[] values = ((string)LocalSettings.Values[DeviceAddress]).Split(','); AlertOnPhone = bool.Parse(values[0]); AlertOnDevice = bool.Parse(values[1]); //alertLevel = (AlertLevel)Enum.Parse(typeof(AlertLevel), values[2]); } this.CompleteDeviceName = device.Name; this.DeviceID = device.DeviceId; this.ConnectionStatus = device.ConnectionStatus; }