Esempio n. 1
0
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

#pragma warning disable 4014
            ProducerConsumer.CreateAsync(

                c => _transportListener.AcceptTransportAsync(c),
                async t =>
            {
                await t.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    t,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                var clientNode = new Node("client", "msging.net", "instance");

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                },
                    (n, a) => new AuthenticationResult(null, clientNode).AsCompletedTask(), _cts.Token);

                var channelListener = new ChannelListener(
                    m => TaskUtil.TrueCompletedTask,
                    n => TaskUtil.TrueCompletedTask,
                    async c =>
                {
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);

                return(true);
            },
                _cts.Token);
        }
 public BlipClientBuilderTests()
 {
     ChannelListener = new ChannelListener(
         m => TaskUtil.TrueCompletedTask,
         n => TaskUtil.TrueCompletedTask,
         c => TaskUtil.TrueCompletedTask);
     Server = new DummyServer();
 }
 public BlipClientBuilderTests()
 {
     ChannelListener = new ChannelListener(
         m => TaskUtil.TrueCompletedTask,
         n => TaskUtil.TrueCompletedTask,
         c => TaskUtil.TrueCompletedTask);
     Server = new DummyServer();
     Lime.Messaging.Registrator.RegisterDocuments();
 }
Esempio n. 4
0
 void worker(TimeSpan timeout, object state)
 {
     try
     {
         IInputChannel inputChannel = ChannelListener.AcceptChannel(timeout);
         Message       message      = inputChannel.Receive();
         Runtime.PublishOneWay(new PublishRequest(typeof(IPassThroughServiceContract), message.Headers.Action, message));
     }
     catch (TimeoutException)
     {
     }
 }
Esempio n. 5
0
        private void StartEnvelopeListeners()
        {
            _cts = new CancellationTokenSource();
            var messageHandler      = new MessageReceivedHandler(_sender, _autoNotify, EnvelopeManager, _cts);
            var notificationHandler = new NotificationReceivedHandler(_sender, EnvelopeManager, _cts);
            var commandHandler      = new CommandReceivedHandler(_sender, EnvelopeManager, _cts);

            _channelListener = new ChannelListener(
                m => messageHandler.HandleAsync(m, _cts.Token),
                n => notificationHandler.HandleAsync(n, _cts.Token),
                c => commandHandler.HandleAsync(c, _cts.Token));
            _channelListener.Start(_connection.OnDemandClientChannel);
        }
        protected ChannelListener GetAndStartTarget()
        {
            if (_createdTargets == null)
            {
                _createdTargets = new List <ChannelListener>();
            }

            var target = new ChannelListener(_messageConsumer, _notificationConsumer, _commandConsumer);

            target.Start(_channel.Object);
            _createdTargets.Add(target);
            return(target);
        }
Esempio n. 7
0
        private void SetupListener(Type channelType, string channelKey)
        {
            if (_listener != null)
            {
                _listener.Dispose();
                _listener = null;
            }

            if (this.AssociatedObject == null || channelType == null)
            {
                return;
            }
            _listener = (ChannelListener)TypeActivator.CreateInstance(CHANNEL_LISTENER_TYPE.MakeGenericType(channelType));
            _listener.Subscribe(channelKey, base.InvokeActions);
        }
Esempio n. 8
0
    public void Bind <T>(string channel, T defaultValue, ChannelListener <T> listener)
    {
        T initialValue = defaultValue;

        if (Provider != null)
        {
            Provider.SubscribeToChannels(this, channel);
            var cachedValue = Provider.GetState(channel);
            if (cachedValue != null && cachedValue is T)
            {
                initialValue = (T)cachedValue;
            }
        }

        channelListeners[channel] = (object data) => listener((T)data);
        listener(initialValue);

        Render();
    }
Esempio n. 9
0
 public FakeChannelListener()
 {
     MessageChannel      = Channel.CreateUnbounded <Message>();
     NotificationChannel = Channel.CreateUnbounded <Notification>();
     CommandChannel      = Channel.CreateUnbounded <Command>();
     _channelListener    = new ChannelListener(
         async(message, token) =>
     {
         await MessageChannel.Writer.WriteAsync(message, token);
         return(true);
     },
         async(notification, token) =>
     {
         await NotificationChannel.Writer.WriteAsync(notification, token);
         return(true);
     },
         async(command, token) =>
     {
         await CommandChannel.Writer.WriteAsync(command, token);
         return(true);
     });
 }
Esempio n. 10
0
        /// <summary>
        /// Attempts to connect to data input source.
        /// </summary>
        /// <remarks>
        /// Derived classes should attempt connection to data input source here.  Any exceptions thrown
        /// by this implementation will result in restart of the connection cycle.
        /// </remarks>
        protected override void AttemptConnection()
        {
            TcpClientConfig  tcpConfig       = m_masterConfig.client;
            string           portName        = tcpConfig.address + ":" + tcpConfig.port;
            TimeSpan         minRetry        = TimeSpan.FromMilliseconds(tcpConfig.minRetryMs);
            TimeSpan         maxRetry        = TimeSpan.FromMilliseconds(tcpConfig.maxRetryMs);
            ChannelRetry     channelRetry    = new ChannelRetry(minRetry, maxRetry);
            IChannelListener channelListener = new ChannelListener(state => OnStatusMessage(MessageLevel.Info, portName + " - Channel state change: " + state));

            IChannel channel = s_manager.AddTCPClient(portName, tcpConfig.level, channelRetry, tcpConfig.address, tcpConfig.port, channelListener);

            m_channel = channel;

            IMaster master = channel.AddMaster(portName, m_soeHandler, DefaultMasterApplication.Instance, m_masterConfig.master);

            if (m_pollingInterval > TimeSpan.Zero)
            {
                master.AddClassScan(ClassField.AllClasses, m_pollingInterval, TaskConfig.Default);
            }

            master.Enable();
            m_active = true;
        }
Esempio n. 11
0
        static async Task Main(string[] args)
        {
            Console.Write("Server URI (ENTER for default): ");

            var serverUriValue = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(serverUriValue))
            {
                serverUriValue = $"net.tcp://{Dns.GetHostName()}:{55321}";
            }

            Console.Write("Identity (name@domain - ENTER for none): ");
            if (!Identity.TryParse(Console.ReadLine(), out var identity))
            {
                identity = null;
            }

            string password = null;

            if (identity != null)
            {
                Console.Write("Password: "******"Number of channels (ENTER for 1): ");
            if (!int.TryParse(Console.ReadLine(), out var channelCount))
            {
                channelCount = 1;
            }

            var setPresence = false;
            var setReceipts = false;

            // Creates a new transport and connect to the server
            var serverUri = new Uri(serverUriValue);
            Func <ITransport> transportFactory = () => CreateTransportForUri(serverUri);

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transportFactory, serverUri)
                          .AddBuiltHandler((channel, token) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(TaskUtil.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .WithEncryption(SessionEncryption.None)
                          .AddEstablishedHandler(async(c, t) =>
            {
                if (setPresence)
                {
                    await c.SetResourceAsync(
                        new LimeUri(UriTemplates.PRESENCE),
                        new Presence()
                    {
                        Status      = PresenceStatus.Available,
                        RoutingRule = RoutingRule.Identity,
                        RoundRobin  = true
                    },
                        t);
                }
            })
                          .AddEstablishedHandler(async(c, t) =>
            {
                if (setReceipts)
                {
                    await c.SetResourceAsync(
                        new LimeUri(UriTemplates.RECEIPT),
                        new Receipt()
                    {
                        Events = new[] { Event.Received, Event.Consumed }
                    },
                        t);
                }
            });

            if (identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(identity)
                          .WithPlainAuthentication(password);
            }

            IOnDemandClientChannel onDemandClientChannel;

            if (channelCount == 1)
            {
                onDemandClientChannel = new OnDemandClientChannel(builder);
            }
            else
            {
                onDemandClientChannel = new MultiplexerClientChannel(builder);
            }

            var running = true;

            onDemandClientChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                Console.Write("Could not establish the session: {0}", information.Exception.Message);
                Console.WriteLine();
                running = false;
                return(TaskUtil.FalseCompletedTask);
            });

            var channelListener = new ChannelListener(message =>
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("Message with id '{0}' received from '{1}': {2}", message.Id, message.GetSender(),
                                  message.Content);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      notification =>
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("Notification with id {0} received from '{1}' - Event: {2}",
                                  notification.Id, notification.GetSender(), notification.Event);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      command =>
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id,
                                  command.GetSender(), command.Method, command.Uri);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            });


            await onDemandClientChannel.EstablishAsync(CancellationToken.None);

            channelListener.Start(onDemandClientChannel);

            while (running)
            {
                Console.Write("Destination node (Type EXIT to quit): ");
                var toInput = Console.ReadLine();
                if (toInput != null &&
                    toInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }

                Node to = null;
                if (string.IsNullOrEmpty(toInput) || Node.TryParse(toInput, out to))
                {
                    Console.Write("Message text: ");
                    var text = Console.ReadLine();

                    var stopwatch = Stopwatch.StartNew();

                    Console.Write("Number of times to send (ENTER to 1): ");
                    int count;
                    if (!int.TryParse(Console.ReadLine(), out count))
                    {
                        count = 1;
                    }

                    await Task.WhenAll(
                        Enumerable
                        .Range(0, count)
                        .Select(async i =>
                    {
                        var message = new Message
                        {
                            Id      = i.ToString(),
                            To      = to,
                            Content = new PlainText
                            {
                                Text = text
                            }
                        };

                        await onDemandClientChannel.SendMessageAsync(message, CancellationToken.None);
                    }));

                    stopwatch.Stop();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
                    Console.ResetColor();
                }
            }

            channelListener.Stop();
            await Task.WhenAll(
                channelListener.MessageListenerTask,
                channelListener.NotificationListenerTask,
                channelListener.CommandListenerTask);

            await onDemandClientChannel.FinishAsync(CancellationToken.None);

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Esempio n. 12
0
File: Rtu.cs Progetto: AKllX/Gemini
        public Rtu(int id, string name, IPEndpoint clientAddress, IPEndpoint hostAddres, ushort localDNP3Addres, ushort remoteDNP3Address,
            Dictionary<int, int> bins, Dictionary<int, int> analogs, Dictionary<int, int> counters, DatabaseTemplate dt, GeminiMap gmap)
        {
            Id = id;
            Name = name;
            //Considerando uma RTU por Canal
            if (Core.LoggingEnabled)
            {
                Channel = Core.DNP3Manager.AddTCPServer(name, LogLevels.ALL, ServerAcceptMode.CloseExisting, hostAddres.address, hostAddres.port, ChannelListener.Print());
            }
            else
            {
                Channel = Core.DNP3Manager.AddTCPServer(name, LogLevels.NONE, ServerAcceptMode.CloseExisting, hostAddres.address, hostAddres.port, ChannelListener.Print());
            }

            //Configuração Padrão de RTU é Outstation
            Config = new OutstationStackConfig
            {
                databaseTemplate = dt
            };
            Config.link.remoteAddr = remoteDNP3Address;
            Config.link.localAddr = localDNP3Addres;
            DNP3ToSNMPBinaries = bins;
            DNP3ToSNMPAnalogs = analogs;
            DNP3ToSNMPCounters = counters;
            Outstation = Channel.AddOutstation(name, RejectingCommandHandler.Instance, DefaultOutstationApplication.Instance, Config);
            Outstation.Enable();
            geminiMap = gmap;

            Target = new SnmpTarget(clientAddress.address, clientAddress.port, Core.Settings.SNMPTimeout, Core.Settings.SNMPRetry);

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPBinaries)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPAnalogs)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPCounters)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            MonitorThread = new Timer(new TimerCallback(Update), null, TimeSpan.FromMilliseconds(10), TimeSpan.FromSeconds(Core.Settings.GatewayPoolingTime));
        }
Esempio n. 13
0
        private static async Task <IOnDemandClientChannel> EstablishChannelAsync(ConnectionInformation connectionInformation, CancellationToken cancellationToken)
        {
            ITransport transportFactory() => CreateTransportForUri(connectionInformation.ServerUri);

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transportFactory, connectionInformation.ServerUri)
                          .AddBuiltHandler((channel, handlerCancellationToken) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(Task.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .WithEncryption(SessionEncryption.None)
                          .WithInstance(connectionInformation.Instance)
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                await channel.SetResourceAsync(
                    new LimeUri(UriTemplates.PRESENCE),
                    connectionInformation.Presence,
                    handlerCancellationToken);
            })
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                await channel.SetResourceAsync(
                    new LimeUri(UriTemplates.RECEIPT),
                    connectionInformation.Receipt,
                    handlerCancellationToken);
            });

            if (connectionInformation.Identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(connectionInformation.Identity)
                          .WithPlainAuthentication(connectionInformation.Password);
            }

            var clientChannel = new OnDemandClientChannel(builder);

            clientChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                WriteError("Could not establish the session: {0}", information.Exception.Message);
                return(TaskUtil.FalseCompletedTask);
            });

            var channelListener = new ChannelListener(message =>
            {
                WriteInfo("Message with id '{0}' received from '{1}': {2}", message.Id, message.GetSender(), message.Content);
                return(TaskUtil.TrueCompletedTask);
            },
                                                      notification =>
            {
                WriteInfo("Notification with id {0} received from '{1}' - Event: {2}", notification.Id, notification.GetSender(), notification.Event);
                return(TaskUtil.TrueCompletedTask);
            },
                                                      command =>
            {
                WriteInfo("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id, command.GetSender(), command.Method, command.Uri);
                return(TaskUtil.TrueCompletedTask);
            });


            await clientChannel.EstablishAsync(cancellationToken);

            channelListener.Start(clientChannel);

            return(clientChannel);
        }
Esempio n. 14
0
        public Rtu(string name, IPEndpoint hostAddres, ushort localDNP3Addres, ushort remoteDNP3Address)
        {
            //Considerando uma RTU por Canal
            Channel = Core.DNP3Manager.AddTCPServer(name, LogLevels.ALL, ServerAcceptMode.CloseExisting, hostAddres.address, hostAddres.port, ChannelListener.Print());
            Config  = new OutstationStackConfig();
            Config.databaseTemplate = new DatabaseTemplate(4, 0, 1, 1, 1, 1, 1, 0, 0);
            Config.databaseTemplate.analogs[0].clazz  = PointClass.Class2;
            Config.outstation.config.allowUnsolicited = false;
            Config.link.remoteAddr = remoteDNP3Address;
            Config.link.localAddr  = localDNP3Addres;

            Outstation = Channel.AddOutstation(name, RejectingCommandHandler.Instance, DefaultOutstationApplication.Instance, Config);
            Outstation.Enable();
        }
Esempio n. 15
0
        internal static void ProcessMessages()
        {
            lock (_processMessagesLock)
            {
                while (!_newChannelListeners.IsEmpty)
                {
                    ChannelListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_newChannelListeners.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    string channel = listener.Channel;
                    if (!_channeledOutgoingMessages.ContainsKey(channel))
                    {
                        _channeledOutgoingMessages[channel] = new List <ConcurrentQueue <Message> >(1);
                    }
                    _channeledOutgoingMessages[channel].Add(listener.Queue);
                }

                while (!_newInstanceListeners.IsEmpty)
                {
                    InstanceListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_newInstanceListeners.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    object instance = listener.Instance;
                    if (!_instanceBoundOutgoingMessages.ContainsKey(instance))
                    {
                        _instanceBoundOutgoingMessages[instance] = new List <ConcurrentQueue <Message> >(1);
                    }
                    _instanceBoundOutgoingMessages[instance].Add(listener.Queue);
                }

                while (!_newTypeListeners.IsEmpty)
                {
                    TypeListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_newTypeListeners.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    Type type = listener.Type;
                    if (!_typeBoundOutgoingMessages.ContainsKey(type))
                    {
                        _typeBoundOutgoingMessages[type] = new List <ConcurrentQueue <Message> >(1);
                    }
                    _typeBoundOutgoingMessages[type].Add(listener.Queue);
                }

                while (!_channelListenersScheduledForRemoval.IsEmpty)
                {
                    ChannelListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_channelListenersScheduledForRemoval.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    string channel = listener.Channel;
                    if (_channeledOutgoingMessages.ContainsKey(channel))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _channeledOutgoingMessages[channel];
                        messageQueueList.Remove(listener.Queue);
                        if (messageQueueList.Count == 0)
                        {
                            _channeledOutgoingMessages.Remove(channel);
                        }
                    }
                }

                while (!_instanceListenersScheduledForRemoval.IsEmpty)
                {
                    InstanceListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_instanceListenersScheduledForRemoval.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    object instance = listener.Instance;
                    if (_instanceBoundOutgoingMessages.ContainsKey(instance))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _instanceBoundOutgoingMessages[instance];
                        messageQueueList.Remove(listener.Queue);
                        if (messageQueueList.Count == 0)
                        {
                            _instanceBoundOutgoingMessages.Remove(instance);
                        }
                    }
                }

                while (!_typeListenersScheduledForRemoval.IsEmpty)
                {
                    TypeListener listener = null;
                    for (int i = 0; i < 10; i++)
                    {
                        if (_typeListenersScheduledForRemoval.TryDequeue(out listener))
                        {
                            break;
                        }
                    }
                    if (listener == null)
                    {
                        break;
                    }
                    Type type = listener.Type;
                    if (_typeBoundOutgoingMessages.ContainsKey(type))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _typeBoundOutgoingMessages[type];
                        messageQueueList.Remove(listener.Queue);
                        if (messageQueueList.Count == 0)
                        {
                            _typeBoundOutgoingMessages.Remove(type);
                        }
                    }
                }

                while (!_incomingMessages.IsEmpty)
                {
                    IncomingMessage message = null;
                    for (int i = 0; i < 5; i++)
                    {
                        if (_incomingMessages.TryDequeue(out message))
                        {
                            break;
                        }
                    }
                    if (message == null)
                    {
                        break;
                    }
                    if (message.Message == null)
                    {
                        continue;
                    }

                    string channel = message.Channel;
                    if (_channeledOutgoingMessages.ContainsKey(channel))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _channeledOutgoingMessages[channel];
                        int length = messageQueueList.Count;
                        for (int i = 0; i < length; i++)
                        {
                            messageQueueList[i].Enqueue(message.Message);
                        }
                    }

                    object instance = message.Sender;
                    if (_instanceBoundOutgoingMessages.ContainsKey(instance))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _instanceBoundOutgoingMessages[instance];
                        int length = messageQueueList.Count;
                        for (int i = 0; i < length; i++)
                        {
                            messageQueueList[i].Enqueue(message.Message);
                        }
                    }

                    Type type = message.Sender.GetType();
                    if (_typeBoundOutgoingMessages.ContainsKey(type))
                    {
                        List <ConcurrentQueue <Message> > messageQueueList = _typeBoundOutgoingMessages[type];
                        int length = messageQueueList.Count;
                        for (int i = 0; i < length; i++)
                        {
                            messageQueueList[i].Enqueue(message.Message);
                        }
                    }
                }
            }
        }
Esempio n. 16
0
        static int Main(string[] args)
        {
            IDNP3Manager mgr = DNP3ManagerFactory.CreateManager(1, new PrintingLogAdapter());

            var channel = mgr.AddTCPServer("server", LogLevels.NORMAL, ChannelRetry.Default, "0.0.0.0", 20000, ChannelListener.Print());

            var config = new OutstationStackConfig();

            // configure the various measurements in our database
            config.databaseTemplate = new DatabaseTemplate(4, 1, 1, 1, 1, 1, 1, 0);
            config.databaseTemplate.binaries[0].clazz = PointClass.Class2;
            // ....
            config.outstation.config.allowUnsolicited = true;

            // Optional: setup your stack configuration here
            config.link.localAddr  = 10;
            config.link.remoteAddr = 1;

            var outstation = channel.AddOutstation("outstation", RejectingCommandHandler.Instance, DefaultOutstationApplication.Instance, config);

            outstation.Enable(); // enable communications

            Console.WriteLine("Press <Enter> to change a value");
            bool   binaryValue = false;
            double analogValue = 0;

            while (true)
            {
                switch (Console.ReadLine())
                {
                case ("x"):
                    return(0);

                default:
                {
                    binaryValue = !binaryValue;
                    ++analogValue;

                    // create a changeset and load it
                    var changeset = new ChangeSet();
                    changeset.Update(new Binary(binaryValue, 1, DateTime.Now), 0);
                    changeset.Update(new Analog(analogValue, 1, DateTime.Now), 0);
                    outstation.Load(changeset);
                }
                break;
                }
            }
        }
Esempio n. 17
0
        static int Main(string[] args)
        {
            IDNP3Manager mgr = DNP3ManagerFactory.CreateManager(1, new PrintingLogAdapter());

            var channel = mgr.AddTCPClient(
                "client",
                LogLevels.NORMAL | LogLevels.APP_COMMS,
                new ChannelRetry(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(5)),
                new List <IPEndpoint> {
                new IPEndpoint("127.0.0.1", 20000)
            },
                ChannelListener.Print()
                );

            var config = new MasterStackConfig();

            //setup your stack configuration here.
            config.link.localAddr  = 1;
            config.link.remoteAddr = 10;

            var key = new byte[16];

            for (int i = 0; i < key.Length; ++i)
            {
                key[i] = 0xFF;
            }

            var master = channel.AddMaster("master", PrintingSOEHandler.Instance, DefaultMasterApplication.Instance, config);

            // you a can optionally add various kinds of polls
            var integrityPoll = master.AddClassScan(ClassField.AllClasses, TimeSpan.FromMinutes(1), PrintingSOEHandler.Instance, TaskConfig.Default);
            var rangePoll     = master.AddRangeScan(30, 2, 5, 7, TimeSpan.FromSeconds(20), PrintingSOEHandler.Instance, TaskConfig.Default);
            var classPoll     = master.AddClassScan(ClassField.AllEventClasses, TimeSpan.FromSeconds(5), PrintingSOEHandler.Instance, TaskConfig.Default);

            /* you can also do very custom scans
             * var headers = new Header[] { Header.Range8(1, 2, 7, 8), Header.Count8(2, 3, 7) };
             * var weirdPoll = master.AddScan(headers, TimeSpan.FromSeconds(20));
             */

            master.Enable(); // enable communications

            Console.WriteLine("Enter a command");

            while (true)
            {
                switch (Console.ReadLine())
                {
                case "a":
                    // perform an ad-hoc scan of all analogs
                    master.ScanAllObjects(30, 0, PrintingSOEHandler.Instance, TaskConfig.Default);
                    break;

                case "c":
                    var task = master.SelectAndOperate(GetCommandHeaders(), TaskConfig.Default);
                    task.ContinueWith((result) => Console.WriteLine("Result: " + result.Result));
                    break;

                case "o":
                    var crob   = new ControlRelayOutputBlock(OperationType.PULSE_ON, TripCloseCode.NUL, false, 1, 100, 100);
                    var single = master.SelectAndOperate(crob, 1, TaskConfig.Default);
                    single.ContinueWith((result) => Console.WriteLine("Result: " + result.Result));
                    break;

                case "l":
                    // add interpretation to the current logging level
                    var filters = channel.GetLogFilters();
                    channel.SetLogFilters(filters.Add(LogFilters.TRANSPORT_TX | LogFilters.TRANSPORT_RX));
                    break;

                case "i":
                    integrityPoll.Demand();
                    break;

                case "r":
                    rangePoll.Demand();
                    break;

                case "e":
                    classPoll.Demand();
                    break;

                case "x":
                    return(0);

                default:
                    break;
                }
            }
        }
Esempio n. 18
0
        static int Main(string[] args)
        {
            IDNP3Manager mgr = DNP3ManagerFactory.CreateManager(1, new PrintingLogAdapter());

            var channel = mgr.AddTCPServer("server", LogLevels.NORMAL, ServerAcceptMode.CloseExisting, new IPEndpoint("0.0.0.0", 20000), ChannelListener.Print());

            var config = new OutstationStackConfig();

            // configure the various measurements in our database
            config.databaseTemplate.binary.Add(3, new BinaryConfig());
            config.databaseTemplate.binary.Add(7, new BinaryConfig());
            config.databaseTemplate.analog.Add(0, new AnalogConfig());
            // ....
            config.outstation.config.allowUnsolicited = true;

            // Optional: setup your stack configuration here
            config.link.localAddr  = 10;
            config.link.remoteAddr = 1;

            var outstation = channel.AddOutstation("outstation", RejectingCommandHandler.Instance, DefaultOutstationApplication.Instance, config);

            outstation.Enable(); // enable communications

            Console.WriteLine("Press <Enter> to change a value");
            bool   binaryValue = false;
            double analogValue = 0;

            while (true)
            {
                switch (Console.ReadLine())
                {
                case ("x"):
                    return(0);

                default:
                {
                    binaryValue = !binaryValue;
                    ++analogValue;

                    // create a changeset and load it
                    var changeset = new ChangeSet();

                    var binaryFlags = new Flags();
                    binaryFlags.Set(BinaryQuality.ONLINE);

                    var analogFlags = new Flags();
                    analogFlags.Set(AnalogQuality.ONLINE);


                    changeset.Update(new Binary(binaryValue, binaryFlags, new DNPTime(DateTime.UtcNow)), 3);
                    changeset.Update(new Analog(analogValue, analogFlags, DNPTime.Now), 0);
                    outstation.Load(changeset);
                }
                break;
                }
            }
        }
        public void registerForPush(string options)
        {
            PushOptions pushOptions;

            if (!TryDeserializeOptions(options, out pushOptions))
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));

                return;
            }

#if DEBUG
            Debug.WriteLine("Registering for push on channel " + pushOptions.ChannelName);
#endif

            HttpNotificationChannel pushChannel     = HttpNotificationChannel.Find(pushOptions.ChannelName);
            ChannelListener         channelListener = null;

            if (!channelListeners.TryGetValue(pushOptions.ChannelName, out channelListener))
            {
                channelListener = new ChannelListener(pushOptions.ChannelName, this, this.CurrentCommandCallbackId);
                channelListeners[pushOptions.ChannelName] = channelListener;
            }

            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(pushOptions.ChannelName);
                channelListener.Subscribe(pushChannel);

                try
                {
                    for (int tries = 0; tries < 3 && pushChannel.ChannelUri == null; ++tries)
                    {
                        pushChannel.Open();
                    }
                }
                catch (InvalidOperationException)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, InvalidRegistrationError));

                    return;
                }

                pushChannel.BindToShellToast();
                pushChannel.BindToShellTile();
            }
            else
            {
                channelListener.Subscribe(pushChannel);
            }

            if (pushChannel.ChannelUri != null)
            {
#if DEBUG
                Debug.WriteLine("Already registered for push on channel " + pushChannel.ChannelName + " with URI " + pushChannel.ChannelUri);
#endif

                PluginResult result = new PluginResult(PluginResult.Status.OK, pushChannel.ChannelUri.ToString());

                result.KeepCallback = true;
                DispatchCommandResult(result);
            }

            FireAllPendingEvents();
        }
Esempio n. 20
0
        static async Task MainAsync(string[] args)
        {
            Console.Write("Host name (ENTER for default): ");

            var hostName = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(hostName))
            {
                hostName = Dns.GetHostName();
            }

            Console.Write("Port number (ENTER for default): ");

            int portNumber;

            if (!int.TryParse(Console.ReadLine(), out portNumber))
            {
                portNumber = 55321;
            }

            Console.Write("Identity (name@domain - ENTER for none): ");

            Identity identity;

            if (!Identity.TryParse(Console.ReadLine(), out identity))
            {
                identity = null;
            }

            string password = null;

            if (identity != null)
            {
                Console.Write("Password: "******"net.tcp://{hostName}:{portNumber}");
            var transport = new TcpTransport(traceWriter: new DebugTraceWriter());

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transport, serverUri)
                          .AddBuiltHandler((channel, token) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(TaskUtil.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .AddEstablishedHandler(async(c, t) =>
                                                 await c.SetResourceAsync(
                                                     new LimeUri(UriTemplates.PRESENCE),
                                                     new Presence()
            {
                Status = PresenceStatus.Available
            },
                                                     t))
                          .AddEstablishedHandler(async(c, t) =>
                                                 await c.SetResourceAsync(
                                                     new LimeUri(UriTemplates.RECEIPT),
                                                     new Receipt()
            {
                Events = new[] { Event.Received, Event.Dispatched }
            },
                                                     t));

            if (identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(identity)
                          .WithPlainAuthentication(password);
            }

            var onDemandChannel = new OnDemandClientChannel(builder);
            var running         = true;

            onDemandChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                Console.Write("Could not establish the session: {0}", information.Exception.Message);
                Console.WriteLine();
                running = false;
                return(TaskUtil.FalseCompletedTask);
            });


            var channelListener = new ChannelListener(message =>
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("Message with id '{0}' received from '{1}': {2}", message.Id, message.GetSender(),
                                  message.Content);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      notification =>
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("Notification with id {0} received from '{1}' - Event: {2}",
                                  notification.Id, notification.GetSender(), notification.Event);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      command =>
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id,
                                  command.GetSender(), command.Method, command.Uri);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            });

            channelListener.Start(onDemandChannel);

            while (running)
            {
                Console.Write("Destination node (Type EXIT to quit): ");
                var toInput = Console.ReadLine();
                if (toInput != null &&
                    toInput.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }

                Node to = null;
                if (string.IsNullOrEmpty(toInput) || Node.TryParse(toInput, out to))
                {
                    Console.Write("Message text: ");
                    var message = new Message
                    {
                        To      = to,
                        Content = new PlainText
                        {
                            Text = Console.ReadLine()
                        }
                    };

                    await onDemandChannel.SendMessageAsync(message, CancellationToken.None);
                }
            }

            channelListener.Stop();
            await Task.WhenAll(
                channelListener.MessageListenerTask,
                channelListener.NotificationListenerTask,
                channelListener.CommandListenerTask);

            await onDemandChannel.FinishAsync(CancellationToken.None);

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Esempio n. 21
0
 /// <summary>
 /// Sets the ChannelListener that will be notified of changes to the channel
 /// </summary>
 /// <param name="channel_listener">The ChannelListener object to receive changes</param>
 public void setChannelListener(ChannelListener channel_listener)
 {
     this.channel_listener=channel_listener;
 }
Esempio n. 22
0
 /// <summary>
 /// Sets the ChannelListener that will be notified of changes to the channel
 /// </summary>
 /// <param name="channel_listener">The ChannelListener object to receive changes</param>
 public void setChannelListener(ChannelListener channel_listener)
 {
     this.channel_listener = channel_listener;
 }
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

            ProducerConsumer.CreateAsync(
                c => _transportListener.AcceptTransportAsync(c),
                async(transport, _) =>
            {
                await transport.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    transport,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                    AuthenticationScheme.External
                },
                    (n, a, _) =>
                {
                    Authentications.Enqueue(a);
                    return(new AuthenticationResult(DomainRole.RootAuthority, a).AsCompletedTask());
                },
                    (n, s, c) =>
                {
                    return(n.AsCompletedTask());
                }, _cts.Token);

                var channelListener = new ChannelListener(
                    m =>
                {
                    Messages.Enqueue(m);
                    return(TaskUtil.TrueCompletedTask);
                },
                    n =>
                {
                    Notifications.Enqueue(n);
                    return(TaskUtil.TrueCompletedTask);
                },
                    async c =>
                {
                    Commands.Enqueue(c);
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);
                Channels.Enqueue(serverChannel);

                return(true);
            },
                _cts.Token);
        }