コード例 #1
0
        private async static void DevicesWithConnectionStatusAsync(bool Connected)
        {
            List <GattDevice>           returnDevices = new List <GattDevice>();
            string                      filter        = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(Connected ? BluetoothConnectionStatus.Connected : BluetoothConnectionStatus.Disconnected);
            DeviceInformationCollection infos         = await DeviceInformation.FindAllAsync(filter);

            if (infos.Count > 0)
            {
                Debug.Log("Found " + infos.Count + " Devices");
                foreach (DeviceInformation info in infos)
                {
                    string deviceID = info.Id;
                    Debug.Log("Device Name: " + info.Name);
                    try
                    {
                        BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceID);

                        GattDevice d = GattDevice.Create(device);
                        returnDevices.Add(d);
                    }
                    catch { }
                }
            }

            OnDevicesAcquired?.Invoke(returnDevices);

            /*Debug.Log("Found " + infos.Count + " Devices");
             * foreach (DeviceInformation info in infos)
             * {
             *  Debug.Log("Device Name: " + info.Name);
             * }*/
        }
コード例 #2
0
        public async Task <IReadOnlyList <TDevice> > Browse()
        {
            var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected), requestedProperties);

            return(devices.Select(d => new TDevice(HIOStaticValues.tmain?.SettingManager,
                                                   d.Name,
                                                   id: d.Id,
                                                   mac: GetMac(d),
                                                   signalValue: BLEDevice.GetSignal(d.Properties),
                                                   isConnected: d.Properties.ContainsKey(BLEDevice.IsConnectableProperty) ? (bool)d.Properties[BLEDevice.IsConnectedProperty] : false)).ToList());
        }
コード例 #3
0
        public static BLEDeviceInfo FindConnectedDevice()
        {
            if (!HIOStaticValues.IsBLESupported)
            {
                return(null);
            }
            BLEDeviceInfo result = null;

            Task.Run(async() =>
            {
                try
                {
                    var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected), requestedProperties);
                    if (Array.TrueForAll(HIOStaticValues.blea.mac, v => v == 0))
                    {
                        var db      = new DataBase();
                        var lastMac = db.GetLastDeviceMac();
                        if (lastMac != null)
                        {
                            Array.Copy(lastMac, HIOStaticValues.blea.mac, 6);
                        }
                    }

                    foreach (var di in devices.Where(d => GetMac(d).SequenceEqual(HIOStaticValues.blea.mac)))
                    {
                        try
                        {
                            var device = await BluetoothLEDevice.FromIdAsync(di.Id);
                            if (await IsConnected(device) && await IsHIO(device))
                            {
                                return(new BLEDeviceInfo(device.Name, device.DeviceId));
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    return(null);
                }
                catch (Exception ex)
                {
                }
                return(null);
            })
            .ContinueWith(r =>
            {
                result = r.Result;
            })
            .Wait();

            return(result);
        }
コード例 #4
0
 //------------------------------------------------------------------------------------
 public void start()
 {
     //create device watcher and start it
     deviceWatcher = DeviceInformation.CreateWatcher(
         //BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
         BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected),  //selector
         requestedProperties,
         DeviceInformationKind.AssociationEndpoint);
     deviceWatcher.Added   += DeviceWatcher_Added;
     deviceWatcher.Updated += DeviceWatcher_Updated;
     deviceWatcher.Removed += DeviceWatcher_Removed;
     deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
     deviceWatcher.Stopped += DeviceWatcher_Stopped;
     deviceWatcher.Start();
 }
コード例 #5
0
 public void Start()
 {
     if (!started)
     {
         string   aqsConnectedFilter  = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected);
         string[] requestedProperties = { "System.Devices.Aep.IsPaired", "System.Devices.Aep.IsConnected", "System.Devices.Aep.DeviceAddress" };
         deviceWatcher          = DeviceInformation.CreateWatcher(aqsConnectedFilter, requestedProperties, DeviceInformationKind.AssociationEndpoint);
         deviceWatcher.Added   += dw_added;
         deviceWatcher.Removed += dw_removed;
         deviceWatcher.Stopped += dw_stopped;
         deviceWatcher.EnumerationCompleted  += dw_enum_completed;
         Window.Current.CoreWindow.Activated += WindowActivated;
         this.started     = true;
         this.activated   = true;
         this.__modeTimer = new System.Threading.Timer(__ModeTimerTick, null, 0, 9000);
         this.RestartDeviceWatcher();
     }
 }
コード例 #6
0
        public void When_GetSelector()
        {
            string testSelector;


            testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelector());

            testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));
            testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR " + _deviceSelectorIssueInquiry + "#True)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));


            testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsConnected:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected));
            testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsConnected:=System.StructuredQueryType.Boolean#False OR " + _deviceSelectorIssueInquiry + "#True)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected));

            string deviceName = "TESTNAME";

            testSelector = _deviceSelectorPrefix + "(System.ItemNameDisplay:=\"" + deviceName + "\" OR " + _deviceSelectorIssueInquiry + "#True)";
            Assert.AreEqual(testSelector, BluetoothLEDevice.GetDeviceSelectorFromDeviceName(deviceName));
        }
コード例 #7
0
        public ERROR_CODE StartScan(string devName, Action <string> callback)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            var            watcher   = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected), _requestedBLEProperties, DeviceInformationKind.AssociationEndpointContainer);

            watcher.Added += (DeviceWatcher arg1, DeviceInformation devInfo) =>
            {
                if (devInfo.Name.Equals(devName))
                {
                    if (_deviceList.FirstOrDefault(d => d.Id.Equals(devInfo.Id) || d.Name.Equals(devInfo.Name)) == null)
                    {
                        _deviceList.Add(devInfo);
                    }
                    callback($"Found {devName}");
                    watcher.Stop();
                    autoEvent.Set();
                }
            };
            watcher.Updated += (_, __) => { }; // We need handler for this event, even an empty!
            //Watch for a device being removed by the watcher
            //watcher.Removed += (DeviceWatcher sender, DeviceInformationUpdate devInfo) =>
            //{
            //    _deviceList.Remove(FindKnownDevice(devInfo.Id));
            //};
            watcher.EnumerationCompleted += (DeviceWatcher arg1, object arg) => { arg1.Stop(); };
            //watcher.Stopped += (DeviceWatcher arg1, object arg) => { _deviceList.Clear(); arg1.Start(); };
            watcher.Stopped += (DeviceWatcher arg1, object arg) => { callback("Scan Stopped"); };
            watcher.Start();
            KnownDevices.Clear();
            autoEvent.WaitOne(5000);
            if (_deviceList.Count == 0)
            {
                return(ERROR_CODE.NO_SELECTED_SERVICE);
            }
            return(ERROR_CODE.BLE_FOUND_DEVICE);
        }
コード例 #8
0
        public ERROR_CODE StartScan()
        {
            var watcher = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected), _requestedBLEProperties, DeviceInformationKind.AssociationEndpointContainer);

            watcher.Added += (DeviceWatcher arg1, DeviceInformation devInfo) =>
            {
                if (_deviceList.FirstOrDefault(d => d.Id.Equals(devInfo.Id) || d.Name.Equals(devInfo.Name)) == null)
                {
                    _deviceList.Add(devInfo);
                }
            };
            watcher.Updated += (_, __) => { }; // We need handler for this event, even an empty!
            //Watch for a device being removed by the watcher
            //watcher.Removed += (DeviceWatcher sender, DeviceInformationUpdate devInfo) =>
            //{
            //    _deviceList.Remove(FindKnownDevice(devInfo.Id));
            //};

            watcher.EnumerationCompleted += (DeviceWatcher arg1, object arg) => { arg1.Stop(); };
            watcher.Stopped += (DeviceWatcher arg1, object arg) => { _deviceList.Clear(); arg1.Start(); };
            watcher.Start();
            KnownDevices.Clear();
            return(ERROR_CODE.BLE_FOUND_DEVICE);
        }
コード例 #9
0
ファイル: BleManager.cs プロジェクト: gcardinale/shiny
 public override IObservable <IEnumerable <IPeripheral> > GetConnectedPeripherals(string?serviceUuid = null) => this.GetDevices(
     BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected)
     );
コード例 #10
0
 public override IObservable <IEnumerable <IDevice> > GetConnectedDevices() => this.GetDevices(
     BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected)
     );
コード例 #11
0
        public void StartScan(ICollection <TDevice> devices, Action onChangeCallback = null)
        {
            devices.Clear();
            if (_Watcher == null)
            {
                Radio radio = null;
                Task.Run(async() =>
                {
                    radio = (await Radio.GetRadiosAsync()).FirstOrDefault(r => r.Kind == RadioKind.Bluetooth);
                    if (radio != null)
                    {
                        radio.StateChanged += (r, args) =>
                        {
                            if (radio.State == RadioState.Off)
                            {
                                App.Current.Dispatcher.Invoke(() => devices.Clear());
                            }
                        }
                    }
                    ;
                });

                _Watcher = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected), requestedProperties);

                _Watcher.Added += async(s, e) =>
                {
                    await semaphoreSlim.WaitAsync();

                    try
                    {
                        var di = await BluetoothLEDevice.FromIdAsync(e.Id);

                        if (di != null && await IsConnected(di) && await IsHIO(di) && !devices.Any(i => i.Id == e.Id))
                        {
                            App.Current.Dispatcher.Invoke(() =>
                                                          devices.Add(new TDevice(HIOStaticValues.tmain?.SettingManager,
                                                                                  e.Name,
                                                                                  id: e.Id,
                                                                                  mac: GetMac(e),
                                                                                  signalValue: BLEDevice.GetSignal(e.Properties),
                                                                                  isConnected: e.Properties.ContainsKey(BLEDevice.IsConnectableProperty) ? (bool)e.Properties[BLEDevice.IsConnectedProperty] : false)));
                            onChangeCallback?.Invoke();
                        }
                    }
                    catch (Exception ex)
                    {
                        _errorHandler.ErrorFunc(ex);
                    }
                    finally
                    {
                        semaphoreSlim.Release();
                    }
                };

                _Watcher.Updated += async(s, e) =>
                {
                    await semaphoreSlim.WaitAsync();

                    try
                    {
                        if (!devices.Any(i => i.Id == e.Id))
                        {
                            var di = await BluetoothLEDevice.FromIdAsync(e.Id);

                            if (await IsConnected(di) && await IsHIO(di))
                            {
                                App.Current.Dispatcher.Invoke(() =>
                                                              devices.Add(new TDevice(HIOStaticValues.tmain?.SettingManager,
                                                                                      di.Name,
                                                                                      id: di.DeviceId,
                                                                                      signalValue: BLEDevice.GetSignal(e.Properties),
                                                                                      mac: GetMac(di))));
                                onChangeCallback?.Invoke();
                            }
                            else
                            {
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _errorHandler.ErrorFunc(ex);
                    }
                    finally
                    {
                        semaphoreSlim.Release();
                    }
                };

                _Watcher.Removed += (s, e) =>
                {
                    semaphoreSlim.WaitAsync();
                    try
                    {
                        App.Current.Dispatcher.Invoke(() => devices.Remove(devices.FirstOrDefault(i => i.Id == e.Id)));
                        onChangeCallback?.Invoke();
                    }
                    catch (Exception ex)
                    {
                        _errorHandler.ErrorFunc(ex);
                    }
                    finally
                    {
                        semaphoreSlim.Release();
                    }
                };

                _Watcher.Start();
            }
            else if (_Watcher.Status == DeviceWatcherStatus.Created ||
                     _Watcher.Status == DeviceWatcherStatus.Stopped ||
                     _Watcher.Status == DeviceWatcherStatus.EnumerationCompleted ||
                     _Watcher.Status == DeviceWatcherStatus.Aborted)
            {
                if (_Watcher.Status == DeviceWatcherStatus.EnumerationCompleted)
                {
                    _Watcher.Stop();
                    _Watcher = null;
                    StartScan(devices, onChangeCallback);
                    return;
                }
                _Watcher.Start();
            }
        }
コード例 #12
0
        private void uiCreate_Click(object sender, RoutedEventArgs e)
        {
            uiResultMsg.Text = "Creating query...";
            bool bBLE = (uiBTtype.SelectedValue as ComboBoxItem).Content.ToString().Contains("LE");

            switch ((uiQuery.SelectedValue as ComboBoxItem).Content.ToString())
            {
            case "GetDeviceSelector":
                if (bBLE)
                {
                    uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelector();
                }
                else
                {
                    uiResultMsg.Text = BluetoothDevice.GetDeviceSelector();
                }
                break;

            case "GetDeviceSelectorFromPairingState(true)":
                if (bBLE)
                {
                    uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromPairingState(true);
                }
                else
                {
                    uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromPairingState(true);
                }
                break;

            case "GetDeviceSelectorFromPairingState(false)":
                if (bBLE)
                {
                    uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromPairingState(false);
                }
                else
                {
                    uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromPairingState(false);
                }
                break;

            case "GetDeviceSelectorFromConnectionStatus(Connected)":
                if (bBLE)
                {
                    uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected);
                }
                else
                {
                    uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected);
                }
                break;

            case "GetDeviceSelectorFromConnectionStatus(Disconnected)":
                if (bBLE)
                {
                    uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected);
                }
                else
                {
                    uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected);
                }
                break;

            default:
                uiResultMsg.Text = "Unknown value in second ComboBox";
                break;
            }
        }