示例#1
0
 /// <summary>
 /// Called when the internal SignalR client is trying to reconnect after a connection loss.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected virtual void OnReconnecting(object sender, EventArgs e)
 {
     if (State == ResonanceComponentState.Connected)
     {
         Reconnecting?.Invoke(this, e);
     }
 }
示例#2
0
 /// <summary>
 /// Connects to client.
 /// </summary>
 /// <returns>A Task that can be awaited</returns>
 protected virtual async Task ConnectToClient()
 {
     using (HttpClient client = new HttpClient())
     {
         if (hasConnected)
         {
             Reconnecting?.Invoke();
         }
         client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
         using (var stream = await client.GetStreamAsync(streamUri))
         {
             if (ReadTimeout > 0)
             {
                 stream.ReadTimeout = ReadTimeout;
             }
             if (!hasConnected)
             {
                 Connected?.Invoke();
                 hasConnected = true;
             }
             else
             {
                 Reconnected?.Invoke();
             }
             await ListensToStreamAsync(stream).ConfigureAwait(true);
         }
     }
 }
示例#3
0
        public HubConfigurator(TaskFactory sync)
        {
            Hub = new HubConnection(Settings.Default.server);

            this.sync = sync;

            Hub.Closed       += () => sync.StartNew(() => Disconnected?.Invoke());
            Hub.Reconnected  += () => sync.StartNew(() => Reconnected?.Invoke());
            Hub.Reconnecting += () => sync.StartNew(() => Reconnecting?.Invoke());

            Hub.Received += Console.WriteLine;
        }
示例#4
0
        private void OnGatewayStateChanged(GatewayStatus newState)
        {
            switch (newState)
            {
            case GatewayStatus.Resuming:
                Resuming?.Invoke();
                break;

            case GatewayStatus.Reconnecting:
                Reconnecting?.Invoke();
                break;

            case GatewayStatus.Disconnected:
                LoggedOut?.Invoke();
                break;
            }
        }
示例#5
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;
                    }
                }
            });
        }
示例#6
0
 /// <summary>
 /// Handles and fires the <see cref="OnReconnecting(EventArgs)"/> event.
 /// </summary>
 protected virtual void OnReconnecting(EventArgs e)
 {
     Reconnecting?.Invoke(this, e);
 }
示例#7
0
        /// <summary>
        /// Starts the connection.
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            if (IsStarted)
            {
                return(Task.FromResult(true));
            }

            TaskCompletionSource <object> completion = new TaskCompletionSource <object>();

            bool completed = false;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    var urlHub  = SplitUrl(Url);
                    _connection = new HubConnection(urlHub.url);
                    _proxy      = _connection.CreateHubProxy(urlHub.hub);
                    _connection.StateChanged += (x) =>
                    {
                        if (x.NewState == ConnectionState.Connected)
                        {
                            if (!completed)
                            {
                                IsStarted = true;
                                completed = true;
                                completion.SetResult(true);
                            }
                        }
                    };

                    bool reconnecting = false;

                    _connection.Error += (exception) =>
                    {
                        if (EnableAutoReconnection)
                        {
                            if (reconnecting && _connection.State == ConnectionState.Reconnecting && exception.GetType() == typeof(TimeoutException))
                            {
                                Error?.Invoke(this, new ResonanceExceptionEventArgs(exception));
                            }
                        }
                    };

                    _connection.Reconnecting += () =>
                    {
                        if (!reconnecting)
                        {
                            reconnecting = true;

                            if (EnableAutoReconnection)
                            {
                                Reconnecting?.Invoke(this, new EventArgs());
                            }
                            else if (_connection.LastError != null)
                            {
                                try
                                {
                                    Stop();
                                    Error?.Invoke(this, new ResonanceExceptionEventArgs(_connection.LastError));
                                }
                                catch { }
                            }
                        }
                    };

                    _connection.Reconnected += () =>
                    {
                        if (EnableAutoReconnection)
                        {
                            reconnecting = false;
                            Reconnected?.Invoke(this, new EventArgs());
                        }
                    };

                    _connection.Start();
                }
                catch (Exception ex)
                {
                    if (!completed)
                    {
                        completed = true;
                        completion.SetException(ex);
                    }
                }
            });

            TimeoutTask.StartNew(() =>
            {
                if (!completed)
                {
                    completed = true;
                    completion.SetException(new TimeoutException("Could not establish the connection within the given timeout."));
                }
            }, TimeSpan.FromSeconds(10));

            return(completion.Task);
        }
示例#8
0
        /// <summary>
        /// Starts the connection.
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            if (IsStarted)
            {
                return;
            }


            var builder = new HubConnectionBuilder().WithUrl(Url).WithAutomaticReconnect();

            if (UseMessagePackProtocol)
            {
                builder = builder.AddMessagePackProtocol();
            }

            if (EnableAutoReconnection)
            {
                builder = builder.WithAutomaticReconnect(new TimeSpan[]
                {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1)
                });
            }

            _connection = builder.Build();

            bool reconnecting = false;

            _connection.Closed += (exception) =>
            {
                if (EnableAutoReconnection)
                {
                    if (reconnecting && _connection.State == HubConnectionState.Disconnected && exception.GetType() == typeof(OperationCanceledException))
                    {
                        Error?.Invoke(this, new ResonanceExceptionEventArgs(exception));
                    }
                }

                return(Task.FromResult(true));
            };

            _connection.Reconnecting += (ex) =>
            {
                if (!reconnecting)
                {
                    reconnecting = true;

                    if (EnableAutoReconnection)
                    {
                        Reconnecting?.Invoke(this, new EventArgs());
                    }
                    else
                    {
                        try
                        {
                            Stop();
                            Error?.Invoke(this, new ResonanceExceptionEventArgs(ex));
                        }
                        catch { }
                    }
                }

                return(Task.FromResult(true));
            };

            _connection.Reconnected += (msg) =>
            {
                if (EnableAutoReconnection)
                {
                    Reconnected?.Invoke(this, new EventArgs());
                    reconnecting = false;
                }

                return(Task.FromResult(true));
            };

            await _connection.StartAsync();

            IsStarted = true;
        }
示例#9
0
        public void Init(string url, string token)
        {
            if (_hubConnection != null)
            {
                return;
            }

            _hubConnection = new HubConnectionBuilder()
                             .WithUrl(url, options =>
            {
                /*
                 *  The access token function you provide is called before every HTTP request made by SignalR.
                 *  If you need to renew the token in order to keep the connection active
                 *  (because it may expire during the connection),
                 *  do so from within this function and return the updated token.
                 *  https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#bearer-token-authentication
                 */
                options.AccessTokenProvider = () =>
                {
                    // verify access token here

                    // if not verified, refresh access token using refresh token

                    //Debug.WriteLine(token);
                    Debug.Assert(token != null);

                    return(Task.FromResult(token));
                };
            })
                             .WithAutomaticReconnect(new[]
            {
                // default: wait 0,2,10,30 seconds and try to reconnect
                TimeSpan.FromSeconds(0),
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(1)
            })
                             .Build();

            // Handle Hub connection events
            _hubConnection.Closed += err =>
            {
                Closed?.Invoke(this, new ConnectionEventArgs($"Connection to SignalR Hub Closed. {err.Message}"));
                return(Task.CompletedTask);
            };
            _hubConnection.Reconnecting += err =>
            {
                Reconnecting?.Invoke(this, new ConnectionEventArgs($"Try to reconnect to SignarR Hub. current error message: {err.Message}"));
                return(Task.CompletedTask);
            };
            _hubConnection.Reconnected += connectionId =>
            {
                Reconnected?.Invoke(this, new ConnectionEventArgs($"Succesfully re-connected to SignalR hub. New Connectionid: {connectionId}"));
                return(Task.CompletedTask);
            };

            // Handle Hub messages
            _hubConnection.On <string, string, int, int, DateTime, string>("ReceiveMessage", ReceiveMessage);

            _hubConnection.On <string>("Entered", user =>
            {
                SomeoneEntered?.Invoke(this, new SignalREventArgs($"{user} entered.", user));
                //AddLocalMessage($"{user} entered.", user);
            });

            _hubConnection.On <string>("Left", user =>
            {
                SomeoneLeft?.Invoke(this, new SignalREventArgs($"{user} left.", user));
            });
        }
示例#10
0
 private void OnReconnecting()
 {
     Reconnecting?.Invoke();
 }
示例#11
0
 /// <summary>
 /// Called when the client starts reconnecting.
 /// </summary>
 protected virtual void OnReconnecting()
 {
     Reconnecting?.Invoke(this, EventArgs.Empty);
 }
 private void Handle_Reconnecting(object sender, ClientReconnectingEventArgs e)
 {
     _logger?.LogTrace($"Reconnecting: {e.Connection.ConnectionName}");
     Reconnecting?.Invoke(sender, e);
 }
示例#13
0
 private void Hub_Reconnecting()
 {
     Reconnecting?.Invoke(true);
 }
示例#14
0
 protected void OnReconnecting() => Reconnecting?.Invoke();
 /// <summary>
 /// Called when the internal SignalR client is reconnecting.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected virtual void OnReconnecting(object sender, EventArgs e)
 {
     IsRegistered = false;
     Reconnecting?.Invoke(this, new EventArgs());
 }
示例#16
0
        public void Reconnect()
        {
            try
            {
                Reconnecting?.Invoke(new DeviceEventArgs(this));
                _reconnecting = true;
                if (phx42 != null)
                {
                    try
                    {
                        phx42.Error                  -= Phx42OnError;
                        phx42.CommandError           -= Phx42OnCommandError;
                        phx42.WriteFlashProgress     -= Phx42OnWriteFlashProgress;
                        phx42.ReadFlashProgress      -= Phx42OnReadFlashProgress;
                        phx42.UpdateFirmwareProgress -= Phx42OnUpdateFirmwareProgress;

                        phx42.ShutdownNow = true;
                    }
                    catch (Exception ex)
                    {
                        phx42?.WriteToPhxLog("Problem disconnecting");
                        phx42?.WriteExceptionToPhxLog(ex);
                    }

                    IsConnected = false;
                    Status      = "Disconnected";
                }

                try
                {
                    var streams = _bluetoothService.Reconnect(_device);

                    phx42 = new Phx42(streams.InputStream,
                                      streams.OutputStream,
                                      _fileManager,
                                      _device.Name, TimeMongerService);

                    phx42.Error                  += Phx42OnError;
                    phx42.CommandError           += Phx42OnCommandError;
                    phx42.WriteFlashProgress     += Phx42OnWriteFlashProgress;
                    phx42.ReadFlashProgress      += Phx42OnReadFlashProgress;
                    phx42.UpdateFirmwareProgress += Phx42OnUpdateFirmwareProgress;

                    if (IsPollingData)
                    {
                        phx42.StartPollingData();
                    }

                    IsConnected = true;
                    Status      = "Connected";
                    ReconnectSuccess?.Invoke(new DeviceEventArgs(this));
                }
                catch (Exception ex)
                {
                    phx42?.WriteToPhxLog("Problem reconnecting");
                    phx42?.WriteExceptionToPhxLog(ex);
                    OnDisconnected(new DeviceEventArgs(this));
                    return;
                }
            }
            finally
            {
                _reconnecting = false;
            }
        }