コード例 #1
0
ファイル: MiBand.cs プロジェクト: worldas/MiBand-Tracker
        public async Task <String> getAddress()
        {
            #if WINDOWS_PHONE_APP
            BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(device.Id);

            ulong maclong = bleDevice.BluetoothAddress;
            var   tempMac = maclong.ToString("X");
            var   mac     = Regex.Replace(tempMac, "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})", "$1:$2:$3:$4:$5:$6");
            return(mac);
            #endif
            #if WINDOWS_APP
            return("00:00:00:00:00:00");
            #endif
        }
コード例 #2
0
        /// <summary>
        /// 按MAC地址查找系统中配对设备
        /// </summary>
        /// <param name="MAC"></param>
        public async Task SelectDevice(string bleDevice)
        {
            CurrentDevice = await BluetoothLEDevice.FromIdAsync(bleDevice);

            if (CurrentDevice == null)
            {
                string msg = "没有发现设备";
                ValueChanged(MsgType.Error, msg, CurrentDevice == null ? null : CurrentDevice.DeviceId);
            }
            else
            {
                await Connect();
            }
        }
コード例 #3
0
        async static void DeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
        {
            // If the random device matches our device name, connect to it.
            //Console.WriteLine("Device found: " + deviceInfo.Name);
            if (deviceInfo.Name.CompareTo(deviceName) == 0)
            {
                // Get the bluetooth object and save it. This function will connect to the device
                device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

                Console.WriteLine("Connected to " + device.Name);

                isDeviceConnected = true;
            }
        }
コード例 #4
0
        public async void SetupBLE()
        {
            txtProgress.Text = "Obtaining BTLE Info...";
            var query      = BluetoothLEDevice.GetDeviceSelector();
            var deviceList = await DeviceInformation.FindAllAsync(query);

            int count = deviceList.Count();

            if (count > 0)
            {
                //Assumes default name of the Adafruit Bluefruit LE
                var deviceInfo = deviceList.Where(x => x.Name == "Adafruit Bluefruit LE").FirstOrDefault();
                if (deviceInfo != null)
                {
                    var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

                    var deviceServices = bleDevice.GattServices;

                    txtProgress.Text = "Retrieving service and GATT characteristics...";
                    var deviceSvc = deviceServices.Where(svc => svc.AttributeHandle == 0x003a).FirstOrDefault();
                    if (deviceSvc != null)
                    {
                        var characteristics = deviceSvc.GetAllCharacteristics();
                        _notifyCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x003b).FirstOrDefault();
                        _writeCharacteristic  = characteristics.Where(x => x.AttributeHandle == 0x003e).FirstOrDefault();
                        _readCharacteristic   = characteristics.Where(x => x.AttributeHandle == 0x0040).FirstOrDefault();
                        _notifyCharacteristic.ValueChanged += NotifyCharacteristic_ValueChanged;
                        await _notifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        txtProgress.Text         = "Bluetooth LE Device service and characteristics initialized";
                        txtBTLEStatus.Text       = "Initialized";
                        txtBTLEStatus.Foreground = new SolidColorBrush(Colors.Green);
                        btnBlue.IsEnabled        = true;
                        btnGreen.IsEnabled       = true;
                        btnYellow.IsEnabled      = true;
                        btnOrange.IsEnabled      = true;
                        btnPurple.IsEnabled      = true;
                        btnRead.IsEnabled        = true;
                    }
                    else
                    {
                        txtInfo.Text = "Custom GATT Service Not Found on the Bluefruit";
                    }
                }
                else
                {
                    txtInfo.Text = "Adafruit Bluefruit LE not found, is it paired ??";
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// attempts to pair a BLE device by ID
        /// </summary>
        /// <param name="deviceId">the BLE device Id</param>
        /// <returns></returns>
        public async Task PairToDeviceAsync(string deviceId)
        {
            // get bluetooth device info
            var device = await BluetoothLEDevice.FromIdAsync(deviceId).AsTask();

            // null check
            if (device == null)
            {
                // TODO: Localize
                throw new ArgumentNullException("Failed to get information about the Bluetooth device");
            }

            // if we already paired...
            if (device.DeviceInformation.Pairing.IsPaired)
            {
                // do nothing..
                return;
            }

            // listen out for pairing requests
            device.DeviceInformation.Pairing.Custom.PairingRequested += (sender, args) =>
            {
                // log it
                // TODO: Remove
                Console.WriteLine("Accepting pairing request...");

                // accept all attempts
                args.Accept();
            };

            // try and pair to the device
            var result = await device.DeviceInformation.Pairing.Custom.PairAsync(

                // for contour we should try provide pin
                // TODO: try different types to see if any works
                DevicePairingKinds.ProvidePin
                ).AsTask();

            // log the result
            if (result.Status == DevicePairingResultStatus.Paired)
            {
                // TODO: Remove
                Console.WriteLine("Pairing successful");
            }
            else
            {
                // TODO: remove
                Console.WriteLine($"Pairing failed: {result.Status}");
            }
        }
コード例 #6
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string[]      requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
            DeviceWatcher deviceWatcher       =
                DeviceInformation.CreateWatcher(
                    BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                    requestedProperties,
                    DeviceInformationKind.AssociationEndpoint);

            // Register event handlers before starting the watcher.
            // Added, Updated and Removed are required to get all nearby devices
            deviceWatcher.Added += new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, devInfo) =>
            {
                if (devInfo.Name != "")
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        DeviceList.Text += String.Format("{0} : {1}\r\n", devInfo.Name, devInfo.Id);
                    });

                    Console.WriteLine(String.Format("{0} : {1}", devInfo.Name, devInfo.Id));
                }
                if (devInfo.Name == "MI Band 2")
                {
                    Console.WriteLine("Find Mi");
                    BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(devInfo.Id);
                    //Console.WriteLine(String.Format("{0} : {1}", bluetoothLeDevice.Name, bluetoothLeDevice.DeviceInformation));
                }
            });;
            deviceWatcher.Updated += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, devInfo) =>
            {
            });;
            deviceWatcher.Removed += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, devInfo) =>
            {
            });;


            // EnumerationCompleted and Stopped are optional to implement.
            deviceWatcher.EnumerationCompleted += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                Console.WriteLine(String.Format("EnumerationCompleted"));
            });
            deviceWatcher.Stopped += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                Console.WriteLine(String.Format("deviceWatcher.Stopped"));
            });;

            // Start the watcher.
            deviceWatcher.Start();
        }
        protected async override void OnNavigatedTo(NavigationEventArgs args)
        {
            SetStatusActive(true);
            var di  = args.Parameter as DeviceInformationWrapper;
            var ble = await BluetoothLEDevice.FromIdAsync(di.di.Id);

            SetStatusActive(false);

            bleDevice.ble = ble;
            bleDevice.Status.OnBluetoothStatus += bleDevice_OnBluetoothStatus;
            await DoReadDevice_Name();
            await DoNotifyDistance();
            await DoNotifyAmbientLight();
        }
コード例 #8
0
ファイル: MyoConnection.cs プロジェクト: CranZuehlke/RozHL
        private async void ConnectKnownDevice(DeviceInformation deviceInfo)
        {
            var bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

            var services = await bluetoothLeDevice.GetGattServicesAsync();

            if (services.Services.Single(s => s.Uuid == ControlServiceUUID) != null)
            {
                Debug.Log("Found known Myo");
                StopScanningForMyo();
                _myoBle = bluetoothLeDevice;
                await ConnectToMyo();
            }
        }
コード例 #9
0
        protected async override void OnNavigatedTo(NavigationEventArgs args)
        {
            uiProgress.IsActive = true;
            var di  = args.Parameter as DeviceInformationWrapper;
            var ble = await BluetoothLEDevice.FromIdAsync(di.di.Id);

            uiProgress.IsActive = false;

            bleDevice.ble = ble;
            bleDevice.Status.OnBluetoothStatus += device_OnBluetoothStatus;

            OnResetTime(null, null);
            IsFullyInitialized = true;
        }
コード例 #10
0
        private async void OHbtnConn_Click(object sender, RoutedEventArgs e)
        {
            OHbtnConn.IsEnabled = false;
            if (OHbtnConn.Content.ToString() == "Connect")
            {
                if (lstDevices.SelectedItem != null)
                {
                    device         = lstDevices.SelectedItem as DeviceInformation;
                    OHtxtStat.Text = "Initializing device...";
                    //HeartRateService.Instance.DeviceConnectionUpdated += OnDeviceConnectionUpdated;
                    //await HeartRateService.Instance.InitializeServiceAsync(device);

                    try
                    {
                        // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                        bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);

                        if (bluetoothLeDevice == null)
                        {
                            var dialog = new MessageDialog("Failed to connect to device.");
                            await dialog.ShowAsync();
                        }
                        else
                        {
                            GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                            if (result.Status == GattCommunicationStatus.Success)
                            {
                                var services = result.Services;
                                OHtxtStat.Text = String.Format("Connected & Found {0} services", services.Count);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var dialog = new MessageDialog("Retrieving device properties failed with message: " + ex.Message);
                        await dialog.ShowAsync();
                    }
                }
            }
            else//Disconnect
            {
                characteristics.ValueChanged -= Characteristic_ValueChanged;
                service.Dispose();
                bluetoothLeDevice = null;
                GC.Collect();
            }
            OHbtnConn.Content   = OHbtnConn.Content.ToString() == "Disconnect" ? "Connect" : "Disconnect";
            OHbtnConn.IsEnabled = true;
        }
コード例 #11
0
        public async void Connect(string id)
        {
            try
            {
                // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id);

                if (bluetoothLeDevice == null)
                {
                    Log.d("Failed to connect to device.", NotifyType.ErrorMessage);
                    return;
                }

                bluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChangedHandler;

                mBluetoothGatt = await GattSession.FromDeviceIdAsync(bluetoothLeDevice.BluetoothDeviceId);

                mBluetoothGatt.MaintainConnection = true;
            }
            catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
            {
                Log.d("Bluetooth radio is not on.", NotifyType.ErrorMessage);
                return;
            }

            if (bluetoothLeDevice != null)
            {
                // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
                // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
                // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event.
                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(RX_SERVICE_UUID);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    _services.Clear();
                    _services.AddRange(result.Services);

                    Log.d(String.Format("Found {0} services", _services.Count), NotifyType.StatusMessage);
                    foreach (var service in _services)
                    {
                        Log.d("SERVICE: " + DisplayHelpers.GetServiceName(service));
                        GetCharachteristics(service);
                    }
                }
                else
                {
                    Log.d("Device unreachable", NotifyType.ErrorMessage);
                }
            }
        }
コード例 #12
0
        private async Task connectDirectDeviceAsync()
        {
            String bluetoothAddress = "BluetoothLE#BluetoothLE3c:f8:62:c6:77:e3-cc:32:24:e9:13:1a";

            try
            {
                BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(bluetoothAddress);

                var instance = UARTService.Instance;
                var dfuVersionCharacteristics           = instance.Service.GetCharacteristics(new Guid(UARTService.UARTCharacteristics_UUID_TX));
                GattCharacteristicProperties properties = dfuVersionCharacteristics[0].CharacteristicProperties;

                if (properties.HasFlag(GattCharacteristicProperties.Read))
                {
                    Console.WriteLine("This characteristic supports reading from it.");
                }
                if (properties.HasFlag(GattCharacteristicProperties.Write))
                {
                    Console.WriteLine("This characteristic supports reading from it.");
                }
                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    Console.WriteLine("This characteristic supports subscribing to notifications.");
                }

                GattCommunicationStatus status = await dfuVersionCharacteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify);
                if (status == GattCommunicationStatus.Success)
                {
                    Console.WriteLine("Success");
                    dfuVersionCharacteristics[0].ValueChanged += Characteristic_ValueChanged;
                    // ...

                    void Characteristic_ValueChanged(GattCharacteristic sender,
                                                     GattValueChangedEventArgs args)
                    {
                        Console.WriteLine("Characteristic_ValueChanged");

                        // An Indicate or Notify reported that the value has changed.
                        var reader = DataReader.FromBuffer(args.CharacteristicValue);

                        Console.WriteLine("Read:" + reader.ReadString(10));
                    }
                }
            }catch (Exception e)
            {
                Console.WriteLine("Error " + e.StackTrace);
            }
            Console.ReadLine();
        }
コード例 #13
0
        private async void ConnectButton_Click()
        {
            ConnectButton.IsEnabled = false;

            if (!await ClearBluetoothLEDeviceAsync())
            {
                rootPage.NotifyUser("Error: Unable to reset state, try again.", NotifyType.ErrorMessage);
                ConnectButton.IsEnabled = false;
                return;
            }

            try
            {
                // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId);

                if (bluetoothLeDevice == null)
                {
                    rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage);
                }
            }
            catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
            {
                rootPage.NotifyUser("Bluetooth radio is not on.", NotifyType.ErrorMessage);
            }

            if (bluetoothLeDevice != null)
            {
                // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
                // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    var services = result.Services;
                    rootPage.NotifyUser(String.Format("Found {0} services", services.Count), NotifyType.StatusMessage);
                    foreach (var service in services)
                    {
                        ServiceCollection.Add(new BluetoothLEAttributeDisplay(service));
                    }
                    ConnectButton.Visibility = Visibility.Collapsed;
                    ServiceList.Visibility   = Visibility.Visible;
                }
                else
                {
                    rootPage.NotifyUser("Device unreachable", NotifyType.ErrorMessage);
                }
            }
            ConnectButton.IsEnabled = true;
        }
コード例 #14
0
        /// <summary>
        /// Connect to paired device
        /// </summary>
        /// <returns></returns>
        public async Task <bool> ConnectAsync()
        {
            Identity          auth   = new Identity();
            DeviceInformation device = await auth.GetPairedBand();

            if (device != null)
            {
                Gatt.bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(device.Id);

                return(Gatt.bluetoothLEDevice != null);
            }

            return(false);
        }
コード例 #15
0
        /// <summary>
        /// Attempts to pair to a BLE device, by ID
        /// </summary>
        /// <param name="deviceId">The BLE device ID</param>
        /// <returns></returns>
        public async Task PairToDeviceAsync(string deviceId)
        {
            // Get bluetooth device info
            using var device = await BluetoothLEDevice.FromIdAsync(deviceId).AsTask();

            // Null guard
            if (device == null)
            {
                // TODO: Localize
                throw new ArgumentNullException("Failed to get information about the Bluetooth device");
            }

            // If we are already paired...
            if (device.DeviceInformation.Pairing.IsPaired)
            {
                // Do nothing
                return;
            }

            // Listen out for pairing request
            device.DeviceInformation.Pairing.Custom.PairingRequested += (sender, args) =>
            {
                // Log it
                // TODO: Remove
                Console.WriteLine("Accepting pairing request...");

                // Accept all attempts
                args.Accept(); // <-- Could enter a pin in here to accept
            };

            // Try and pair to the device
            var result = await device.DeviceInformation.Pairing.Custom.PairAsync(
                // For Contour we should try Provide Pin
                // TODO: Try different types to see if any work
                DevicePairingKinds.ProvidePin
                ).AsTask();

            // Log the result
            if (result.Status == DevicePairingResultStatus.Paired)
            {
                // TODO: Remove
                Console.WriteLine("Pairing successful");
            }
            else
            {
                // TODO: Remove
                Console.WriteLine($"Pairing failed: {result.Status}");
            }
        }
コード例 #16
0
        /// <summary>
        /// Connects to the device.
        /// </summary>
        public async Task ConnectAsync()
        {
            Console.WriteLine("Connecting to LOGITOW device: " + deviceInfo.Id);
            try
            {
                bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

                OnConnectionStatusUpdate(bluetoothLEDevice, BluetoothConnectionStatus.Connected);
                await RegisterNotificationsAsync();
            }
            catch (Exception e)
            {
                OnConnectionError(e);
            }
        }
コード例 #17
0
        protected async override void OnNavigatedTo(NavigationEventArgs args)
        {
            var di = args.Parameter as DeviceInformation;

            uiProgress.IsActive = true;
            var ble = await BluetoothLEDevice.FromIdAsync(di.Id);

            Sensything.ble = ble;
            Sensything.Status.OnBluetoothStatus += Status_OnBluetoothStatus;
            Sensything.PropertyChanged          += Sensything_PropertyChanged;

            await Sensything.StartDataNotifications();

            uiProgress.IsActive = false;
        }
コード例 #18
0
        public static async Task <MiDeviceData> Do()
        {
            IEnumerable <DeviceInformation> devices = await DiscoverDevices();

            foreach (DeviceInformation device in devices)
            {
                using (var mi_device = await BluetoothLEDevice.FromIdAsync(device.Id))
                {
                    MiDeviceData datas = await GetData(mi_device);

                    Console.WriteLine($"device : {device.Id} : {datas.Moisture}/{datas.Temperature}");
                }
            }
            return(null);
        }
コード例 #19
0
        /// <summary>
        /// Static method to make it easier to create this class form a DeviceInformation object or any other
        /// object containing the devide ID.
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public static async Task <NotificationConsumer> FromDeviceIdAsync(string deviceId)
        {
            BluetoothLEDevice device;

            try
            {
                device = await BluetoothLEDevice.FromIdAsync(deviceId);
            }
            catch (Exception e)
            {
                throw e;
            }

            return(new NotificationConsumer(device));
        }
コード例 #20
0
ファイル: MainPage.xaml.cs プロジェクト: vadmkp/AT93C56Tests
        async void ConnectDevice(DeviceInformation deviceInfo)
        {
            // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
            BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

            // ...

            GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();

            if (result.Status == GattCommunicationStatus.Success)
            {
                var services = result.Services;
                // ...
            }
        }
コード例 #21
0
        public async void StartReceivingData()
        {
            leDevice = await BluetoothLEDevice.FromIdAsync(device.Id);

            string selector = "(System.DeviceInterface.Bluetooth.DeviceAddress:=\"" + leDevice.BluetoothAddress.ToString("X") + "\")";

            watcher          = DeviceInformation.CreateWatcher(selector);
            watcher.Added   += Watcher_Added;
            watcher.Removed += Watcher_Removed;
            watcher.Start();

            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
コード例 #22
0
        public async Task EnterBootloader()
        {
            var bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(options.DeviceId);

            var svc = (await bluetoothLeDevice.GetGattServicesForUuidAsync(new Guid("0000fe59-0000-1000-8000-00805f9b34fb")))
                      .Services.Single();
            var chars = (await svc.GetCharacteristicsForUuidAsync(new Guid("8ec90003-f315-4f60-9fb8-838830daea50"))).Characteristics.Single();
            await chars.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

            byte[] data = { 0x01 };
            //chars.ValueChanged += Chars_ValueChanged;
            await chars.WriteValueAsync(data.AsBuffer());

            return;
        }
コード例 #23
0
        // Pairs device with Sensortag
        public async Task PairSensorTagAsync()
        {
            device = await BluetoothLEDevice.FromBluetoothAddressAsync(bleadress);


            bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.DeviceId);



            var status = await device.DeviceInformation.Pairing.PairAsync();



            await GetGATTServicesDataAsync(device);
        }
コード例 #24
0
ファイル: DeviceController.cs プロジェクト: R-EM/BleLab
        public async Task Connect(DeviceInfo deviceInfo)
        {
            Disconnect();
            ConnectedDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.DeviceId);

            if (ConnectedDevice == null)
            {
                return;
            }

            deviceInfo.MacAddress = ConnectedDevice.BluetoothAddress.ToMacAddressString();
            deviceInfo.Name       = ConnectedDevice.Name;

            _infoManager.SaveDevice(deviceInfo);
        }
コード例 #25
0
 async void MDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
 {
     mDevice = sender;
     Deregister();
     if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected)
     {
         Debug.WriteLine("Reconnecting...");
         await BluetoothLEDevice.FromIdAsync(sender.DeviceId).AsTask().ContinueWith((obj) => { ConnectionComplete(obj.Result); });
     }
     else
     {
         ConnectionComplete(sender);
     }
     Debug.WriteLine("MDevice_ConnectionStatusChanged end.");
 }
コード例 #26
0
        /// <summary>
        /// Connect to the desired device.
        /// </summary>
        /// <param name="deviceName"></param>
        public async void selectDevice(string deviceName)
        {
            foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()))
            {
                BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id);

                // Check if the name of the device founded is EMU Bridge.
                if (bleDevice.Name == deviceName)
                {
                    // Save detected device in the current device variable.
                    currentDevice = bleDevice;
                    break;
                }
            }
        }
コード例 #27
0
ファイル: BleClient.cs プロジェクト: drewdz/SandCastle
        private async Task <bool> ConnectDeviceAsync(BleDevice device)
        {
            try
            {
                var bleDevice = await BluetoothLEDevice.FromIdAsync(device.Guid);

                _Connected.Add(bleDevice);
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("BleClient.ConnectDeviceAsync - Exception: {0}", ex);
                return(false);
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs args)
        {
            SetStatusActive(true);
            var di = args.Parameter as DeviceInformationWrapper;

            if (di.SerialPortPreferences == null)
            {
                // Make sure we set up good defaults.
                const string DefaultShortcutId = "CraftyRobot-Smartibot";
                di.SerialPortPreferences = new UserSerialPortPreferences()
                {
                    LineEnd    = UserSerialPortPreferences.TerminalLineEnd.CR,
                    SavePrefix = "CraftyRobot_Smartibot_",
                    ShortcutId = DefaultShortcutId, // must match the Id value in CraftyRobot_Smartibot_Commands.json
                };
                di.SerialPortPreferences.ReadFromLocalSettings();
                if (di.SerialPortPreferences.ShortcutId == "(name)")
                {
                    di.SerialPortPreferences.ShortcutId = DefaultShortcutId;
                }
            }
            var ble = await BluetoothLEDevice.FromIdAsync(di.di.Id);

            SetStatusActive(false);

            // // // bleDevice.ble = ble;
            // // // bleDevice.Status.OnBluetoothStatus += bleDevice_OnBluetoothStatus;

            Uart = new Nordic_Uart(ble);
            await Uart.EnsureCharacteristicAsync();

            Uart.Status.OnBluetoothStatus += bleDevice_OnBluetoothStatus;
            // NOTE: check for status?

            // Set up the terminal adapter, connecting the terminal control and the bluetooth device.
            TerminalAdapter = new nRFUartTerminalAdapter(uiTerminalControl, Uart);
            uiTerminalControl.ParentTerminal = this;
            uiTerminalControl.UserCanSetSerialLineEndings = false;
            // the adapter tells the terminal control to display the status.
            // The terminal control would rather we display the status.

            await TerminalAdapter.InitAsync();

            uiTerminalControl.DI = di;

            // Get the buttons to show!
            uiTerminalControl.UpdateShortcutButtons();
        }
コード例 #29
0
ファイル: IGrill.cs プロジェクト: thomas-bingel/iGrill
        public async Task ConnectAsync()
        {
            if (!await IsBluetoothEnabledAsync())
            {
                throw new Exception("Bluetooth is not enabled.");
            }

            if (!await IsBluetoothSupportedAsync())
            {
                throw new Exception("Bluetooth is not supportet.");
            }

            bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceId);

            if (bluetoothLeDevice == null)
            {
                throw new Exception("iGrill not found");
            }

            // Event for connection status changed
            bluetoothLeDevice.ConnectionStatusChanged += (BluetoothLEDevice device, object obj) =>
            {
                Debug.WriteLine("Connection status changed to: " + device.ConnectionStatus);
                ConnectionStatusChanged?.Invoke(device, device.ConnectionStatus);
            };

            // Read basic device information like name, etc.
            this.DeviceName = await genericService.GetDeviceNameAsync(bluetoothLeDevice);

            this.FirmwareVersion = await genericService.GetFirmwareVersionAsync(bluetoothLeDevice);

            // Read battery level and register for updates
            batteryService.BatteryLevelChanged += (sender, level) =>
            {
                this.BatteryLevelChanges?.Invoke(sender, level);
            };
            await batteryService.RegisterForBatteryChanges(bluetoothLeDevice);

            // Authenticate iGrill to read probes
            await authenticationService.Authenticate(bluetoothLeDevice);

            // Read probes and register for updates
            temperatureService.TemperatureChanged += (sender, args) =>
            {
                this.TemperatureChanged?.Invoke(sender, args);
            };
            await temperatureService.RegisterForTemperatureChanges(bluetoothLeDevice);
        }
コード例 #30
0
        /// <summary>
        /// Asynchronous call to re-populate the ListBox of paired devices.
        /// </summary>
        private async void RefreshPairedDevicesList()
        {
            FindPairedDevices.IsEnabled    = false;
            ConnectingIndicator.Visibility = Windows.UI.Xaml.Visibility.Visible;
            try
            {
                // Search for all paired devices
                string genericUUID = GattDeviceService.GetDeviceSelectorFromUuid(Guid.Parse(BLEDeviceConstants.HM_10_CONF));
                //string genericUUID = GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess);
                var peers = await DeviceInformation.FindAllAsync(genericUUID);

                // By clearing the backing data, we are effectively clearing the ListBox
                _pairedDevices.Clear();

                if (peers.Count == 0)
                {
                    await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
                }
                else
                {
                    // Found paired devices.
                    foreach (var peer in peers)
                    {
                        try
                        {
                            BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(peer.Id);

                            if (bleDevice.Name == "MyTeletouch")
                            {
                                _pairedDevices.Add(new PairedDeviceInfo(bleDevice));
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            catch /*(Exception ex)*/
            {
            }
            finally
            {
                FindPairedDevices.IsEnabled    = true;
                ConnectingIndicator.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                EmptyIndicator.Visibility      = _pairedDevices.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            }
        }