private async Task RegisterChannel(IServerChannel channel, Node node, CancellationToken cancellationToken) { IDictionary <string, Guid> instanceSessionDictionary; if (!_identityInstanceSessionIdDictionary.TryGetValue(node.ToIdentity(), out instanceSessionDictionary)) { instanceSessionDictionary = new Dictionary <string, Guid>(); _identityInstanceSessionIdDictionary.Add(node.ToIdentity(), instanceSessionDictionary); } instanceSessionDictionary.Add(node.Instance, channel.SessionId); await channel.SendEstablishedSessionAsync(node); var receiveMessageTask = this.ReceiveMessagesAsync(channel, cancellationToken); await channel.ReceiveFinishingSessionAsync(cancellationToken); await channel.SendFinishedSessionAsync(); instanceSessionDictionary.Remove(node.Instance); if (instanceSessionDictionary.Count == 0) { _identityInstanceSessionIdDictionary.Remove(node.ToIdentity()); } }
static async Task ConsumeCommandsAsync(IServerChannel serverChannel, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Console.ResetColor(); var command = await serverChannel.ReceiveCommandAsync(cancellationToken); Console.ForegroundColor = ConsoleColor.DarkGreen; IServerChannel destinationServerChannel; // Check the destination of the envelope if (command.To == null || command.To.Equals(_serverNode)) { // Destination is the current node var responseCommand = new Command() { Id = command.Id, Status = Lime.Protocol.CommandStatus.Failure, Reason = new Reason() { Code = ReasonCodes.COMMAND_RESOURCE_NOT_SUPPORTED, Description = "The resource is not supported" } }; await serverChannel.SendCommandAsync(responseCommand, CancellationToken.None); Console.WriteLine("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id, command.From ?? serverChannel.RemoteNode, command.Method, command.Uri); } else if (_nodeChannelsDictionary.TryGetValue(command.To, out destinationServerChannel)) { // Destination is a node that has a session with the server command.From = serverChannel.RemoteNode; await destinationServerChannel.SendCommandAsync(command, CancellationToken.None); Console.WriteLine("Command forwarded from '{0}' to '{1}'", serverChannel.RemoteNode, destinationServerChannel.RemoteNode); } else { // Destination not found var responseCommand = new Command() { Id = command.Id, Status = Lime.Protocol.CommandStatus.Failure, Reason = new Reason() { Code = ReasonCodes.ROUTING_DESTINATION_NOT_FOUND, Description = "Destination not found" } }; await serverChannel.SendCommandAsync(responseCommand, CancellationToken.None); Console.WriteLine("Invalid command destination from '{0}': '{1}'", serverChannel.RemoteNode, command.To); } } }
static async Task ConsumeNotificationsAsync(IServerChannel serverChannel, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Console.ResetColor(); var notification = await serverChannel.ReceiveNotificationAsync(cancellationToken); Console.ForegroundColor = ConsoleColor.DarkBlue; IServerChannel destinationServerChannel; // Check the destination of the envelope if (notification.To == null || notification.To.Equals(_serverNode)) { Console.WriteLine("Notification with id {0} received from '{1}' - Event: {2}", notification.Id, notification.From ?? serverChannel.RemoteNode, notification.Event); } else if (_nodeChannelsDictionary.TryGetValue(notification.To, out destinationServerChannel)) { // Destination is a node that has a session with the server notification.From = serverChannel.RemoteNode; await destinationServerChannel.SendNotificationAsync(notification, CancellationToken.None); } } }
private static async Task <bool> ConsumeCommandAsync(Command command, IServerChannel serverChannel, CancellationToken cancellationToken) { Console.ForegroundColor = ConsoleColor.DarkGreen; // Check the destination of the envelope if (command.To == null || command.To.Equals(_serverNode)) { // Destination is the current node var responseCommand = new Command() { Id = command.Id, Status = CommandStatus.Failure, Reason = new Reason() { Code = ReasonCodes.COMMAND_RESOURCE_NOT_SUPPORTED, Description = "The resource is not supported" } }; await serverChannel.SendCommandAsync(responseCommand, CancellationToken.None); Console.WriteLine("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id, command.From ?? serverChannel.RemoteNode, command.Method, command.Uri); } else { var destinationServerChannel = await _nodeRegistry.GetAsync(command.To, cancellationToken); if (destinationServerChannel != null) { // Destination is a node that has a session with the server command.From = serverChannel.RemoteNode; await destinationServerChannel.SendCommandAsync(command, CancellationToken.None); Console.WriteLine("Command forwarded from '{0}' to '{1}'", serverChannel.RemoteNode, destinationServerChannel.RemoteNode); } else { // Destination not found var responseCommand = new Command() { Id = command.Id, Status = CommandStatus.Failure, Reason = new Reason() { Code = ReasonCodes.ROUTING_DESTINATION_NOT_FOUND, Description = "Destination not found" } }; await serverChannel.SendCommandAsync(responseCommand, CancellationToken.None); Console.WriteLine("Invalid command destination from '{0}': '{1}'", serverChannel.RemoteNode, command.To); } } return(true); }
public LockableServerChannel(IServerChannel innerChannel, LockableChannel channelWithSharedLock = null) : base(innerChannel, channelWithSharedLock) { InnerChannel = innerChannel; InnerChannel.RequestReceived += InnerChannel_RequestReceived; InnerChannel.ResponseSent += InnerChannel_ResponseSent; }
/// <summary> /// Use <see cref="Initialize()"/> when initializing server /// </summary> /// <param name="mainChannel">The server main channel to use</param> public UNetServer(IServerChannel mainChannel) { _channelMgr = new ChannelManager(); mainChannel.IsMainChannel = true; _channelMgr.UnsafeAddChannel(mainChannel); mainChannel.HostServer = this; }
/// <inheritdoc /> protected override IRemoteHostService AcquireRemoteHostService() { try { string hostConnectionArguments; GallioFunc <IClientChannel> clientChannelFactory; GallioFunc <IServerChannel> callbackChannelFactory; PrepareConnection(uniqueId, out hostConnectionArguments, out clientChannelFactory, out callbackChannelFactory); StartProcess(hostConnectionArguments); EnsureProcessIsRunning(); clientChannel = clientChannelFactory(); callbackChannel = callbackChannelFactory(); IRemoteHostService hostService = HostServiceChannelInterop.GetRemoteHostService(clientChannel); WaitUntilReady(hostService); return(hostService); } catch (Exception ex) { FreeResources(true); throw new HostException("Error attaching to the host process.", ex); } }
/// <summary> /// Initializes a new instance of the <see cref="BeamPositionMonitor"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public BeamPositionMonitor(int componentNo, Location location) : base(componentNo, location) { this.Current = this.CreateChannel <double>(PredefinedChannels.BeamPositionMonitor.Current); this.XPosition = this.CreateChannel <double>(PredefinedChannels.BeamPositionMonitor.XPosition); this.YPosition = this.CreateChannel <double>(PredefinedChannels.BeamPositionMonitor.YPosition); }
/// <summary> /// Initializes a new instance of the <see cref="BeamPositionMonitor"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public BeamPositionMonitor(int componentNo, Location location) : base(componentNo, location) { this.Current = this.CreateChannel<double>(PredefinedChannels.BeamPositionMonitor.Current); this.XPosition = this.CreateChannel<double>(PredefinedChannels.BeamPositionMonitor.XPosition); this.YPosition = this.CreateChannel<double>(PredefinedChannels.BeamPositionMonitor.YPosition); }
private async Task ListenAsync(IServerChannel serverChannel) { // Initializes a new consumer var channelListener = _channelListenerFactory(serverChannel); try { // Consume the channel envelopes channelListener.Start(serverChannel); // Awaits for the finishing envelope var finishingSessionTask = serverChannel.ReceiveFinishingSessionAsync(_listenerCts.Token); // Stops the consumer when any of the tasks finishes await Task.WhenAny( finishingSessionTask, channelListener.MessageListenerTask, channelListener.CommandListenerTask, channelListener.NotificationListenerTask); if (finishingSessionTask.IsCompleted) { await serverChannel.SendFinishedSessionAsync(_listenerCts.Token); } } finally { channelListener.Stop(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await _nodeRegistry.UnregisterAsync(serverChannel.RemoteNode, cts.Token); } }
public BeamProfileMonitor(int componentNo, Location location) : base(componentNo, location) { this.CameraOn = this.CreateChannel <int>(PredefinedChannels.BeamProfileMonitor.CameraOn); this.ViewScreenIn = this.CreateChannel <int>(PredefinedChannels.BeamProfileMonitor.ViewScreenIn); this.LaserOn = this.CreateChannel <int>(PredefinedChannels.BeamProfileMonitor.LaserOn); this.Image = this.CreateChannel <string>(PredefinedChannels.BeamProfileMonitor.Image); }
public BeamProfileMonitor(int componentNo, Location location) : base(componentNo, location) { this.CameraOn = this.CreateChannel<int>(PredefinedChannels.BeamProfileMonitor.CameraOn); this.ViewScreenIn = this.CreateChannel<int>(PredefinedChannels.BeamProfileMonitor.ViewScreenIn); this.LaserOn = this.CreateChannel<int>(PredefinedChannels.BeamProfileMonitor.LaserOn); this.Image = this.CreateChannel<string>(PredefinedChannels.BeamProfileMonitor.Image); }
public TaskExecutor(TaskExecutionOptions options, ILogger logger) { _log = logger; _channel = options.ServerChannel; _processRunner = options.ProcessRunner; _fileSystem = options.FileSystem; _workingDirectory = options.WorkingDirectory; }
public Solenoid(int componentNo, Location location) : base(componentNo, location) { this.CurrentOn = this.CreateChannel<int>(PredefinedChannels.Solenoid.CurrentOn); this.Current = this.CreateChannel<double>(PredefinedChannels.Solenoid.Current); // Default values this.Current.Value = 1500E-3; // 1500mA }
/// <summary> /// Creates a new <see cref="PipelineSession"/> for the server-side pipeline. /// Sharable handlers are re-used, non-shareable handlers are cloned. /// All handlers are notified about activity. /// </summary> /// <returns></returns> public PipelineSession CreateNewServerSession(IServerChannel serverChannel) { Logger.Debug("Creating session for {0}.", serverChannel); // for each non-sharable handler, a new instance has to be created var newInbounds = CreateNewInstances(InboundHandlers, serverChannel).Cast <IInboundHandler>(); var newOutbounds = CreateNewInstances(OutboundHandlers, serverChannel).Cast <IOutboundHandler>(); return(new PipelineSession(serverChannel, this, newInbounds, newOutbounds)); }
public Aperture(int componentNo, Location location) : base(componentNo, location) { this.In = this.CreateChannel<int>(PredefinedChannels.Aperture.In); this.Radius = this.CreateChannel<double>(PredefinedChannels.Aperture.Radius); // Default values this.Radius.Value = 20E-3; // 20mm }
/// <summary> /// Initializes HttpClient for use with proxy /// </summary> /// <param name="settings"></param> /// <param name="logger"></param> /// <param name="serverChannel"></param> public HttpClient(HttpClientSettings settings, InstanceLogger logger, IServerChannel serverChannel) { this.setttings = settings; client = new TcpClient(settings.TcpSettings); client.ChannelCreated += channelCreatedHandler; client.ErrorOccured += client_ErrorOccured; this.logger = logger; this.serverChannel = serverChannel as HttpServerChannel; }
public Aperture(int componentNo, Location location) : base(componentNo, location) { this.In = this.CreateChannel <int>(PredefinedChannels.Aperture.In); this.Radius = this.CreateChannel <double>(PredefinedChannels.Aperture.Radius); // Default values this.Radius.Value = 20E-3; // 20mm }
private void upgradeServer(IServerChannel c) { var channel = c as HttpServerChannel; if (channel != null) { channel.UpgradeProtocol(upgrader); } }
private void OnChannelCreated(IServerChannel channel) { var ev = ChannelCreated; if (ev != null) { ev(this, channel); } }
/// <summary> /// Registers the host service with a channel. /// </summary> /// <param name="hostService">The remote host service.</param> /// <param name="channel">The channel.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="hostService"/> or /// <paramref name="channel"/> is null.</exception> public static void RegisterWithChannel(RemoteHostService hostService, IServerChannel channel) { if (hostService == null) throw new ArgumentNullException("hostService"); if (channel == null) throw new ArgumentNullException("channel"); channel.RegisterService(ServiceName, hostService); }
public CalcServerChannel(IServerChannel c) { channel = c; channel.RequestReceived += channel_RequestReceived; channel.ResponseSent += channel_ResponseSent; channel.ChannelReady += channel_ChannelReady; channel.ChannelClosed += channel_ChannelClosed; channel.ErrorOccured += channel_ErrorOccured; }
public Solenoid(int componentNo, Location location) : base(componentNo, location) { this.CurrentOn = this.CreateChannel <int>(PredefinedChannels.Solenoid.CurrentOn); this.Current = this.CreateChannel <double>(PredefinedChannels.Solenoid.Current); // Default values this.Current.Value = 1500E-3; // 1500mA }
/// <summary> /// Creates a new <see cref="PipelineSession"/> for the server-side pipeline. /// Sharable handlers are re-used, non-shareable handlers are cloned. /// All handlers are notified about activity. /// </summary> /// <returns></returns> public PipelineSession CreateNewServerSession(IServerChannel serverChannel) { Logger.Debug("Creating session for {0}.", serverChannel); // for each non-sharable handler, a new instance has to be created var newInbounds = CreateNewInstances(InboundHandlers, serverChannel).Cast<IInboundHandler>(); var newOutbounds = CreateNewInstances(OutboundHandlers, serverChannel).Cast<IOutboundHandler>(); return new PipelineSession(serverChannel, this, newInbounds, newOutbounds); }
public Vacuum(int componentNo, Location location) : base(componentNo, location) { this.Pressure = this.CreateChannel <double>(PredefinedChannels.Vacuum.Pressure); this.On = this.CreateChannel <int>(PredefinedChannels.Vacuum.On); // Default channel value this.Pressure.Value = 6E-9; this.On.Value = 1; }
private void channelCreatedHandler(object sender, IServerChannel e) { var channel = new HttpServerChannel(e, logger); var ev = ChannelCreated; if (ev != null) { ev(this, channel); } }
public TaskExecutionOptions(IServerChannel serverChannel, IFileSystem fileSystem, IProcessRunner processRunner, string workingDirectory) { ServerChannel = serverChannel; FileSystem = fileSystem; ProcessRunner = processRunner; WorkingDirectory = workingDirectory; }
private void server_ChannelCreated(object sender, IServerChannel e) { var channel = new CalcServerChannel(e); var ev = ChannelCreated; if (ev != null) { ev(this, channel); } }
public IClient CreateClient(IServerChannel serverChannel) { return(new TcpClient( new TcpClientSettings { RemoteEndPoint = settings.RemoteEndPoint, LocalEndPoint = new IPEndPoint(settings.LocalIPAddress, 0), Properties = settings.Properties, })); }
public Vacuum(int componentNo, Location location) : base(componentNo, location) { this.Pressure = this.CreateChannel<double>(PredefinedChannels.Vacuum.Pressure); this.On = this.CreateChannel<int>(PredefinedChannels.Vacuum.On); // Default channel value this.Pressure.Value = 6E-9; this.On.Value = 1; }
static async Task ConsumeMessagesAsync(IServerChannel serverChannel, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Console.ResetColor(); var message = await serverChannel.ReceiveMessageAsync(cancellationToken); Console.ForegroundColor = ConsoleColor.DarkRed; IServerChannel destinationServerChannel; // Check the destination of the envelope if (message.To == null || message.To.Equals(_serverNode)) { // Destination is the current node var notification = new Notification() { Id = message.Id, Event = Event.Received }; await serverChannel.SendNotificationAsync(notification, CancellationToken.None); Console.WriteLine("Message with id '{0}' received from '{1}': {2}", message.Id, message.From ?? serverChannel.RemoteNode, message.Content); } else if (_nodeChannelsDictionary.TryGetValue(message.To, out destinationServerChannel)) { // Destination is a node that has a session with the server message.From = serverChannel.RemoteNode; await destinationServerChannel.SendMessageAsync(message, CancellationToken.None); Console.WriteLine("Message forwarded from '{0}' to '{1}'", serverChannel.RemoteNode, destinationServerChannel.RemoteNode); } else { // Destination not found var notification = new Notification() { Id = message.Id, Event = Event.Failed, Reason = new Reason() { Code = ReasonCodes.ROUTING_DESTINATION_NOT_FOUND, Description = "Destination not found" } }; await serverChannel.SendNotificationAsync(notification, CancellationToken.None); Console.WriteLine("Invalid message destination from '{0}': '{1}'", serverChannel.RemoteNode, message.To); } } }
/// <summary> /// Initializes a new instance of the <see cref="HighVoltageSupply"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public HighVoltageSupply(int componentNo, Location location) : base(componentNo, location) { this.HighVoltageSupplyOn = this.CreateChannel <int>(PredefinedChannels.HighVoltageSupply.On); this.HighVoltageSupplyPreset = this.CreateChannel <double>(PredefinedChannels.HighVoltageSupply.PresetVoltage); this.HighVoltageSupplyMeasured = this.CreateChannel <double>(PredefinedChannels.HighVoltageSupply.MeasuredVoltage); // Default values this.HighVoltageSupplyOn.Value = 1; this.HighVoltageSupplyPreset.Value = -250E3; this.HighVoltageSupplyMeasured.Value = -50E3; }
/// <summary> /// Initializes a new instance of the <see cref="HighVoltageSupply"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public HighVoltageSupply(int componentNo, Location location) : base(componentNo, location) { this.HighVoltageSupplyOn = this.CreateChannel<int>(PredefinedChannels.HighVoltageSupply.On); this.HighVoltageSupplyPreset = this.CreateChannel<double>(PredefinedChannels.HighVoltageSupply.PresetVoltage); this.HighVoltageSupplyMeasured = this.CreateChannel<double>(PredefinedChannels.HighVoltageSupply.MeasuredVoltage); // Default values this.HighVoltageSupplyOn.Value = 1; this.HighVoltageSupplyPreset.Value = -250E3; this.HighVoltageSupplyMeasured.Value = -50E3; }
/// <summary> /// Initializes a new instance of the <see cref="Cathode"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public Cathode(int componentNo, Location location) : base(componentNo, location) { this.BeamOn = this.CreateChannel<int>(PredefinedChannels.Cathode.BeamOn); this.CathodeCurrent = this.CreateChannel<double>(PredefinedChannels.Cathode.Current); this.CathodeTemperature = this.CreateChannel<double>(PredefinedChannels.Cathode.Temperature); // Default channel values this.BeamOn.Value = 1; this.CathodeCurrent.Value = 700E-6; // 700uA this.CathodeTemperature.Value = Parameters.AmbientTemperature + 130; }
private static async Task <bool> ConsumeMessageAsync(Message message, IServerChannel serverChannel, CancellationToken cancellationToken) { Console.ForegroundColor = ConsoleColor.DarkRed; // Check the destination of the envelope if (message.To == null || message.To.Equals(_serverNode)) { // Destination is the current node var notification = new Notification() { Id = message.Id, Event = Event.Received }; await serverChannel.SendNotificationAsync(notification, CancellationToken.None); Console.WriteLine("Message with id '{0}' received from '{1}': {2}", message.Id, message.From ?? serverChannel.RemoteNode, message.Content); } else { var destinationServerChannel = await _nodeRegistry.GetAsync(message.To, cancellationToken); if (destinationServerChannel != null) { // Destination is a node that has a session with the server message.From = serverChannel.RemoteNode; await destinationServerChannel.SendMessageAsync(message, CancellationToken.None); Console.WriteLine("Message forwarded from '{0}' to '{1}'", serverChannel.RemoteNode, destinationServerChannel.RemoteNode); } else { // Destination not found var notification = new Notification() { Id = message.Id, Event = Event.Failed, Reason = new Reason() { Code = ReasonCodes.ROUTING_DESTINATION_NOT_FOUND, Description = "Destination not found" } }; await serverChannel.SendNotificationAsync(notification, CancellationToken.None); Console.WriteLine("Invalid message destination from '{0}': '{1}'", serverChannel.RemoteNode, message.To); } } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="Cathode"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public Cathode(int componentNo, Location location) : base(componentNo, location) { this.BeamOn = this.CreateChannel <int>(PredefinedChannels.Cathode.BeamOn); this.CathodeCurrent = this.CreateChannel <double>(PredefinedChannels.Cathode.Current); this.CathodeTemperature = this.CreateChannel <double>(PredefinedChannels.Cathode.Temperature); // Default channel values this.BeamOn.Value = 1; this.CathodeCurrent.Value = 700E-6; // 700uA this.CathodeTemperature.Value = Parameters.AmbientTemperature + 130; }
/// <summary> /// Adds a channel to this server /// </summary> /// <remarks> /// May throw a <see cref="ChannelOperationException"/> if used incorrectly /// </remarks> /// <param name="channel">The channel to add</param> /// <returns>Returns true if channel was added successfully</returns> public bool AddChannel(IServerChannel channel) { if (!_channelMgr.AddChannel(channel)) { return(false); } OnChannelCreated.Raise(this, new ChannelEventArgs(channel)); channel.HostServer = this; channel.OnPeerConnected += (sender, e) => OnPeerConnected.Raise(this, e); channel.PacketProcessor = _channelMgr.GetMainChannel().PacketProcessor; return(true); }
public WebSocketServerChannel(IServerChannel innerChannel, InstanceLogger logger) { this.id = innerChannel.ID; this.name = innerChannel.Name; this.innerChannel = innerChannel; innerChannel.ChannelClosed += innerChannel_ChannelClosed; innerChannel.ErrorOccured += innerChannel_ErrorOccured; innerChannel.RequestReceived += innerChannel_RequestReceived; innerChannel.ResponseSent += innerChannel_ResponseSent; webSocket = new BaseWebSocket(logger); webSocket.MessageParsed += webSocket_MessageParsed; }
public DefaultProxyChannel(IClient client, IServerChannel srvChannel) { if (client == null) { throw new ArgumentNullException("client"); } if (srvChannel == null) { throw new ArgumentNullException("srvChannel"); } clientHandlers = new IChannelExtensions.ChannelHandlers { ErrorOccured = errorOccuredHandler, ChannelClosed = channelClosedHandler, ChannelReplaced = client_ChannelReplaced, RequestSent = client_RequestSent, ResponseReceived = client_ResponseReceived, }; serverHandlers = new IChannelExtensions.ChannelHandlers { ErrorOccured = errorOccuredHandler, ChannelClosed = channelClosedHandler, ChannelReplaced = server_ChannelReplaced, RequestReceived = server_RequestReceived, ResponseSent = server_ResponseSent, }; Exception clientException = null; EventHandler <Exception> handler = delegate(object sender, Exception e) { clientException = e; }; client.ErrorOccured += handler; clientChannel = client.Start(); client.ErrorOccured -= handler; if (clientChannel != null) { clientChannel.BindAllEvents(clientHandlers); serverChannel = srvChannel; serverChannel.BindAllEvents(serverHandlers); } else { srvChannel.Close(); if (clientException != null) { throw clientException; } throw new DefaultProxyException("Unable to start a client channel."); } }
/// <summary> /// Initializes a new instance of the <see cref="SteeringMagnet"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public SteeringMagnet(int componentNo, Location location) : base(componentNo, location) { this.XCurrentOn = this.CreateChannel<int>(PredefinedChannels.SteeringMagnet.XCurrentOn); this.XCurrent = this.CreateChannel<double>(PredefinedChannels.SteeringMagnet.XCurrent); this.YCurrentOn = this.CreateChannel<int>(PredefinedChannels.SteeringMagnet.YCurrentOn); this.YCurrent = this.CreateChannel<double>(PredefinedChannels.SteeringMagnet.YCurrent); // Default channel values this.XCurrentOn.Value = 1; this.XCurrent.Value = 0.5; this.YCurrentOn.Value = 1; this.YCurrent.Value = -0.5; }
public void Dispose() { if (serverChannel != null) { serverChannel.Dispose(); serverChannel = null; } if (callbackChannel != null) { callbackChannel.Dispose(); callbackChannel = null; } if (assemblyLoader != null) { assemblyLoader.Dispose(); assemblyLoader = null; } }
private void FreeResources(bool abortImmediately) { if (processTask != null) { if (! abortImmediately) { if (!processTask.Join(JoinBeforeAbortWarningTimeout)) { Logger.Log(LogSeverity.Info, "Waiting for the host process to terminate."); if (!processTask.Join(JoinBeforeAbortTimeout - JoinBeforeAbortWarningTimeout)) Logger.Log(LogSeverity.Info, string.Format("Timed out after {0} minutes.", JoinBeforeAbortTimeout.TotalMinutes)); } } if (! processTask.Join(TimeSpan.Zero)) { Logger.Log(LogSeverity.Warning, "Forcibly killing the host process!"); processTask.Abort(); processTask.Join(JoinAfterAbortTimeout); } processTask = null; } if (clientChannel != null) { clientChannel.Dispose(); clientChannel = null; } if (callbackChannel != null) { callbackChannel.Dispose(); callbackChannel = null; } if (temporaryConfigurationFilePath != null) { File.Delete(temporaryConfigurationFilePath); temporaryConfigurationFilePath = null; } lock (logConsoleOutputBufferTimer) { logConsoleOutputBufferTimer.Dispose(); } }
/// <inheritdoc /> protected override IRemoteHostService AcquireRemoteHostService() { try { string hostConnectionArguments; Func<IClientChannel> clientChannelFactory; Func<IServerChannel> callbackChannelFactory; PrepareConnection(uniqueId, out hostConnectionArguments, out clientChannelFactory, out callbackChannelFactory); StartProcess(hostConnectionArguments); EnsureProcessIsRunning(); clientChannel = clientChannelFactory(); callbackChannel = callbackChannelFactory(); IRemoteHostService hostService = HostServiceChannelInterop.GetRemoteHostService(clientChannel); WaitUntilReady(hostService); return hostService; } catch (Exception ex) { FreeResources(true); throw new HostException("Error attaching to the host process.", ex); } }
public GateValve(int componentNo, Location location) : base(componentNo, location) { this.Closed = this.CreateChannel<int>(PredefinedChannels.GateValve.Closed); }
/// <summary> /// Initializes a new instance of the <see cref="BeamLossMonitor"/> class. /// </summary> /// <param name="componentNo">Identifier number for the common component types.</param> /// <param name="location">Location of this component relative to the origin of the vector space.</param> public BeamLossMonitor(int componentNo, Location location) : base(componentNo, location) { this.BeamLoss = this.CreateChannel<int>(PredefinedChannels.BeamLossMonitor.BeamLoss); }
private async Task EstablishSessionAsync(IServerChannel channel, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); _serverConnectedNodesDictionary.Add(channel.SessionId, channel); var timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var newSession = await channel.ReceiveNewSessionAsync( CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token).Token); timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var negotiatedSession = await channel.NegotiateSessionAsync( channel.Transport.GetSupportedCompression(), channel.Transport.GetSupportedEncryption(), CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token).Token); if (negotiatedSession.State == SessionState.Negotiating && negotiatedSession.Compression != null && negotiatedSession.Encryption != null) { await channel.SendNegotiatingSessionAsync( negotiatedSession.Compression.Value, negotiatedSession.Encryption.Value ); timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(60)); if (channel.Transport.Compression != negotiatedSession.Compression.Value) { await channel.Transport.SetCompressionAsync( negotiatedSession.Compression.Value, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token).Token); } if (channel.Transport.Encryption != negotiatedSession.Encryption.Value) { await channel.Transport.SetEncryptionAsync( negotiatedSession.Encryption.Value, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token).Token); } timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var authenticatedSession = await channel.AuthenticateSessionAsync( new AuthenticationScheme[] { AuthenticationScheme.Plain, AuthenticationScheme.Transport }, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token).Token); if (authenticatedSession.Authentication != null && authenticatedSession.From != null && authenticatedSession.From.Domain.Equals(_serverNode.Domain, StringComparison.OrdinalIgnoreCase)) { if (authenticatedSession.Authentication is PlainAuthentication) { var plainAuthentication = authenticatedSession.Authentication as PlainAuthentication; string password; if (_identityPasswordDictionary.TryGetValue(authenticatedSession.From.ToIdentity(), out password) && password.Equals(plainAuthentication.GetFromBase64Password())) { await RegisterChannel(channel, authenticatedSession.From, cancellationToken); } else { await channel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_AUTHENTICATION_FAILED, Description = "Invalid username or password" }); } } else if (authenticatedSession.Authentication is TransportAuthentication) { var transportAuthentication = authenticatedSession.Authentication as PlainAuthentication; if (channel.Transport is IAuthenticatableTransport) { var authenticableTransport = channel.Transport as IAuthenticatableTransport; if (await authenticableTransport.AuthenticateAsync(authenticatedSession.From.ToIdentity()) != DomainRole.Unknown) { await RegisterChannel(channel, authenticatedSession.From, cancellationToken); } else { await channel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_AUTHENTICATION_FAILED, Description = "The authentication failed" }); } } else { await channel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_AUTHENTICATION_FAILED, Description = "The current transport doesn't support authentication" }); } } else { await channel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_AUTHENTICATION_FAILED, Description = "Unsupported authenticaiton scheme" }); } } else { await channel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_AUTHENTICATION_FAILED, Description = "Invalid user" }); } } else { await channel.SendFailedSessionAsync( new Reason() { Code = 1, Description = "Invalid selected negotiation options" }); } } finally { channel.DisposeIfDisposable(); } }
private async Task RegisterChannel(IServerChannel channel, Node node, CancellationToken cancellationToken) { IDictionary<string, Guid> instanceSessionDictionary; if (!_identityInstanceSessionIdDictionary.TryGetValue(node.ToIdentity(), out instanceSessionDictionary)) { instanceSessionDictionary = new Dictionary<string, Guid>(); _identityInstanceSessionIdDictionary.Add(node.ToIdentity(), instanceSessionDictionary); } instanceSessionDictionary.Add(node.Instance, channel.SessionId); await channel.SendEstablishedSessionAsync(node); var receiveMessageTask = this.ReceiveMessagesAsync(channel, cancellationToken); await channel.ReceiveFinishingSessionAsync(cancellationToken); await channel.SendFinishedSessionAsync(); instanceSessionDictionary.Remove(node.Instance); if (instanceSessionDictionary.Count == 0) { _identityInstanceSessionIdDictionary.Remove(node.ToIdentity()); } }
public void InitializeIpcChannel(string portName) { serverChannel = new BinaryIpcServerChannel(portName); callbackChannel = new BinaryIpcClientChannel(portName + @".Callback"); }
public void InitializeTcpChannel(int portNumber) { serverChannel = new BinaryTcpServerChannel("localhost", portNumber); callbackChannel = new BinaryTcpClientChannel("localhost", portNumber, null); }