Esempio n. 1
0
        /// <summary>
        /// Listen for a connection.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task StartListening()
        {
            try
            {
                // If already listening, do nothing
                if (IsListening)
                {
                    return;
                }

                // Create device
                var deviceInfo = await GetBluetoothDeviceInfo();

                device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

                device.ConnectionStatusChanged += Device_ConnectionStatusChanged;

                // Initiate connection
                gattSession = await GattSession.FromDeviceIdAsync(device.BluetoothDeviceId);

                gattSession.MaintainConnection = true;
            }
            catch
            {
                // Stop the device and rethrow exception
                StopListening();
                throw;
            }
        }
        private async Task CreateSession( )
        {
            _session?.Dispose( );

            _session = await GattSession.FromDeviceIdAsync(_device.BluetoothDeviceId);

            _session.MaintainConnection = true;
        }
        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);
                }
            }
        }
Esempio n. 4
0
    public async void ConnectDevice(ulong addr)
    {
        string addrString = addr.ToString("X");

        Console.WriteLine("{0}: {1}",
                          addrString, loops.ContainsKey(addr) ? "Updating connection" : "Connecting");

        BluetoothLEDevice loop = await BluetoothLEDevice.FromBluetoothAddressAsync(addr);

        loop.ConnectionStatusChanged += ConnectionStatusHandler;

        // Maintain the connection (not sure this does anything)
        //Console.WriteLine("{0}: Maintaining connection ...", addrString);
        GattSession s =
            await GattSession.FromDeviceIdAsync(BluetoothDeviceId.FromId(loop.DeviceId));

        s.MaintainConnection = true;

        //Console.WriteLine("{0}: Getting services ...", addrString);
        GattDeviceServicesResult serviceResult =
            await loop.GetGattServicesAsync(BluetoothCacheMode.Uncached);

        foreach (GattDeviceService service in serviceResult.Services)
        {
            if (service.Uuid.Equals(loopService))
            {
                //Console.WriteLine("{0}: Finding characteristics ...", addrString);
                GattCharacteristicsResult charResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                foreach (GattCharacteristic characteristic in charResult.Characteristics)
                {
                    if (characteristic.Uuid.Equals(loopChar))
                    {
                        Subscribe(characteristic, addr);
                        // Prevent GC of the device and session
                        loops[addr] = loop;
                        break;
                    }
                }
            }
            else if (service.Uuid.Equals(GattServiceUuids.Battery))
            {
                GattCharacteristicsResult charResult = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                foreach (GattCharacteristic characteristic in charResult.Characteristics)
                {
                    if (!characteristic.Uuid.Equals(GattCharacteristicUuids.BatteryLevel))
                    {
                        continue;
                    }

                    GattReadResult batt = await characteristic.ReadValueAsync();

                    DataReader reader = DataReader.FromBuffer(batt.Value);
                    byte[]     input  = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    Console.WriteLine("Loop battery: {0}%", input[0]);
                    break;
                }
            }
        }
    }