public AlfaWrapper(AlfaDirectMessageAdapter adapter) { if (adapter == null) throw new ArgumentNullException(nameof(adapter)); _adapter = adapter; _sysCulture = ThreadingHelper.GetSystemCulture(); _adapter.AddInfoLog(LocalizedStrings.Str2270Params, _sysCulture); _ad = new AlfaDirectClass(); _ad.OnConnectionChanged += OnConnectionChanged; _ad.OnTableChanged += OnTableChanged; _ad.OrderConfirmed += OrderConfirmed; _tableSecurities = new AlfaTable(_ad, _adapter, AlfaTable.TableName.papers, "paper_no, p_code, ansi_name, place_code, at_code, lot_size, i_last_update, expired, mat_date, price_step, base_paper_no, go_buy, go_sell, price_step_cost, curr_code, strike"); _tableDepth = new AlfaTable(_ad, _adapter, AlfaTable.TableName.queue, "paper_no, sell_qty, price, buy_qty"); _tableLevel1 = new AlfaTable(_ad, _adapter, AlfaTable.TableName.fin_info, "paper_no, status, go_buy, go_sell, open_pos_qty, open_price, close_price, sell, sell_qty, buy, buy_qty, min_deal, max_deal, lot_size, volatility, theor_price, last_price, last_qty, last_update_date, last_update_time, price_step, buy_sqty, sell_sqty, buy_count, sell_count", "trading_status"); _tableTrades = new AlfaTable(_ad, _adapter, AlfaTable.TableName.all_trades, "paper_no, trd_no, qty, price, ts_time, b_s", "b_s_num"); _tableOrders = new AlfaTable(_ad, _adapter, AlfaTable.TableName.orders, "ord_no, acc_code, paper_no, status, b_s, price, qty, rest, ts_time, comments, place_code, stop_price, avg_trd_price, blank, updt_grow_price, updt_down_price, updt_new_price, trailing_level, trailing_slippage", "order_status, b_s_str"); _tablePositions = new AlfaTable(_ad, _adapter, AlfaTable.TableName.balance, "acc_code, p_code, place_code, paper_no, income_rest, real_rest, forword_rest, pl, profit_vol, income_vol, real_vol, open_vol, var_margin, balance_price"); _tableMyTrades = new AlfaTable(_ad, _adapter, AlfaTable.TableName.trades, "trd_no, ord_no, treaty, paper_no, price, qty, b_s, ts_time", "b_s_str"); _tableNews = new AlfaTable(_ad, _adapter, AlfaTable.TableName.news, "new_no, provider, db_data, subject, body"); _tableAccounts = new AlfaTable(_ad, _adapter, AlfaTable.TableName.accounts, "treaty"); _connState = IsConnected ? ConnectionStates.Connected : ConnectionStates.Disconnected; _adapter.AddInfoLog("AlfaDirect {0}", _ad.Version.ToString()); }
public void Connect() { ConnectionState = ConnectionStates.Connecting; var error = client.Open(); if (error != ErrorCode.NoError) { ConnectionState = ConnectionStates.Offline; throw new Exception(error.ToString()); } ConnectionState = ConnectionStates.Online; }
private void SetState(ConnectionStates state, string errorReason = null) { if (string.IsNullOrEmpty(errorReason)) { HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "'"); } else { HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "' errorReason: '" + errorReason + "'"); } if (this.State == state) { return; } this.State = state; switch (state) { case ConnectionStates.Initial: case ConnectionStates.Authenticating: case ConnectionStates.Negotiating: case ConnectionStates.CloseInitiated: break; case ConnectionStates.Connected: try { if (this.OnConnected != null) { this.OnConnected(this); } } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnConnected user code!", ex); } HTTPManager.Heartbeats.Subscribe(this); this.lastMessageSent = DateTime.UtcNow; break; case ConnectionStates.Closed: if (string.IsNullOrEmpty(errorReason)) { if (this.OnClosed != null) { try { this.OnClosed(this); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnClosed user code!", ex); } } } else { if (this.OnError != null) { try { this.OnError(this, errorReason); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnError user code!", ex); } } } HTTPManager.Heartbeats.Unsubscribe(this); break; } }
protected virtual void OnStateChanged(Connection con, ConnectionStates oldState, ConnectionStates newState) { VKDebug.LogWarning("Code: OnStateChanged - oldState: " + oldState + " - newState: " + newState, VKCommon.HEX_VIOLET); }
async private void ConnectButton_Click(object sender, RoutedEventArgs e) { if (connectionState == ConnectionStates.NotConnected) { if (!Uri.TryCreate(ServerUri.Text.Trim(), UriKind.Absolute, out serverUri)) { Diag.DebugPrint("Please provide a valid URI input."); return; } ConnectButton.Content = "Connecting..."; connectionState = ConnectionStates.Connecting; // Finally, initiate the connection and set up transport // to be CCT capable. But do this heavy lifting outside of the UI thread. bool result = await Task<bool>.Factory.StartNew(() => { return communicationModule.SetUpTransport(serverUri, GetType().Name); }); Diag.DebugPrint("CommunicationModule setup result: " + result); if (result == true) { ConnectButton.Content = "Disconnect"; connectionState = ConnectionStates.Connected; } else { ConnectButton.Content = "Failed to connect. Click to retry."; connectionState = ConnectionStates.NotConnected; } } else if (connectionState == ConnectionStates.Connected) { await Task.Factory.StartNew(() => { communicationModule.Reset(); }); connectionState = ConnectionStates.NotConnected; ConnectButton.Content = "Connect"; } }
private void EnterSleepMode() { string r = mySerialCommunicator.SendCommand("FSLEEP", 2000); if (r.Contains("ZZ")) { connectionState = ConnectionStates.Sleep; } else throw new ApplicationException("Device did not confirm that it entered sleep mode."); }
public void Connect(string login, string password) { if (_ad.Connected) { _connState = ConnectionStates.Connected; Connected.SafeInvoke(); return; } if (!login.IsEmpty() && !password.IsEmpty()) { _ad.UserName = login; _ad.Password = password; } _connState = ConnectionStates.Connecting; _ad.Connected = true; }
private async void APIEventHandler(ConnectionStates State) { ConnectionState = State; switch (ConnectionState) { case ConnectionStates.Initializing: case ConnectionStates.Initialized: case ConnectionStates.Discovering: case ConnectionStates.Authenticating: case ConnectionStates.RetrievingData: case ConnectionStates.Disconnecting: LogStatus(State.ToString()); break; case ConnectionStates.NotConnected: if (IsConnecting || IsConnected) { AdapterNotConnected(); LogStatus(State.ToString()); } break; case ConnectionStates.Connecting: if (BlueFire.IsReconnecting) { if (!IsConnecting) { AdapterReconnecting(); } } LogStatus(State.ToString()); break; case ConnectionStates.Authenticated: if (!IsConnected) { await AdapterConnected(); LogStatus(State.ToString()); } break; case ConnectionStates.KeyTurnedOn: LogKeyState(); await GetTruckData(); // get data if key is turned on after app is started break; case ConnectionStates.KeyTurnedOff: LogKeyState(); break; case ConnectionStates.Disconnected: if ((IsConnecting || IsConnected) && !BlueFire.IsReconnecting) { AdapterDisconnected(); } LogStatus(State.ToString()); break; case ConnectionStates.Reconnecting: if (!IsConnecting) { AdapterReconnecting(); } LogStatus(State.ToString()); break; case ConnectionStates.Reconnected: if (IsConnecting) { AdapterReconnected(); LogStatus(State.ToString()); } break; case ConnectionStates.NotReconnected: if (IsConnecting) { AdapterNotReconnected(); } LogStatus(State.ToString()); break; case ConnectionStates.CANStarting: LogMessage("The Adapter is connected to the " + BlueFire.CanBusToString() + "."); await GetTruckData(); break; case ConnectionStates.J1708Restarting: LogMessage("J1708 is restarting."); await GetTruckData(); break; case ConnectionStates.DataAvailable: if (IsConnected) { CheckData(); LogStatus(State.ToString()); } break; case ConnectionStates.CANFilterFull: LogMessage("The CAN Filter is Full. Some data will not be retrieved."); LogStatus(State.ToString()); break; case ConnectionStates.ConnectTimeout: case ConnectionStates.AdapterTimeout: if (IsConnecting || IsConnected) { AdapterNotConnected(); LogStatus(State.ToString()); LogMessage("The Adapter Timed Out."); } break; case ConnectionStates.Notification: LogNotification(); break; case ConnectionStates.AdapterMessage: LogAdapterMessage(); break; case ConnectionStates.DataError: LogError(); break; case ConnectionStates.SystemError: LogError(); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.NotAuthenticated: LogMessage("You are not authorized to access this adapter. Check your adapter security settings."); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.NotFound: LogMessage("A valid adapter was not found. Check your adapter connection settings."); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.IncompatibleAPI: LogMessage("The API is not compatible with this App."); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.IncompatibleAdapter: LogMessage("The Adapter is not compatible with this API."); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.IncompatibleSecurity: LogMessage("App Security is not compatible with this API."); AdapterNotConnected(); LogStatus(State.ToString()); break; case ConnectionStates.NoAdapter: case ConnectionStates.BluetoothNA: AdapterNotConnected(); LogStatus(State.ToString()); break; } // Allow App to stop the service await Task.Delay(10); }
/// <summary> /// Vykona interny start klienta /// </summary> /// <returns>True = start klienta bol uspesny</returns> protected override bool InternalStart() { //zacina pripajanie this.m_connectionState = ConnectionStates.Connecting; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //inicializujeme spojenie return this.InternalConnect(); }
/// <summary> /// Podla inicializacie otvori TCP spojenie na pripojeneho clienta /// </summary> /// <returns>True = uspesne otvorene spojenie, False = chyba pri otvarani spojenia</returns> protected override bool InternalStart() { //zmenime stav this.m_connectionState = ConnectionStates.Connecting; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //pokusime sa vytvorit spojenie if (!this.InternalConnect(!this.AutoReconnect)) { if (this.IsRun) { //spustime automaticky reconnec this.StartReconnect(); } else { //start nebol uspesny return false; } } //spojenie bolo uspesne vytvorene return true; }
/// <summary> /// Zatvori spojenie /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> /// <returns>True = uspesne zatvorene spojenie, False = chyba pri zatvarani spojenia</returns> protected override void InternalStop() { //ak bol stav connecting tak bol spusteny reconnect if (this.m_connectionState == ConnectionStates.Connecting) this.StopReconnect(); //ziskame stav Boolean state = this.IsConnected; //deinicializacia base this.InternalDisconnect(true); //ak sme pripojeny if (state) { //spojenie bolo ukoncene this.OnDisconnected(EventArgs.Empty); } //uz nie sme pripojeny this.m_actualIpEndPoint = null; //spojenie nie ja aktivne if (this.m_connectionState != ConnectionStates.Closed) { //zmena stavu this.m_connectionState = ConnectionStates.Closed; //event oznamujuci zmenu stavu this.OnChangeConnectionState(EventArgs.Empty); } }
private void ProcessReconnection(TimeSpan diff) { switch (_currState) { case ConnectionStates.Disconnecting: case ConnectionStates.Connecting: { _connectionTimeOut -= diff; if (_connectionTimeOut <= TimeSpan.Zero) { this.AddWarningLog("RCM: Connecting Timeout Left {0}.", _connectionTimeOut); switch (_currState) { case ConnectionStates.Connecting: RaiseNewOutMessage(new ConnectMessage { Error = new TimeoutException(LocalizedStrings.Str170) }); break; case ConnectionStates.Disconnecting: RaiseNewOutMessage(new DisconnectMessage { Error = new TimeoutException(LocalizedStrings.Str171) }); break; } if (_prevState != _none) { this.AddInfoLog("RCM: Connecting AttemptError."); //ReConnectionSettings.RaiseAttemptError(new TimeoutException(message)); lock (_timeSync) _currState = _prevState; } else { //ReConnectionSettings.RaiseTimeOut(); if (_currState == ConnectionStates.Connecting && _connectingAttemptCount != 0) { lock (_timeSync) _currState = _reConnecting; this.AddInfoLog("RCM: To Reconnecting Attempts {0} Timeout {1}.", _connectingAttemptCount, _connectionTimeOut); } else { lock (_timeSync) _currState = _none; } } } break; } case _reConnecting: { if (_connectingAttemptCount == 0) { this.AddWarningLog("RCM: Reconnecting attemts {0} PrevState {1}.", _connectingAttemptCount, _prevState); lock (_timeSync) _currState = _none; break; } _connectionTimeOut -= diff; if (_connectionTimeOut > TimeSpan.Zero) { break; } if (IsTradeTime()) { this.AddInfoLog("RCM: To Connecting. CurrState {0} PrevState {1} Attempts {2}.", _currState, _prevState, _connectingAttemptCount); if (_connectingAttemptCount != -1) { _connectingAttemptCount--; } _connectionTimeOut = _reConnectionSettings.Interval; //_prevState = _currState; SendInMessage(new ConnectMessage()); } else { this.AddWarningLog("RCM: Out of trade time. CurrState {0}.", _currState); _connectionTimeOut = TimeSpan.FromMinutes(1); } break; } } }
/// <summary> /// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message. /// </summary> /// <param name="message">The message.</param> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { var isReconnecting = false; if (((ConnectMessage)message).Error == null) { isReconnecting = _prevState == _reConnecting; lock (_timeSync) _prevState = _currState = ConnectionStates.Connected; } else { lock (_timeSync) _prevState = _currState = ConnectionStates.Failed; _connectionTimeOut = _reConnectionSettings.Interval; _connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } if (isReconnecting) { RaiseNewOutMessage(new RestoredConnectMessage { Adapter = message.Adapter }); } else { base.OnInnerAdapterNewOutMessage(message); } break; } case MessageTypes.Disconnect: { if (((DisconnectMessage)message).Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Disconnected; } else { lock (_timeSync) { if (_currState == ConnectionStates.Connected) { _prevState = _reConnecting; } _currState = _reConnecting; } _connectionTimeOut = _reConnectionSettings.Interval; _connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } base.OnInnerAdapterNewOutMessage(message); break; } default: base.OnInnerAdapterNewOutMessage(message); break; } }
private void signalRConnection_OnStateChanged(Connection connection, ConnectionStates oldState, ConnectionStates newState) { this.messages.Add($"[State Change] {oldState} => {newState}"); }
/// <summary> /// Vykona interny pokus o pripojenie k vzdialenemu bodu /// </summary> /// <returns>True = spojenie bolo uspesne vytvorene</returns> private Boolean InternalConnect() { try { lock (this) { //inicializujeme klienta this.m_client = new UdpClient(this.m_localIpEndPoint); this.m_client.Connect(this.m_remoteIpEndPoint); //spustime vlakno na citanie dat this.InternalInitializeThread(); //doslo ku konektu this.m_isConnectied = true; //spojenie bolo vytvorene this.OnConnected(EventArgs.Empty); //start komunikacie sa podaril this.m_connectionState = ConnectionStates.Connected; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); } //inicializacia komunikacie bola uspesna return true; } catch (Exception ex) { //zalogujeme this.InternalTrace(TraceTypes.Error, "Chyba pri vytvarani spojenia. {0}", ex); //inicializacia nebola uspesna return false; } }
/// <summary> /// Vykona interny stop klienta /// </summary> protected override void InternalStop() { //ukoncime pracovne vlakno this.InternalDeinitializeThread(); //ukoncime spojenie this.InternalDisconnect(); //doslo ku konektu this.m_isConnectied = false; //ukoncenie spojenia this.OnDisconnected(EventArgs.Empty); //zmena stavu this.m_connectionState = ConnectionStates.Closed; //event oznamujuci zmenu stavu this.OnChangeConnectionState(EventArgs.Empty); }
/// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { var connectMsg = (ConnectMessage)message; var isRestored = false; var isReconnecting = false; var isReconnectionStarted = false; if (connectMsg.Error == null) { isRestored = _currState == ConnectionStates.Connecting && _prevState == ConnectionStates.Failed; lock (_timeSync) { _prevState = _currState = ConnectionStates.Connected; _connectionTimeOut = _reConnectionSettings.Interval; _connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } } else { lock (_timeSync) { if (_connectingAttemptCount != 0) { isReconnectionStarted = _prevState == ConnectionStates.Connected; _prevState = _currState == ConnectionStates.Connected ? _reConnecting : ConnectionStates.Failed; _currState = _reConnecting; isReconnecting = true; } else { _prevState = _currState = ConnectionStates.Failed; } } } if (isRestored) { this.AddInfoLog(LocalizedStrings.Str2958); if (SuppressReconnectingErrors) { RaiseNewOutMessage(new ReconnectingFinishedMessage { Adapter = message.Adapter }); } else { RaiseNewOutMessage(new RestoredConnectMessage { Adapter = message.Adapter }); } } else { if (connectMsg.Error == null || !SuppressReconnectingErrors || !isReconnecting) { base.OnInnerAdapterNewOutMessage(message); } else if (isReconnectionStarted) { this.AddInfoLog(LocalizedStrings.Reconnecting); base.OnInnerAdapterNewOutMessage(new ReconnectingStartedMessage()); } } break; } case MessageTypes.Disconnect: { var disconnectMsg = (DisconnectMessage)message; if (disconnectMsg.Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Disconnected; } else { lock (_timeSync) { if (_suppressDisconnectError) { _suppressDisconnectError = false; RaiseNewOutMessage(disconnectMsg.Error.ToErrorMessage()); disconnectMsg.Error = null; } //if (_currState == ConnectionStates.Connected) // _prevState = _reConnecting; //_currState = _reConnecting; } //_connectionTimeOut = _reConnectionSettings.Interval; //_connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } base.OnInnerAdapterNewOutMessage(message); break; } default: base.OnInnerAdapterNewOutMessage(message); break; } }
public bool CheckIfDeviceIsSleeping() { EventLogger.LogMessage("Checking if device is sleeping.", TraceLevel.Verbose); try{ string resp = mySerialCommunicator.SendCommand("FWCxxx", 250); if (resp.Contains("Z")) { connectionState = ConnectionStates.Sleep; return true; } else return false; } catch{return false;} }
private void ProcessReconnection(TimeSpan diff) { switch (_currState) { case ConnectionStates.Disconnecting: case ConnectionStates.Connecting: { _connectionTimeOut -= diff; if (_connectionTimeOut <= TimeSpan.Zero) { this.AddWarningLog("RCM: Connecting Timeout Left {0}.", _connectionTimeOut); switch (_currState) { case ConnectionStates.Connecting: if (!SuppressReconnectingErrors) { RaiseNewOutMessage(new ConnectMessage { Error = new TimeoutException(LocalizedStrings.Str170) }); } break; case ConnectionStates.Disconnecting: RaiseNewOutMessage(new DisconnectMessage { Error = new TimeoutException(LocalizedStrings.Str171) }); break; } if (_prevState != _none) { this.AddInfoLog("RCM: Connecting AttemptError."); lock (_timeSync) _currState = _prevState; } else { if (_currState == ConnectionStates.Connecting && _connectingAttemptCount != 0) { lock (_timeSync) _currState = _reConnecting; this.AddInfoLog("RCM: To Reconnecting Attempts {0} Timeout {1}.", _connectingAttemptCount, _connectionTimeOut); } else { lock (_timeSync) _currState = _none; } } } break; } case _reConnecting: { if (_connectingAttemptCount == 0) { this.AddWarningLog("RCM: Reconnecting attemts {0} PrevState {1}.", _connectingAttemptCount, FormatState(_prevState)); lock (_timeSync) _currState = _none; break; } _connectionTimeOut -= diff; if (_connectionTimeOut > TimeSpan.Zero) { break; } if (_reConnectionSettings.WorkingTime.IsTradeTime(TimeHelper.Now, out _)) { this.AddInfoLog("RCM: To Connecting. CurrState {0} PrevState {1} Attempts {2}.", FormatState(_currState), FormatState(_prevState), _connectingAttemptCount); if (_connectingAttemptCount != -1) { _connectingAttemptCount--; } _connectionTimeOut = _reConnectionSettings.Interval; //_prevState = _currState; RaiseNewOutMessage(new ReconnectMessage { IsBack = true, Adapter = this }); } else { this.AddWarningLog("RCM: Out of trade time. CurrState {0}.", FormatState(_currState)); _connectionTimeOut = TimeSpan.FromMinutes(1); } break; } } }
private void RefreshDeviceStatusAutoMode() { try { string received = mySerialCommunicator.ReadALine(1200); Debug.Print(received); if (received.Contains("ER=1")) { throw new ER1_Exception("The device lost communication with the temperature probe. The probe will now be disabled and " + "the device must exit Temperature Compensation mode. " + "To continue using the temperature probe, resolve the connection problem and then re-enable the probe."); } else if (received.Contains("P=") && received.Length == 6) { ConsecutivePosTimeouts_AutoMode = 0; // parse the position int pos = int.Parse(received.Substring(2), CultureInfo.InvariantCulture); if (pos != currentPosition) { currentPosition = pos; TriggerAnEvent(DeviceStatusChanged); } } else if (received.Contains("T=") && received.Length == 7) { ConsecutivePosTimeouts_AutoMode = 0; // parse the temperature double temp = double.Parse(received.Substring(2), CultureInfo.InvariantCulture); if (temp != currentTemperature) { currentTemperature = temp; TriggerAnEvent(DeviceStatusChanged); } } } catch (ER1_Exception) { // Try to exit temp comp mode... PauseRefresh(); // Timer is stopped, it is safe to enter serial mode mySerialCommunicator.SendCommand("FMMODE", 1000); mySerialCommunicator.SendCommand("FMMODE", 1000); mySerialCommunicator.SendCommand("FMMODE", 1000); // Set the state connectionState = ConnectionStates.SerialMode; //Disable the probe TempProbeDisabled = true; TriggerAnEvent(DeviceStatusChanged); // Start the timer again ResumeRefresh(); throw; } catch (Exception) { Debug.Print("Consecutive Timeouts = " + ConsecutivePosTimeouts_AutoMode.ToString()); if (ConsecutivePosTimeouts_AutoMode++ > 3) { ConnectionState = ConnectionStates.Disconnected; // TriggerAnEvent(DeviceStatusChanged); throw new ApplicationException("Lost communication with device while in Temp Comp mode. " + "More than 5 consecutive serial timeouts have occurred."); } } }
/// <summary> /// Vykona interny pokus o pripojenie k vzdialenemu bodu /// </summary> /// <param name="starting">Definuje ci ide o pripajanie pri starte alebo reconnecte</param> /// <returns>True = spojenie bolo uspesne vytvorene</returns> private Boolean InternalConnect(Boolean starting) { try { lock (this) { //pokusime sa vytvorit spojenie this.InternalOnConnect(); //ak bol aktivny reconnect tak ho ukoncime this.StopReconnect(); //start komunikacie sa podaril this.m_connectionState = ConnectionStates.Connected; //spojenie bolo vytvorene this.OnConnected(EventArgs.Empty); //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); } //inicializacia komunikacie bola uspesna return true; } catch (Exception) { //ak doslo k chybe pri starte klienta if (starting == true) { throw; } //inicializacia nebola uspesna return false; } }
/// <summary> /// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message. /// </summary> /// <param name="message">The message.</param> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { if (((ConnectMessage)message).Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Connected; // heart beat is disabled if (InnerAdapter.HeartbeatInterval == TimeSpan.Zero) { break; } lock (_timeSync) { _canSendTime = true; _heartBeatTimer = ThreadingHelper.Timer(() => { try { OnHeartbeatTimer(); } catch (Exception ex) { ex.LogError(); } }).Interval(InnerAdapter.HeartbeatInterval); } } else { lock (_timeSync) _prevState = _currState = ConnectionStates.Failed; } break; } case MessageTypes.Disconnect: { lock (_timeSync) { _prevState = _currState = ConnectionStates.Disconnected; if (_heartBeatTimer != null) { _heartBeatTimer.Dispose(); _heartBeatTimer = null; } } break; } } base.OnInnerAdapterNewOutMessage(message); }
public void Disconnect() { ConnectionState = ConnectionStates.Offline; client.Close(); }
/// <summary> /// Overi nastavenia triedy. Vykona start automatickehor reconnectu alebo ukonci klienta /// </summary> private void ValidateConnection() { //overime ci je mozne spustit reconnect if (this.CanAutoReconnect && this.AutoReconnect) { //event o ukonceni spojenia len ak uz bolo oznamenie o connecte if (this.m_connectionState == ConnectionStates.Connected) { //doslo k ukonceniu spojenia this.OnDisconnected(EventArgs.Empty); } //zmenime stav this.m_connectionState = ConnectionStates.Connecting; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //spustime automaticky reconnect this.StartReconnect(); } else { //event o ukonceni spojenia len ak uz bolo oznamenie o connecte if (this.m_connectionState == ConnectionStates.Connected) { //doslo k ukonceniu spojenia this.OnDisconnected(EventArgs.Empty); } //zmenime stav this.m_connectionState = ConnectionStates.Closed; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //ukoncime klienta if (!this.IsDisposed) if (this.IsRun) { //ukoncime klienta this.Stop(); } } }
private void EnterSerialMode() { // Send FMMODE to first to possible get device out of another mode EventLogger.LogMessage("Entering Serial Mode", TraceLevel.Verbose); //RefreshTimer.Stop(); PauseRefresh(); DateTime start = DateTime.Now; string response = ""; bool success = false; try { mySerialCommunicator.SendCommand("FWAKEE", 200); } catch { } mySerialCommunicator.ClearBuffers(); while (DateTime.Now.Subtract(start).TotalSeconds < 5) { try { response = mySerialCommunicator.SendCommand("FMMODE", 1000); if (response == "!") { success = true; break; } else System.Threading.Thread.Sleep(100); } catch (TimeoutException ex) { mySerialCommunicator.ClearBuffers(); EventLogger.LogMessage(ex); } System.Windows.Forms.Application.DoEvents(); } if (success) connectionState = ConnectionStates.SerialMode; else { mySerialCommunicator.ClearBuffers(); throw new ApplicationException("Device failed to enter serial mode"); } // Entered Serial Mode // Next try to get firmware version try { mySerialCommunicator.ClearBuffers(); response = mySerialCommunicator.SendCommand("FVxxxx", 1000); // Firmware version should look like 4.01.3 or 4.0.1 or 4.01.255 or if (response.Length < 6) { Debug.Print("Bad Firmware Version: " + response); throw new ApplicationException("Bad firmware version"); } string FirmVerString = ""; double FirmVerNum = 0; int DecimalIndex = response.IndexOf("."); FirmVerString = response.Substring(0, DecimalIndex + 1); response = response.Substring(DecimalIndex + 1, (response.Length - 1 - DecimalIndex)); // response now looks like 01.3 DecimalIndex = response.IndexOf("."); FirmVerString += response.Substring(0, DecimalIndex); response = response.Substring(DecimalIndex + 1, response.Length - 1 - DecimalIndex); FirmVerNum = double.Parse(FirmVerString, CultureInfo.InvariantCulture); firmwareVersion = "V" + FirmVerString; string DevTypeString = response; int DevTypeNum = int.Parse(response, CultureInfo.InvariantCulture); // Finished parsing the firmware version and device type // Now set the device properties accordingly. // Only set the device type if it has never been set before... switch (DevTypeNum) { case 1: if (FirmVerNum >= 3 && FirmVerNum < 4) deviceType = DeviceTypes.TCF_Si; else deviceType = DeviceTypes.TCF_S; break; case 2: deviceType = DeviceTypes.TCF_Si; break; case 3: if (FirmVerNum >= 3 && FirmVerNum < 4) deviceType = DeviceTypes.TCF_S3i; else deviceType = DeviceTypes.TCF_S3; break; case 4: deviceType = DeviceTypes.TCF_S3i; break; default: // This will happen if the device type has not been selected in firmware but // the firmware defaults to the 2" focuser. if (FirmVerNum >= 3 && FirmVerNum < 4) deviceType = DeviceTypes.TCF_Si; else deviceType = DeviceTypes.TCF_S; break; } // Determine if it has Backlash Compensation if (DeviceIs_i()) { if (FirmVerNum >= FIRST_TCFSI_WITH_BACKLASH) { hasBacklashCompensation = true; } else hasBacklashCompensation = false; } else { if (FirmVerNum >= FIRST_TCFS_WITH_BACKLASH) { hasBacklashCompensation = true; } else hasBacklashCompensation = false; } // Determine if backlash comp is turned on or off. backlashCompEnabled = CheckIfBCEnabled(); // Determine if it can adjust the display brightness if (DeviceIs_i()) { // All the TCF-Si's can adjust the brightness canAdjustBrightness = true; } else { if (FirmVerNum >= FIRST_TCFS_WITH_DISPLAY_ADJUST) canAdjustBrightness = true; else canAdjustBrightness = false; } // Determine if it can report the brightness if (canAdjustBrightness) { if (DeviceIs_i()) { if (FirmVerNum >= FIRST_TCFSI_CAN_REPORT_BRIGHTNESS) canReportBrightness = true; else canReportBrightness = false; } else { if (FirmVerNum >= FIRST_TCFS_CAN_REPORT_BRIGHTNESS) canReportBrightness = true; else canReportBrightness = false; } } // Determine the DisplayBrightnessValue displayBrightness = GetDisplayBrightness(); // Set the class property according to whether the probe is disabled or enabled. tempProbeDisabled = CheckIfTempProbeDisabled(); // Set the current and target positions initially to the same value. GetPos(); targetPosition = (int)currentPosition; } catch (TimeoutException) { // Firmware is too old to report version info. firmwareVersion = OLD_FIRMWARE_STRING; canAdjustBrightness = false; tempProbeDisabled = XMLSettings.TemperatureProbeDisabled; // We know it is not a TCF-Si if (!XMLSettings.DeviceTypeManuallySet) { deviceType = DeviceTypes.TCF_S; } // Set the current and target positions initially to the same value. GetPos(); targetPosition = (int)currentPosition; } tempCoefficientA = GetTempCoefficient('A'); tempCoefficientB = GetTempCoefficient('B'); RefreshDeviceStatus(); ResumeRefresh(); }
public static extern bool InternetGetConnectedState(out ConnectionStates lpdwFlags, long dwReserved);
void signalRConnection_OnStateChanged(Connection manager, ConnectionStates oldState, ConnectionStates newState) { // display state changes messages.Add(string.Format("[State Change] {0} => {1}", oldState.ToString(), newState.ToString())); }
/// <summary> /// Retrieves the connected state of the local system. /// </summary> /// <param name="connectionStates">A <see cref="ConnectionStates"/> value that receives the connection description.</param> /// <returns> /// A return value of true indicates that either the modem connection is active, /// or a LAN connection is active and a proxy is properly configured for the LAN. /// A return value of false indicates that neither the modem nor the LAN is connected. /// If false is returned, the <see cref="ConnectionStates.Configured"/> flag may be set /// to indicate that auto-dial is configured to "always dial" but is not currently active. /// If auto-dial is not configured, the function returns false. /// </returns> public static bool IsConnectedToInternet(out ConnectionStates connectionStates) { connectionStates = ConnectionStates.Unknown; return(InternetGetConnectedState(out connectionStates, 0)); }
static extern bool InternetGetConnectedState(out ConnectionStates lpdwFlags, int dwReserved);
protected override void OnStateChanged(Connection con, ConnectionStates oldState, ConnectionStates newState) { base.OnStateChanged(con, oldState, newState); }
/// <summary> /// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message. /// </summary> /// <param name="message">The message.</param> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { var connectMsg = (ConnectMessage)message; var isRestored = false; var isReconnecting = false; if (connectMsg.Error == null) { isRestored = _prevState == _reConnecting; lock (_timeSync) { _prevState = _currState = ConnectionStates.Connected; _connectionTimeOut = _reConnectionSettings.Interval; _connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } } else { lock (_timeSync) { if (_connectingAttemptCount != 0) { _prevState = _currState == ConnectionStates.Connected ? _reConnecting : ConnectionStates.Failed; _currState = _reConnecting; isReconnecting = true; } else { _prevState = _currState = ConnectionStates.Failed; } } } if (isRestored) { if (!SuppressReconnectingErrors) { RaiseNewOutMessage(new RestoredConnectMessage { Adapter = message.Adapter }); } } else { if (connectMsg.Error == null || !SuppressReconnectingErrors || !isReconnecting) { base.OnInnerAdapterNewOutMessage(message); } } break; } case MessageTypes.Disconnect: { var disconnectMsg = (DisconnectMessage)message; if (disconnectMsg.Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Disconnected; } else { //lock (_timeSync) //{ // if (_currState == ConnectionStates.Connected) // _prevState = _reConnecting; // _currState = _reConnecting; //} //_connectionTimeOut = _reConnectionSettings.Interval; //_connectingAttemptCount = _reConnectionSettings.ReAttemptCount; } base.OnInnerAdapterNewOutMessage(message); break; } default: base.OnInnerAdapterNewOutMessage(message); break; } }
/// <summary> /// Called when the SignalR Connection's state changes. /// </summary> void signalRConnection_OnStateChanged(Connection manager, ConnectionStates oldState, ConnectionStates newState) { messages.Add(string.Format("[State Change] {0} => {1}", oldState, newState)); }
public void Disconnect() { _connState = ConnectionStates.Disconnecting; _ad.Connected = false; }
public PacketKey(int packetId, ConnectionStates connectionState, Bounds bounds) { this.PacketId = packetId; this.ConnectionState = connectionState; this.Bound = bounds; }
internal static bool InternetGetConnectedState(out ConnectionStates lpdwFlags) { return(InternetGetConnectedState(out lpdwFlags, 0)); }
/// <inheritdoc /> protected override void OnSendInMessage(Message message) { var isStartTimer = false; switch (message.Type) { case MessageTypes.Reset: { _prevState = _none; lock (_timeSync) { _currState = _none; StopTimer(); _connectingAttemptCount = 0; _connectionTimeOut = default; _canSendTime = false; _suppressDisconnectError = false; } break; } case MessageTypes.Connect: { if (_isFirstTimeConnect) { _isFirstTimeConnect = false; } else { base.OnSendInMessage(new ResetMessage()); } lock (_timeSync) { _currState = ConnectionStates.Connecting; if (_prevState == _none) { _connectionTimeOut = _reConnectionSettings.TimeOutInterval; _connectingAttemptCount = _reConnectionSettings.AttemptCount; } isStartTimer = true; } break; } case MessageTypes.Disconnect: { lock (_timeSync) { _suppressDisconnectError = _timer != null; _currState = ConnectionStates.Disconnecting; _connectionTimeOut = _reConnectionSettings.TimeOutInterval; StopTimer(); _canSendTime = false; } break; } case MessageTypes.Time: { if (_timeMessage == message) { lock (_timeSync) { if (_currState == ConnectionStates.Disconnecting || _currState == ConnectionStates.Disconnected) { return; } } } break; } case ExtendedMessageTypes.Reconnect: { OnSendInMessage(new ConnectMessage()); return; } } try { base.OnSendInMessage(message); lock (_timeSync) { if (isStartTimer && (_currState == ConnectionStates.Connecting || _currState == ConnectionStates.Connected)) { StartTimer(); } } } finally { if (message == _timeMessage) { lock (_timeSync) _canSendTime = true; } } }
private static extern bool InternetGetConnectedState(out ConnectionStates lpdwFlags, int dwReserved);
private void AdapterOnNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { if (((ConnectMessage)message).Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Connected; // heart beat is disabled if (_adapter.HeartbeatInterval == TimeSpan.Zero) { break; } lock (_timeSync) { _canSendTime = true; _heartBeatTimer = ThreadingHelper.Timer(OnHeartbeatTimer).Interval(_adapter.HeartbeatInterval); } } else { lock (_timeSync) _prevState = _currState = ConnectionStates.Failed; } break; } case MessageTypes.Disconnect: { lock (_timeSync) { _prevState = _currState = ConnectionStates.Disconnected; if (_heartBeatTimer != null) { _heartBeatTimer.Dispose(); _heartBeatTimer = null; } } break; } case MessageTypes.Time: { if (message == _timeMessage) { lock (_timeSync) _canSendTime = true; return; } break; } } _newOutMessage.SafeInvoke(message); }
public void DisconnectVegetablePLC() { ConnectionState = ConnectionStates.Vegetable; client.Close(); }
private void ProcessState(ConnectionStates state, object userState) { State = state; this.UserState = userState; if (PingProgress != null) { EventArgs e = new EventArgs(); //e. .... mozno poslat ve vlastnim EventArgs PingProgress(this, e); } }
private void SetState(ConnectionStates state, string errorReason = null) { if (string.IsNullOrEmpty(errorReason)) { HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "'"); } else { HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "' errorReason: '" + errorReason + "'"); } if (this.State == state) { return; } var previousState = this.State; this.State = state; switch (state) { case ConnectionStates.Initial: case ConnectionStates.Authenticating: case ConnectionStates.Negotiating: case ConnectionStates.CloseInitiated: break; case ConnectionStates.Reconnecting: HTTPManager.Heartbeats.Subscribe(this); break; case ConnectionStates.Connected: // If reconnectStartTime isn't its default value we reconnected if (this.reconnectStartTime != DateTime.MinValue) { try { if (this.OnReconnected != null) { this.OnReconnected(this); } } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "OnReconnected", ex); } } else { try { if (this.OnConnected != null) { this.OnConnected(this); } } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnConnected user code!", ex); } } HTTPManager.Heartbeats.Subscribe(this); this.lastMessageSent = DateTime.UtcNow; // Clean up reconnect related fields this.currentContext = new RetryContext(); this.reconnectStartTime = DateTime.MinValue; this.reconnectAt = DateTime.MinValue; break; case ConnectionStates.Closed: // No errorReason? It's an expected closure. if (string.IsNullOrEmpty(errorReason)) { if (this.OnClosed != null) { try { this.OnClosed(this); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnClosed user code!", ex); } } } else { // If possible, try to reconnect if (this.ReconnectPolicy != null && (previousState == ConnectionStates.Connected || this.reconnectStartTime != DateTime.MinValue)) { // It's the first attempt after a successful connection if (this.reconnectStartTime == DateTime.MinValue) { this.reconnectStartTime = DateTime.UtcNow; try { if (this.OnReconnecting != null) { this.OnReconnecting(this, errorReason); } } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "SetState - ConnectionStates.Reconnecting", ex); } } RetryContext context = new RetryContext { ElapsedTime = DateTime.UtcNow - this.reconnectStartTime, PreviousRetryCount = this.currentContext.PreviousRetryCount, RetryReason = errorReason }; TimeSpan?nextAttempt = null; try { nextAttempt = this.ReconnectPolicy.GetNextRetryDelay(context); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "ReconnectPolicy.GetNextRetryDelay", ex); } // No more reconnect attempt, we are closing if (nextAttempt == null) { HTTPManager.Logger.Warning("HubConnecction", "No more reconnect attempt!"); // Clean up everything this.currentContext = new RetryContext(); this.reconnectStartTime = DateTime.MinValue; this.reconnectAt = DateTime.MinValue; } else { HTTPManager.Logger.Information("HubConnecction", "Next reconnect attempt after " + nextAttempt.Value.ToString()); this.currentContext = context; this.currentContext.PreviousRetryCount += 1; this.reconnectAt = DateTime.UtcNow + nextAttempt.Value; this.SetState(ConnectionStates.Reconnecting); return; } } if (this.OnError != null) { try { this.OnError(this, errorReason); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnError user code!", ex); } } } HTTPManager.Heartbeats.Unsubscribe(this); break; } }
/// <summary> /// Initializes a new instance of the ConnectionStateChangedEventArgs class. /// </summary> public ConnectionStateChangedEventArgs(ConnectionStates state) { State = state; }
void OnSignalRStatusChange(Connection conection, ConnectionStates oldState, ConnectionStates newState) { }
/// <summary> /// Display state changes /// </summary> void signalRConnection_OnStateChanged(Connection connection, ConnectionStates oldState, ConnectionStates newState) { messages.Add(string.Format("[State Change] {0} => {1}", oldState, newState)); }
public override void OnDisconnected(NetConnection connection, string reason, bool lostConnection) { ConnectionStates.Remove(connection); base.OnDisconnected(connection, reason, lostConnection); }
public ConnectionManager() { this.State = ConnectionStates.Disconnected; }
public override void OnConnected(NetConnection connection) { ConnectionStates.Add(connection, new NetConnectionSnapshotState(snapshotSystem, connection)); base.OnConnected(connection); }
private void ChangeConnectionState(ConnectionStates value) { switch (value) { #region Disconnected case ConnectionStates.Disconnected: try { switch (connectionState) { case ConnectionStates.Disconnected: // The port is already closed, just set the mode break; case ConnectionStates.SerialMode: // Release the device ReleaseDevice(); break; case ConnectionStates.Sleep: // Wake up the device, (into serial mode) // WakeDevice(); // COMMENTED OUT FOR VERSION 5.3.0, This is undesired // Release the device ReleaseDevice(); break; case ConnectionStates.TempCompMode: // Get the device back into serial mode try { ExitTempCompMode(); ReleaseDevice(); } catch { } break; default: // Should never get here. Something is wrong... throw new ApplicationException("Tried to disconnect from unknown mode"); } //RefreshTimer.Stop(); } catch (Exception) { throw; } finally { // Close the port mySerialCommunicator.CloseThePort(); // Set the mode connectionState = ConnectionStates.Disconnected; } break; #endregion #region Serial Mode case ConnectionStates.SerialMode: try { switch (connectionState) { case ConnectionStates.Disconnected: EnterSerialMode(); break; case ConnectionStates.SerialMode: return; case ConnectionStates.Sleep: // Wake up the device WakeDevice(); // Then enter serial mode break; case ConnectionStates.TempCompMode: // Exit temp comp mode enters into serial mode ExitTempCompMode(); break; default: throw new ApplicationException("Tried to disconnect from unknown mode"); } } catch { throw; } break; #endregion #region TempCompMode case ConnectionStates.TempCompMode: // Check what the current state is... switch (connectionState) { case ConnectionStates.Disconnected: throw new ApplicationException("You must connect to device before you can enter temp comp mode"); case ConnectionStates.SerialMode: EnterTempCompMode(); break; case ConnectionStates.Sleep: // Wake up the device, and go into serial mode... WakeDevice(); // Enter temp comp mode... EnterTempCompMode(); break; case ConnectionStates.TempCompMode: return; } break; #endregion #region Sleep case ConnectionStates.Sleep: switch (connectionState) { case ConnectionStates.Disconnected: throw new ApplicationException("You must connect to device before you can put the device to sleep."); case ConnectionStates.SerialMode: EnterSleepMode(); break; case ConnectionStates.Sleep: return; case ConnectionStates.TempCompMode: ExitTempCompMode(); EnterSleepMode(); break; } break; #endregion } }
private void EnterTempCompMode() { // first check that the probe is enabled if (tempProbeDisabled) throw new ApplicationException("Cannot use temperature compensation when the temperature probe is disabled. Enable the probe and try again."); Debug.Print("Entering Temp Comp Mode"); try { // Stop the Timer... PauseRefresh(); // Timer is stopped, it is safe to enter serial mode string r = mySerialCommunicator.SendCommand("F" + tempCompMode + "MODE", 2000); if (r.Contains(tempCompMode.ToString())) connectionState = ConnectionStates.TempCompMode; ResumeRefresh(); } catch (Exception) { throw; } }
/// <summary> /// Internally handled disconnection and event pass through /// </summary> private void OnInternalDisconnected() { _currentState = ConnectionStates.Disconnected; OnDisconnected?.Invoke(); }
private void ReleaseDevice() { if (connectionState == ConnectionStates.Sleep) { PauseRefresh(); // Stop the Refresh Timer connectionState = ConnectionStates.Disconnected; return; } else if (connectionState != ConnectionStates.SerialMode) throw new ApplicationException("Can not release device when not in serial mode"); // Stop the Timer... try { PauseRefresh(); } catch { } DateTime Start = DateTime.Now; string r = ""; try { while (DateTime.Now.Subtract(Start).TotalSeconds < 1.5) { r = mySerialCommunicator.SendCommand("FFxxxx", 700); if (r.Contains("END")) { break; } System.Windows.Forms.Application.DoEvents(); } } catch (TimeoutException) { // Timeout exception could mean the device is alredy released // Don't catch any other exceptions because we don't know the cause of them } catch (Exception) { } finally { connectionState = ConnectionStates.Disconnected; } }
/// <summary> /// Spusti automaticky connect k sql serveru /// </summary> /// <returns>True = spojenie bolo vytvorene, inak false</returns> private bool InternalConnect() { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Spustenie automatickeho pripajania k SQL serveru."); //zmena stavu this._state = ConnectionStates.Connecting; //zmena stavu this.OnConnectionStateChange(EventArgs.Empty); //pokus o vytvorenie spojenia if (this.InternalOpenConnection()) { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Spojenie so serverom bolo uspesne vytvorene."); //zmena stavu spojenia this._state = ConnectionStates.Connected; //oznamenie o zmene stavu this.OnConnectionStateChange(EventArgs.Empty); //spojenie je vytvorene return true; } else { //zalogujeme this.InternalTrace(TraceTypes.Error, "Spojenie so serverom sa nepodarilo vytvorit."); //zmena stavu spojenia this._state = ConnectionStates.Connected; //oznamenie o zmene stavu this.OnConnectionStateChange(EventArgs.Empty); //spojenie nei je vytvorene return false; } }
private void OnConnectionChanged(eConnectionState state) { try { _adapter.AddInfoLog("OnConnectionChanged {0}", state); switch (state) { case eConnectionState.Connected: _connState = ConnectionStates.Connected; Connected.SafeInvoke(); break; case eConnectionState.Disconnected: if (_connState == ConnectionStates.Disconnecting) Disconnected.SafeInvoke(); else ConnectionError.SafeInvoke(new AlfaException(tagStateCodes.stcNotConnected, LocalizedStrings.Str1611)); _connState = ConnectionStates.Disconnected; break; default: ConnectionError.SafeInvoke(new InvalidOperationException("Error eConnectionState: " + state)); break; } } catch (Exception e) { _adapter.AddErrorLog(LocalizedStrings.Str2273Params, e); Error.SafeInvoke(e); } }
/// <summary> /// Ukonci automaticky reconnect alebo aktivne spojenie k sql serveru /// </summary> private void InternalDisconnect() { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Ukoncenie spojenia, alebo automatickeho pripajania k SQL serveru."); //ukoncime komunikaciu this.InternalCloseConnection(); //zmena stavu this._state = ConnectionStates.Closed; //zmena stavu this.OnConnectionStateChange(EventArgs.Empty); }
/// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> public override void SendInMessage(Message message) { var isStartTimer = false; switch (message.Type) { case MessageTypes.Reset: { _prevState = _none; lock (_timeSync) { _currState = _none; StopTimer(); _connectingAttemptCount = 0; _connectionTimeOut = default(TimeSpan); _canSendTime = false; } break; } case MessageTypes.Connect: { if (_isFirstTimeConnect) { _isFirstTimeConnect = false; } else { base.SendInMessage(new ResetMessage()); } lock (_timeSync) { _currState = ConnectionStates.Connecting; if (_prevState == _none) { _connectionTimeOut = _reConnectionSettings.TimeOutInterval; _connectingAttemptCount = _reConnectionSettings.AttemptCount; } isStartTimer = true; } break; } case MessageTypes.Disconnect: { lock (_timeSync) { _currState = ConnectionStates.Disconnecting; _connectionTimeOut = _reConnectionSettings.TimeOutInterval; StopTimer(); _canSendTime = false; } break; } case ExtendedMessageTypes.Reconnect: { SendInMessage(new ConnectMessage()); break; } } base.SendInMessage(message); lock (_timeSync) { if (isStartTimer && (_currState == ConnectionStates.Connecting || _currState == ConnectionStates.Connected)) { StartTimer(); } } if (message != _timeMessage) { return; } lock (_timeSync) _canSendTime = true; }
/// <summary> /// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message. /// </summary> /// <param name="message">The message.</param> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { if (((ConnectMessage)message).Error == null) { lock (_timeSync) _prevState = _currState = ConnectionStates.Connected; // heart beat is disabled if (InnerAdapter.HeartbeatInterval == TimeSpan.Zero) break; lock (_timeSync) { _canSendTime = true; _heartBeatTimer = ThreadingHelper.Timer(OnHeartbeatTimer).Interval(InnerAdapter.HeartbeatInterval); } } else { lock (_timeSync) _prevState = _currState = ConnectionStates.Failed; } break; } case MessageTypes.Disconnect: { lock (_timeSync) { _prevState = _currState = ConnectionStates.Disconnected; if (_heartBeatTimer != null) { _heartBeatTimer.Dispose(); _heartBeatTimer = null; } } break; } case MessageTypes.Time: { if (message == _timeMessage) { lock (_timeSync) _canSendTime = true; return; } break; } } base.OnInnerAdapterNewOutMessage(message); }
private void SetState(ConnectionStates state, string errorReason = null) { HTTPManager.Logger.Information("HubConnection", "SetState - from State: " + this.State.ToString() + " to State: " + state.ToString() + " errorReason: " + errorReason ?? string.Empty); if (this.State == state) { return; } this.State = state; switch (state) { case ConnectionStates.Initial: case ConnectionStates.Authenticating: case ConnectionStates.Negotiating: case ConnectionStates.CloseInitiated: break; case ConnectionStates.Connected: try { if (this.OnConnected != null) { this.OnConnected(this); } } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnConnected user code!", ex); } break; case ConnectionStates.Closed: if (string.IsNullOrEmpty(errorReason)) { if (this.OnClosed != null) { try { this.OnClosed(this); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnClosed user code!", ex); } } } else { if (this.OnError != null) { try { this.OnError(this, errorReason); } catch (Exception ex) { HTTPManager.Logger.Exception("HubConnection", "Exception in OnError user code!", ex); } } } break; } }