Esempio n. 1
0
        /// <summary>
        /// Connect to the device given host name
        /// </summary>
        /// <param name="deviceHostName">Raw host name of the device</param>
        /// <returns>True if connected successfully. Else False</returns>
        public async Task <bool> ConnectAsync(string deviceHostName)
        {
            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (!_adapter.IsEnabled)
            {
                throw new Exception("Bluetooth is off. Please turn it on from settings.");
            }

            SelectedDevice = _adapter.BondedDevices.FirstOrDefault(d => d.Address == deviceHostName);

            if (SelectedDevice != null)
            {
                var uuids = SelectedDevice.GetUuids();
                if (uuids != null && uuids.Length > 0)
                {
                    return(await Task.Run <bool>(() =>
                    {
                        _socket = SelectedDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuids[0].ToString()));
                        _socket.Connect();
                        return IsConnected;
                    }));
                }
            }

            return(IsConnected);
        }
Esempio n. 2
0
        public async Task ConnectAsync()
        {
            try
            {
                _socket = SelectedDevice.CreateRfcommSocketToServiceRecord(_myUuid);
                await _socket.ConnectAsync();

                await Task.Run(() =>
                {
                    var reader = new BinaryReader(_socket.InputStream);

                    while (true)
                    {
                        try
                        {
                            int size = reader.ReadInt16();
                            var b    = reader.ReadBytes(size);

                            ReportReceived?.Invoke(this, new ReportReceivedEventArgs {
                                Report = b
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            break;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Disconnect();
                Console.WriteLine(ex.Message);
            }
        }