public override void Close(TimeSpan timeout) { lock (thisLock) { this.state = CommunicationState.Closed; } }
public ConnectionState(int instanceId, ProxyState proxyState, CommunicationState commState, string proxyType) { this.InstanceId = instanceId; this.ProxyState = proxyState; this.CommState = commState; this.ProxyType = proxyType; }
protected virtual void SetState(CommunicationState state) { State = state; switch (state) { case CommunicationState.Created: break; case CommunicationState.Opening: Opening?.Invoke(this, new EventArgs()); break; case CommunicationState.Opened: Opened?.Invoke(this, new EventArgs()); break; case CommunicationState.Closing: Closing?.Invoke(this, new EventArgs()); break; case CommunicationState.Closed: Closed?.Invoke(this, new EventArgs()); break; case CommunicationState.Faulted: Faulted?.Invoke(this, new EventArgs()); break; default: throw new ArgumentOutOfRangeException(nameof(state), state, null); } StateChanged?.Invoke(this, new EventArgs()); }
public void ReInitialize(Message requestMessage) { this.state = CommunicationState.Opened; this.requestMessageException = null; this.replySent = false; this.replyInitiated = false; this.aborted = false; this.requestMessage = requestMessage; }
public FileRequestContext(Message message, FileReplyChannel parent) { this.aborted = false; this.message = message; this.parent = parent; this.state = CommunicationState.Opened; this.thisLock = new object(); this.writeLock = new object(); }
public void GetStateTest() { SGServiceHost target = new SGServiceHost(); // TODO: Initialize to an appropriate value CommunicationState expected = new CommunicationState(); // TODO: Initialize to an appropriate value CommunicationState actual; actual = target.GetState(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public ToGameClient(SilverSocket socket) { _socket = socket; { socket.OnDataArrivalEvent += DataArrival; socket.OnSocketClosedEvent += OnSocketClosed; } _communicationState = CommunicationState.VerifyGame; }
internal SharedConnectionListener(BaseUriWithWildcard baseAddress, int queueId, Guid token, Func<Uri, int> onDuplicatedViaCallback) { this.baseAddress = baseAddress; this.queueId = queueId; this.token = token; this.onDuplicatedViaCallback = onDuplicatedViaCallback; this.connectionQueue = TraceUtility.CreateInputQueue<DuplicateConnectionAsyncResult>(); this.state = CommunicationState.Created; this.reconnectEvent = new ManualResetEvent(true); this.StartListen(false); }
public override void Abort() { lock (thisLock) { if (this.aborted) { return; } this.aborted = true; this.state = CommunicationState.Faulted; } }
public override void Abort() { lock (_aLock) { if (_aborted) { return; } _aborted = true; _state = CommunicationState.Faulted; } }
public void Open() { lock (this.thisLock) { if (this.currentState != CommunicationState.Created) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CommunicationObjectCannotBeModified, this.GetType().ToString()))); } this.currentState = CommunicationState.Opened; this.ScheduleRetryTimerIfNotSet(); } }
protected AppDomainHost(Type serviceType,AppDomain appDomain,PermissionSet permissions,Uri[] baseAddresses) { State = CommunicationState.Faulted; //Cannot grant service permissions the host does not have permissions.Demand(); string assemblyName = Assembly.GetAssembly(typeof(ServiceHostActivator)).FullName; m_ServiceHostActivator = appDomain.CreateInstanceAndUnwrap(assemblyName,typeof(ServiceHostActivator).ToString()) as ServiceHostActivator; appDomain.SetPermissionsSet(permissions); m_ServiceHostActivator.CreateHost(serviceType,baseAddresses); State = CommunicationState.Created; }
public MessageBusRequestContext( Message message, MessageBusReplyChannel parent, EndpointAddress address, IBus bus, string relatedTo) { _aborted = false; _parent = parent; _message = message; _address = address; _busMessageId = relatedTo; _bus = bus; _aLock = new object(); _state = CommunicationState.Opened; }
/// <summary> /// Causes a communication object to transition immediately from its current state into the closing state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task AbortAsync(CancellationToken token = default(CancellationToken)) { await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { if (this.aborted || this.State == CommunicationState.Closed) { return; } this.aborted = true; this.State = CommunicationState.Closing; } finally { this.semaphore.Release(); } bool flag2 = true; try { await this.OnClosingAsync(token).ConfigureAwait(false); if (!this.onClosingCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnClosingAsync did not call await base.OnClosingAsync"); } await this.OnAbortAsync(token).ConfigureAwait(false); await this.OnClosedAsync(token).ConfigureAwait(false); if (!this.onClosedCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnClosedAsync did not call await base.OnClosedAsync"); } flag2 = false; } finally { if (flag2) { Log.Warn($"{this.GetType().Name}.AbortAsync failed."); } } }
private void Close() { lock (this.ThisLock) { if (this.state == CommunicationState.Closed) { return; } this.state = CommunicationState.Closed; } if (this.connectionQueue != null) { this.connectionQueue.Close(); } if (this.reconnectEvent != null) { this.reconnectEvent.Close(); } }
protected virtual void OnClosed() { this.onClosedCalled = true; lock (this.ThisLock) { if (!this.raisedClosed) { this.raisedClosed = true; this.state = CommunicationState.Closed; } else { return; } } if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceVerbose) { DiagnosticTrace diagnosticTrace = Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.DiagnosticTrace; string traceCodeCommunicationObjectClosed = Resources.TraceCodeCommunicationObjectClosed; object[] objArray = new object[] { DiagnosticTrace.CreateSourceString(this) }; diagnosticTrace.TraceEvent(TraceEventType.Verbose, TraceCode.CommunicationObjectClosed, Microsoft.ServiceBus.SR.GetString(traceCodeCommunicationObjectClosed, objArray), null, null, this); } EventHandler eventHandler = this.Closed; if (eventHandler != null) { try { eventHandler(this.eventSender, EventArgs.Empty); } catch (Exception exception1) { Exception exception = exception1; if (!Fx.IsFatal(exception)) { throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } throw; } } }
public override async Task CloseAsync(CancellationToken token) { bool sendAck = false; lock (ThisLock) { if (_state != CommunicationState.Opened) { return; } if (TryInitiateReply()) { sendAck = true; } _state = CommunicationState.Closing; } bool throwing = true; try { if (sendAck) { await OnReplyAsync(null, token); } await OnCloseAsync(token); _state = CommunicationState.Closed; throwing = false; } finally { if (throwing) { Abort(); } } }
public void Close() { if (State != CommunicationState.Opened) { return; } try { Closing(this, EventArgs.Empty); m_ServiceHostActivator.Close(); State = CommunicationState.Closed; Closed(this, EventArgs.Empty); } catch { State = CommunicationState.Faulted; } }
private void clear() { _ecustate = ICommunication.ECUState.NotInitialized; _startctr = 0; _timeout = 0; _wakeupRetries = 1; _echo = 0; _idlesent = false; _kw1 = 0; _kw2 = 0; _syncseen = false; _kw1seen = false; _kw2seen = false; _invaddrseen = false; _sendctr = 0; _state = CommunicationState.Start; }
/// <summary> /// Finds any HW device /// </summary> /// <returns>Result.eERR_SUCCESS if successfull</returns> public Result FindHW() { Result result = Result.eERR_INITIAL_STATE; if (CommState == CommunicationState.Ready) { STBLogger.AddEvent(ToString(), STBLogger.EventLevel.Information, "Find HW: The comm driver was already initialized.", "Comm Drv CommunicationState:" + CommState.ToString() + " Extended Find HW"); result = Result.eERR_NOT_READY; } else if (CommState == CommunicationState.Idle) { result = Result.eERR_SUCCESS; lock (objectLock) CommState = CommunicationState.HWFind; IsExtendedFindHW = true; SetCommStatus(""); } return(result); }
public override void Close(TimeSpan timeout) { try { try { this.communicationState = CommunicationState.Closing; this.amqpRelay.CloseAsync(timeout).Wait(); } catch (AggregateException aggregateException1) { AggregateException aggregateException = aggregateException1; throw Fx.Exception.AsWarning(aggregateException.GetBaseException(), this.client.Activity); } } finally { this.receivedMessages.Close(); this.OnClosed(); } }
public AmqpRelayedConnection(RelayedOnewayListener.RelayedOnewayAmqpListenerClient client, System.Uri via, ConnectivitySettings connectivitySettings, HttpConnectivitySettings httpConnectivitySettings) : base(via) { this.communicationState = CommunicationState.Created; this.client = client; this.receivedMessages = new InputQueue <Message>(); this.amqpRelay = new AmqpRelay(client.Uri, client.TokenProvider, connectivitySettings, httpConnectivitySettings); this.amqpRelay.Connecting += new EventHandler((object s, EventArgs e) => base.RaiseClosed(this, e)); this.amqpRelay.Offline += new EventHandler((object s, EventArgs e) => base.RaiseFaulted(this, e)); ServiceSettings serviceSettings = client.listener.nameSettings.ServiceSettings; if (serviceSettings.RelayClientAuthenticationType == RelayClientAuthenticationType.None) { this.amqpRelay.RelayClientAuthorizationRequired = false; } this.amqpRelay.DisplayName = client.listener.nameSettings.DisplayName; this.amqpRelay.ListenerType = serviceSettings.ListenerType; this.amqpRelay.IsDynamic = serviceSettings.IsDynamic; this.amqpRelay.ClientAgent = serviceSettings.ClientAgent; this.amqpRelay.PublishToRegistry = serviceSettings.IsDiscoverable; this.amqpRelay.TransportSecurityRequired = serviceSettings.TransportProtection == RelayTransportProtectionMode.EndToEnd; }
private void HandleInitByte(byte b) { if (!_syncseen) { if (b == SYNC_BYTE) { _syncseen = true; Console.WriteLine("Sync byte received!"); } //CastInfoEvent("Synchronization in progress", 0); } else { if (!_kw1seen) { _kw1seen = true; _kw1 = b; } else if (!_kw2seen) { _kw2seen = true; _kw2 = b; //TODO: need to apply W4 delay (25-50ms) before sending this? SendAck(_kw2, true); Console.WriteLine("Keywords: " + _kw1.ToString("X2") + _kw2.ToString("X2")); //AddToLog("kw1: " + kw1.ToString("X2") + " kw2: " + kw2.ToString("X2")); //AddToLog("Entering idle state"); } else if (!_invaddrseen) { _invaddrseen = true; _state = CommunicationState.Idle; _timeout = 0; _ecustate = ICommunication.ECUState.CommunicationRunning; CastInfoEvent("Communication ready", 0); CastECUInfoEvent(3, "M2.10.3"); //a bit of hack but works Console.WriteLine("Inverted address received!"); } } }
public void Abort() { lock (this.ThisLock) { if (this.aborted || (this.state == CommunicationState.Closed)) { return; } this.aborted = true; this.state = CommunicationState.Closing; } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, 0x80002, System.ServiceModel.SR.GetString("TraceCodeCommunicationObjectAborted", new object[] { TraceUtility.CreateSourceString(this) }), this); } bool flag = true; try { this.OnClosing(); if (!this.onClosingCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); } this.OnAbort(); this.OnClosed(); if (!this.onClosedCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } flag = false; } finally { if (flag && DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, 0x80003, System.ServiceModel.SR.GetString("TraceCodeCommunicationObjectAbortFailed", new object[] { this.GetCommunicationObjectType().ToString() }), this); } } }
//Metodo que se llama para poder saber cuando se pierde una conexión y en otras circustancias public static void GestionarProxy() { if (proxy != null) { estadoComunicacion = proxy.State; switch (proxy.State) { case CommunicationState.Closed: proxy = null; estadoConversacion = "Desconectado"; break; case CommunicationState.Closing: estadoConversacion = "Cerrando..."; break; case CommunicationState.Created: estadoConversacion = "Creada..."; break; case CommunicationState.Faulted: proxy.Abort(); proxy = null; estadoConversacion = "Fallida"; break; case CommunicationState.Opened: estadoConversacion = "Conectado"; break; case CommunicationState.Opening: estadoConversacion = "Abriendo..."; break; default: break; } ActualizarInterfaceConversacion(null, new EventArgs()); } }//Gestionar Proxy
public static void Close(this ICommunicationObject communicationObject, bool throwOnException = true) { if (communicationObject == null) { return; } try { CommunicationState state = communicationObject.State; if (CommunicationState.Faulted == state) { communicationObject.Abort(); } else { if (state == CommunicationState.Closing || state == CommunicationState.Closed) { return; } communicationObject.Close(); } } catch (CommunicationException ex) { communicationObject.Abort(); } catch (TimeoutException ex) { communicationObject.Abort(); } catch (Exception ex) { communicationObject.Abort(); if (!throwOnException) { return; } throw; } }
private void verifyList() { //myClients = myClients.Where(c => ((ICommunicationObject)c.client).State == CommunicationState.Opened).ToList(); Dictionary <string, ClientInstance> updated_myClients = new Dictionary <string, ClientInstance>(); foreach (KeyValuePair <string, ClientInstance> cItem in myClients) { ICommunicationObject oComm = cItem.Value.client as ICommunicationObject; CommunicationState state = oComm.State; if (state == CommunicationState.Opened) { updated_myClients.Add(cItem.Key, cItem.Value); } } myClients = updated_myClients; /* myClients = myClients * .Where(c => ((ICommunicationObject)c.Value.client).State == CommunicationState.Opened) * .ToDictionary(c => c.Key, c=> c.Value);*/ //adminClients = adminClients.Where(c => ((ICommunicationObject)c).State == CommunicationState.Opened).ToList(); }
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { IAsyncResult result2; if (timeout < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", System.ServiceModel.SR.GetString("SFxTimeoutOutOfRange0"))); } lock (this.ThisLock) { this.ThrowIfDisposedOrImmutable(); this.state = CommunicationState.Opening; } bool flag = true; try { this.OnOpening(); if (!this.onOpeningCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this); } IAsyncResult result = new OpenAsyncResult(this, timeout, callback, state); flag = false; result2 = result; } finally { if (flag) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, 0x80005, System.ServiceModel.SR.GetString("TraceCodeCommunicationObjectOpenFailed", new object[] { this.GetCommunicationObjectType().ToString() }), this); } this.Fault(); } } return(result2); }
/* ******************** */ /* ******************** */ /* Generic */ /* ******************** */ /* ******************** */ #region Generic /* TestCallBack */ /* ******************** */ #region TestCallBack bool TestCallBack(ReneServiceCallback callback) { try { CommunicationState state = ((IChannel)callback).State; if (state == CommunicationState.Closed || state == CommunicationState.Faulted) { foreach (ReneServiceCallbackUserPair rs in ReneCommunicatorService.ReneServiceCallbackUserPairs) { if (rs.ReneServiceCallback == callback) { UserDisconnect(rs.User); ReneCommunicatorService.ReneServiceCallbackUserPairs.Remove(rs); return(false); } } } else if (state == CommunicationState.Opened) { //Is it REALLY opened? Guid g = callback.User().PublicKey; } } catch (Exception e) { foreach (ReneServiceCallbackUserPair rs in ReneCommunicatorService.ReneServiceCallbackUserPairs) { if (rs.ReneServiceCallback == callback) { UserDisconnect(rs.User); ReneCommunicatorService.ReneServiceCallbackUserPairs.Remove(rs); return(false); } } return(false); } return(true); }
protected override bool TryGetChannel(TimeSpan timeout) { CommunicationState currentState = this.State; TChannel channel = null; if ((currentState == CommunicationState.Created) || (currentState == CommunicationState.Opening) || (currentState == CommunicationState.Opened)) { channel = this.factory.CreateChannel(this.to, this.via); if (!this.Synchronizer.SetChannel(channel)) { channel.Abort(); } } else { channel = null; } return(true); }
protected void Fault(Exception ex = null) { if (ex != null) { Console.WriteLine("Fault: {0}", ex.ToString()); } lock (ThisLock) { if (_state == CommunicationState.Closed || _state == CommunicationState.Closing) { return; } if (_state == CommunicationState.Faulted) { return; } _state = CommunicationState.Faulted; } OnFaulted(); }
protected override Task <bool> TryGetChannelAsync(TimeSpan timeout) { CommunicationState currentState = State; TChannel channel = null; if ((currentState == CommunicationState.Created) || (currentState == CommunicationState.Opening) || (currentState == CommunicationState.Opened)) { channel = _factory.CreateChannel(_to, Via); if (!Synchronizer.SetChannel(channel)) { channel.Abort(); } } else { channel = null; } return(Task.FromResult(true)); }
private void CommunicationMessage(CommunicationState state, string message) { if (state == CommunicationState.Connected) { isOnlineMode = true; Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadDelegate(MakeGameBoard)); Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadDelegate(ConnectedMessage)); } else if (state == CommunicationState.MessageRecieved) { if (message[0] == 't') //turn message { int x = Convert.ToInt32(message[1].ToString()); int y = Convert.ToInt32(message[2].ToString()); int z = Convert.ToInt32(message[3].ToString()); int p = Convert.ToInt32(message[4].ToString()); Move recievedMove = new Move(x, y, z); if (p == ((int)PlayerNumber.First)) { recievedMove.Player = PlayerNumber.First; } else if (p == ((int)PlayerNumber.Second)) { recievedMove.Player = PlayerNumber.Second; } else { return; //error } Dispatcher.Invoke(DispatcherPriority.Normal, new NextMoveNotify(ThreadSafeUpdate), recievedMove); } else if (message[0] == 'g') //new game message { Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadDelegate(MakeGameBoard)); } } }
protected virtual void OnClosed() { this.onClosedCalled = true; lock (ThisLock) { if (this.raisedClosed) { return; } this.raisedClosed = true; this.state = CommunicationState.Closed; } if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.CommunicationObjectClosed, SR.GetString(SR.TraceCodeCommunicationObjectClosed, TraceUtility.CreateSourceString(this)), this); } EventHandler handler = Closed; if (handler != null) { try { handler(eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } }
protected override bool TryGetChannel(TimeSpan timeout) { CommunicationState state = base.State; TChannel channel = default(TChannel); switch (state) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Opened: channel = this.factory.CreateChannel(this.to, this.via); if (!base.Synchronizer.SetChannel(channel)) { channel.Abort(); } break; default: channel = default(TChannel); break; } return(true); }
public override void Abort() { lock (ThisLock) { if (_state == CommunicationState.Closed) { return; } _state = CommunicationState.Closing; _aborted = true; } try { this.OnAbort(); } finally { _state = CommunicationState.Closed; } }
public void Parse(string inputBuffer, CommunicationState communicationState) { if (communicationState == CommunicationState.Open) { if (inputBuffer.Contains("Y")) { NotifyLogData(communicationState, null); } } else if (communicationState == CommunicationState.Reading) { var charAry = inputBuffer.Split(' '); List<string > lst = new List<string>(); foreach (var s in charAry) { if(!string.IsNullOrWhiteSpace(s)) lst.Add(s); } AddToReading(lst); } }
public void DoEvents(int callTime, string dataStream) { try { lastConnectTimeMS = callTime; communicationFrame.Clear(); communicationFrame = fastJSON.JSON.ToObject <CommunicationFrame>(dataStream); if (communicationState == CommunicationState.DISCONNECTED || communicationState == CommunicationState.WAITFORDATA) { ProcessStream(); communicationState = CommunicationState.SENDRESP; } if (communicationState == CommunicationState.SENDRESP) { string sendStream = StreamBuilder(CommandList.RESP_OK); Communication.SendStream(deviceIPAddress, sendStream); DebugInfo.debugInfo.Add("设备" + deviceName + " (" + deviceIPAddress + ") 发送: " + sendStream); communicationState = CommunicationState.WAITFORDATA; } } catch (Exception) { }; }
internal void BindIncomingChannel(ServiceChannel channel) { this.ThrowIfDisposed(); channel.InstanceContext = this; IChannel proxy = (IChannel)channel.Proxy; this.channels.AddIncomingChannel(proxy); // CSDMain 265783: Memory Leak on Chat Stress test scenario // There's a race condition while on one thread we received a new request from underlying sessionful channel // and on another thread we just aborted the channel. So the channel will be added to the IncomingChannels list of // ServiceChannelManager and never get a chance to be removed. if (proxy != null) { CommunicationState state = channel.State; if (state == CommunicationState.Closing || state == CommunicationState.Closed || state == CommunicationState.Faulted) { this.channels.RemoveChannel(proxy); } } }
public void Abort() { lock (ThisLock) { if (Aborted || _state == CommunicationState.Closed) { return; } Aborted = true; _state = CommunicationState.Closing; } try { OnClosing(); if (!_onClosingCalled) { throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); } OnAbort(); OnClosed(); if (!_onClosedCalled) { throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } } finally { } }
public override void Abort() { lock (this.ThisLock) { if (this.state == CommunicationState.Closed) { return; } this.state = CommunicationState.Closing; this.aborted = true; } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, 0x4001e, System.ServiceModel.SR.GetString("TraceCodeRequestContextAbort"), this); } try { this.OnAbort(); } finally { this.state = CommunicationState.Closed; } }
protected void Fault() { lock (ThisLock) { if (this.state == CommunicationState.Closed || this.state == CommunicationState.Closing) { return; } if (this.state == CommunicationState.Faulted) { return; } #if DEBUG if (faultedStack == null) { faultedStack = new StackTrace(); } #endif this.state = CommunicationState.Faulted; } OnFaulted(); }
/// <summary> /// 刷新服务的地址端口,自动关闭,关闭后自动打开 /// </summary> /// <param name="port">地址端口</param> public bool UpdateAddressPort(int port) { bool bResult = true; CommunicationState state = this.State; if (this.State == CommunicationState.Opened) { Close(); } try { IEnumerable <ContractDescription> cds = GetContracts(Meta.ServiceType); ServiceEndpoint se = this.Description.Endpoints.First <ServiceEndpoint>(e => cds.Count(cd => cd.ContractType == e.Contract.ContractType) > 0); string IP4v = CommonUtility.GetHostIP4v(); var builder = new UriBuilder("net.tcp", IP4v, port, Meta.Name); EndpointAddress addrNew = new EndpointAddress(builder.Uri); se.Address = addrNew; } catch (ArgumentNullException) { bResult = false; } catch (InvalidOperationException) { bResult = false; } if (state == CommunicationState.Opened) { Open(); } return(bResult); }
public void Abort() { lock (ThisLock) { if (this.aborted || this.state == CommunicationState.Closed) return; this.aborted = true; #if DEBUG if (closeStack == null) closeStack = new StackTrace(); #endif this.state = CommunicationState.Closing; } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.CommunicationObjectAborted, SR.GetString(SR.TraceCodeCommunicationObjectAborted, TraceUtility.CreateSourceString(this)), this); } bool throwing = true; try { OnClosing(); if (!this.onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); OnAbort(); OnClosed(); if (!this.onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); throwing = false; } finally { if (throwing) { if (DiagnosticUtility.ShouldTraceWarning) TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectAbortFailed, SR.GetString(SR.TraceCodeCommunicationObjectAbortFailed, this.GetCommunicationObjectType().ToString()), this); } } }
protected virtual void OnOpened() { this.onOpenedCalled = true; lock (ThisLock) { if (this.aborted || this.state != CommunicationState.Opening) return; this.state = CommunicationState.Opened; } if (DiagnosticUtility.ShouldTraceVerbose) TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.CommunicationObjectOpened, SR.GetString(SR.TraceCodeCommunicationObjectOpened, TraceUtility.CreateSourceString(this)), this); EventHandler handler = Opened; if (handler != null) { try { handler(eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } }
public void Open(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.GetString(SR.SFxTimeoutOutOfRange0))); using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity && this.TraceOpenAndClose ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, this.OpenActivityName, this.OpenActivityType); } lock (ThisLock) { ThrowIfDisposedOrImmutable(); this.state = CommunicationState.Opening; } bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnOpening(); if (!this.onOpeningCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this); OnOpen(actualTimeout.RemainingTime()); OnOpened(); if (!this.onOpenedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpened"), Guid.Empty, this); throwing = false; } finally { if (throwing) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectOpenFailed, SR.GetString(SR.TraceCodeCommunicationObjectOpenFailed, this.GetCommunicationObjectType().ToString()), this); } Fault(); } } } }
protected void Fault() { lock (ThisLock) { if (this.state == CommunicationState.Closed || this.state == CommunicationState.Closing) return; if (this.state == CommunicationState.Faulted) return; #if DEBUG if (faultedStack == null) faultedStack = new StackTrace(); #endif this.state = CommunicationState.Faulted; } OnFaulted(); }
internal CommunicationObject(object mutex, object eventSender) { this.mutex = mutex; this.eventSender = eventSender; this.state = CommunicationState.Created; }
protected CommunicationObject(object mutex) { this.mutex = mutex; this.eventSender = this; this.state = CommunicationState.Created; }
/// <summary> /// Causes a communication object to transition from its current state into the closed state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task CloseAsync(CancellationToken token = default(CancellationToken)) { CommunicationState communicationState; await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { communicationState = this.State; if (communicationState != CommunicationState.Closed) { this.State = CommunicationState.Closing; } this.closeCalled = true; } finally { this.semaphore.Release(); } switch (communicationState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: await this.AbortAsync(token).ConfigureAwait(false); if (communicationState == CommunicationState.Faulted) { throw new InvalidOperationException($"{this.GetType().Name} faulted."); } break; case CommunicationState.Opened: { bool flag2 = true; try { await this.OnClosingAsync(token).ConfigureAwait(false); if (!this.onClosingCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnClosingAsync did not call await base.OnClosingAsync"); } await this.OnCloseAsync(token).ConfigureAwait(false); await this.OnClosedAsync(token).ConfigureAwait(false); if (!this.onClosedCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnClosedAsync did not call await base.OnClosedAsync"); } flag2 = false; return; } finally { if (flag2) { Log.Warn($"{this.GetType().Name}.CloseAsync failed."); await this.AbortAsync(token).ConfigureAwait(false); } } } case CommunicationState.Closing: case CommunicationState.Closed: break; } }
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.GetString(SR.SFxTimeoutOutOfRange0))); lock (ThisLock) { ThrowIfDisposedOrImmutable(); this.state = CommunicationState.Opening; } bool throwing = true; try { OnOpening(); if (!this.onOpeningCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this); IAsyncResult result = new OpenAsyncResult(this, timeout, callback, state); throwing = false; return result; } finally { if (throwing) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectOpenFailed, SR.GetString(SR.TraceCodeCommunicationObjectOpenFailed, this.GetCommunicationObjectType().ToString()), this); } Fault(); } } }
/// <summary> /// Monitor connection state and recconect if needed. /// </summary> static protected void ConnectionMonitorThread() { while (GeneralHelper.ApplicationClosing == false) { Thread.Sleep(500); MessageContainerTransportClient[] clients; lock (Clients) { if (Clients.Count == 0) { return; } clients = Clients.ToArray(); } foreach (MessageContainerTransportClient client in clients) { bool keepAliveTimeOut; IMessageContainerTransport messageInterface; lock (client) { keepAliveTimeOut = ((DateTime.Now - client._lastServerCall) >= client._keepAliveTimeOut); messageInterface = client._proxyServerInterface; } if (keepAliveTimeOut && client.IsConnected && messageInterface != null) { try { TracerHelper.Trace("Pinging..."); bool result = messageInterface.Ping(); lock (client) { client._lastServerCall = DateTime.Now; if (result == false) {// Server returned false. TracerHelper.Trace("Closing client interface..."); ((IChannel)client._proxyServerInterface).Close(TimeSpan.FromSeconds(2)); ((IChannel)client._proxyServerInterface).Abort(); client._proxyServerInterface = null; } } } catch (Exception ex) { SystemMonitor.OperationWarning("Connection to server failed [" + ex.Message + "]."); } } lock (client) { if (client._channelFactory == null) {// Client has no factory, disposed or not initialized, skip it. continue; } CommunicationState state = CommunicationState.Closed; if (client._proxyServerInterface != null) { state = ((IChannel)client._proxyServerInterface).State; } // Synchronized entering here. if (client._proxyServerInterface != null && state != CommunicationState.Closed && state != CommunicationState.Closing && state != CommunicationState.Faulted ) {// Interface OK, continue. continue; } } CreateClientProxyInterface(client); } // For each client } // While }
/// <summary> /// Invoked during the transition of a communication object into the opened state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected virtual async Task OnOpenedAsync(CancellationToken token = default(CancellationToken)) { this.onOpenedCalled = true; await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { if (this.aborted || this.State != CommunicationState.Opening) { return; } this.State = CommunicationState.Opened; } finally { this.semaphore.Release(); } Log.Info($"{this.GetType().Name} opened."); EventHandler opened = this.Opened; if (opened != null) { opened(this, EventArgs.Empty); } }
/// <summary> /// Causes a communication object to transition from its current state into the faulted state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected async Task FaultAsync(CancellationToken token = default(CancellationToken)) { await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { if (this.State == CommunicationState.Closed || this.State == CommunicationState.Closing) { return; } if (this.State == CommunicationState.Faulted) { return; } this.State = CommunicationState.Faulted; } finally { this.semaphore.Release(); } await this.OnFaulted(token).ConfigureAwait(false); }
/// <summary> /// Causes a communication object to transition from the created state into the opened state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task OpenAsync(CancellationToken token = default(CancellationToken)) { await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { this.ThrowIfDisposedOrImmutable(); this.State = CommunicationState.Opening; } finally { this.semaphore.Release(); } bool flag2 = true; try { await this.OnOpeningAsync(token).ConfigureAwait(false); if (!this.onOpeningCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnOpeningAsync did not call await base.OnOpeningAsync"); } await this.OnOpenAsync(token).ConfigureAwait(false); await this.OnOpenedAsync(token).ConfigureAwait(false); if (!this.onOpenedCalled) { throw new InvalidOperationException($"{this.GetType().Name}.OnOpenedAsync did not call await base.OnOpenedAsync"); } flag2 = false; } finally { if (flag2) { Log.Warn($"{this.GetType().Name}.OpenAsync failed."); await this.FaultAsync().ConfigureAwait(false); } } }
public void TransitionToState(ClientGoalHandle <TGoal, TResult, TFeedback> goalHandle, CommunicationState nextState) { ROS.Debug()($"Transitioning CommState from {goalHandle.State} to {nextState}"); goalHandle.FireTransitionCallback(nextState); }
public void Close(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.GetString(SR.SFxTimeoutOutOfRange0))); using (DiagnosticUtility.ShouldUseActivity && this.TraceOpenAndClose ? this.CreateCloseActivity() : null) { CommunicationState originalState; lock (ThisLock) { originalState = this.state; #if DEBUG if (closeStack == null) closeStack = new StackTrace(); #endif if (originalState != CommunicationState.Closed) this.state = CommunicationState.Closing; this.closeCalled = true; } switch (originalState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: this.Abort(); if (originalState == CommunicationState.Faulted) { throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); } break; case CommunicationState.Opened: { bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnClosing(); if (!this.onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); OnClose(actualTimeout.RemainingTime()); OnClosed(); if (!this.onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); throwing = false; } finally { if (throwing) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectCloseFailed, SR.GetString(SR.TraceCodeCommunicationObjectCloseFailed, this.GetCommunicationObjectType().ToString()), this); } Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: break; default: throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } } }
/// <summary> /// Invoked during the transition of a communication object into the closed state. /// </summary> /// <param name="token">The <see cref="T:ConverterSystems.Threading.CancellationToken" /> that notifies when the task should be canceled.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected virtual async Task OnClosedAsync(CancellationToken token = default(CancellationToken)) { this.onClosedCalled = true; await this.semaphore.WaitAsync(token).ConfigureAwait(false); try { if (this.raisedClosed) { return; } this.raisedClosed = true; this.State = CommunicationState.Closed; } finally { this.semaphore.Release(); } Log.Info($"{this.GetType().Name} closed."); EventHandler closed = this.Closed; if (closed != null) { closed(this, EventArgs.Empty); } }
void _timer_Elapsed(object sender, ElapsedEventArgs e) { _timer.Enabled = false; if (_port.IsOpen) { try { switch (_state) { case CommunicationState.Start: _ecustate = ECUState.NotInitialized; CastInfoEvent("Sending init/wakeup sequence [" + _wakeupRetries.ToString() + "/5]", 0); //_port.BaudRate = 5; // we need to send 0x10 at 5 baud //_port.Write("\x10"); _port.BreakState = true; Thread.Sleep(200); _port.BreakState = true; Thread.Sleep(200); _port.BreakState = true; Thread.Sleep(200); _port.BreakState = true; Thread.Sleep(200); _port.BreakState = true; Thread.Sleep(200); _port.BreakState = false; Thread.Sleep(200); _port.BreakState = true; Thread.Sleep(600); _port.BreakState = false; Thread.Sleep(200); //Thread.Sleep(2000); //while (_port.BytesToWrite > 0) Thread.Sleep(0); _state = CommunicationState.WaitForKeywords; _port.BaudRate = 9600; _timeout = 0; break; case CommunicationState.WaitForKeywords: if (_timeout == 0 || _timeout == 100 || _timeout == 200 || _timeout == 300 || _timeout == 400 || _timeout == 500) { int secs = _timeout / 100; CastInfoEvent("Waiting for keywords from ECU (" + secs.ToString() + "/5 seconds)", 0); } if (_timeout++ > 500) { _ecustate = ECUState.NotInitialized; CastInfoEvent("Timeout waiting for keywords", 0); _state = CommunicationState.Start; _timeout = 0; _wakeupRetries++; if (_wakeupRetries == 6) { _wakeupRetries = 1; StopCommunication(); CastInfoEvent("Unable to connect to ECU", 0); return; // don't restart the timer } } // timeout? break; case CommunicationState.Idle: //CastInfoEvent("In idle state waiting for messages", 0); // doin' nuthing break; case CommunicationState.SendCommand: break; } } catch (Exception E) { AddToLog(E.Message); } } _timer.Enabled = true; }