Ejemplo n.º 1
0
        public void SendTestString(BTPeer peer)
        {
            if (!Clients.ContainsKey(peer))
            {
                Log.Warn(_tag, $"Attempting to send test string to disconnected peer {peer.Device.Address}."); return;
            }

            var r       = new Random();
            var message = new Message(MsgType.PushSpeech, $"Test string {r.Next(100)}");

            RelayToast($"Sending test string '{message.Content}'.");
            Clients[peer].SendMessage(message);
        }
Ejemplo n.º 2
0
        public void Disconnect(BTPeer peer)
        {
            if (!Clients.ContainsKey(peer))
            {
                return;
            }
            if (!Clients.Keys.Any(p => p.Address == peer.Device.Address))
            {
                return;
            }

            Clients[peer].Disconnect();
            //Clients.Remove(peer);
            //RefreshDetails();
        }
Ejemplo n.º 3
0
        public void Connect(BTPeer peer)
        {
            // Make this a no-op if it's already connected, just in case.
            if (Clients.ContainsKey(peer.Device))
            {
                return;
            }
            // Maybe that's not working?
            if (Clients.Keys.Any(p => p.Address == peer.Device.Address))
            {
                return;
            }

            if (_progressDialog != null && _progressDialog.IsShowing)
            {
                _progressDialog.Dismiss();
            }
            bluetoothAdapter.CancelDiscovery();

            //_progressDialog = ProgressDialog.Show(this, $"Connecting to {_device.Name} ({_device.MACaddressOrRole})", "Press back to cancel", true, true);

            var newTeamMate = new CommsContact();

            newTeamMate.BtPeer    = peer;
            newTeamMate.Name      = peer.Device.Name;
            newTeamMate.IPaddress = peer.Device.Address;
            var client = new BluetoothClient(GlobalBluetoothDeactivator.Token);

            // Arrange for appropriate outcomes to success or failure of our connection attempt...
            client.OnConnectionSuccess += (o, e) =>
            {
                //newTeamMate.Client = client;
                //AddressBook.Add(newTeamMate);
                newTeamMate.Client = client;
                BluetoothMessageCenter.TemporaryAddressBook_SingleEntry = newTeamMate;
                Clients.Add(_device, client);
                KnownMACaddresses.Add(_device.MACaddressOrRole);
                Res.Storage.Put(KnownMACaddressesKey, KnownMACaddresses);
                _progressDialog?.Dismiss();
                RefreshDetails(true);
            };
            client.OnConnectionFailure += (o, e) =>
            {
                _progressDialog?.Dismiss();
                KnownMACaddresses.Remove(_device.MACaddressOrRole);
                Res.Storage.Put(KnownMACaddressesKey, KnownMACaddresses);
                client = null;
                RefreshDetails();
            };
            client.OnDisconnection += (o, e) =>
            {
                Clients.Remove(_device);
                RefreshDetails();
            };
            client.OnMessageReceived += (o, e) =>
            {
                RelayToast($"Client received ({e.Value.Type}) {e.Value.Content}");
            };

            //... then make the attempt itself.
            client?.Connect(newTeamMate.BtPeer);
        }
Ejemplo n.º 4
0
        public virtual void Connect(BTPeer peer, int numberOfRetries = 5)
        {
            Task.Run(async() =>
            {
                try
                {
                    socket = peer.Device.CreateRfcommSocketToServiceRecord(BluetoothServer.ServiceUUID);
                    await Task.Delay(100);
                    socket.Connect();
                    await Task.Delay(250);

                    if (socket.IsConnected)
                    {
                        Log.Debug(_tag, $"Client: Connection accepted to {socket.RemoteDevice.Address}.");
                        OnConnectionSuccess?.Invoke(this, EventArgs.Empty);
                        IsConnected = true;
                    }
                    else
                    {
                        OnConnectionFailure?.Invoke(this, EventArgs.Empty);
                        IsConnected = false;
                        if (numberOfRetries > 0)
                        {
                            Log.Debug(_tag, $"Client: Connection unsuccessful; retrying in {SocketTimeout} ms.");
                            await Task.Delay(SocketTimeout)
                            .ContinueWith((_) => { Connect(peer, numberOfRetries - 1); })
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            Log.Debug(_tag, "Client: Connection unsuccessful, retry limit exhausted.");
                        }
                        return;
                    }

                    inStream  = new DataInputStream(socket.InputStream);
                    outStream = new DataOutputStream(socket.OutputStream);

                    BluetoothCore.RunSendingLooper(this);

                    Task.Delay(500)
                    .ContinueWith(_ =>
                                  SendMessage(new Message(MsgType.Notify,
                                                          $"{CONFIRM_AS_CLIENT}{NEXT}{socket.RemoteDevice.Address}")))
                    .LaunchAsOrphan();

                    //await Task.Delay(100);
                    var ListeningLoop = Task.Run((Action)Listen); // When finished, *should* mean that it's received its stop signal and is thus ready to close.

                    //foreach (var teammate in HeyYou.MyTeammates.TeamMembers)
                    //{
                    //    var teamMate = teammate as CommsContact;
                    //    if (teamMate == null) continue;
                    //    if (teamMate.IPaddress == socket.RemoteDevice.Address) continue; // Don't bother suggesting themselves as a teammate!
                    //    SendMessage(new Message(MsgType.Notify, $"{SUGGEST_TEAMMATE}{NEXT}{teamMate.IPaddress}"));
                    //}

                    await ListeningLoop;
                }
                catch (Exception e)
                {
                    Log.Debug(_tag, e.ToString());
                }
                finally
                {
                    Log.Debug(_tag, "Closing client connection.");
                    //socket.Close();
                    //IsConnected = false;
                    Disconnect();
                }
            });
        }