예제 #1
0
        /// <summary>
        /// Connects to known device async.
        ///
        /// https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForInteractingWithARemotePeripheralDevice/BestPracticesForInteractingWithARemotePeripheralDevice.html
        ///
        /// </summary>
        /// <returns>The to known device async.</returns>
        /// <param name="deviceGuid">Device GUID.</param>
        public async Task <Device> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default(ConnectParameters), CancellationToken cancellationToken = default(CancellationToken), bool dontThrowExceptionOnNotFound = false)
        {
            // Wait for the PoweredOn state
            await WaitForState(CBManagerState.PoweredOn, cancellationToken, true);

            if (cancellationToken.IsCancellationRequested)
            {
                throw new TaskCanceledException("ConnectToKnownDeviceAsync cancelled");
            }

            //FYI attempted to use tobyte array insetead of string but there was a problem with byte ordering Guid->NSUui
            var uuid = new NSUuid(deviceGuid.ToString());

            Trace.Message($"[Adapter] Attempting connection to {uuid}");

            var peripherials = _centralManager.RetrievePeripheralsWithIdentifiers(uuid);
            var peripherial  = peripherials.SingleOrDefault();

            if (peripherial == null)
            {
                var systemPeripherials = _centralManager.RetrieveConnectedPeripherals(new CBUUID[0]);

#if __IOS__
                var cbuuid = CBUUID.FromNSUuid(uuid);
#endif
                peripherial = systemPeripherials.SingleOrDefault(p =>
#if __IOS__
                                                                 p.UUID.Equals(cbuuid)
#else
                                                                 p.Identifier.Equals(uuid)
#endif
                                                                 );

                if (peripherial == null)
                {
                    if (dontThrowExceptionOnNotFound == true)
                    {
                        return(null);
                    }

                    throw new DeviceNotFoundException(deviceGuid);
                }
            }

            var device = new Device(this, peripherial, _bleCentralManagerDelegate, peripherial.Name, 0, new List <AdvertisementRecord>());

            await ConnectToDeviceAsync(device, connectParameters, cancellationToken);

            return(device);
        }
        internal void Connect(ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            IsOperationRequested = true;

            if (connectParameters.ForceBleTransport)
            {
                ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect, cancellationToken);
            }
            else
            {
                var connectGatt = NativeDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback);
                _connectCancellationTokenRegistration.Dispose();
                _connectCancellationTokenRegistration = cancellationToken.Register(() => DisconnectAndClose(connectGatt));
            }
        }
        protected async Task ConnectToDeviceNativeAsync(Device device, ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            Trace.Message($"Connecting to device with ID:  {device.Id.ToString()}");

            if (!(device.NativeDevice is ObservableBluetoothLEDevice nativeDevice))
            {
                return;
            }

            nativeDevice.PropertyChanged -= Device_ConnectionStatusChanged;
            nativeDevice.PropertyChanged += Device_ConnectionStatusChanged;

            ConnectedDeviceRegistry[device.Id.ToString()] = device;

            await nativeDevice.ConnectAsync();
        }
예제 #4
0
        public async Task <Device> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default(ConnectParameters), CancellationToken cancellationToken = default(CancellationToken), bool dontThrowExceptionOnNotFound = false)
        {
            var macBytes     = deviceGuid.ToByteArray().Skip(10).Take(6).ToArray();
            var nativeDevice = _bluetoothAdapter.GetRemoteDevice(macBytes);

            if (nativeDevice == null)
            {
                if (dontThrowExceptionOnNotFound == true)
                {
                    return(null);
                }

                throw new DeviceNotFoundException(deviceGuid);
            }

            var device = new Device(this, nativeDevice, null, 0, new byte[] { });

            await ConnectToDeviceAsync(device, connectParameters, cancellationToken);

            return(device);
        }
        protected Task ConnectToDeviceNativeAsync(Device device, ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            if (connectParameters.AutoConnect)
            {
                Trace.Message("Warning: Autoconnect is not supported in iOS");
            }

            _deviceOperationRegistry[device.Id.ToString()] = device;

            _centralManager.ConnectPeripheral(device.NativeDevice as CBPeripheral,
                                              new PeripheralConnectionOptions());

            // this is dirty: We should not assume, AdapterBase is doing the cleanup for us...
            // move ConnectToDeviceAsync() code to native implementations.
            cancellationToken.Register(() =>
            {
                Trace.Message("Canceling the connect attempt");
                _centralManager.CancelPeripheralConnection(device.NativeDevice as CBPeripheral);
            });

            return(Task.FromResult(true));
        }
        public async Task <Device> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default, CancellationToken cancellationToken = default, bool dontThrowExceptionOnNotFound = false)
        {
            //convert GUID to string and take last 12 characters as MAC address
            var guidString       = deviceGuid.ToString("N").Substring(20);
            var bluetoothAddress = Convert.ToUInt64(guidString, 16);
            var nativeDevice     = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress);


            if (nativeDevice == null)
            {
                if (dontThrowExceptionOnNotFound == true)
                {
                    return(null);
                }

                throw new DeviceNotFoundException(deviceGuid);
            }

            var knownDevice = new Device(this, nativeDevice, 0, deviceGuid);

            await ConnectToDeviceAsync(knownDevice, cancellationToken : cancellationToken);

            return(knownDevice);
        }
예제 #7
0
 /// <summary>
 /// Connects to a known device asynchronously.
 /// </summary>
 /// <param name="deviceGuid">The device unique identifier.</param>
 /// <param name="connectParameters">The connection parameters.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="dontThrowExceptionOnNotFound">if set to <c>true</c> [dont throw exception on not found].</param>
 /// <returns></returns>
 /// <exception cref="PlatformNotSupportedException"></exception>
 public Task <Device> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default, CancellationToken cancellationToken = default(CancellationToken), bool dontThrowExceptionOnNotFound = false) => throw new PlatformNotSupportedException();
예제 #8
0
 protected Task ConnectToDeviceNativeAsync(Device device, ConnectParameters connectParameters, CancellationToken cancellationToken) => throw new PlatformNotSupportedException();
예제 #9
0
 protected Task ConnectToDeviceNativeAsync(Device device, ConnectParameters connectParameters,
                                           CancellationToken cancellationToken)
 {
     ((Device)device).Connect(connectParameters, cancellationToken);
     return(Task.CompletedTask);
 }
 /// <summary>
 /// Connects to the <paramref name="device"/>.
 /// </summary>
 /// <param name="adapter">Target adapter.</param>
 /// <param name="device">Device to connect to.</param>
 /// <param name="connectParameters">Connection parameters. Contains platform specific parameters needed to achieved connection. The default value is None.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.</param>
 /// <returns>A task that represents the asynchronous read operation. The Task will finish after the device has been connected successfuly.</returns>
 /// <exception cref="DeviceConnectionException">Thrown if the device connection fails.</exception>
 public static Task ConnectToDeviceAsync(this Adapter adapter, Device device, ConnectParameters connectParameters, CancellationToken cancellationToken)
 {
     return(adapter.ConnectToDeviceAsync(device, connectParameters: connectParameters, cancellationToken: cancellationToken));
 }