Ejemplo n.º 1
0
Archivo: Ssh.cs Proyecto: 4vz/Aveezo
        private async Task Main()
        {
            IsReconnect = true;

            while (true)
            {
                try
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }

                    await OnBeforeConnect();

                    BeforeConnect?.Invoke(this, new EventArgs());

                    client = new SshClient(Host, User, Password);

                    await OnConnecting();

                    Connecting?.Invoke(this, new EventArgs());

                    client.Connect();
                }
                catch (Exception ex)
                {
                    var connectionFailArgs = new SshConnectionFailEventArgs(ex.Message switch
                    {
                        "No such host is known" => SshConnectionFailReason.HostUnknown,
                        "A socket operation was attempted to an unreachable host." => SshConnectionFailReason.HostUnreachable,
                        string b when b.IndexOf("connected party did not properly") > -1 => SshConnectionFailReason.TimeOut,
                        "Permission denied (password)." => SshConnectionFailReason.AuthenticationFailed,
                        _ => SshConnectionFailReason.Unknown
                    }, ex.Message);
Ejemplo n.º 2
0
        protected virtual bool OnConnecting(IPEndPoint ip, NetSessionId sessionId)
        {
            var args = new NetConnectingArgs(sessionId, ip);

            Connecting?.Invoke(this, args);
            return(!args.Deny);
        }
Ejemplo n.º 3
0
 private ConnectWidget(Builder builder) : base(builder.GetObject(typeof(ConnectWidget).Name).Handle)
 {
     builder.Autoconnect(this);
     _cvAccept.Clicked += new EventHandler((o, e) =>
     {
         try
         {
             string sHost = _cvEnterIP.Text, sPort = _cvEnterPort.Text, sName = _cvEnterName.Text;
             if (int.TryParse(sPort, out int port))
             {
                 IPAddress iPAddress;
                 IPHostEntry iPHostEntry = Dns.GetHostEntry(sHost);
                 if (!IPAddress.TryParse(sHost, out iPAddress))
                 {
                     iPAddress = iPHostEntry.AddressList[0];
                 }
                 IPEndPoint iPEndPoint                  = new IPEndPoint(iPAddress, port);
                 ClientManager clientManager            = new ClientManager(new GameCore.Game());
                 Client <IServer, ClientManager> client = new Client <IServer, ClientManager>(clientManager, iPEndPoint);
                 clientManager.SetServer(client.Server, sName);
                 Connecting?.Invoke(this, new EventArgsConnecting(iPEndPoint, client, sName));
             }
             else
             {
                 throw new Exception($"Неверный порт: {sPort}");
             }
         }
         catch (Exception ex)
         {
             ErrorValidating?.Invoke(this, new EventArgsValue <Exception>(ex));
         }
     });
     _cvCancel.Clicked += new EventHandler((o, e) => Cancel?.Invoke(this, EventArgs.Empty));
 }
Ejemplo n.º 4
0
 // When the socket is connecting to the host.
 protected virtual void OnConnecting(EndPoint remoteEndPoint)
 {
     Connecting?.Invoke(this, new SocketConnectEventArgs()
     {
         RemoteEndPoint = remoteEndPoint
     });
 }
Ejemplo n.º 5
0
        public async Task ConnectAsync()
        {
            if (IsConnected)
            {
                return;
            }

            try
            {
                Connecting?.Invoke(this, new ConnectionEventArgs($"Try to Connect to SignalR Hub"));

                await _hubConnection.StartAsync().ConfigureAwait(false);

                if (!IsConnected)
                {
                    throw new InvalidOperationException($"Connecting to SignalR Hub failed.");
                }

                Connected?.Invoke(this, new ConnectionEventArgs($"Successfully Connected to SignarR Hub. ConnectionId:{_hubConnection.ConnectionId}"));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                ConnectionFailed?.Invoke(this, new ConnectionEventArgs(ex.Message));
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Internal thread Run code
 /// </summary>
 /// <param name="token">Triggering a cancellation notification when the user calls the Stop method</param>
 protected override void DoRun(CancellationToken token)
 {
     mListener = new TcpListener(mListenerPoint);
     mListener.Start();
     try
     {
         while (!token.IsCancellationRequested)
         {
             if (mListener.Pending())
             {
                 var tcpClient = mListener.AcceptTcpClient();
                 var e         = new ConnectingEventArgs(tcpClient);
                 Connecting?.Invoke(this, e);
                 if (e.Cancel)
                 {
                     tcpClient.Close();
                     continue;
                 }
                 CreateNewServerClient(tcpClient);
             }
             else
             {
                 Thread.Sleep(WaitPendingTime);
             }
         }
     }
     finally
     {
         mListener.Stop();
     }
 }
Ejemplo n.º 7
0
        public ClientWorld(ClientOptions options) : base(options, new ClientWorldCreator(options))
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));

            Connected    += i => NetworkId = i;
            Disconnected += () => NetworkId = 0;

            void OnWorldCreate()
            {
                HookSystem hookSystem = World.GetHookSystem();

                hookSystem.RegisterHook <DisconnectedEvent>(e => Disconnected?.Invoke());
                hookSystem.RegisterHook <ConnectionInitiatedEvent>(e => Connecting?.Invoke());
                hookSystem.RegisterHook <ConnectionCompleteEvent>(e =>
                {
                    Connected?.Invoke(World.EntityManager
                                      .GetComponentData <NetworkIdComponent>(
                                          World.GetExistingSystem <CreateRpcRequestSystem>().CommandTargetComponentEntity)
                                      .Value);
                });
                hookSystem.RegisterHook <ConnectionFailedEvent>(e =>
                                                                ConnectionFailed?.Invoke(((ConnectionFailedEvent)e).Message.ToString()));
            }

            if (WorldCreator.WorldIsCreated)
            {
                OnWorldCreate();
            }

            WorldCreated += OnWorldCreate;
        }
Ejemplo n.º 8
0
        public bool Connect(string host, int port, string password)
        {
            Connecting?.Invoke(this, EventArgs.Empty);

            try
            {
                if (!rcon.Connect(host, port))
                {
                    throw new Exception("Connection to server failed. Check your host and port.");
                }

                if (!rcon.Authenticate(password))
                {
                    Disconnect();
                    throw new Exception("Authentication with server failed. The password is incorrect.");
                }
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, ex.Message);
                throw;
            }

            Connected?.Invoke(this, EventArgs.Empty);

            return(true);
        }
Ejemplo n.º 9
0
        protected virtual bool OnConnecting(string ip)
        {
            var args = new NetConnectingArgs(ip);

            Connecting?.Invoke(this, args);
            return(!args.Deny);
        }
Ejemplo n.º 10
0
        public async Task Connect()
        {
            _client = new TcpClient();
            Connecting?.Invoke(this, EventArgs.Empty);
            while (!_client.Connected)
            {
                try
                {
                    await _client.ConnectAsync(_address.ToString(), _portno);

                    Connected?.Invoke(this, EventArgs.Empty);
                    _reader = new StreamReader(_client.GetStream());
                    _writer = new StreamWriter(_client.GetStream())
                    {
                        AutoFlush = true
                    };
                    StartReading();
                    Write(new ClientStatusChanged()
                    {
                        Status   = "online",
                        Username = _username
                    });
                }
                catch (Exception)
                {
                    await Task.Delay(5000);
                }
            }
        }
Ejemplo n.º 11
0
        public async void StartWithReconnectionAsync()
        {
            if (connection.State != HubConnectionState.Disconnected)
            {
                return;
            }

            Connecting?.Invoke(this, null);
            connection.Closed      += OnConnectionClosed;
            connection.Reconnected += OnConnectionReconnected;

            connection.On <MessageItem>("NewMessage", NewMessage);

            while (true)
            {
                try
                {
                    await connection.StartAsync();

                    break;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"SignalR error {ex.Message}");
                    await Task.Delay(3000);
                }
            }

            Debug.WriteLine($"SignalR connected");
            await Init();

            Connected?.Invoke(this, null);
        }
Ejemplo n.º 12
0
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            base.OnConnectionStateChange(gatt, status, newState);

            switch (newState)
            {
            case ProfileState.Connecting:
                Connecting?.Invoke(this, EventArgs.Empty);

                break;

            case ProfileState.Connected:
                Connected?.Invoke(this, EventArgs.Empty);

                break;

            case ProfileState.Disconnecting:
                Disconnecting?.Invoke(this, EventArgs.Empty);

                break;

            case ProfileState.Disconnected:
                Disconnected?.Invoke(this, EventArgs.Empty);

                break;
            }
        }
Ejemplo n.º 13
0
        public virtual void OnConnecting()
        {
            lock (_stateLock) {
                State = ConnectionState.Connecting;
            }

            Connecting?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 14
0
        public void Connect()
        {
            TvDirectSocket = new Windows.Networking.Sockets.StreamSocket();
            TvDirectSocket.ConnectAsync(ConnectedHostName, ConnectedPort.ToString()).Completed += newConnected;
            ConnectionState = TvConnectionState.Connecting;

            Connecting?.Invoke();
        }
Ejemplo n.º 15
0
        async public Task Connect(GitLabInstance gitLabInstance, DataCacheConnectionContext connectionContext)
        {
            assertNotConnected();

            string          hostname       = gitLabInstance.HostName;
            IHostProperties hostProperties = gitLabInstance.HostProperties;

            _operator = new DataCacheOperator(hostname, hostProperties, gitLabInstance.NetworkOperationStatusListener);
            DataCacheOperator myOperator = _operator;

            _isConnecting = true;
            try
            {
                Connecting?.Invoke(hostname);

                InternalCacheUpdater cacheUpdater = new InternalCacheUpdater(new InternalCache());
                bool isApprovalStatusSupported    = await gitLabInstance.IsApprovalStatusSupported();

                IMergeRequestListLoader mergeRequestListLoader = new MergeRequestListLoader(
                    hostname, _operator, cacheUpdater,
                    _cacheContext.Callbacks, connectionContext.QueryCollection,
                    isApprovalStatusSupported);

                traceInformation(String.Format("Connecting data cache to {0}...", hostname));
                string accessToken = hostProperties.GetAccessToken(hostname);
                await new CurrentUserLoader(_operator).Load(hostname, accessToken);
                User currentUser = GlobalCache.GetAuthenticatedUser(hostname, accessToken);

                await mergeRequestListLoader.Load();

                _internal = createCacheInternal(cacheUpdater, hostname, hostProperties, currentUser,
                                                connectionContext.QueryCollection, gitLabInstance.ModificationNotifier,
                                                gitLabInstance.NetworkOperationStatusListener, isApprovalStatusSupported);

                ConnectionContext = connectionContext;
                traceInformation(String.Format("Data cache connected to {0}", hostname));
                Connected?.Invoke(hostname, currentUser);
            }
            catch (BaseLoaderException ex)
            {
                reset();

                if (ex is BaseLoaderCancelledException)
                {
                    throw new DataCacheConnectionCancelledException();
                }
                throw new DataCacheException(ex.OriginalMessage, ex);
            }
            finally
            {
                _isConnecting = false;
            }
        }
Ejemplo n.º 16
0
 protected virtual bool Connect(bool isNormal)
 {
     if (IsConnected)
     {
         Disconnect(isNormal);
     }
     Connecting?.Invoke();
     if (ConnectInternal(isNormal))
     {
         IsConnected = true;
         Connected?.Invoke();
     }
     return(true);
 }
Ejemplo n.º 17
0
        public async Task Connect()
        {
            _logService.Start();
            Connecting?.Invoke(this, null);
            _server                        = new Server();
            _server.ApiKey                 = Properties.Settings.Default.ApiKey;
            _server.OnDistressSignal      += server_OnDistressSignal;
            _server.OnConnectionClosed    += server_OnConnectionClosed;
            _server.DistressSignalCreated += _server_DistressSignalCreated;
            await _server.Connect();

            Connected?.Invoke(this, null);
            IsConnected = true;
        }
Ejemplo n.º 18
0
        public static bool Connect()
        {
            Disconnect();

            current = getServer();

            if (current == null)
            {
                return(false);
            }

            Connecting?.Invoke();

            return(true);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Tries to establich a connection to Soundpad
        /// </summary>
        /// <returns></returns>
        public async Task ConnectAsync()
        {
            Connecting?.Invoke(this, EventArgs.Empty);
            try {
                await _pipe.ConnectAsync(ConnectionTimeout);
            } catch {
                if (AutoReconnect)
                {
                    await Task.Delay(ReconnectInterval);
                    await ConnectAsync();

                    return;
                }
            }

            Connected?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 20
0
        public async Task StartAsync(bool automaticRetry, Exception exception = null)
        {
            if (Running)
            {
                throw new InvalidOperationException("The SignalR client is running.");
            }
            Running = true;

            AutomaticRetry = automaticRetry;
            await Task.Run(() =>
            {
                while (true)
                {
                    if (exception is null)
                    {
                        Connecting?.Invoke(this);
                    }
                    else
                    {
                        Reconnecting?.Invoke(this, exception);
                    }

                    try
                    {
                        Connection.StartAsync().Wait();
                        Connected?.Invoke(this);
                        RetryCount = 0;
                        return;
                    }
                    catch (Exception ex)
                    {
                        RetryCount++;
                        Exception?.Invoke(this, ex);
                        if (!AutomaticRetry || RetryCount >= MaxRetry)
                        {
                            HandleFailed(ex);
                            throw;
                        }

                        Thread.Sleep(ExceptionRetryDelay);
                        continue;
                    }
                }
            });
        }
Ejemplo n.º 21
0
        public void Connect()
        {
            _vanillaClient.OnConnected  += (o, e) => _vanillaClient.Send(new ClientVersionCheck(Config.MAJOR, Config.MINOR, Config.BUILD));
            _vanillaClient.Disconnected += (o, e) => Reconnect();

            Connecting?.Invoke(this, EventArgs.Empty);

            var serverIP = GetIP();

            if (serverIP != null)
            {
                _vanillaClient.Connect(serverIP, 8080);
            }
            else
            {
                Reconnect();
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Opens this PortBridgeServerProxy instance and listens for new connections coming through Service Bus.
        /// </summary>
        /// <exception cref="System.Security.SecurityException">Throws a SecurityException if Group Policy prohibits Resource Publishing.</exception>
        public async Task Open()
        {
            if (this.IsOpen)
            {
                throw new InvalidOperationException();
            }

            this.listener             = new HybridConnectionListener(connectionString.ToString());
            this.listener.Online     += (s, e) => { Online?.Invoke(this, e); };
            this.listener.Offline    += (s, e) => { Offline?.Invoke(this, e); };
            this.listener.Connecting += (s, e) => { Connecting?.Invoke(this, e); };

            await listener.OpenAsync(shuttingDown.Token);

            this.IsOpen = true;

            AcceptLoopAsync().Fork(this);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="et"></param>
        /// <param name="arg"></param>
        private void CompleteProcessing(EventEntry entry)
        {
            switch (entry.Type)
            {
            case EventType.Connecting:
                Connecting?.Invoke(this, ( int )entry.Argument);
                break;

            case EventType.Listening:
                Listening?.Invoke(this, ( int )entry.Argument);
                break;

            case EventType.Connected:
                Connected?.Invoke(this, ( int )entry.Argument);
                break;

            case EventType.Disconnected:
                Disconnected?.Invoke(this, ( int )entry.Argument);
                break;

            case EventType.Terminated:
                Terminated?.Invoke(this, EventArgs.Empty);
                break;

            case EventType.Sent:
                Sent?.Invoke(this, (Tuple <byte [], Message>)entry.Argument);
                break;

            case EventType.Received:
                Received?.Invoke(this, (Tuple <byte [], Message>)entry.Argument);
                break;

            case EventType.T3Timeout:
                T3Timeout?.Invoke(this, ( Message )entry.Argument);
                break;

            default: break;
            }
        }
Ejemplo n.º 24
0
        public void Connect()
        {
            _remoteClient.OnConnected += (s, e) =>
            {
                Console.WriteLine("Connected to remoteServer");
                ((Client)s).thread.Abort();
                var serverIP = GetIP();
                if (serverIP != null)
                {
                    _vanillaClient.Connect(serverIP, 8080);
                }
                else
                {
                    Reconnect();
                }
            };

            _vanillaClient.OnConnected  += (o, e) => _vanillaClient.Send(new ClientVersionCheck(Config.MAJOR, Config.MINOR, Config.BUILD));
            _vanillaClient.Disconnected += (o, e) => Reconnect();
            _remoteClient.Disconnected  += (o, e) => Reconnect();

            Connecting?.Invoke(this, EventArgs.Empty);
            _remoteClient.Connect(_ip, 8082);
        }
Ejemplo n.º 25
0
        public async Task ConnectAsync(string macAddress, string serviceUuid, bool noRetry = false)
        {
            if (IsConnecting)
            {
                Log.Debug($"WindowsRT.BluetoothService: Already connecting. Skipping request.");
                return;
            }
            if (IsStreamConnected)
            {
                Log.Debug($"WindowsRT.BluetoothService: Already connected. Skipping request.");
                return;
            }

            Connecting?.Invoke(this, EventArgs.Empty);

            try
            {
                var matches = _deviceCache.Where(x =>
                                                 string.Equals(x.Address, macAddress, StringComparison.CurrentCultureIgnoreCase)).ToList();
                if (matches.Count <= 0)
                {
                    Log.Error(
                        $"WindowsRT.BluetoothService: Registered device not available. Expected MAC: {macAddress}");
                    BluetoothErrorAsync?.Invoke(this, new BluetoothException(
                                                    BluetoothException.ErrorCodes.ConnectFailed,
                                                    "Device unavailable. Not device with registered MAC address not found nearby. If you are certain that your earbuds are connected to this computer, please unregister them and try again."));
                }
                else
                {
                    Log.Debug(
                        $"WindowsRT.BluetoothService: Selected '{matches[0].Name}' ({matches[0].Address}) from cache as target");
                }

                // Perform device access checks before trying to get the device.
                // First, we check if consent has been explicitly denied by the user.
                var accessStatus = DeviceAccessInformation.CreateFromId(matches[0].Id).CurrentStatus;
                if (accessStatus == DeviceAccessStatus.DeniedByUser)
                {
                    Log.Error($"WindowsRT.BluetoothService: Access to device explicitly denied by user");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"));
                    return;
                }

                if (accessStatus == DeviceAccessStatus.DeniedBySystem)
                {
                    Log.Error($"WindowsRT.BluetoothService: Access to device denied by system");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "Access denied by system. This app does not have access to connect to the remote device"));
                    return;
                }

                // If not, try to get the Bluetooth device
                try
                {
                    _bluetoothDevice = await Windows.Devices.Bluetooth.BluetoothDevice.FromIdAsync(matches[0].Id);
                }
                catch (Exception ex)
                {
                    Log.Error(
                        $"WindowsRT.BluetoothService: Error while getting Bluetooth device from cached id: {ex.Message}");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       ex.Message));
                    return;
                }

                // If we were unable to get a valid Bluetooth device object,
                // it's most likely because the user has specified that all unpaired devices
                // should not be interacted with.
                if (_bluetoothDevice == null)
                {
                    Log.Error($"WindowsRT.BluetoothService: BluetoothDevice.FromIdAsync returned NULL");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "Unable to retrieve device object. Try to re-pair your Bluetooth device."));
                    return;
                }

                // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call
                var rfcommServices = await _bluetoothDevice.GetRfcommServicesForIdAsync(
                    RfcommServiceId.FromUuid(new Guid(serviceUuid)), BluetoothCacheMode.Uncached);

                if (rfcommServices.Services.Count > 0)
                {
                    _service = rfcommServices.Services[0];
                }
                else
                {
                    Log.Error($"WindowsRT.BluetoothService: SPP service not discovered");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "Unable to discover SDP record for the RFCOMM protocol. Either your earbuds are out of range or ran out of battery."));
                    return;
                }

                lock (this)
                {
                    _socket = new StreamSocket();
                }

                try
                {
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);

                    Connected?.Invoke(this, EventArgs.Empty);
                    Log.Debug($"WindowsRT.BluetoothService: Connected");

                    _writer = new DataWriter(_socket.OutputStream);

                    Log.Debug("WindowsRT.BluetoothService: Launching BluetoothServiceLoop...");
                    RfcommConnected?.Invoke(this, EventArgs.Empty);

                    IsStreamConnected = true;

                    _loopCancellation = new CancellationTokenSource();
                    _loop             = Task.Run(BluetoothServiceLoop);
                }
                catch (Exception ex) when((uint)ex.HResult == 0x80070490)   // ERROR_ELEMENT_NOT_FOUND
                {
                    Log.Error(
                        "WindowsRT.BluetoothService: Error while connecting (HRESULT: ERROR_ELEMENT_NOT_FOUND): " +
                        ex.Message);
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "SPP server on remote device unavailable. Please reboot your earbuds by placing both into the case and closing it. (ERROR_ELEMENT_NOT_FOUND)"));
                }
                catch (Exception ex) when((uint)ex.HResult == 0x80072740)   // WSAEADDRINUSE
                {
                    Log.Error("WindowsRT.BluetoothService: Address already in use");
                    BluetoothErrorAsync?.Invoke(this,
                                                new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                       "Target address already in use. Only one app can talk to the Galaxy Buds at a time. " +
                                                                       "Please make sure to close duplicate instances of this app and close all applications that are interacting with the proprietary RFCOMM protocol, such as Samsung's official firmware updater"));
                }
            }
            catch (Exception ex)
            {
                Log.Error("WindowsRT.BluetoothService: Unknown error while connecting: " + ex);
                BluetoothErrorAsync?.Invoke(this,
                                            new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed,
                                                                   ex.Message));
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Called before the network connects to the server.
 /// </summary>
 /// <param name="sender">The sender instance.</param>
 /// <param name="ev">The <see cref="ConnectingEventArgs"/> instance.</param>
 protected virtual void OnConnecting(object sender, ConnectingEventArgs ev) => Connecting?.Invoke(sender, ev);
Ejemplo n.º 27
0
        public async Task ConnectAsync(string macAddress, string uuid, bool noRetry = false)
        {
            var semResult = await _connSemaphore.WaitAsync(5000);

            if (semResult == false)
            {
                Log.Error($"Windows.BluetoothService: Connection attempt timed out due to blocked semaphore");
                throw new BluetoothException(BluetoothException.ErrorCodes.TimedOut, "Timed out while waiting to enter connection phase. Another task is already preparing a connection.");
            }

            if (_client?.Connected ?? false)
            {
                Log.Debug("Windows.BluetoothService: Already connected, skipped.");
                _connSemaphore.Release();
                return;
            }

            SelectAdapter();

            Connecting?.Invoke(this, EventArgs.Empty);
            Log.Debug($"Windows.BluetoothService: Connecting...");

            _cancelSource?.Cancel();
            _client?.Close();
            _client = null;
            SelectAdapter();

            if (_client == null)
            {
                Log.Error("Windows.BluetoothService: Cannot create client and connect.");
                BluetoothErrorAsync?.Invoke(this, new BluetoothException(BluetoothException.ErrorCodes.Unknown, "Cannot create client"));
                _connSemaphore.Release();
                return;
            }

            try
            {
                try
                {
                    var addr = MacUtils.ToAddress(macAddress);
                    if (addr == null)
                    {
                        Log.Error("Windows.BluetoothService: Invalid MAC address. Failed to connect.");
                        throw new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed, "Invalid MAC address. Please deregister your device and try again.");
                    }

                    _currentMac  = macAddress;
                    _currentUuid = uuid;

                    _client.Connect(addr, new Guid(uuid));

                    /*await  Task.Factory.FromAsync(
                     *  (callback, stateObject) => _client.BeginConnect(addr, new Guid(uuid), callback, stateObject),
                     *  _client.EndConnect, null);*/
                }
                catch (ArgumentException)
                {
                    BluetoothErrorAsync?.Invoke(this, new BluetoothException(
                                                    BluetoothException.ErrorCodes.ConnectFailed,
                                                    $"Invalid MAC address. Please deregister your device and try again."));
                    _connSemaphore.Release();
                    return;
                }

                Connected?.Invoke(this, EventArgs.Empty);
                Log.Debug($"Windows.BluetoothService: Connected. Launching BluetoothServiceLoop.");

                _cancelSource = new CancellationTokenSource();
                _loop         = Task.Run(BluetoothServiceLoop, _cancelSource.Token);
            }
            catch (SocketException e)
            {
                BluetoothErrorAsync?.Invoke(this,
                                            new BluetoothException(BluetoothException.ErrorCodes.ConnectFailed, e.Message));
            }
            finally
            {
                _connSemaphore.Release();
            }
        }
Ejemplo n.º 28
0
        private BluetoothImpl()
        {
            try
            {
                if (PlatformUtils.IsWindows && SettingsProvider.Instance.UseBluetoothWinRT &&
                    PlatformUtils.IsWindowsContractsSdkSupported)
                {
                    Log.Debug("BluetoothImpl: Using WinRT.BluetoothService");
                    _backend = new Bluetooth.WindowsRT.BluetoothService();
                }
#if WindowsNoARM
                else if (PlatformUtils.IsWindows)
                {
                    Log.Debug("BluetoothImpl: Using Windows.BluetoothService");
                    _backend = new Bluetooth.Windows.BluetoothService();
                }
#else
                else if (PlatformUtils.IsWindows && PlatformUtils.IsWindowsContractsSdkSupported)
                {
                    Log.Debug("BluetoothImpl: Using WinRT.BluetoothService (ARM)");
                    _backend = new Bluetooth.WindowsRT.BluetoothService();
                }
#endif
                else if (PlatformUtils.IsLinux)
                {
                    Log.Debug("BluetoothImpl: Using Linux.BluetoothService");
                    _backend = new Bluetooth.Linux.BluetoothService();
                }
                else
                {
                    Log.Warning("BluetoothImpl: Using Dummy.BluetoothService");
                    _backend = new Dummy.BluetoothService();
                }
            }
            catch (PlatformNotSupportedException)
            {
                Log.Error("BluetoothImpl: Critical error while preparing bluetooth backend");
                Log.Error("BluetoothImpl: Backend swapped out with non-functional dummy object in order to prevent crash");
                _backend = new Dummy.BluetoothService();
            }

            _cancelSource = new CancellationTokenSource();
            _loop         = Task.Run(DataConsumerLoop, _cancelSource.Token);

            _backend.Connecting          += (sender, args) => Connecting?.Invoke(this, EventArgs.Empty);
            _backend.NewDataAvailable    += OnNewDataAvailable;
            _backend.NewDataAvailable    += (sender, bytes) => NewDataReceived?.Invoke(this, bytes);
            _backend.BluetoothErrorAsync += (sender, exception) => OnBluetoothError(exception);

            _backend.RfcommConnected += (sender, args) => Task.Run(async() =>
                                                                   await Task.Delay(150).ContinueWith((_) =>
            {
                if (RegisteredDeviceValid)
                {
                    Connected?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    Log.Error("BluetoothImpl: Suppressing Connected event, device not properly registered");
                }
            }));

            _backend.Disconnected += (sender, reason) =>
            {
                if (!SuppressDisconnectionEvents)
                {
                    Disconnected?.Invoke(this, reason);
                }
            };

            MessageReceived += SPPMessageHandler.Instance.MessageReceiver;
        }
Ejemplo n.º 29
0
            public void ProcessPackets()
            {
                while (_messageChannel.Reader.TryRead(out var item))
                {
                    switch (item)
                    {
                    case ConnectMessage connect:
                    {
                        DebugTools.Assert(IsServer);

                        var writer = connect.ChannelWriter;

                        var uid       = _genConnectionUid();
                        var sessionId = new NetSessionId($"integration_{uid}");

                        var connectArgs =
                            new NetConnectingArgs(sessionId, new IPEndPoint(IPAddress.IPv6Loopback, 0));
                        Connecting?.Invoke(this, connectArgs);
                        if (connectArgs.Deny)
                        {
                            writer.TryWrite(new DeniedConnectMessage());
                            continue;
                        }

                        writer.TryWrite(new ConfirmConnectMessage(uid, sessionId));
                        var channel = new IntegrationNetChannel(this, connect.ChannelWriter, uid, sessionId, connect.Uid);
                        _channels.Add(uid, channel);
                        Connected?.Invoke(this, new NetChannelArgs(channel));
                        break;
                    }

                    case DataMessage data:
                    {
                        IntegrationNetChannel?channel;
                        if (IsServer)
                        {
                            if (!_channels.TryGetValue(data.Connection, out channel))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (ServerChannel == null || data.Connection != ServerChannel.ConnectionUid)
                            {
                                continue;
                            }

                            channel = ServerChannel;
                        }

                        var message = data.Message;
                        message.MsgChannel = channel;
                        if (_callbacks.TryGetValue(message.GetType(), out var callback))
                        {
                            callback(message);
                        }

                        break;
                    }

                    case DisconnectMessage disconnect:
                    {
                        if (IsServer)
                        {
                            if (_channels.TryGetValue(disconnect.Connection, out var channel))
                            {
                                Disconnect?.Invoke(this, new NetDisconnectedArgs(channel, string.Empty));

                                _channels.Remove(disconnect.Connection);
                            }
                        }
                        else
                        {
                            _channels.Clear();
                        }

                        break;
                    }

                    case DeniedConnectMessage _:
                    {
                        DebugTools.Assert(IsClient);

                        ConnectFailed?.Invoke(this, new NetConnectFailArgs("I didn't implement a deny reason!"));
                        break;
                    }

                    case ConfirmConnectMessage confirm:
                    {
                        DebugTools.Assert(IsClient);

                        var channel = new IntegrationNetChannel(this, NextConnectChannel !, _clientConnectingUid,
                                                                confirm.SessionId, confirm.AssignedUid);

                        _channels.Add(channel.ConnectionUid, channel);

                        Connected?.Invoke(this, new NetChannelArgs(channel));
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
Ejemplo n.º 30
0
 private void ChannelConnecting(IChannel channel)
 {
     Connecting?.Invoke(this, new ConnectingEventArgs {
         Binding = channel.Binding, Socket = this
     });
 }