public static async Task Main(string[] args)
        {
            // Create and start receive channel
            var passiveTcpChannel = new MessageChannel(
                new TcpPassiveByteStreamHandlerSettings(IPAddress.Loopback, 12000),
                new EndSymbolsMessageRecognizerSettings(Encoding.UTF8, "##"),
                (message) =>
            {
                Console.WriteLine($"Received message on passive channel: {message}");
            });
            await passiveTcpChannel.StartAsync();

            // Create and start send channel
            var activeTcpChannel = new MessageChannel(
                new TcpActiveByteStreamHandlerSettings(IPAddress.Loopback, 12000),
                new EndSymbolsMessageRecognizerSettings(Encoding.UTF8, "##"),
                (message) =>
            {
                Console.WriteLine($"Received message on active channel: {message}");
            });
            await activeTcpChannel.StartAsync();

            // Wait until both channels are connected
            while (passiveTcpChannel.State != ConnectionState.Connected)
            {
                await Task.Delay(500);
            }

            // Send some messages (active -> passive)
            await activeTcpChannel.SendAsync("Message 1 from active to passive...");

            await activeTcpChannel.SendAsync("Message 2 from active to passive...");

            await activeTcpChannel.SendAsync("Message 3 from active to passive...");

            // Send some messages (passive -> active)
            await passiveTcpChannel.SendAsync("Message 1 from active to passive...");

            await passiveTcpChannel.SendAsync("Message 2 from active to passive...");

            await passiveTcpChannel.SendAsync("Message 3 from active to passive...");

            // Wait
            Console.ReadLine();

            // Stop both channels
            await activeTcpChannel.StopAsync();

            await passiveTcpChannel.StopAsync();
        }
Esempio n. 2
0
        public async Task Check_SimpleUdpConnection()
        {
            var testingPort1 = TestUtility.GetFreeTcpPort();
            var testingPort2 = TestUtility.GetFreeTcpPort();

            var receiveTaskOnPassiveChannel = new TaskCompletionSource <string>();
            var receiveTaskOnActiveChannel  = new TaskCompletionSource <string>();

            // Define channels
            var passiveChannel = new MessageChannel(
                new UdpByteStreamHandlerSettings(testingPort1, IPAddress.Loopback, testingPort2),
                new DefaultMessageRecognizerSettings(Encoding.UTF8),
                (msg) =>
            {
                receiveTaskOnPassiveChannel.SetResult(msg.ToString());
                msg.ReturnToPool();
            });
            var activeChannel = new MessageChannel(
                new UdpByteStreamHandlerSettings(testingPort2, IPAddress.Loopback, testingPort1),
                new DefaultMessageRecognizerSettings(Encoding.UTF8),
                (msg) =>
            {
                receiveTaskOnActiveChannel.SetResult(msg.ToString());
                msg.ReturnToPool();
            });

            try
            {
                // Start both channels
                await Task.WhenAll(
                    passiveChannel.StartAsync(),
                    activeChannel.StartAsync());

                // Wait for connection
                var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5.0));
                await Task.WhenAll(
                    passiveChannel.WaitForConnectionAsync(timeoutTokenSource.Token),
                    activeChannel.WaitForConnectionAsync(timeoutTokenSource.Token));

                Assert.AreEqual(ConnectionState.Connected, passiveChannel.State, $"Unable to connect on port {testingPort2}");
                Assert.AreEqual(ConnectionState.Connected, activeChannel.State, $"Unable to connect on port {testingPort1}");

                // Send/Receive some messages in both directions
                await passiveChannel.SendAsync("Message from passive endpoint");

                await activeChannel.SendAsync("Message from active endpoint");

                // Check for received messages
                var receivedOnPassiveChannel = await receiveTaskOnPassiveChannel.Task;
                var receivedOnActiveChannel  = await receiveTaskOnActiveChannel.Task;
                Assert.IsTrue(receivedOnPassiveChannel == "Message from active endpoint");
                Assert.IsTrue(receivedOnActiveChannel == "Message from passive endpoint");
            }
            finally
            {
                await Task.WhenAll(
                    passiveChannel.StopAsync(),
                    activeChannel.StopAsync());
            }
        }
Esempio n. 3
0
        public async Task Check_SerialConnection_Send()
        {
            var encoding = Encoding.UTF8;

            // Fake serial port api and listen for Write calls
            var receivedString = string.Empty;

            SerialPortByteStreamHandler.SerialPortFactory = () =>
            {
                var isOpened = false;

                var fakedSerialPort = A.Fake <ISerialPort>();
                A.CallTo(() => fakedSerialPort.IsOpen).ReturnsLazily(call => isOpened);
                A.CallTo(() => fakedSerialPort.Open()).Invokes(call => isOpened  = true);
                A.CallTo(() => fakedSerialPort.Close()).Invokes(call => isOpened = false);
                A.CallTo(fakedSerialPort)
                .Where(call => call.Method.Name == nameof(ISerialPort.Write))
                .Invokes(call =>
                {
                    var buffer = (byte[])call.Arguments[0] !;
                    var offset = (int)call.Arguments[1] !;
                    var count  = (int)call.Arguments[2] !;

                    receivedString = encoding.GetString(buffer, offset, count);
                });

                return(fakedSerialPort);
            };

            // Define channels
            var serialChannel = new MessageChannel(
                new SerialPortByteStreamHandlerSettings("COM1"),
                new StartAndEndSymbolsRecognizerSettings(encoding, "<", ">"));

            try
            {
                // Start both channels
                await serialChannel.StartAsync();

                // Wait for connection
                var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5.0));
                await serialChannel.WaitForConnectionAsync(timeoutTokenSource.Token);

                Assert.AreEqual(serialChannel.State, ConnectionState.Connected);

                // Send/Receive some messages in both directions
                await serialChannel.SendAsync("Message sent through serial channel");

                // Check for written message
                Assert.AreEqual(receivedString, "<Message sent through serial channel>");
            }
            finally
            {
                await serialChannel.StopAsync();
            }
        }
        public async Task SendMessageAsync(string message)
        {
            if (await _messageChannel.SendAsync(new Message(message)))
            {
                var newLoggingMessage = new LoggingMessage(
                    DateTime.UtcNow, LoggingMessageType.Info, "OUT", message, null);

                this.LogTo(_syncContext, newLoggingMessage, this.DetailLogging);
                this.LogTo(_syncContext, newLoggingMessage, this.Messages);
            }
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            log4net.Config.BasicConfigurator.Configure();
            Tracer.Initialize(new TracerManager());
            AppDomain.CurrentDomain.UnhandledException += (s, e) => Tracer.Get<Client>().Error(e.ExceptionObject);
            TaskScheduler.UnobservedTaskException += (s, e) => Tracer.Get<Client>().Error(e.Exception);

            try
            {
                var ipPort = ServiceDiscovery.DiscoverBroker();
                var host = ipPort.Ip;
                var port = ipPort.Port;

                //var host = "localhost";
                //var port = 1055;

                //if (args.Length > 0)
                //    host = args[0];
                //if (args.Length > 1)
                //    port = int.Parse(args[1]);

                var client = new ReactiveClient(host, port);
                var binary = new BinaryChannel(client);
                var channel = new MessageChannel(binary);

                channel.Receiver.SubscribeOn(TaskPoolScheduler.Default).Subscribe(
                    s =>
                    {
                        Console.WriteLine("Received: {0}", s);
                        // Report state change immediately.
                        var topic = s as Topic;
                        if (topic != null)
                        {
                            Console.WriteLine("Sending back to cause state change: {0}", topic);
                            channel.SendAsync(topic);
                        }
                    },
                    e => Console.WriteLine(e),
                    () => Console.WriteLine("Socket receiver completed"));

                Console.WriteLine("To connect, enter: connect [device id] [device type]");
                Console.WriteLine("To send message once connected: [topic] = [value], where [value] can be:");
                Console.WriteLine("  * a boolean (words 'true' or 'false' without quotes)");
                Console.WriteLine("  * a number (a numberic value followed by the suffic 'f' denoting a floating point number)");
                Console.WriteLine("  * a string (without quotes)");
                Console.WriteLine("If no value is provided after the topic, then it's assumed to be a void topic (no payload needed)");

                string line = null;
                while ((line = Console.ReadLine()) != "")
                {
                    if (line.StartsWith("connect "))
                    {
                        var connectInfo = line.Substring(8).Split(' ');
                        var deviceId = connectInfo[0];
                        var deviceType = connectInfo[1];

                        Console.WriteLine("Connecting...");
                        try
                        {
                            client.ConnectAsync().Wait();
                            channel.SendAsync(new Connect(deviceId, deviceType)).Wait();
                            Console.WriteLine("Connected!");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Failed to connect: {0}", e);
                        }
                    }
                    else if (line == "disconnect")
                    {
                        if (client.IsConnected)
                        {
                            Console.WriteLine("Disconnecting...");
                            try
                            {
                                channel.SendAsync(new Disconnect()).Wait();
                                client.Disconnect();
                                Console.WriteLine("Disconnected!");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Failed to disconnect: {0}", e);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Client was already disconnected.");
                        }
                    }
                    else if (line == "r")
                    {
                        Console.WriteLine("Reconnecting...");
                        client.Disconnect();
                        client.ConnectAsync().Wait();
                        Console.WriteLine("IsConnected = {0}. Re-send Connect message.", client.IsConnected);
                    }
                    else
                    {
                        Console.WriteLine("Sending...");
                        if (line.IndexOf('=') == -1)
                        {
                            channel.SendAsync(new Topic(line.Trim()));
                        }
                        else
                        {
                            var parts = line.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(s => s.Trim()).ToArray();
                            if (parts[1].Equals("true", StringComparison.OrdinalIgnoreCase))
                                channel.SendAsync(new Topic(parts[0], Payload.ToBytes(true)));
                            else if (parts[1].Equals("false", StringComparison.OrdinalIgnoreCase))
                                channel.SendAsync(new Topic(parts[0], Payload.ToBytes(false)));
                            else if (parts[1].EndsWith("f"))
                                channel.SendAsync(new Topic(parts[0], Payload.ToBytes(float.Parse(parts[1].Substring(0, parts[1].Length - 1)))));
                            else
                                channel.SendAsync(new Topic(parts[0], Payload.ToBytes(parts[1])));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed: {0}", e);
            }
        }