public void Dispose() { foreach (var confirmation in _confirmations) { confirmation.Value.TrySetCanceled(); } _cts.Cancel(); _client?.Dispose(); _counters.Clear(); _task.Wait(); ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); ConnectionStatusChanged -= OnConnectionStatusChanged; _onDispose?.Invoke(); }
void OnConnectionStatusChanged(uint state) { NetworkState newState = (NetworkState)Enum.ToObject(typeof(NetworkState), state); NetworkConnected = (newState == NetworkState.ConnectedGlobal || newState == NetworkState.ConnectedLocal || newState == NetworkState.ConnectedSite); if (ConnectionStatusChanged != null) { Delegate [] handlers = ConnectionStatusChanged.GetInvocationList(); foreach (Delegate d in handlers) { try { d.DynamicInvoke(new object [] { this, new ConnectionStatusChangeEventArgs(newState) }); } catch (Exception e) { Log.Error("Error in ConnectionStatusChanged handler, {0}", e.Message); Log.Debug(e.StackTrace); } } } }
public void Dispose() { foreach (var confirmation in _confirmations) { confirmation.Value.TrySetCanceled(); } _cts.Cancel(); _client?.Dispose(); foreach (var state in _counters.ForceEnumerateInThreadSafeManner()) { state.Value.Dispose(); } _counters.Clear(); try { _task.Wait(); } catch { // we're disposing the document store // nothing we can do here } try { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); } catch { // we are disposing } ConnectionStatusChanged -= OnConnectionStatusChanged; _onDispose?.Invoke(); }
private async void DeviceOnConnectionStatusChanged(BluetoothLEDevice device, object args) { ConnectionStatusChanged?.Invoke(device, args); if (device.ConnectionStatus == BluetoothConnectionStatus.Connected) { //Get stuff up and running if ( this.NotificationSourceCharacteristic.CharacteristicProperties.HasFlag( GattCharacteristicProperties.Notify)) { this.NotificationSourceCharacteristic.ValueChanged += NotificationSourceCharacteristicOnValueChanged; // Set the notify enable flag try { await this.NotificationSourceCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); } catch (Exception ex) { } } this.DataSourceCharacteristic.ValueChanged += DataSourceCharacteristicOnValueChanged; await this.DataSourceCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); } if (device.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { //Stop doing stuff this.DataSourceCharacteristic.ValueChanged -= DataSourceCharacteristicOnValueChanged; this.NotificationSourceCharacteristic.ValueChanged -= NotificationSourceCharacteristicOnValueChanged; } }
/// <summary> /// Indicate that the reverse hello connection attempt completed. /// </summary> /// <remarks> /// The server tried to connect to a client using a reverse hello message. /// </remarks> private void OnReverseHelloComplete(IAsyncResult result) { var channel = (TcpServerChannel)result.AsyncState; try { channel.EndReverseConnect(result); lock (m_lock) { m_channels.Add(channel.Id, channel); } if (m_callback != null) { channel.SetRequestReceivedCallback(new TcpChannelRequestEventHandler(OnRequestReceived)); } } catch (Exception e) { ConnectionStatusChanged?.Invoke(this, new ConnectionStatusEventArgs(channel.ReverseConnectionUrl, new ServiceResult(e), true)); } }
private async void _baseDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args) { try { if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) { if (_busTxChar != null) { await _busTxChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } ConnectionStatusChanged?.Invoke(this, ConnectionStatus.Connected); } else { ConnectionStatusChanged?.Invoke(this, ConnectionStatus.Disconnected); } } catch (Exception) { /* Currently ignore */ } }
public async Task ConnectAsync() { try { if (AudioConnection != null) { AudioConnection.Dispose(); AudioConnection = null; } ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); ActionButtonEnabled = false; Status = Globalization.GetString("BluetoothAudio_Status_2"); OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, true); AudioConnection = AudioPlaybackConnection.TryCreateFromId(Id); if (AudioConnection != null) { await AudioConnection.StartAsync(); AudioPlaybackConnectionOpenResult Result = await AudioConnection.OpenAsync(); switch (Result.Status) { case AudioPlaybackConnectionOpenResultStatus.Success: { IsConnected = true; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_2"); Status = Globalization.GetString("BluetoothAudio_Status_3"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); break; } case AudioPlaybackConnectionOpenResultStatus.RequestTimedOut: { IsConnected = false; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); Status = Globalization.GetString("BluetoothAudio_Status_4"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, false); LogTracer.Log("Connect to AudioPlayback failed for time out"); break; } case AudioPlaybackConnectionOpenResultStatus.DeniedBySystem: { IsConnected = false; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); Status = Globalization.GetString("BluetoothAudio_Status_5"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, false); LogTracer.Log("Connect to AudioPlayback failed for being denied by system"); break; } case AudioPlaybackConnectionOpenResultStatus.UnknownFailure: { IsConnected = false; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); Status = Globalization.GetString("BluetoothAudio_Status_6"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, false); if (Result.ExtendedError != null) { LogTracer.Log(Result.ExtendedError, "Connect to AudioPlayback failed for unknown reason"); } else { LogTracer.Log("Connect to AudioPlayback failed for unknown reason"); } break; } } } else { IsConnected = false; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); Status = Globalization.GetString("BluetoothAudio_Status_7"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, false); } } catch (Exception ex) { LogTracer.Log(ex, $"Unable to create a new {nameof(AudioPlaybackConnection)}"); IsConnected = false; ActionButtonText = Globalization.GetString("BluetoothAudio_Button_Text_1"); Status = Globalization.GetString("BluetoothAudio_Status_7"); ActionButtonEnabled = true; OnPropertyChanged(nameof(ActionButtonEnabled)); OnPropertyChanged(nameof(ActionButtonText)); OnPropertyChanged(nameof(Status)); ConnectionStatusChanged?.Invoke(this, false); } }
private void OnConnectionStatusChanged(WifiStatus newStatus) { ConnectionStatus = newStatus; ConnectionStatusChanged?.Invoke(this, new WifiStatusEventArgs(newStatus)); }
void cbChangeConnectionStateComplete(IAsyncResult result) { ConnectionStatusChanged.EndInvoke(result); }
public Task StartAsync(string target = null) { ConnectionStatusChanged?.Invoke(new StatusChange(ServiceConnectionStatus.Connecting, Status)); return(Task.CompletedTask); }
private async Task DoWork() { try { await _requestExecutor.GetPreferredNode().ConfigureAwait(false); } catch (OperationCanceledException e) { NotifyAboutError(e); return; } catch (ChangeProcessingException e) { NotifyAboutError(e); return; } catch (Exception e) { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); NotifyAboutError(e); return; } var url = new Uri($"{_requestExecutor.Url}/databases/{_database}/changes" .ToLower() .ToWebSocketPath(), UriKind.Absolute); while (_cts.IsCancellationRequested == false) { try { if (Connected == false) { await _client.ConnectAsync(url, _cts.Token).ConfigureAwait(false); Interlocked.Exchange(ref _immediateConnection, 1); foreach (var counter in _counters) { counter.Value.Set(counter.Value.OnConnect()); } ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); } await ProcessChanges().ConfigureAwait(false); } catch (OperationCanceledException e) { NotifyAboutError(e); return; } catch (ChangeProcessingException) { continue; } catch (Exception e) { //We don't report this error since we can automatically recover from it and we can't // recover from the OnError accessing the faulty WebSocket. try { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); if (ReconnectClient() == false) { return; } } catch { // we couldn't reconnect NotifyAboutError(e); throw; } } finally { foreach (var confirmation in _confirmations) { confirmation.Value.TrySetCanceled(); } _confirmations.Clear(); } try { await TimeoutManager.WaitFor(TimeSpan.FromSeconds(1), _cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { return; } } }
private void RaiseConnectionStatusChanged() { ConnectionStatusChanged?.Invoke(this, new ConnectionStatusEventArgs(ConnectionStatus, ConnectionName)); }
private void ConnectionStatusChangesHandler(ConnectionStatus status, ConnectionStatusChangeReason reason) { LastKnownConnectionStatus = status; LastKnownConnectionChangeReason = reason; ConnectionStatusChanged?.Invoke(this, status); }
protected internal virtual void OnConnectionStatusChanged(ConnectionStatusChangedEventArgs e) { ConnectionStatusChanged.RaiseEvent(this, e); }
private void Channel_StatusChanged(TcpServerChannel channel, ServiceResult status, bool closed) { ConnectionStatusChanged?.Invoke(this, new ConnectionStatusEventArgs(channel.ReverseConnectionUrl, status, closed)); }
public override void OnReceive(Context context, Intent intent) { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); }
protected void OnStatusCallback(object sender, ConnectionStatusEventArgs cscp) { ConnectionStatusChanged?.Invoke(sender, cscp); }
protected virtual void OnConnectionStatusChanged(object args) { ConnectionStatusChanged?.Invoke(this, args); }
/// <summary> /// Raised when a connection arrives and is waiting for a callback. /// </summary> protected virtual void OnConnectionStatusChanged(object sender, ConnectionStatusEventArgs e) { ConnectionStatusChanged?.Invoke(sender, e); }
private void OnConnectionStatusChangedEvent() { OnPropertyChanged(nameof(IsConnected)); ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); }
private void RaiseConnectionStatusChanged() { ConnectionStatusChanged?.Invoke(IsConnected); }
//private void ConnectionWatcherTask(CancellationToken cancellationToken) //{ // // This task takes care of automatically reconnecting the interface // // when the connection is drop or if an I/O error occurs // while (!cancellationToken.IsCancellationRequested) // { // if (gotReadWriteError) // { // try // { // Close(); // // wait 1 sec before reconnecting // Thread.Sleep(1000); // if (!cancellationToken.IsCancellationRequested) // { // try // { // Open(); // } // catch (Exception e) // { // Console.WriteLine(e); // } // } // } // catch (Exception e) // { // Console.WriteLine(e); // } // } // if (!cancellationToken.IsCancellationRequested) // Thread.Sleep(1000); // } //} #endregion #region Events Raising /// <summary> /// Raises the connected state changed event. /// </summary> /// <param name="args">Arguments.</param> protected virtual void OnConnectionStatusChanged(ConnectionStatusChangedEventArgs args) { ConnectionStatusChanged?.Invoke(this, args); }
/// <summary>A receive message loop for processing obtained data from the WebSocket.</summary> private async void BeginReceive() { // The clientWebSocket.ReceiveAsync needs a buffer to store the frames coming in. byte[] buffer = new byte[BufferSize]; try { // This will loop while the ClientWebSocket is still open. while (_clientWebSocket.State == WebSocketState.Open) { // Frames arrive with partial messages, the FrameReassembler ensures that the messages are appropriately chunked. FrameReassembler frameReassembler = new FrameReassembler(); WebSocketReceiveResult result; do { // Ask the ClientWebSocket for any data. result = await _clientWebSocket.ReceiveAsync(new ArraySegment <byte>(buffer), _cancellationTokenSource.Token); switch (result.MessageType) { case WebSocketMessageType.Text: // If we are in the middle of an incomplete message then we need to provide additional frame data. frameReassembler.HandleReceivedData(Encoding.UTF8.GetString(buffer, 0, result.Count)); // Does the frameReassembler have any complete messages? while (frameReassembler.HasCompleteMessages()) { // Raise an event containing the full message. DataReceived?.Invoke(this, new SubscriptionDataEvent(frameReassembler.GetNextCompleteMessage(), responseTypeMappings)); } break; case WebSocketMessageType.Close: // We have been asked to close the socket gracefully. if (_clientWebSocket != null) { await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, _cancellationTokenSource.Token); } // Raise an event. ConnectionStatusChanged?.Invoke(this, ConnectionStatus.DisconnectedByHost); break; default: throw new NotImplementedException(result.MessageType.ToString() + " is not implemented."); } // Although EdgeOS does set the EndOfMessage flag, it lies. } while (_clientWebSocket.State == WebSocketState.Open && (!result.EndOfMessage || frameReassembler.IsMissingData())); } } // EdgeOS non-gracefully closes the socket when a session ends. catch (WebSocketException exception) { if (!exception.Message.Equals("The remote party closed the WebSocket connection without completing the close handshake.")) { throw; } ConnectionStatusChanged?.Invoke(this, ConnectionStatus.DisconnectedByHost); } catch (OperationCanceledException) { // We cancelled the receive. } finally { _clientWebSocket.Dispose(); } }
private void OnConnectionStatusChanged(ConnectionStatusChangedEventArgs args) { ConnectionStatusChanged?.Invoke(this, args); }
public Task StopAsync() { ConnectionStatusChanged?.Invoke(new StatusChange(Status, ServiceConnectionStatus.Disconnected)); return(Task.CompletedTask); }
private static void Current_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e) { ConnectionStatusChanged?.Invoke(sender, null); }
private void EmitStatus(string status) { ConnectionStatusChanged?.Invoke(this, new StatusChangeEventArgs(status)); }
public void Poll() { NetIncomingMessage message; while ((message = netPeer.ReadMessage()) != null) { try { Intent intent; switch (message.MessageType) { case NetIncomingMessageType.ConnectionApproval: intent = Intent.Hail; break; case NetIncomingMessageType.Data: intent = (Intent)message.ReadByte(); if (intent == Intent.Hail || intent == Intent.StatusChanged) { if (netPeer is NetServer) { message.SenderConnection.Disconnect("InvalidData"); break; // Stop reading messages. } else { Console.Error.WriteLine("[CLIENT] Received invalid intent from server?? (" + intent + ")"); } continue; } break; case NetIncomingMessageType.StatusChanged: intent = Intent.StatusChanged; break; default: Console.WriteLine("Unhandled message: " + message.MessageType); continue; } if (messageHandlers.ContainsKey(intent)) { if (message.MessageType == NetIncomingMessageType.ConnectionApproval) { var bytes = message.SenderConnection.RemoteHailMessage.ReadBytes(message.SenderConnection.RemoteHailMessage.LengthBytes); if (messageTypes.ContainsKey(intent)) { var typeofIntent = messageTypes[intent]; var networkMessage = CreateIntentInstance(typeofIntent, bytes); messageHandlers[intent](message.SenderConnection, networkMessage); } else { throw new NotImplementedException("ConnectionApproval not handled!"); } } else if (message.MessageType == NetIncomingMessageType.StatusChanged) { var status = (NetConnectionStatus)message.ReadByte(); var arg = new ConnectionStatusChanged(status, message.ReadString()); if (status == NetConnectionStatus.Connected && netPeer is NetClient) { arg.HailResponse = new HailResponse(); arg.HailResponse.Deserialize(message.SenderConnection.RemoteHailMessage.ReadBytes(message.SenderConnection.RemoteHailMessage.LengthBytes)); } messageHandlers[intent](message.SenderConnection, arg); } else { var bytes = message.ReadBytes(message.LengthBytes - message.PositionInBytes); var typeofIntent = messageTypes[intent]; var msg = CreateIntentInstance(typeofIntent, bytes); messageHandlers[intent](message.SenderConnection, msg); } } else { throw new NotImplementedException("Received message with unhandled intent \"" + intent + "\"."); } } catch (Exception exception) { HandleInvalidMessage(message, exception); } } }
private async Task DoWork(string nodeTag) { try { var task = nodeTag == null || _requestExecutor.Conventions.DisableTopologyUpdates ? _requestExecutor.GetPreferredNode() : _requestExecutor.GetRequestedNode(nodeTag); (_nodeIndex, _serverNode) = await task.ConfigureAwait(false); } catch (OperationCanceledException e) { NotifyAboutError(e); _tcs.TrySetCanceled(); return; } catch (Exception e) { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); NotifyAboutError(e); _tcs.TrySetException(e); return; } var wasConnected = false; while (_cts.IsCancellationRequested == false) { try { if (Connected == false) { _url = new Uri($"{_serverNode.Url}/databases/{_database}/changes" .ToLower() .ToWebSocketPath(), UriKind.Absolute); await _client.ConnectAsync(_url, _cts.Token).ConfigureAwait(false); wasConnected = true; Interlocked.Exchange(ref _immediateConnection, 1); foreach (var counter in _counters) { counter.Value.Set(counter.Value.OnConnect()); } ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); } await ProcessChanges().ConfigureAwait(false); } catch (OperationCanceledException) when(_cts.Token.IsCancellationRequested) { // disposing return; } catch (ChangeProcessingException) { continue; } catch (Exception e) { //We don't report this error since we can automatically recover from it and we can't // recover from the OnError accessing the faulty WebSocket. try { if (wasConnected) { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); } wasConnected = false; try { _serverNode = await _requestExecutor.HandleServerNotResponsive(_url.AbsoluteUri, _serverNode, _nodeIndex, e).ConfigureAwait(false); } catch (DatabaseDoesNotExistException databaseDoesNotExistException) { e = databaseDoesNotExistException; throw; } catch (Exception) { //We don't want to stop observe for changes if server down. we will wait for one to be up } if (ReconnectClient() == false) { return; } } catch { // we couldn't reconnect NotifyAboutError(e); _tcs.TrySetException(e); throw; } } finally { foreach (var confirmation in _confirmations) { confirmation.Value.TrySetCanceled(); } _confirmations.Clear(); } try { await TimeoutManager.WaitFor(TimeSpan.FromSeconds(1), _cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { return; } } }
/// <summary> /// Raises the <see cref="E:ConnectionStatusChanged" /> event. /// </summary> /// <param name="e">The <see cref="Events.ConnectionStatusChangedEventArgs"/> instance containing the event data.</param> protected virtual void OnConnectionStatusChanged(Events.ConnectionStatusChangedEventArgs e) { ConnectionStatusChanged?.Invoke(this, e); }