Esempio n. 1
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();

            if (Device.RuntimePlatform == "Android")
            {
                DependencyService.Get <IKeyboardHelper>().HideKeyboard();
            }
            var systemDevices = adapter.GetSystemConnectedOrPairedDevices();

            foreach (var device in systemDevices)
            {
                await adapter.ConnectToDeviceAsync(device);
            }
        }
        private async void Connect_Clicked()
        {
            //Метод для подключения к устройству. Поскольку GUID сервисов
            //и харрактеристик для устройств на базе CC2541 одинаковые,
            //можно не выполнять их глобальный поиск по дискрипторам и свойствам
            if (device != null)
            {
                try
                {
                    await adapter.ConnectToDeviceAsync(device);

                    service = await device.GetServiceAsync(Guid.Parse("0000ffe0-0000-1000-8000-00805f9b34fb"));

                    characteristic = await service.GetCharacteristicAsync(Guid.Parse("0000ffe1-0000-1000-8000-00805f9b34fb"));
                    await DisplayAlert(null, "Соединение успешно", "ОК");

                    IsConnected = true;
                }
                catch (DeviceConnectionException ex)
                {
                    await DisplayAlert("Ошибка!", "Не удалось соединится" + ex.Message, "ОК");
                }
            }
            else
            {
                await DisplayAlert("Ошибка!", "Выберете устройство для соединения", "ОК");
            }
        }
Esempio n. 3
0
 private void AddOrUpdateDevice(IDevice device)
 {
     Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(async() =>
     {
         if (device.Name == "SH-HC-08")
         {
             IService uartService     = null;
             ICharacteristic uartChar = null;
             TargetDevice             = device;
             try
             {
                 await BleAdapter.ConnectToDeviceAsync(TargetDevice);
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
             try
             {
                 var services = await TargetDevice.GetServicesAsync();
                 foreach (var s in services)
                 {
                     Console.WriteLine(s.Id + " " + s.Name);
                 }
                 uartService = await TargetDevice.GetServiceAsync(Guid.Parse("0000ffe0-0000-1000-8000-00805F9B34FB"));
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
             try
             {
                 var chars = await uartService.GetCharacteristicsAsync();
                 foreach (var s in chars)
                 {
                     Console.WriteLine(s.Id + " " + s.Name);
                 }
                 uartChar = await uartService.GetCharacteristicAsync(Guid.Parse("0000ffe1-0000-1000-8000-00805F9B34FB"));
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
             if (uartChar == null)
             {
                 Console.WriteLine("Char is null");
                 return;
             }
             try
             {
                 uartChar.ValueUpdated += ValueUpdated;
                 await uartChar.StartUpdatesAsync();
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
         }
     });
 }
Esempio n. 4
0
        /*
         * Como la impresora ya esta configurada se conecta solo a la impresora
         */
        public async void Autoconexion(IDevice impBT)
        {
            await adaptador.StopScanningForDevicesAsync();

            try
            {
                // Estas lineas conectan el dispositivo e imprimen el parte;
                var parameters = new ConnectParameters(forceBleTransport: true);
                await adaptador.ConnectToDeviceAsync(impBT, parameters);

                Lista.Clear();
                Lista.Add(dispositivo);
                bool imprimir = true; // IMPORTANTE Este booleano permite imprimir a la impresora
                Imprimir(imprimir);
            }
            catch (DeviceConnectionException e)
            {
                Console.WriteLine(e.Message);
                await Application.Current.MainPage.DisplayAlert("Aviso", "No es posible conectarse a la impresora", "OK");

                popupLoadingView.IsVisible  = false;
                activityIndicator.IsRunning = false;
                btnImprimir.IsEnabled       = true;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// FOUND BLUETOOTH - SELECT ITEM IN THE LISTVIEW, THEN SEND THE SELECTED FILE
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FoundBluetoothDevicesListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            //IDevice selectedItem = e.SelectedItem as IDevice;
            //MainPage selectedFile = new MainPage(); //'selectedFile' es la var que toma de la clase Main
            //PickedFile.PickedFile_Selected = selectedFile.SelectedFile(); //Dentro de Main class se encuentra este metodo
            if (selectedDevice.State == Plugin.BLE.Abstractions.DeviceState.Connected) //If the Client is already connected
            {
                await PickAndSendFile(PickedFile.PickedFile_Selected);                 //Send the selected file

                //await Navigation.PushAsync(new BluetoothDataPage(selectedItem));
            }
            else //If it's not connected yet
            {
                try
                {
                    await _bluetoothAdapter.ConnectToDeviceAsync(selectedDevice);      //Connect to the selected device

                    if (selectedDevice.State == Plugin.BLE.Abstractions.DeviceState.Connected)
                    {
                        await IsConnected(PickedFile.PickedFile_Selected);                    //Sends a confirmation message if it's connected
                        await PickAndSendFile(PickedFile.PickedFile_Selected);                //And then send the selected file
                    }
                }
                catch
                {
                    // ... could not connect to device
                    //Idea for improvement : A message box saying "Could not connect to the selected device, try again"
                }
            }
        }
Esempio n. 6
0
        protected async void TryConnect()
        {
            if (_device != null)
            {
                IsConnectEnabled = false;
                OnPropertyChanged(nameof(IsConnectEnabled));

                UserDialogs.Instance.ShowLoading("Connecting to device");

                try
                {
                    await _bluetoothAdapter.ConnectToDeviceAsync(_device);
                }
                catch (DeviceConnectionException ex)
                {
                    UserDialogs.Instance.ShowError("Could not connect to the Device! Error: " + ex.Message.ToString());
                }
                catch (Exception ex)
                {
                    UserDialogs.Instance.ShowError("Could not connect to the Device! Error: " + ex.Message.ToString());
                }

                UserDialogs.Instance.HideLoading();
            }
        }
Esempio n. 7
0
        private async void DevicesList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            device = DevicesList.SelectedItem as IDevice;

            var result = await DisplayAlert("AVISO", "Deseja se conectar a esse dispositivo?", "Conectar", "Cancelar");

            if (!result)
            {
                return;
            }

            //Stop Scanner
            await adapter.StopScanningForDevicesAsync();

            try
            {
                await adapter.ConnectToDeviceAsync(device);

                await DisplayAlert("Conectado", "Status:" + device.State, "OK");
            }
            catch (DeviceConnectionException ex)
            {
                await DisplayAlert("Erro", ex.Message, "OK");
            }
        }
Esempio n. 8
0
        async void DevicesList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var devicesListed = (ListView)sender;

            device = devicesListed.SelectedItem as IDevice;

            var result = await DisplayAlert(" WARNING ", " Do you want to connect to this device? ", " Connect ", " Cancel ");

            //texxt.Text = texxt.Text +"hi";
            if (!result)
            {
                //texxt.Text = texxt.Text + "hi2";
                return;
            }
            // Stop Scanner
            await adapter.StopScanningForDevicesAsync();

            try
            {
                await adapter.ConnectToDeviceAsync(device);

                await DisplayAlert(" Connected ", " Status: " + device.State, " OK ");

                btnGetServices_Clicked();
            }
            catch (DeviceConnectionException ex)
            {
                await DisplayAlert(" Error ", ex.Message, " OK ");
            }
            texxt.Text = device.State.ToString();
        }
        public async Task <ObservableCollection <IDevice> > ListarDispositivos(IAdapter adapter)
        {
            ObservableCollection <IDevice> deviceList = new ObservableCollection <IDevice>();

            adapter.DeviceDiscovered += (s, a) => deviceList.Add(a.Device);
            //adapter.ScanMode = ScanMode.LowLatency;
            adapter.ConnectedDevices.Clear();
            await adapter.StopScanningForDevicesAsync();

            await adapter.StartScanningForDevicesAsync();

            try
            {
                Debug.WriteLine("STAGUS: " + adapter.ScanMode);
                Debug.WriteLine("DISPOSITIVOS ENCONTRADOS: " + deviceList.Count);
                await adapter.ConnectToDeviceAsync(deviceList[0]);
            }
            catch (System.Exception e)
            {
                Debug.WriteLine(e.Message);
            }


            return(deviceList);
        }
        private async void DevicesList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            device = DevicesList.SelectedItem as IDevice;

            var result = await DisplayAlert("WARNING", "Are you sure you want to connect to this device?", "Connect", "Cancel");

            if (!result)
            {
                return;
            }

            // Stop Scanner
            await adapter.StopScanningForDevicesAsync();

            try
            {
                await adapter.ConnectToDeviceAsync(device);

                await DisplayAlert("Connection", "Status: " + device.State, " OK ");

                if (device.State == Plugin.BLE.Abstractions.DeviceState.Connected)
                {
                    ConnectedDevice.globalDevice = device;

                    await Application.Current.MainPage.Navigation.PopModalAsync(true);
                }
            }
            catch (DeviceConnectionException ex)
            {
                await DisplayAlert(" Error ", ex.Message, " OK ");
            }
        }
Esempio n. 11
0
        public async void lv_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            GlobalVariables.device = lv.SelectedItem as IDevice;
            if (GlobalVariables.device != null)
            {
                try
                {
                    //Connecteren met de device
                    await adapter.ConnectToDeviceAsync(GlobalVariables.device);

                    GlobalVariables.connection = true;
                    lblSoleStatus.Text         = "Connected";

                    await this.DisplayAlert("Succesfully connected", "You are connected!", "OK");

                    //lv.SelectedItem = null;
                }
                catch (DeviceConnectionException)
                {
                    //    //Could not connect to device
                    GlobalVariables.connection = false;
                    await this.DisplayAlert("Bluetooth Error", "Failed to connect", "OK");

                    //lv.SelectedItem = null;
                }
                catch (Exception)
                {
                    GlobalVariables.connection = false;
                    await this.DisplayAlert("Error", "Something went wrong", "OK");

                    //lv.SelectedItem = null;
                }
            }
        }
        //------------------------------------------------------------
        async void connect()
        {
            try
            {
                if (device != null)
                {
                    await adapter.ConnectToDeviceAsync(device);

                    // Status_label.Text = "Connected. ";
                    Status_label.Text = "Selected Device: " + Environment.NewLine +
                                        device.Id.ToString() + Environment.NewLine +
                                        device.Name.ToString() + Environment.NewLine +
                                        device.NativeDevice.ToString() + Environment.NewLine +
                                        device.Rssi.ToString() + Environment.NewLine +
                                        device.State.ToString() + Environment.NewLine;

                    // await adapter.DisconnectDeviceAsync(device); //disconnection command
                }
                else
                {
                    Status_label.Text = "Status: Conected" + device.Id.ToString();
                    //await DisplayAlert("Notice", "No Device selected!", "OK");
                }
            }
            catch (DeviceConnectionException ex)
            {
                //Could not connect to the device
                await DisplayAlert("Error!", ex.Message.ToString(), "OK");
            }
        }
Esempio n. 13
0
        private async void BtnConnect_Clicked(object sender, EventArgs a)
        {
            if (device != null)
            {
                try
                {
                    await adapter.ConnectToDeviceAsync(device);

                    //await _adapter.ConnectToKnownDeviceAsync(guid, cancellationToken);
                    //await DisplayAlert("Connected", "Status:" + device.State, "Accept");
                    txtBle.Text = device.State.ToString() + " (" + device.Name.ToString() + ") : " + device.Id;
                    btnGetServices.IsEnabled             = true;
                    btnGetCharacteristics.IsEnabled      = true;
                    dimSlider.IsEnabled                  = true;
                    btnReadCharacteristics.IsEnabled     = true;
                    btnWriteOffCharacteristics.IsEnabled = true;
                    btnWriteOnCharacteristics.IsEnabled  = true;
                    btnDisconnect.IsEnabled              = true;
                }
                catch (DeviceConnectionException ex)
                {
                    // ... could not connect to device
                    await DisplayAlert("Error", ex.Message.ToString(), "Accept");
                }
            }
            else
            {
                await DisplayAlert("Warning", "No device selected !", "Accept");
            }
        }
        async void btlist_ItemSelected(System.Object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return;
            }
            IDevice selecteddevice = e.SelectedItem as IDevice;

            ((ListView)sender).SelectedItem = null;
            Console.WriteLine("seleted is " + selecteddevice.Name);
            try
            {
                await adapter.ConnectToDeviceAsync(selecteddevice);

                Console.WriteLine("Connect to " + selecteddevice.Name + " successfully!");
                await DisplayAlert("Successful", "Connect to " + selecteddevice.Name + " successfully!", "Perfect!");

                dataviewmodel.record_device(selecteddevice);
            }
            catch (DeviceConnectionException)
            {
                try
                {
                    await adapter.ConnectToKnownDeviceAsync(new Guid("guid"));

                    //Console.WriteLine(selecteddevice.Name + " is already connected");
                    //await DisplayAlert("Successful", selecteddevice.Name + " is already connected", "Perfect!");
                }
                catch (DeviceConnectionException)
                {
                    await DisplayAlert("Error", "Cant connet to that device", "OK");
                }
            }
        }
        async void ListView1_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var device = e.SelectedItem as IDevice;

            if (device == null)
            {
                return;
            }

            try
            {
                await _Adapter.ConnectToDeviceAsync(device);

                if (device.State == DeviceState.Disconnected)
                {
                    await DisplayAlert("PluginBleTest", "Do Not Connect", "OK");

                    return;
                }
                if (device.State == DeviceState.Connected || device.State == DeviceState.Limited)
                {
                    await Navigation.PushAsync(new ServicesPage(device));
                }
            }
            catch (DeviceConnectionException ex)
            {
                Debug.WriteLine(ex.StackTrace);
                await DisplayAlert("PluginBleTest", "Do Not Connect", "OK");
            }
            finally
            {
                ListView1.SelectedItem = null;
            }
        }
Esempio n. 16
0
        public async Task <bool> ConnectDeviceAsync(BLEDevice device)
        {
            try
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();

                System.Diagnostics.Debug.WriteLine("Connecting to " + device.Name);

                await _adapterInstance.ConnectToDeviceAsync(device.Device, new ConnectParameters(autoConnect : true, forceBleTransport : false), tokenSource.Token);

                System.Diagnostics.Debug.WriteLine("Connected to " + device.Name);

                _findMeConnected = device;

                // Send message
                MessagingCenter.Send <BLEService>(this, "deviceConnected");

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Connection error " + ex.Message);
                return(false);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Подключение к устройству
        /// </summary>
        /// <param name="device">Блутус устройство</param>
        /// <returns>Результат подключения</returns>
        public async Task <bool> ConnectAsync(IDevice device)
        {
            if (device == null)
            {
                return(false);
            }

            if (!_adapter.IsScanning)
            {
                await _adapter.StopScanningForDevicesAsync();
            }

            try
            {
                await _adapter.ConnectToDeviceAsync(device);

                return(true);
            }
            catch (DeviceConnectionException ex)
            {
                //Debug.WriteLine($"BleService: connection exception {ex}");
            }
            catch (Exception ex)
            {
                //Debug.WriteLine($"BleService: generic exception {ex}");
            }
            return(await Task.FromResult(false));
        }
        //public BluetoothViewModel(INavigationService navigationService, IAdapter btAdapter) //INavigationService navigationService, IAdapter //btAdapter
        //{
        //
        //    _navigationService = navigationService;
        //    _btAdapter = btAdapter;
        //    _btAdapter.DeviceDiscovered += OnDeviceDiscovered;
        //    //tapCommand = new DelegateCommand(OnButtonTapped);
        //}

        private async void OnDeviceDiscovered(object sender, DeviceEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(e.Device.Name) && e.Device.Name.Contains("MLT-BT05"))
            {
                _btDevice  = e.Device;
                StatusText = "Connecting...";
                try
                {
                    await _btAdapter.ConnectToDeviceAsync(_btDevice);
                }
                catch (DeviceConnectionException exeption)
                {
                    await Application.Current.MainPage.DisplayAlert("Alert", "Could not connect to bluetooth\nError: " + exeption, "OK");
                }
                catch (Exception exeption)
                {
                    await Application.Current.MainPage.DisplayAlert("Alert", "Could not connect to bluetooth\nError: " + exeption, "OK");
                }
                NavigationParameters p = new NavigationParameters
                {
                    { "Device", _btDevice }
                };

                // _navigationService.NavigateAsync(new Uri(nameof(DeviceInfoView), UriKind.Relative), p);
            }
        }
Esempio n. 19
0
        private async void DevicesList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            App.Device = DevicesList.SelectedItem as IDevice;
            var result = await DisplayAlert("AVISO", "Deseja se conectar a esse dispositivo?", "Conectar", "Cancelar");

            if (!result)
            {
                return;
            }
            //Stop Scanner
            await adapter.StopScanningForDevicesAsync();

            try
            {
                await adapter.ConnectToDeviceAsync(App.Device);
                await DisplayAlert("Conectado", "Status:" + App.Device.State, "OK");

                System.Console.WriteLine("Connectado: " + BLEManager.connectedToDevice().ToString());
                await BLEManager.SendMessageAsync("Hello from Xamarin!!!");
            }
            catch (DeviceConnectionException ex)
            {
                await DisplayAlert("Erro", ex.Message, "OK");
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Receives connection request from user-interface.
        /// Check device bluetooth is on, attempt connection and register service and characteristics.
        /// If successful, begin main communication menu algorithm.
        /// </summary>
        /// <param name="brace">Virtual BLE device containing data about remote physical device.</param>
        public async Task Connect(IDevice device)
        {
            Brace = device;

            try
            {
                Write("Connecting...");

                // If connection successful, stop scanning for devices.
                await adapter.StopScanningForDevicesAsync();

                // Attempt connection to device
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await adapter.ConnectToDeviceAsync(device);
                });
            }
            catch (Exception e)
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Application.Current.MainPage.DisplayAlert("Connection failure.", e.Message, "OK");
                });
                return;
            }
        }
Esempio n. 21
0
        public async override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            if (adapter == null)
            {
                return;
            }

            try
            {
                if (deviceList[indexPath.Row].State == Plugin.BLE.Abstractions.DeviceState.Connected)
                {
                    var device = deviceList[indexPath.Row];
                    navigation.launchViewController(device);

                    //await adapter.DisconnectDeviceAsync(device);
                }
                else
                {
                    await adapter.ConnectToDeviceAsync(deviceList[indexPath.Row]);
                }
            }
            catch (DeviceConnectionException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
Esempio n. 22
0
        private async void lv_ItemSelected(object sender, EventArgs e)
        {
            if (lv.SelectedItem == null)
            {
                await DisplayAlert("Notice", "No Device selected", "OK");

                return;
            }
            else
            {
                selectedDevice = lv.SelectedItem as IDevice;
                try
                {
                    await adapter.ConnectToDeviceAsync(selectedDevice);
                }
                catch (DeviceConnectionException ex)
                {
                    await DisplayAlert("Notice", "Error connecting to device!", "OK");
                }
                catch (ArgumentNullException ex)
                {
                    await DisplayAlert("Notice", "Selected device is null!", "OK");
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Notice", "Unknown exception!", "OK");
                }
            }
        }
Esempio n. 23
0
        public Task <IBleResult> TryConnectToDeviceAsync(IDevice device, bool connectWhenAvailable, CancellationToken cancellationToken)
        {
            _logger?.Log(LogSender, $"Trying to connect to device [DeviceName={device.Name},GUID={device.Id:D}]");

            return(_bleAvailability.ExecuteWithBleAvailabilityCheckAsync(async() =>
            {
                IBleResult result;

                _logger?.Log(LogSender, $"Internal connect to device started");
                try
                {
                    var connectParameters = new ConnectParameters(connectWhenAvailable);
                    await _bleAdapter.ConnectToDeviceAsync(device, connectParameters, cancellationToken);
                    result = device.State == DeviceState.Connected ? BleResult.Success() : BleResult.Failure(BleFailure.ConnectNotCompleted);
                }
                catch (TimeoutException)
                {
                    result = BleResult.Failure(BleFailure.OperationTimeout);
                }
                catch (OperationCanceledException)
                {
                    result = BleResult.Failure(BleFailure.OperationCancelled);
                }
                catch (Exception e)
                {
                    result = BleResult.Failure(e);
                }
                _logger?.Log(LogSender, $"Internal connect to device completed with result: {result}");

                return result;
            }));
        }
Esempio n. 24
0
        private async void FoundBluetoothDevicesListView_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            //  IsBusyIndicator.IsVisible = IsBusyIndicator.IsRunning = !(ScanButton.IsEnabled = false);
            IDevice selectedItem = e.Item as IDevice;

            //ScanButton.Text = "Rescan";


            if (selectedItem.State == DeviceState.Connected)
            {
                await Navigation.PushAsync(new BluetoothDataPage(selectedItem));
            }
            else
            {
                try
                {
                    var connectParameters = new ConnectParameters(false, true);
                    await _bluetoothAdapter.ConnectToDeviceAsync(selectedItem, connectParameters);

                    await Navigation.PushAsync(new BluetoothDataPage(selectedItem));
                }
                catch
                {
                    await DisplayAlert("Error connecting", $"Error connecting to BLE device: {selectedItem.Name ?? "N/A"}", "Retry");
                }
            }

            //   IsBusyIndicator.IsVisible = IsBusyIndicator.IsRunning = !(ScanButton.IsEnabled = true);
        }
Esempio n. 25
0
        public static async Task <bool> Test1(IDevice device, IAdapter adapter)
        {
            bool testResult = true;

            try
            {
                await adapter.ConnectToDeviceAsync(device);

                await Task.Delay(1500);

                var searchServicesTask = device.GetServicesAsync();
                if (await Task.WhenAny(Task.Delay(10000), searchServicesTask) != searchServicesTask)
                {
                    return(false);
                }
                var services = await searchServicesTask;
                testResult &= InsureServices(services);
                if (!testResult)
                {
                    return(false);
                }
                var movService = services.FirstOrDefault(x => x.Id == GuidCollection.MOVEMENT_SERV_UUID);
                var chars      = await movService.GetCharacteristicsAsync();

                testResult &= InsureMovementServiceChars(chars);
                if (!testResult)
                {
                    return(false);
                }
                var output       = chars.FirstOrDefault(x => x.Id == GuidCollection.MOVEMENT_UID_UUID);
                var outputResult = await output.ReadAsync();

                testResult &= outputResult.Length == 0;
                if (!testResult)
                {
                    return(false);
                }
                var passChar = chars.FirstOrDefault(x => x.Id == GuidCollection.MOVEMENT_PASS_UUID);
                testResult &= await passChar.WriteAsync(_defaultPassBytes);

                if (!testResult)
                {
                    return(false);
                }
                outputResult = await output.ReadAsync();

                testResult &= outputResult.Length != 0;
            }
            catch (Exception ex)
            {
                testResult = false;
            }
            finally
            {
                adapter.DisconnectDeviceAsync(device);
            }
            return(testResult);
        }
        public void Connect(IDeviceBLE pInput)
        {
            if (pInput == null)
            {
                return;
            }

            var inputType  = pInput.GetType();
            var searchType = typeof(UnPairedDeviceBLE);

            Device = null;
            if (inputType == searchType)
            {
                //Pair if the device is able to pair
                AcceptRescan     = false;
                ConnectingDevice = pInput;
                Debug.WriteLine("Connecting to new device.");
                mAdapter.ConnectToDeviceAsync((ConnectingDevice as UnPairedDeviceBLE).mDevice).ContinueWith(StopScanning);
            }
        }
Esempio n. 27
0
        async void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var currentDevice = e.CurrentSelection.FirstOrDefault() as IDevice;

            try {
                await Adapter.ConnectToDeviceAsync(currentDevice);
                await DisplayAlert("Conectado", $"Status {currentDevice.State}", "Ok");
            } catch (Exception ex) {
                Debug.WriteLine(ex);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Connect to a Go+ device.
        /// </summary>
        /// <param name="device">Go+ to connect.</param>
        public async Task ConnectDevice(GoPlus device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (!_devicesFound.ContainsKey(device))
            {
                throw new ArgumentException("This device does not exist in discovered devices");
            }

            // There should only be one connection at a time.
            foreach (IDevice connectedDevice in _adapter.ConnectedDevices)
            {
                _logger.Log("Connected device already exists! Disconnecting.", Category.Info, Priority.None);
                await _adapter.DisconnectDeviceAsync(connectedDevice);
            }

            _charCache.Clear();

            _logger.Log("Connecting to Pokemon GO Plus.", Category.Info, Priority.None);

            // Wait a bit before connecting.
            await Task.Delay(Constants.DelayMS);

            for (int i = 0; i < Constants.RetryCount; i++)
            {
                try
                {
                    await _adapter.ConnectToDeviceAsync(_devicesFound[device]);

                    _logger.Log("Successfully connected to Pokemon GO Plus.", Category.Info, Priority.None);
                    return;
                }
                catch (Exception e)
                {
                    if (i < Constants.RetryCount - 1)
                    {
                        _logger.Log($"Error connecting to Pokemon GO Plus: {e.Message}. Trying Again.", Category.Exception, Priority.High);
                        await Task.Delay(Constants.DelayMS);
                    }
                    else
                    {
                        _logger.Log($"Error connecting to Pokemon GO Plus: {e.Message}.", Category.Exception, Priority.High);
                        _notifyManager.ShowShortToast("Unable to connect to Pokemon GO Plus.");
                    }
                }
            }

            _logger.Log($"Unable to Connect to Pokemon GO Plus.", Category.Exception, Priority.High);
            throw new Exception("Unable to Connect to Pokemon GO Plus");
        }
 public async Task <bool> ConnectDeviceAsync(DeviceItemViewModel device)
 {
     try
     {
         await adapter.ConnectToDeviceAsync(device.Device);
     }
     catch (DeviceConnectionException ex)
     {
         Debug.WriteLine("Error ConnectDeviceAsync : " + ex);
     }
     return(true);
 }
Esempio n. 30
0
        public async void StartDeviceSequence(IDevice device)
        {
            try
            {
                await adapter.ConnectToDeviceAsync(device);

                var services = await GetServices(device);

                var characterstics = await GetCharacterstics(services.FirstOrDefault());

                ///read charactestics
                ///
                var characteristic = characterstics.FirstOrDefault();
                var bytes          = await characteristic.ReadAsync();

                await characteristic.WriteAsync(bytes);


                characteristic.ValueUpdated += (o, args) =>
                {
                    var bytes1 = args.Characteristic.Value;
                };

                await characteristic.StartUpdatesAsync();



                //read descriptitor
                var descriptors = await characteristic.GetDescriptorsAsync();

                var descriptor = descriptors.FirstOrDefault();
                var bytes2     = await descriptor.ReadAsync();

                await descriptor.WriteAsync(bytes2);
            }
            catch (DeviceConnectionException e)
            {
                // ... could not connect to device
            }
        }