private async void AddNearByBtDevice(string deviceID, string btName)
        {
            string btID        = BluetoothDevices.ConvertDeviceIdType(deviceID, AddressType.Bluetooth);
            string bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceID, AddressType.BLE);

            DeviceInformation found = GetNearbyBleDevice(bleDeviceID);

            if (found != null)
            {
                return;
            }

            DeviceInformation bleDeviceInformation = await DeviceInformation.CreateFromIdAsync(bleDeviceID);

            lock (NearbyDeviceList) {
                NearbyDeviceList.Add(bleDeviceInformation);
            }

            BleDeviceUpdated?.Invoke(this, DeviceWatchEvent.Added, bleDeviceInformation);

            if (App.IsForeground)
            {
                OnBleDeviceUpdated_InBackground("added", btName, btID);
            }
        }
        private Earbuds GetNaerByEarbirds(string deviceId)
        {
            Earbuds foundEarbuds = null;

            string bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceId, AddressType.BLE);

            if (string.IsNullOrEmpty(bleDeviceID))
            {
                return(foundEarbuds);
            }

            lock (NearbyEarbudsList)
            {
                foreach (Earbuds earbuds in NearbyEarbudsList)
                {
                    if (bleDeviceID.Equals(earbuds.BleID))
                    {
                        foundEarbuds = earbuds;
                        break;
                    }
                }
            }

            return(foundEarbuds);
        }
        private DeviceInformation GetPairedBtDevice(string deviceId)
        {
            DeviceInformation found = null;

            if (string.IsNullOrEmpty(deviceId))
            {
                return(found);
            }

            string btDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceId, AddressType.Bluetooth);

            lock (PairedDeviceList)
            {
                foreach (DeviceInformation deviceInfo in PairedDeviceList)
                {
                    if (btDeviceID.Equals(deviceInfo.Id))
                    {
                        found = deviceInfo;
                        break;
                    }
                }
            }

            return(found);
        }
        private DeviceInformation RemoveNearByBtDevice(string deviceID, string btName)
        {
            string btID        = BluetoothDevices.ConvertDeviceIdType(deviceID, AddressType.Bluetooth);
            string bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceID, AddressType.BLE);

            DeviceInformation found = GetNearbyBleDevice(bleDeviceID);

            if (found == null)
            {
                return(null);
            }

            lock (NearbyDeviceList)
            {
                NearbyDeviceList.Remove(found);
            }

            BleDeviceUpdated?.Invoke(this, DeviceWatchEvent.Added, found);

            if (App.IsForeground)
            {
                OnBleDeviceUpdated_InBackground("remove", btName, btID);
            }

            return(found);
        }
Exemplo n.º 5
0
        public void OpenDeviceConnection(ContentPage contentPage, BluetoothDevices bluetoothDevice)
        {
            mDevice = mBoundedDevices[bluetoothDevice.Name] as BluetoothDevice;
            ConnectThread connectThread = new ConnectThread(contentPage, mDevice);

            connectThread.Start();
        }
        private async void OnBleAdvertisementUpdated(BleAdvertisementWatcher sender, DeviceWatchEvent eventCode, BLEAdvertisementInfo bleAdvertisementInfo)
        {
            DeviceInformation btDeviceInformation = await BluetoothDevices.CreateDeviceInformation(bleAdvertisementInfo.ToBtAddressString(), AddressType.Bluetooth);

            DeviceInformation bleDeviceInformation = await BluetoothDevices.CreateDeviceInformation(bleAdvertisementInfo.ToBtAddressString(), AddressType.BLE);

            if (!App.sUserManager.IsSingnIn())
            {
                // FIXME: SERVICE CODE to configuration
                if (bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data.Length > 5)
                {
                    // ignore, because it has user Key.
                    Log.D(string.Format($"Other User's Device Found: {bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data}"));
                    return;
                }
            }

            if (eventCode == DeviceWatchEvent.Added)
            {
                Log.D(string.Format($"New BLE Advertisement Found: {bleAdvertisementInfo.ToBtAddressString()}"));

                AddNearByEarbuds(bleDeviceInformation.Id);
                AddNearByBtDevice(bleDeviceInformation.Id, btDeviceInformation.Name);
            }
            else if (eventCode == DeviceWatchEvent.Removed)
            {
                Log.D(string.Format($"BLE Advertisement Removed: {bleAdvertisementInfo.ToBtAddressString()}"));

                Earbuds removeEarBuds = RemoveNearByEarbuds(bleDeviceInformation.Id);
                if (removeEarBuds != null)
                {
                    RemoveNearByBtDevice(bleDeviceInformation.Id, btDeviceInformation.Name);
                }
            }
        }
Exemplo n.º 7
0
        private void PairButtonClicked()
        {
            DeviceInformationDisplay deviceInfoDisp = bleDeviceListView.SelectedItem as DeviceInformationDisplay;

            if (deviceInfoDisp != null)
            {
                App.sDeviceManager.PairWithMac(BluetoothDevices.ConvertDeviceIdType(deviceInfoDisp.Id, AddressType.Bluetooth));
            }
        }
        public void ConfigureViewModel()
        {
            var devices = _bluetoothService.GetBondedDevices();

            foreach (var device in devices)
            {
                if (!BluetoothDevices.Any(d => d.Name == device.Name && d.Mac == device.Mac))
                {
                    BluetoothDevices.Add(new BluetoothDevice(device.Name, device.Mac));
                }
            }
        }
        // BLE Advertisement Handler
        private void OnBleAdvertisementUpdated(BleAdvertisementWatcher sender, DeviceWatchEvent eventCode, BLEAdvertisementInfo bleAdvertisementInfo)
        {
            if (userKey == null || userKey.Length == 0)
            {
                // FIXME: SERVICE CODE to configuration
                if (bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data.Length > 5)
                {
                    // ignore, because it has user Key.
                    return;
                }
            }

            if (eventCode == DeviceWatchEvent.Added)
            {
                Log.D($"New BLE Advertisement Found: {bleAdvertisementInfo.ToBtAddressString()}");
                ValueSet newBleDeviceMessage = new ValueSet
                {
                    { "opcode", "ble_device" },
                    { "status", "added" },
                    { "name", bleAdvertisementInfo.Advertisement.LocalName },
                    { "id", $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}" }
                };
                systrayApplicationServiceConnection.SendMessageAsync(newBleDeviceMessage);
            }
            else if (eventCode == DeviceWatchEvent.Removed)
            {
                Log.D($"BLE Advertisement Removed: {bleAdvertisementInfo.ToBtAddressString()}");
                ValueSet removeBleDeviceMessage = new ValueSet
                {
                    { "opcode", "ble_device" },
                    { "status", "removed" },
                    { "name", bleAdvertisementInfo.Advertisement.LocalName },
                    { "id", $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}" }
                };
                systrayApplicationServiceConnection.SendMessageAsync(removeBleDeviceMessage);
            }

            // Propergate Event to Earbuds Menu
            string deviceId = $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}";

            foreach (EarbudsMenuItem earbudsMenuItem in PairedDeviceMenuItems)
            {
                if (BluetoothDevices.EqualDevice(deviceId, earbudsMenuItem.BtID))
                {
                    earbudsMenuItem.HandleBleAdvertisement(eventCode);
                    break;
                }
            }
        }
Exemplo n.º 10
0
        async void RegisterForInboundPairingRequests()
        {
            // Make the system discoverable for Bluetooth
            await MakeDiscoverable();

            // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present
            // so leave the diagnositic message put out by the call to MakeDiscoverable()
            if (App.IsBluetoothDiscoverable)
            {
                string formatString;
                string confirmationMessage;

                // Get state of ceremony checkboxes
                DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();
                int iCurrentSelectedCeremonies        = (int)ceremoniesSelected;

                // Find out if we changed the ceremonies we orginally registered with - if we have registered before these will be saved
                var    localSettings            = Windows.Storage.ApplicationData.Current.LocalSettings;
                Object supportedPairingKinds    = localSettings.Values["supportedPairingKinds"];
                int    iSavedSelectedCeremonies = -1; // Deliberate impossible value
                if (supportedPairingKinds != null)
                {
                    iSavedSelectedCeremonies = (int)supportedPairingKinds;
                }

                ResourceLoader loader = ResourceLoader.GetForCurrentView();

                if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected))
                {
                    confirmationMessage = loader.GetString("BluetoothInboundRegistrationFailed/Text");
                }
                else
                {
                    // Save off the ceremonies we registered with
                    localSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies;
                    formatString        = loader.GetString("BluetoothInboundRegistrationSucceeded/Text");
                    confirmationMessage = formatString + ceremoniesSelected.ToString();
                }

                // Clear the current collection
                BluetoothDevices.Clear();
                // Start the watcher
                StartWatcher();
                // Display a message
                confirmationMessage += loader.GetString("BluetoothOn/Text");
                DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
            }
        }
Exemplo n.º 11
0
        public async void TurnOffBluetooth()
        {
            // Clear any devices in the list
            BluetoothDevices.Clear();
            // Stop the watcher
            //Check StopWatcher();

            // Display a message
            ResourceLoader loader = ResourceLoader.GetForCurrentView();
            string         confirmationMessage = loader.GetString("BluetoothOff/Text");

            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);

            StackLoadingVisibility = false;

            await ToggleBluetoothAsync(false);
        }
Exemplo n.º 12
0
        public void SearchForDevices()
        {
            BluetoothDevices.Clear();
            localEndPoint = new BluetoothEndPoint(CurrentAdapter.LocalAddress, BluetoothService.SerialPort);
            client        = new BluetoothClient(localEndPoint);
            foreach (BluetoothDeviceInfo device in client.DiscoverDevices())
            {
                BluetoothDevices.Add(device);
            }

            if (BluetoothDevices.Any())
            {
                ChosenDevice = BluetoothDevices[0];
            }
            else
            {
                MessageBox.Show("No bluetooth devices were found", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 13
0
        public void GetConnectedDevices()
        {
            _connectedDisposable = _centralManager.GetConnectedPeripherals().Subscribe(scanResult =>
            {
                scanResult.ToList().ForEach(
                    item =>
                {
                    if (!string.IsNullOrEmpty(item.Name))
                    {
                        BluetoothDevices.Add(item);
                    }
                });

                _connectedDisposable?.Dispose();
            });

            if (_centralManager.IsScanning)
            {
                _centralManager.StopScan();
            }
        }
        private async void AddPairedBtDevice(DeviceInformation deviceInformation)
        {
            DeviceInformation found = GetPairedBtDevice(deviceInformation);

            if (found != null)
            {
                return;
            }

            lock (PairedDeviceList)
            {
                PairedDeviceList.Add(deviceInformation);
            }

            Earbuds earbuds = GetNaerByEarbirds(deviceInformation.Id);

            if (earbuds != null)
            {
                earbuds.EnableGattConnection();
            }
            else
            {
                var BtDevice = await BluetoothDevice.FromIdAsync(deviceInformation.Id);

                if (BtDevice != null)
                {
                    if (BtDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    {
                        string bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceInformation.Id, AddressType.BLE);
                        AddNearByEarbuds(bleDeviceID);
                        Log.D($"\tAlready Connected Device Found: Add it to NearByEarbuds List");
                        AddNearByBtDevice(bleDeviceID, deviceInformation.Name);
                    }
                    BtDevice.Dispose();
                }
            }

            return;
        }
Exemplo n.º 15
0
        private void ApplyBT(object sender, RoutedEventArgs e)
        {
            Log.Information("Applying selected bluetooth device.");
            try
            {
                BluetoothDevices  SelectedDevice = BluetoothDevices[BtDevices.SelectedIndex];
                PairedDevicesJson PairedDevices  = PairedDevicesJson.FromJson(File.ReadAllText(Helper.PairedDevicesFile));
                Log.Information("Got current devices.");
                PairedDevices.Devices.Add(new Device {
                    DeviceAddress = SelectedDevice.DeviceID, DeviceName = btName.Text, DeviceType = "Bluetooth", TemplateLocation = ""
                });
                File.WriteAllText(Helper.PairedDevicesFile, PDSerialize.ToJson(PairedDevices));
                Log.Information("Wrote to PairedDevices.json");

                MessageBox.Show("Done!", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "There was a error applying the bluetooth device.");
                Helper.Error("Error", "There was a error writing to the PairedDevices.json file. Please contact the developer.");
            }
        }
        public override async Task RefreshAsync()
        {
            IsBusy = true;

            // Check BluetoothLE connection status
            if (bluetoothLeService.GetConnectionStatus())
            {
                // Get a list of BluetoothLE devices
                var availableBluetoothDevices = await bluetoothLeService.ScanForDevicesAsync();

                BluetoothDevices.ReplaceRange(availableBluetoothDevices);

                IsBusy = false;
            }
            else
            {
                IsBusy = false;

                // Bluetooth LE not available
                await dialogService.DisplayDialogAsync("Bluetooth not available", "Bluetooth is not available. Please check your Bluetooth settings and try again", "Ok");
            }
        }
        private DeviceInformation GetNearbyBleDevice(string deviceID)
        {
            if (string.IsNullOrEmpty(deviceID))
            {
                return(null);
            }

            DeviceInformation found       = null;
            string            bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceID, AddressType.BLE);

            lock (NearbyDeviceList)
            {
                foreach (DeviceInformation deviceInfo in NearbyDeviceList)
                {
                    if (deviceInfo.Id.Equals(bleDeviceID))
                    {
                        found = deviceInfo;
                        break;
                    }
                }
            }

            return(found);
        }
Exemplo n.º 18
0
        private void GetDeviceList()
        {
            if (_centralManager.IsScanning)
            {
                _scanDisposable?.Dispose();
            }
            else
            {
                if (_centralManager.Status == Shiny.AccessState.Available && !_centralManager.IsScanning)
                {
                    _scanDisposable = _centralManager.ScanForUniquePeripherals().Subscribe(scanResult =>
                    {
                        IsSelected = false;

                        if (!string.IsNullOrEmpty(scanResult.Name) && !BluetoothDevices.Contains(scanResult))
                        {
                            BluetoothDevices.Add(scanResult);
                        }
                    });
                }
            }

            IsScanning = _centralManager.IsScanning;
        }
Exemplo n.º 19
0
        public void SearchForDevices()
        {
            // urządzenia znalezione w poprzednim wyszukiwaniu nie muszą być aktywne przy aktualnym wyszukaniu
            BluetoothDevices.Clear();

            // utworzenie endpointu (adres hosta i port usługi (emulacja portu szeregowego))
            localEndPoint = new BluetoothEndPoint(CurrentAdapter.LocalAddress, BluetoothService.SerialPort);
            client        = new BluetoothClient(localEndPoint);

            // przepisanie znalezionych urządzeń za pomocą client.DiscoverDevices() do BluetoothDevice
            foreach (BluetoothDeviceInfo device in client.DiscoverDevices())
            {
                BluetoothDevices.Add(device);
            }

            if (BluetoothDevices.Any())
            {
                ChosenDevice = BluetoothDevices[0];
            }
            else
            {
                MessageBox.Show("Nie znaleziono urządzeń bluetooth", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 20
0
 public void OpenDeviceConnection(ContentPage contentPage, BluetoothDevices bluetoothDevice)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 21
0
        /// <summary>
        /// Start the Device Watcher and set callbacks to handle devices appearing and disappearing
        /// </summary>
        public void StartWatcher()
        {
            //ProtocolSelectorInfo protocolSelectorInfo;
            string aqsFilter = @"System.Devices.Aep.ProtocolId:=""{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}"" OR System.Devices.Aep.ProtocolId:=""{bb7bb05e-5972-42b5-94fc-76eaa7084d49}""";  //Bluetooth + BluetoothLE

            // Request the IsPaired property so we can display the paired status in the UI
            string[] requestedProperties = { "System.Devices.Aep.IsPaired" };

            //// Get the device selector chosen by the UI, then 'AND' it with the 'CanPair' property
            //protocolSelectorInfo = (ProtocolSelectorInfo)selectorComboBox.SelectedItem;
            //aqsFilter = protocolSelectorInfo.Selector + " AND System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True";

            deviceWatcher = DeviceInformation.CreateWatcher(
                aqsFilter,
                requestedProperties,
                DeviceInformationKind.AssociationEndpoint
                );

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    BluetoothDevices.Add(new BluetoothDeviceInformationDisplay(deviceInfo));
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (BluetoothDeviceInformationDisplay deviceInfoDisp in BluetoothDevices)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (BluetoothDeviceInformationDisplay deviceInfoDisp in BluetoothDevices)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            BluetoothDevices.Remove(deviceInfoDisp);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Finished enumerating
                    StackLoadingVisibility = false;

                    ResourceLoader loader = ResourceLoader.GetForCurrentView();

                    var index = ConfirmationText.IndexOf(loader.GetString("BluetoothOn/Text"));
                    if (index != -1)
                    {
                        DisplayMessagePanelAsync(ConfirmationText.Substring(0, index), MessageType.InformationalMessage, true);
                    }
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Device watcher stopped
                    StackLoadingVisibility = false;
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            // Start the Device Watcher
            deviceWatcher.Start();
            StackLoadingVisibility = true;
        }
Exemplo n.º 22
0
 public void OpenDeviceConnection(ContentPage contentPage, BluetoothDevices bluetoothDevice)
 {
     communication.OpenDeviceConnection(contentPage, bluetoothDevice);
 }