Exemplo n.º 1
0
        public bool ConnectUEI(string address)
        {
            int ndx = addressList.IndexOf(address);

            rssi = ndx >= 0 ? (int)(short)rssiList[ndx] : 1;

            string addrStr = "0x";

            for (int i = 0; i < 18; i += 3)
            {
                addrStr += address.Substring(i, 2);
            }
            ulong addrVal       = Convert.ToUInt64(addrStr, 16);
            var   selector      = BluetoothLEDevice.GetDeviceSelectorFromBluetoothAddress(addrVal, BluetoothAddressType.Public);
            var   deviceWatcher = DeviceInformation.CreateWatcher(selector);

            deviceWatcher.Added   += DeviceWatcher_Added;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            stage = 1;
            done  = false;
            deviceWatcher.Start();
            while (!done)
            {
            }
            ;
            stage = 2;
            if (bleDevice != null)
            {
                bleDevice.ConnectionStatusChanged += BleDevice_ConnectionStatusChanged;
            }
            return(bleDevice != null);
        }
Exemplo n.º 2
0
        public async Task FindDevice(ulong address)
        {
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(address);

            if (device != null)
            {
                Device = device;
            }

            string[]      requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
            DeviceWatcher deviceWatcher       =
                DeviceInformation.CreateWatcher(
                    BluetoothLEDevice.GetDeviceSelectorFromBluetoothAddress(address),
                    requestedProperties);

            deviceWatcher.Added   += DeviceWatcher_Added;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            deviceWatcher.Updated += DeviceWatcher_Updated;
            deviceWatcher.Start();

            Device = await BluetoothLEDevice.FromBluetoothAddressAsync(address);

            if (Device == null)
            {
                throw new KeyNotFoundException();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initialize the device.
        /// </summary>
        /// <param name="deviceInformation">An instance of DeviceInformation class corresponding to the BluetoothLEDevice.</param>
        /// <param name="bluetoothAddress">The bluetooth address of the device.</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task Initialize(DeviceInformation deviceInformation, ulong bluetoothAddress, CancellationToken cancellationToken)
        {
            if (deviceInformation.Pairing.IsPaired)
            {
                // If the device is paired, all we have to do is just getting BluetoothLEDevice object by its ID.
                this.bleDevice = (await BluetoothLEDevice.FromIdAsync(deviceInformation.Id)).AddTo(this.disposables);
                this.service   = this.bleDevice.GetGattService(ServiceUuid).AddTo(this.disposables);
            }
            else
            {
                // If the device is not paired, pair with the device.
                var result = await deviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);

                switch (result.Status)
                {
                case DevicePairingResultStatus.Paired:
                    // The device has been paired successfully.
                    break;

                default:
                    throw new ImbleOperationException("Failed to pair with the device.");
                }

                // After the PairAsync method returns, we have to wait until the device paired is registered to the system.
                var selector        = BluetoothLEDevice.GetDeviceSelectorFromBluetoothAddress(bluetoothAddress);
                var watcher         = DeviceInformation.CreateWatcher(selector);
                var deviceAddedTask = EventSubscription.ReceiveFirst <DeviceWatcher, DeviceInformation>(handler => watcher.Added += handler, handler => watcher.Added -= handler, cancellationToken);
                watcher.Start();
                var bleDeviceInformation = await deviceAddedTask;   // Wait until the target device is added.
                watcher.Stop();

                this.bleDevice = (await BluetoothLEDevice.FromIdAsync(bleDeviceInformation.Id)).AddTo(this.disposables);
                var gattServiceChangedTask = EventSubscription.ReceiveFirst <BluetoothLEDevice, object>(handler => this.bleDevice.GattServicesChanged += handler, handler => this.bleDevice.GattServicesChanged -= handler, cancellationToken);

                this.service = this.bleDevice.GetGattService(ServiceUuid);
                if (this.service == null)
                {
                    // If the GATT services have not been enumerated yet, wait until the enumeration completes.
                    await gattServiceChangedTask;
                    this.service = this.bleDevice.GetGattService(ServiceUuid);
                }
            }

            // Get the READ characteristic in the IMBLE service.
            this.readCharacteristic = this.service.GetCharacteristics(ReadCharacteristicUuid).Single();
            EventSubscription.Subscribe <GattCharacteristic, GattValueChangedEventArgs>(
                handler => this.readCharacteristic.ValueChanged += handler,
                handler => this.readCharacteristic.ValueChanged -= handler,
                (sender, args) =>
            {
                if (args.CharacteristicValue.Length < 4)
                {
                    return;                                          // The length of data is too short.
                }
                var data   = args.CharacteristicValue.ToArray();
                var length = data[0] + 1;
                if (data.Length < length)
                {
                    return;                           // The length field is invalid. Ignore this data.
                }
                var body = new byte[length - 4];
                Array.Copy(data, 4, body, 0, body.Length);
                this.DataArrived?.Invoke(this, new DataArrivedEventArgs(body, args.Timestamp));
            })
            .AddTo(this.disposables);

            // Enable notification of the READ characteristic.
            var readCccdResult = await this.readCharacteristic.ReadClientCharacteristicConfigurationDescriptorAsync().AsTask(cancellationToken);

            var readCccd = readCccdResult.ClientCharacteristicConfigurationDescriptor | GattClientCharacteristicConfigurationDescriptorValue.Notify;

            for (var retryCount = 0;; retryCount++)
            {
                try
                {
                    using (var timeoutCancel = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
                        using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancel.Token))
                        {
                            await this.readCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(readCccd).AsTask(linkedTokenSource.Token);
                        }
                    break;
                }
                catch (Exception ex)
                {
                    if (retryCount > 3)
                    {
                        throw new ImbleOperationException("Failed to configure the device.", ex);
                    }
                }
            }

            this.writeCharacteristic = this.service.GetCharacteristics(WriteCharacteristicUuid).Single();

            EventSubscription.Subscribe <TypedEventHandler <BluetoothLEDevice, object> >(
                handler => this.bleDevice.ConnectionStatusChanged += handler,
                handler => this.bleDevice.ConnectionStatusChanged -= handler,
                (device, _) =>
            {
                this.ConnectionStatus = device.ConnectionStatus;
            })
            .AddTo(this.disposables);

            this.ConnectionStatus = this.service.Device.ConnectionStatus;

            this.Status = ImbleDeviceStatus.Running;
        }