Ejemplo n.º 1
0
        /// <summary>
        /// Find and connect to a device using its MAC address
        /// </summary>
        /// <param name="iDevice">Device info providing a MAC address</param>
        /// <param name="iMTU">Required MTU for connection (specify 0 if not required)</param>
        /// <param name="iServices">List of services and characteristic we are going to use</param>
        /// <param name="iBond">Optional parameter you set to true if you wish to pair (bond) with the device</param>
        /// <param name="iConnectionEvent">Optional callback event for connection success or failure</param>
        public void ConnectToDevice(DeviceInfo iDevice,
                                    int iMTU,
                                    List <ServiceAndCharacteristicsParcel> iServices,
                                    bool iBond = false,
                                    EventHandler <SuccessEventArgs> iConnectionEvent = null)
        {
            // Ensure the adaptor is present
            CreateAdaptor();

            // Find the BluetoothDevice already scanned
            string mac = MacAddressUtils.MacAddressAsString(iDevice.DeviceId, true);

            // Clear some fields
            _mtu = DEFAULT_MTU;
            _servicesDiscovered = false;

            // Specify the services and characteristics we are going to use
            _bleManager.ServiceAndCharacteristics(iServices);

            // Locate the device object - must have already been scanned
            BluetoothDevice bluetoothDevice = FoundDevices.FirstOrDefault(d => d.Address == mac);

            // Create the connection request
            ConnectRequest request = _bleManager.Connect(bluetoothDevice);

            // Add in handlers if specified
            if (iConnectionEvent != null)
            {
                _connectionSuccessEventArgs = iConnectionEvent;
                request
                .Done(new SuccessCallBack(ConnectionRequestEvent))
                .Fail(new SuccessCallBack(ConnectionRequestEvent));
            }
            else
            {
                _connectionSuccessEventArgs = null;
            }

            // Enqueue the connection request and process it
            request.Retry(CONNECT_RETRIES, CONNECT_RETRY_DELAY_MS)
            .UseAutoConnect(false)
            .Enqueue();

            // Bond to the device if required
            if (iBond)
            {
                // Request bonding with device
                _bleManager.BondToDevice(new SuccessCallBack(_bleManager_DeviceBondedEvent));
            }

            // Enqueue an MTU request if required
            if (iMTU != 0)
            {
                Thread.Sleep(50);
                _bleManager.MakeMtuRequest(iMTU);
            }
        }