/// <summary> /// Updates the status control when a keep alive event occurs. /// </summary> static void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e) { if (sender != null && sender.Endpoint != null) { Console.WriteLine(Utils.Format( "{0} ({1}) {2}", sender.Endpoint.EndpointUrl, sender.Endpoint.SecurityMode, (sender.EndpointConfiguration.UseBinaryEncoding) ? "UABinary" : "XML")); } if (e != null && m_session != null) { if (ServiceResult.IsGood(e.Status)) { Console.WriteLine(Utils.Format( "Server Status: {0} {1:yyyy-MM-dd HH:mm:ss} {2}/{3}", e.CurrentState, e.CurrentTime.ToLocalTime(), m_session.OutstandingRequestCount, m_session.DefunctRequestCount)); } else { Console.WriteLine(String.Format( "{0} {1}/{2}", e.Status, m_session.OutstandingRequestCount, m_session.DefunctRequestCount)); } } }
private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new KeepAliveEventHandler(Notification_KeepAlive), sender, e); return; } try { // check for events from discarded sessions. if (!Object.ReferenceEquals(sender, mySession)) { return; } // check for disconnected session. if (!ServiceResult.IsGood(e.Status)) { // try reconnecting using the existing session state mySession.Reconnect(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); ResetUI(); } }
/// <summary> /// Raised when a keep alive response is returned from the server. /// </summary> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { if (ServiceResult.IsBad(e.Status)) { Report("KEEP ALIVE LATE: {0}", e.Status); } }
//TODO: reconnect static void Session_KeepAlive(Session session, KeepAliveEventArgs e) { try { if (session.KeepAliveStopped) { session.Reconnect(); } if (Object.ReferenceEquals(_session, session)) { return; } if (!session.Connected) { session.Reconnect(); Console.WriteLine("was reconnected!"); } } catch (Exception ex) { _logger.Error(ex, "Error can't reconnect to session: {0}", ex.Message); } }
/// <summary> /// Handle keep alives /// </summary> /// <param name="session"></param> /// <param name="e"></param> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { _logger.Debug($"Keep Alive received from session {session.SessionName}, state: {e.CurrentState}."); if (ServiceResult.IsGood(e.Status)) { return; } _lock.Wait(); try { var entry = _sessions.SingleOrDefault(s => s.Value.Session.SessionName == session.SessionName); if (entry.Key == null) { return; } entry.Value.MissedKeepAlives++; if (entry.Value.MissedKeepAlives >= entry.Value.MaxKeepAlives) { _logger.Warning("Session '{name}' exceeded max keep alive count. Disconnecting and removing session...", session.SessionName); _sessions.Remove(entry.Key); Try.Op(session.Close); Try.Op(session.Dispose); } _logger.Warning("{missedKeepAlives}/{_maxKeepAlives} missed keep alives from session '{name}'...", entry.Value.MissedKeepAlives, entry.Value.MaxKeepAlives, session.SessionName); } finally { _lock.Release(); } }
/// <summary> /// 处理保持连接心跳事件 /// </summary> private void OnKeepAliveNotification(Session session, KeepAliveEventArgs e) { try { if (e.Status != null && ServiceResult.IsNotGood(e.Status)) { IsConnected = false; if (ReconnectPeriod <= 0) { OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs((OpcUaStatusCodes)e.Status.Code, $"{ToString()},保持连接时错误", null)); return; } if (sessionReconnectHandler == null) { OnLogHappened?.Invoke(this, new OpcUaLogEventArgs($"{ToString()},重新连接中... ")); sessionReconnectHandler = new SessionReconnectHandler(); sessionReconnectHandler.BeginReconnect(session, ReconnectPeriod * 1000, Server_ReconnectComplete); } } } catch (Exception ex) { OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs(OpcUaStatusCodes.Uncertain, $"{ToString()},保持连接时发生未处理的异常", ex)); } }
private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new KeepAliveEventHandler(Notification_KeepAlive), sender, e); return; } // check for events from discarded sessions. if (!Object.ReferenceEquals(sender, mySession)) { return; } // check for disconnected session. if (!ServiceResult.IsGood(e.Status)) { // AddLogCallback("Client", "Lost connection to server; Reconnect failed", false); //Release connection myHelperApi.Disconnect(); mySession = myHelperApi.Session; DisconnectB.Enabled = false; ConnectB.Enabled = true; ConnectionStatusLabel.Text = "Disconnected"; ConnectionStatusLabel.ForeColor = Color.Red; } }
/// <summary> /// The session the keep alive handler. /// </summary> /// <param name="session">The session.</param> /// <param name="e">The <see cref="Opc.Ua.Client.KeepAliveEventArgs"/> instance containing the event data.</param> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { int missedKeepAlives = 0; lock (m_lock) { // check if the session is closed. if (!m_running || !Object.ReferenceEquals(m_session, session)) { return; } // check if everything is ok. if (ServiceResult.IsGood(e.Status)) { m_missedKeepAlives = 0; m_lastKeepAliveTime = DateTime.UtcNow; return; } // increment miss count. missedKeepAlives = ++m_missedKeepAlives; } // attempt to reconnect after two misses. if (missedKeepAlives == 2) { ThreadPool.QueueUserWorkItem(OnReconnectSession, session); Utils.Trace("Calling OnReconnectSession NOW."); } }
private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new KeepAliveEventHandler(Notification_KeepAlive), sender, e); return; } // check for events from discarded sessions. if (!Object.ReferenceEquals(sender, mySession)) { return; } // check for disconnected session. if (!ServiceResult.IsGood(e.Status)) { // UpdateLog("Client", "Lost connection to server; Reconnect failed", false); //Release connection try { myHelperApi.RemoveSubscription(mySubscription); } catch { ; } myHelperApi.Disconnect(); mySession = myHelperApi.Session; // ClearUI(); } }
private void OnSessionKeepAlive(Session session, KeepAliveEventArgs e) { var status = string.Empty; if (e.Status != null && e.Status.StatusCode != null) { status = e.Status.StatusCode.ToString(); } if (e.CurrentState != ServerState.Running) { m_FailedKeepAliveEvents++; m_NumberOfCommunicationErrors++; m_Log.Error(status); } else if (m_PreviousState != ServerState.Running && e.CurrentState == ServerState.Running) { m_Log.Error($"OPC is running again, after state: '{m_PreviousState}'."); m_FailedKeepAliveEvents = 0; } if (m_FailedKeepAliveEvents == NumberOfFailedKeepingAliveEventsBeforeRestart) { m_FailedKeepAliveEvents = 0; m_Log.Error($"Restarting OPC server due to keep alive failures."); ReConnectToServer(); } m_PreviousState = e.CurrentState; }
private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { if (ServiceResult.IsBad(e.Status)) { session?.Dispose(); } }
/// <summary> /// Handles a keep alive event from a session. /// </summary> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { try { // check for events from discarded sessions. if (!Object.ReferenceEquals(session, m_session)) { return; } // start reconnect sequence on communication error. if (ServiceResult.IsBad(e.Status)) { lock (m_lock) { if (m_reconnectPeriod <= 0) { return; } BeginReconnect(); } } } catch (Exception exception) { Utils.Trace(exception, "Unexpected error handling keep alive."); } }
private void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e != null && sender != null) { // ignore callbacks from discarded objects. if (!Object.ReferenceEquals(sender, Session)) { return; } if (!ServiceResult.IsGood(e.Status)) { Program.Trace(String.Format( "Status: {0} Outstanding requests: {1} Defunct requests: {2}", e.Status, sender.OutstandingRequestCount, sender.DefunctRequestCount)); if (e.Status.StatusCode == StatusCodes.BadNoCommunication && m_reconnectHandler == null) { Program.Trace("--- RECONNECTING --- {0}", sender.Endpoint.EndpointUrl); m_reconnectHandler = new SessionReconnectHandler(); m_reconnectHandler.BeginReconnect(sender, c_reconnectPeriod, Client_ReconnectComplete); } } } }
private void Server_KeepAlive(Session session, KeepAliveEventArgs e) { if (InvokeRequired) { BeginInvoke(new KeepAliveEventHandler(Server_KeepAlive), session, e); return; } try { // check for events from discarded sessions. if (!Object.ReferenceEquals(session, m_server.Session)) { return; } // start reconnect sequence on communication error. if (ServiceResult.IsBad(e.Status)) { UpdateStatus(true, e.CurrentTime, "Communication Error ({0})", e.Status); return; } // update status. UpdateStatus(false, e.CurrentTime, "Connected {0}", session.ConfiguredEndpoint); } catch (Exception exception) { ExceptionDlg.Show(this.Text, exception); } }
private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e) { //if (this.InvokeRequired) //{ // this.BeginInvoke(new KeepAliveEventHandler(Notification_KeepAlive), sender, e); // return; //} try { // check for events from discarded sessions. if (!Object.ReferenceEquals(sender, mySession)) { return; } // check for disconnected session. if (!ServiceResult.IsGood(e.Status)) { // try reconnecting using the existing session state mySession.Reconnect(); } } catch (Exception ex) { PageUtility.MessageBox(this, ex.ToString()); //ResetUI(); } }
private void Notification_KeepAlive(Session session, KeepAliveEventArgs e) { // check for events from discarded sessions. if (!Object.ReferenceEquals(session, myHelperApi.Session)) { return; } }
/// <summary> /// Handler for the standard "keep alive" event sent by all OPC UA servers /// </summary> private static void StandardClient_KeepAlive(Session session, KeepAliveEventArgs e) { // Ignore if we are shutting down. if (PublisherShutdownInProgress == true) { return; } if (e != null && session != null && session.ConfiguredEndpoint != null) { OpcSession opcSession = null; try { OpcSessionsSemaphore.Wait(); var opcSessions = OpcSessions.Where(s => s.Session != null); opcSession = opcSessions.Where(s => s.Session.ConfiguredEndpoint.EndpointUrl.Equals(session.ConfiguredEndpoint.EndpointUrl)).FirstOrDefault(); if (!ServiceResult.IsGood(e.Status)) { Trace($"Session endpoint: {session.ConfiguredEndpoint.EndpointUrl} has Status: {e.Status}"); Trace($"Outstanding requests: {session.OutstandingRequestCount}, Defunct requests: {session.DefunctRequestCount}"); Trace($"Good publish requests: {session.GoodPublishRequestCount}, KeepAlive interval: {session.KeepAliveInterval}"); Trace($"SessionId: {session.SessionId}"); if (opcSession != null && opcSession.State == SessionState.Connected) { opcSession.MissedKeepAlives++; Trace($"Missed KeepAlives: {opcSession.MissedKeepAlives}"); if (opcSession.MissedKeepAlives >= OpcKeepAliveDisconnectThreshold) { Trace($"Hit configured missed keep alive threshold of {Program.OpcKeepAliveDisconnectThreshold}. Disconnecting the session to endpoint {session.ConfiguredEndpoint.EndpointUrl}."); session.KeepAlive -= StandardClient_KeepAlive; opcSession.Disconnect(); } } } else { if (opcSession != null && opcSession.MissedKeepAlives != 0) { // Reset missed keep alive count Trace($"Session endpoint: {session.ConfiguredEndpoint.EndpointUrl} got a keep alive after {opcSession.MissedKeepAlives} {(opcSession.MissedKeepAlives == 1 ? "was" : "were")} missed."); opcSession.MissedKeepAlives = 0; } } } finally { OpcSessionsSemaphore.Release(); } } else { Trace("Keep alive arguments seems to be wrong."); } }
private void KeepAlive(Session session, KeepAliveEventArgs e) { //检查会话状态 if (!ServiceResult.IsGood(e.Status)) { // 重新连接 uAClient.Session.Reconnect(); } }
private void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e != null && sender != null) { if (!ServiceResult.IsGood(e.Status)) { Console.WriteLine($"Opc.Ua.Client.SampleModule: Server {sender.ConfiguredEndpoint.EndpointUrl} Status NOT good: {e.Status} {sender.OutstandingRequestCount}/{sender.DefunctRequestCount}"); } } }
/// <summary> /// Handles a keep alive event from a session. /// </summary> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new KeepAliveEventHandler(Session_KeepAlive), session, e); return; } try { // check for events from discarded sessions. if (!Object.ReferenceEquals(session, m_session)) { return; } // start reconnect sequence on communication error. if (ServiceResult.IsBad(e.Status)) { if (m_reconnectPeriod <= 0) { UpdateStatus(true, e.CurrentTime, "Communication Error ({0})", e.Status); return; } UpdateStatus(true, e.CurrentTime, "Reconnecting in {0}s", m_reconnectPeriod); if (m_reconnectHandler == null) { if (m_ReconnectStarting != null) { m_ReconnectStarting(this, e); } m_reconnectHandler = new SessionReconnectHandler(); m_reconnectHandler.BeginReconnect(m_session, m_reconnectPeriod * 1000, Server_ReconnectComplete); } return; } // update status. UpdateStatus(false, e.CurrentTime, "Connected [{0}]", session.Endpoint.EndpointUrl); // raise any additional notifications. if (m_KeepAliveComplete != null) { m_KeepAliveComplete(this, e); } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Keep the OPC UA connection alive /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> /// <exception cref="ArgumentNullException"></exception> private void SessionKeepAlive_Event(Session sender, KeepAliveEventArgs eventArgs) { if (eventArgs.Status != null && ServiceResult.IsNotGood(status: eventArgs.Status)) { if (this.ReconnectHandler == null) { this.SessionReconnect(session: sender); } } }
/// <summary> /// Reports keep alive responses from the server. /// </summary> void Session_KeepAlive(Session session, KeepAliveEventArgs e) { if (ServiceResult.IsBad(e.Status)) { m_error = e.Status; m_errorEvent.Set(); return; } m_keepAliveCount++; }
private void Client_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e.Status != null && ServiceResult.IsNotGood(e.Status)) { if (m_reconnectHandler == null) { m_reconnectHandler = new SessionReconnectHandler(); m_reconnectHandler.BeginReconnect(sender, 10000, Client_ReconnectComplete); } } }
/// <summary> /// Updates the status control when a keep alive event occurs. /// </summary> async void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e) { if (!Dispatcher.HasThreadAccess) { await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { StandardClient_KeepAlive(sender, e); }); return; } if (sender != null && sender.Endpoint != null) { ServerUrlTB.Text = Utils.Format( "{0} ({1}) {2}", sender.Endpoint.EndpointUrl, sender.Endpoint.SecurityMode, (sender.EndpointConfiguration.UseBinaryEncoding) ? "UABinary" : "XML"); } else { ServerUrlTB.Text = "None"; } if (e != null && m_session != null) { SessionsCTRL.UpdateSessionNode(m_session); if (ServiceResult.IsGood(e.Status)) { ServerStatusTB.Text = Utils.Format( "Server Status: {0} {1:yyyy-MM-dd HH:mm:ss} {2}/{3}", e.CurrentState, e.CurrentTime.ToLocalTime(), m_session.OutstandingRequestCount, m_session.DefunctRequestCount); ServerStatusTB.Foreground = new SolidColorBrush(Colors.Black); ServerStatusTB.FontWeight = FontWeights.Normal; } else { ServerStatusTB.Text = String.Format( "{0} {1}/{2}", e.Status, m_session.OutstandingRequestCount, m_session.DefunctRequestCount); ServerStatusTB.Foreground = new SolidColorBrush(Colors.Red); ServerStatusTB.FontWeight = FontWeights.Bold; } } }
/// <summary> /// Ensures session is closed when server does not reply. /// </summary> private static void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e != null) { if (ServiceResult.IsBad(e.Status)) { e.CancelKeepAlive = true; sender.Close(); } } }
/// <summary> /// Hier wird die Session überwacht und gegebenenfalls ein Reconnect angestoßen /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Client_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e.Status != null && ServiceResult.IsNotGood(e.Status)) { if (reconnectHandler == null) { Console.WriteLine("--- RECONNECTING ---"); reconnectHandler = new SessionReconnectHandler(); reconnectHandler.BeginReconnect(sender, reconnectPeriod * 1000, Client_ReconnectComplete); } } }
/// <summary> /// Handles a keep alive event from a session. /// 处理会话中维持状态的事件 /// </summary> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { if (InvokeRequired) { BeginInvoke(new KeepAliveEventHandler(Session_KeepAlive), session, e); return; } try { // 检查会话是否已经被丢弃 if (!ReferenceEquals(session, m_session)) { return; } // start reconnect sequence on communication error. // 当通信出错的时候进行重连 if (ServiceResult.IsBad(e.Status)) { if (m_reconnectPeriod <= 0) { UpdateStatus(true, e.CurrentTime, "Communication Error ({0})", e.Status); return; } UpdateStatus(true, e.CurrentTime, "Reconnecting in {0}s", m_reconnectPeriod); if (m_reconnectHandler == null) { m_ReconnectStarting?.Invoke(this, e); m_reconnectHandler = new SessionReconnectHandler(); m_reconnectHandler.BeginReconnect(m_session, m_reconnectPeriod * 1000, Server_ReconnectComplete); } return; } // update status. // 更新状态 UpdateStatus(false, e.CurrentTime, "Connected [{0}]", session.Endpoint.EndpointUrl); // raise any additional notifications. // 触发保持成功状态的事件,相当于心跳机制确认 m_KeepAliveComplete?.Invoke(this, e); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Handle keep alives /// </summary> /// <param name="session"></param> /// <param name="e"></param> private void Session_KeepAlive(Session session, KeepAliveEventArgs e) { try { if (session?.Handle is SessionWrapper wrapper) { _logger.Debug("Keepalive received from session '{id}': server current state: {state}", wrapper.Id, e.CurrentState); if (ServiceResult.IsGood(e.Status)) { wrapper.MissedKeepAlives = 0; if (!wrapper._subscriptions.Any()) { if (wrapper.IdleCount < wrapper.MaxKeepAlives) { wrapper.IdleCount++; } else { _logger.Information("Idle session '{id}' set to disconnect due to idle", wrapper.Id); wrapper.State = SessionState.Disconnect; TriggerKeepAlive(); } } else { wrapper.IdleCount = 0; } } else { wrapper.ReportedStatus = e.Status.Code; _logger.Information("Session '{id}' set to refresh due to Keepalive with reported status {status}", wrapper.Id, e.Status); if (wrapper.State == SessionState.Running) { wrapper.State = SessionState.Refresh; } TriggerKeepAlive(); } } else { _logger.Warning("Keepalive received from unidentified session '{name}', server current state is {state}", session?.SessionName, e.CurrentState); } } catch (Exception ex) { _logger.Error(ex, "Failed to process Keepalive for session '{name}'", session.SessionName); } }
private void Client_KeepAlive(Session sender, KeepAliveEventArgs e) { if (e.Status != null && ServiceResult.IsNotGood(e.Status)) { //log.InfoFormat("{0} {1}/{2}", e.Status, sender.OutstandingRequestCount, sender.DefunctRequestCount); if (reconnectHandler == null) { reconnectHandler = new SessionReconnectHandler(); reconnectHandler.BeginReconnect(sender, ReconnectPeriod * 1000, Client_ReconnectComplete); } } }
/// <summary> /// Reports keep alive responses from the server. /// </summary> void Session_Reconnect(Session session, KeepAliveEventArgs e) { m_keepAliveCount++; if (ServiceResult.IsBad(e.Status)) { if (m_keepAliveCount > 2) { m_error = e.Status; m_errorEvent.Set(); } } }