コード例 #1
0
        public async Task <bool> ConnectByIdAsync(string deviceId)
        {
            CurrentDevice = null;
            CurrentDevice = Devices.FirstOrDefault(d => d.Id.Equals(deviceId));
            if (CurrentDevice != null)
            {
                return(true);
            }
            using (var cts = new CancellationTokenSource())
            {
                var  connectionTask = adapter.ConnectToKnownDeviceAsync(new Guid(deviceId), cancellationToken: cts.Token);
                uint delayCount     = 0;
                while ((!connectionTask.IsCompleted) && (delayCount < 50))
                {
                    await Task.Delay(100);

                    delayCount++;
                }
                if (connectionTask.IsCompleted)
                {
                    CurrentDevice = new SoterDeviceBle(connectionTask.Result);
                    return(true);
                }
                else
                {
                    cts.Cancel();
                    return(false);
                }
            }
        }
コード例 #2
0
        private async Task ConnectDevice(DeviceModel device, CancellationToken cancellationToken)
        {
            try
            {
                if (adapter.ConnectedDevices.ToList().Find(d => d.Id != null && d.Id.Equals(device.Uuid)) == null)
                {
                    var connectedDevice = await adapter.ConnectToKnownDeviceAsync(Guid.Parse(device.Uuid), new ConnectParameters(false, false), cancellationToken);

                    var service = await connectedDevice.GetServiceAsync(Guid.Parse(device.Service));

                    var characteristic = await service.GetCharacteristicAsync(Guid.Parse(device.Characteristic));

                    UnicodeEncoding uniencoding = new UnicodeEncoding();
                    byte[]          zero        = uniencoding.GetBytes("0");
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        characteristic.WriteAsync(zero);
                    });

                    characteristic.ValueUpdated += (s, a) =>
                    {
                        byte[] valueBytes = a.Characteristic.Value;

                        string data = string.Concat(valueBytes.Select(b => b.ToString("X2")));

                        DeviceData deviceData = new DeviceData();
                        deviceData.DeviceName = connectedDevice.NativeDevice.ToString();
                        deviceData.Data       = valueBytes;
                        lDeviceData.Add(deviceData);

                        Debug.WriteLine(data, "Leyendo datos de " + connectedDevice.NativeDevice.ToString() + ": ");
                    };
                    characteristics.Add(characteristic);

                    await characteristic.StartUpdatesAsync();
                }
            }
            catch (DeviceConnectionException e)
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Application.Current.MainPage.DisplayAlert("Atención", "No es posible conectar con el dispositivo " + device.Name, "Aceptar");
                    Debug.WriteLine("Error al conectar con el dispositivo: " + device.Name + "." + e);
                    Loading = false;
                });
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("Las tareas han sido canceladas");
            }
            catch (Exception e)
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Application.Current.MainPage.DisplayAlert("Atención", "Se ha producido un error innesperado", "Aceptar");
                    Debug.WriteLine("Error al conectar con el dispositivo: " + device.Name + "." + e);
                    Loading = false;
                });
            }
        }
コード例 #3
0
ファイル: ScanPage.xaml.cs プロジェクト: asierdanjou/BleAsier
        private async void BtnKnowConnect_Clicked(object sender, EventArgs e)
        {
            TimeSpan scantime;
            DateTime datetime = DateTime.Now;

            //Guid myGuid = new Guid("00000000-0000-0000-0000-000b57ef2d90"); // Public Address Silicon Labs peripheral

            if (string.IsNullOrEmpty(entryGUID.Text))
            {
                return;
            }
            Guid myGuid = Guid.Parse(entryGUID.Text);

            try
            {
                device = await adapter.ConnectToKnownDeviceAsync(myGuid);

                //scantime = DateTime.Now - datetime;
                //txtBle.Text = adapter.ConnectedDevices.Count.ToString() + " (" + scantime.ToString() + ")";
                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;
                //await this.WaitAndExecute(2000, ()=>DisplayAlert("Alert", "This fired after 2 seconds", "Ok"));
            }
            catch (DeviceConnectionException ex)
            {
                //Could not connect to the device
                await DisplayAlert("Notice", ex.Message.ToString(), "OK");
            }
        }
コード例 #4
0
        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");
                }
            }
        }
コード例 #5
0
ファイル: WagonBluetooth.cs プロジェクト: JontyMC/WagonLights
        async Task Connect()
        {
            using (UserDialogs.Instance.Loading("Connecting..."))
            {
                await retryForever.ExecuteAsync(async() =>
                {
                    device                   = await adapter.ConnectToKnownDeviceAsync(WagonId);
                    var services             = await device.GetServicesAsync();
                    var characs              = await services[3].GetCharacteristicsAsync();
                    tempCharacteristic       = characs[0];
                    programCharacteristic    = characs[1];
                    brightnessCharacteristic = characs[2];
                    paletteCharacteristic    = characs[3];
                    speedCharacteristic      = characs[4];
                    widthCharacteristic      = characs[5];
                    //resetCharacteristic = characs[6];
                    vjCharacteristic     = characs[6];
                    customCharacteristic = characs[7];

                    tempCharacteristic.ValueUpdated += (x, y) =>
                    {
                        Temperature = y.Characteristic.StringValue + "°C";
                    };
                    await tempCharacteristic.StartUpdatesAsync();
                });

                Connected = true;
            }
        }
コード例 #6
0
 private async void btnKnowConnect_Clicked(object sender, EventArgs e)
 {
     try
     {
         await _adapter.ConnectToKnownDeviceAsync(new Guid("guid"));
     }
     catch (DeviceConnectionException ex)
     {
         await DisplayAlert("Notice", ex.Message, "OK");
     }
 }
コード例 #7
0
 public async void ConnectDeviceByGuid(Guid guid)
 {
     try
     {
         await adapter.ConnectToKnownDeviceAsync(guid);
     }
     catch (DeviceConnectionException e)
     {
         // ... could not connect to device
     }
 }
コード例 #8
0
 private async void btnKnowConnect_clicked(object sender, EventArgs e)
 {
     try
     {
         await adapter.ConnectToKnownDeviceAsync(new Guid("guid"));
     }
     catch (DeviceConnectionException ex)
     {
         await DisplayAlert("Problem", ex.Message.ToString(), "OK");
     }
 }
コード例 #9
0
 private async void btnKnowConnect_Clicked(object sender, EventArgs e)
 {
     try
     {
         await adapter.ConnectToKnownDeviceAsync(new Guid("guid"));
     }
     catch (DeviceConnectionException ex)
     {
         //Could not connect to the device
         DisplayAlert("Notice", ex.Message.ToString(), "OK");
     }
 }
コード例 #10
0
        public async Task TryConnect(Guid?id)
        {
            if (Status != AccelerometerStatus.NotConnected || id == null)
            {
                return;
            }

            Status = AccelerometerStatus.Connecting;

            try {
                await adapter.ConnectToKnownDeviceAsync(id.Value);
            } catch (DeviceConnectionException) {
                Status = AccelerometerStatus.NotConnected;
            }
        }
コード例 #11
0
        private async void BtnConnectKnown_Clicked(object sender, EventArgs e)
        {
            try
            {
                await adapter.ConnectToKnownDeviceAsync(het);

                string notif = ("You've connected to " + device.Name);
                await DisplayAlert("Notice", notif, "OK");
            }
            catch (DeviceConnectionException ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                await DisplayAlert("Notice", ex.Message.ToString(), "OK");
            }
        }
コード例 #12
0
        //if th device from previous session is found then this method should be used
        public async Task GetConnectionToKnownDevice()
        {
            try
            {
                status = "CONNECTING";


                Task[] t = { adapter.ConnectToKnownDeviceAsync(prevguid) };
                await Task.Factory.ContinueWhenAll(t, _ => SetSelectedDevice_ToPrevDevice());
            }
            catch (DeviceConnectionException ex)
            {
                //Could not connect to the device
                MessagingCenter.Send <BluetoothHandler>(this, "BHConnectToDeviceFail");
            }
        }
コード例 #13
0
        private async void btnConnect_Clicked(object sender, EventArgs e)
        {
            //await adapter.ConnectToDeviceAsync(device);
            device = await adapter.ConnectToKnownDeviceAsync(new Guid("00000000-0000-0000-0000-c7e4e3e2e157"));

            //device = await adapter.ConnectToKnownDeviceAsync(new Guid("00000000-0000-0000-0000-c7e4e3e2e1fc"));
            service = await device.GetServiceAsync(Guid.Parse("0000fff0-0000-1000-8000-00805f9b34fb"));

            recv_character = await service.GetCharacteristicAsync(Guid.Parse("0000fff1-0000-1000-8000-00805f9b34fb"));

            send_character = await service.GetCharacteristicAsync(Guid.Parse("0000fff2-0000-1000-8000-00805f9b34fb"));

            var state = device.State;

            lblRecvValue.Text = state.ToString();

            recv_character.ValueUpdated += Character_ValueUpdated;
            await recv_character.StartUpdatesAsync();
        }
コード例 #14
0
        /// <summary>
        /// Opens the connection interface associated with this Bluetooth device.
        /// </summary>
        /// <exception cref="Exception">If there is any problem opening the connection with this bluetooth
        /// device.</exception>
        /// <exception cref="XBeeException">If there is any XBee error.</exception>
        /// <seealso cref="IsOpen"/>
        /// <seealso cref="Close"/>
        public void Open()
        {
            Debug.WriteLine("----- Open");

            // Do nothing if the device is already open.
            if (IsOpen)
            {
                return;
            }

            string connectExceptionMessage = null;

            // Create a task to connect the device.
            Task task = Task.Run(async() =>
            {
                try
                {
                    // Abort the connect operation if the given timeout expires.
                    CancellationTokenSource token = new CancellationTokenSource();
                    token.CancelAfter(CONNECTION_TIMEOUT);

                    // Connect the device. Try to connect up to 3 times.
                    var retries = BT_CONNECT_RETRIES;
                    while (!IsOpen && retries > 0)
                    {
                        if (device == null)
                        {
                            device = await adapter.ConnectToKnownDeviceAsync(deviceGuid, new ConnectParameters(), token.Token);
                        }
                        else
                        {
                            await adapter.ConnectToDeviceAsync(device, new ConnectParameters(), token.Token);
                        }
                        await Task.Delay(1000);
                        if (device != null && device.State == DeviceState.Connected)
                        {
                            IsOpen = true;
                        }
                        retries--;
                    }

                    // Check if device is connected.
                    if (!IsOpen)
                    {
                        throw new Exception();
                    }

                    // Request a larger MTU.
                    mtu = await device.RequestMtuAsync(REQUESTED_MTU);
                    Console.WriteLine("----- MTU: " + mtu);

                    // Get the TX and RX characteristics.
                    IService service = await device.GetServiceAsync(Guid.Parse(SERVICE_GUID));
                    if (service == null)
                    {
                        throw new Exception(ERROR_GET_SERVICE);
                    }
                    txCharacteristic = await service.GetCharacteristicAsync(Guid.Parse(TX_CHAR_GUID));
                    rxCharacteristic = await service.GetCharacteristicAsync(Guid.Parse(RX_CHAR_GUID));
                    if (txCharacteristic == null || rxCharacteristic == null)
                    {
                        throw new Exception(ERROR_GET_CHARS);
                    }

                    // Subscribe to the RX characteristic.
                    if (rxCharacteristic.CanUpdate)
                    {
                        rxCharacteristic.ValueUpdated += DataReceived;
                        await rxCharacteristic.StartUpdatesAsync();
                    }

                    encrypt = false;
                }
                catch (Exception e)
                {
                    connectExceptionMessage = e.Message == null ? ERROR_CONNECTION : ERROR_CONNECTION + " > " + e.Message;
                }
                finally
                {
                    lock (connectLock)
                    {
                        Monitor.Pulse(connectLock);
                    }
                }
            });

            if (!task.IsCompleted)
            {
                // Wait until the task finishes.
                lock (connectLock)
                {
                    Monitor.Wait(connectLock);
                }
            }

            // If the task finished with excepction, throw it.
            if (connectExceptionMessage != null)
            {
                if (device != null && device.State != DeviceState.Connected)
                {
                    IsOpen = false;
                }
                Close();
                throw new XBeeException(connectExceptionMessage);
            }

            // If the task was cancelled, throw an exception.
            if (task.IsCanceled)
            {
                if (device != null && device.State != DeviceState.Connected)
                {
                    IsOpen = false;
                }
                Close();
                throw new XBeeException(ERROR_CONNECTION_CANCELED);
            }

            // Check again if the device is connected. We've seen that sometimes the
            // Rx subscribe process could make the device to disconnect.
            if (device != null && device.State != DeviceState.Connected)
            {
                IsOpen = false;
                Close();
                throw new XBeeException(ERROR_CONNECTION);
            }
        }
コード例 #15
0
        private async void FromCupButton_Clicked(object sender, EventArgs e)
        {
            IBluetoothLE   bluetoothBLE = CrossBluetoothLE.Current;
            IAdapter       adapter      = CrossBluetoothLE.Current.Adapter;
            List <IDevice> deviceList   = new List <IDevice>();
            IDevice        device       = null;

            var state = bluetoothBLE.State;

            CupInput.Text += $"BLE State: {state}\n";

            /*if (bluetoothBLE.State == BluetoothState.Off)
             * {
             *  await DisplayAlert("Error", "Bluetooth disabled.", "OK");
             * }
             * else
             * {
             *  deviceList.Clear();
             *
             *  adapter.ScanTimeout = 3000;
             *  adapter.ScanMode = ScanMode.Balanced;
             *
             *  adapter.DeviceDiscovered += (obj, a) =>
             *  {
             *      if (!deviceList.Contains(a.Device))
             *          deviceList.Add(a.Device);
             *  };
             *
             *
             *  CupInput.Text += $"Start scaning\n";
             *  await adapter.StartScanningForDevicesAsync();
             *
             *  FromCupButton.Text = "Scaning\n";
             * }
             * CupInput.Text += $"Device count: {deviceList.Count}";
             *
             * foreach(var dev in deviceList)
             * {
             *  CupInput.Text += $"{dev.Name} {dev.Id} {dev.State}\n";
             *  if (dev.Name == "CC41-A")
             *  {
             *      device = dev;
             *  }
             * }*/


            CupInput.Text += "Connecting...";
            try
            {
                device = await adapter.ConnectToKnownDeviceAsync(new Guid("00000000-0000-0000-0000-00158310d640"));

                CupInput.Text += $"{device.Name}: {device.State}\n";
            }
            catch (Exception ex)
            {
                CupInput.Text     += $"Error: {ex.Message}\n";
                FromCupButton.Text = "Error";
                return;
            }
            CupInput.Text += "OK\n";



            // start
            var srv = await device.GetServiceAsync(new Guid("0000ffe0-0000-1000-8000-00805f9b34fb"));

            var ch = await srv.GetCharacteristicAsync(new Guid("0000ffe1-0000-1000-8000-00805f9b34fb"));

            await ch.WriteAsync(Encoding.UTF8.GetBytes("1"));

            string hex = BitConverter.ToString(Encoding.UTF8.GetBytes("1"));

            CupInput.Text += $"Hex Repr: {hex}\n";

            var services = await device.GetServicesAsync();

            foreach (var service in services)
            {
                //CupInput.Text += $"Service: {service.Name} {service.Id}\n";
                var chars = await service.GetCharacteristicsAsync();

                foreach (var chr in chars)
                {
                    CupInput.Text += $"--Char: {chr.Name} [{chr.Id},{chr.Uuid}[{chr.StringValue},{chr.Value}] {chr.CanRead} {chr.CanWrite} {chr.CanUpdate}]\n";
                    var desriptors = await chr.GetDescriptorsAsync();

                    foreach (var desc in desriptors)
                    {
                        //CupInput.Text += $"----Desc: {desc.Name} [{desc.Id},{desc.Value}]\n";
                        var res = await desc.ReadAsync();

                        var str = Encoding.UTF8.GetString(res);
                        //CupInput.Text += ($"Readed: /{str}/\n");
                    }
                    if (chr.CanRead)
                    {
                        byte[] bytes;
                        bytes = await chr.ReadAsync();

                        var str = Encoding.UTF8.GetString(bytes);
                        CupInput.Text += ($"Readed: /{str}/\n");
                    }
                    if (chr.CanUpdate)
                    {
                        CupInput.Text += ($"Updatable: /{chr.Name}/\n");

                        /*chr.ValueUpdated += async (obj, a) =>
                         * {
                         *  try
                         *  {
                         *      var res = await a.Characteristic.ReadAsync();
                         *      var str = Encoding.UTF8.GetString(res);
                         *      Console.WriteLine($"[BLE {chr.Name}: '{str}']");
                         *  }
                         *  catch (Exception ex)
                         *  {
                         *      Console.WriteLine($"[BLE ERROR {chr.Name}: '{ex.Message}']");
                         *  }
                         * };
                         * await chr.StartUpdatesAsync();*/
                    }
                }
            }

            Console.WriteLine(CupInput.Text);

            FromCupButton.Text = "Finished";

            /*FromCupButton.BackgroundColor = Color.Green;
             * if (FromCameraButton.BackgroundColor == Color.Green && FromCupButton.BackgroundColor == Color.Green)
             * {
             *  ReadyButton.IsVisible = true;
             *  FromCameraButton.IsVisible = false;
             *  FromCupButton.IsVisible = false;
             * }*/
        }
コード例 #16
0
ファイル: CgmPageViewModel.cs プロジェクト: xians78/eDroplet
        private async void connectBleDevice()
        {
            if (IsBleConnected)
            {
                BtnBleConnectTxt = "CONNECT";
                IsBleConnected   = false;
                lblDataSource    = "";
                bleDevices.Clear();
                await bleAdapter.DisconnectDeviceAsync(connectedDevice);
            }
            else
            {
                BtnBleConnectTxt = "DISCONNECT";
                try
                {
                    IsBleConnected     = false;
                    connectedDevice    = null;
                    gridDataVisible    = false;
                    gridBleScanVisible = true;
                    connectedDevice    = await bleAdapter.ConnectToKnownDeviceAsync(new Guid(currentDeviceUuid));

                    dialogScr.Toast("Droplet state: " + connectedDevice.State.ToString());
                    try
                    {
                        batteryInfoService = await connectedDevice.GetServiceAsync(new Guid("0000180f-0000-1000-8000-00805f9b34fb"));

                        batteryVoltageCharacteristic = await batteryInfoService.GetCharacteristicAsync(new Guid("00002a19-0000-1000-8000-00805f9b34fb"));

                        batteryVoltageCharacteristic.ValueUpdated += BatteryVoltageCharacteristic_ValueUpdated;
                        await batteryVoltageCharacteristic.StartUpdatesAsync();
                    }
                    catch (Exception e)
                    {
                        dialogScr.Toast("Battery read error: " + e.Message);
                    }

                    deviceInfoService = await connectedDevice.GetServiceAsync(Guid.Parse("0000180a-0000-1000-8000-00805f9b34fb"));

                    manufacturerCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a29-0000-1000-8000-00805f9b34fb"));

                    deviceModelCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a24-0000-1000-8000-00805f9b34fb"));

                    deviceSerialCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a25-0000-1000-8000-00805f9b34fb"));

                    deviceHWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a27-0000-1000-8000-00805f9b34fb"));

                    deviceFWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a26-0000-1000-8000-00805f9b34fb"));

                    deviceSWrevCharacteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002a28-0000-1000-8000-00805f9b34fb"));

                    dataService = await connectedDevice.GetServiceAsync(Guid.Parse("c97433f0-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataReadCharacteristic = await dataService.GetCharacteristicAsync(Guid.Parse("c97433f1-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataWriteCharacteristic = await dataService.GetCharacteristicAsync(Guid.Parse("c97433f2-be8f-4dc8-b6f0-5343e6100eb4"));

                    dataReadCharacteristic.ValueUpdated += DataReadCharacteristic_ValueUpdated;
                    await dataReadCharacteristic.StartUpdatesAsync();

                    byte[] batteryVoltageBytes = await batteryVoltageCharacteristic.ReadAsync();

                    byte[] manufacturerBytes = await manufacturerCharacteristic.ReadAsync();

                    byte[] deviceModelBytes = await deviceModelCharacteristic.ReadAsync();

                    byte[] deviceSerialBytes = await deviceSerialCharacteristic.ReadAsync();

                    byte[] deviceHWrevBytes = await deviceHWrevCharacteristic.ReadAsync();

                    byte[] deviceFWrevBytes = await deviceFWrevCharacteristic.ReadAsync();

                    byte[] deviceSWrevBytes = await deviceSWrevCharacteristic.ReadAsync();

                    Debug.WriteLine("Battery : " + batteryVoltageBytes[0].ToString() + " %");
                    Debug.WriteLine("Manufacturer: " + System.Text.Encoding.Default.GetString(manufacturerBytes));
                    Debug.WriteLine("Device model: " + System.Text.Encoding.Default.GetString(deviceModelBytes));
                }
                catch (Exception e)
                {
                    dialogScr.Toast("BLE connection error: " + e.Message);
                    Debug.WriteLine("BLE connection error: " + e.Message);
                }
                IsBleConnected     = true;
                gridBleScanVisible = false;
                gridDataVisible    = true;
                lblDataSource      = "BLE - Droplet";
            }
        }