public async Task Setup()
        {
            new TopicGenerator().Generate(NumPublishers, NumTopicsPerPublisher, out _topicsByPublisher, out _singleWildcardTopicsByPublisher, out _multiWildcardTopicsByPublisher);

            var serverOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();
            var factory       = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(serverOptions);
            await _mqttServer.StartAsync();

            Console.WriteLine();
            Console.WriteLine("Begin connect " + NumPublishers + " publisher(s)...");

            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();
            _mqttPublisherClientsByPublisherName = new Dictionary <string, Client.MqttClient>();
            foreach (var pt in _topicsByPublisher)
            {
                var publisherName    = pt.Key;
                var mqttClient       = factory.CreateMqttClient();
                var publisherOptions = new MqttClientOptionsBuilder()
                                       .WithTcpServer("localhost")
                                       .WithClientId(publisherName)
                                       .Build();
                await mqttClient.ConnectAsync(publisherOptions);

                _mqttPublisherClientsByPublisherName.Add(publisherName, mqttClient);
            }
            stopWatch.Stop();

            Console.Write(string.Format("{0} publisher(s) connected in {1:0.000} seconds, ", NumPublishers, stopWatch.ElapsedMilliseconds / 1000.0));
            Console.WriteLine(string.Format("connections per second: {0:0.000}", NumPublishers / (stopWatch.ElapsedMilliseconds / 1000.0)));

            _mqttSubscriberClients = new List <Client.MqttClient>();
            for (var i = 0; i < NumSubscribers; ++i)
            {
                var mqttClient       = factory.CreateMqttClient();
                var subsriberOptions = new MqttClientOptionsBuilder()
                                       .WithTcpServer("localhost")
                                       .WithClientId("sub" + i)
                                       .Build();
                await mqttClient.ConnectAsync(subsriberOptions);

                mqttClient.ApplicationMessageReceivedAsync += HandleApplicationMessageReceivedAsync;
                _mqttSubscriberClients.Add(mqttClient);
            }
        }
Exemplo n.º 2
0
            public async void startServer()
            {
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithConnectionBacklog(100)
                                     .WithDefaultEndpointPort(1883)
                                     .WithDefaultEndpointBoundIPAddress(IPAddress.Parse("172.22.111.55"))
                ;

                mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(optionsBuilder.Build());

                mqttServer.ClientConnected += (s, e) =>
                {
                    Console.WriteLine(e.ClientId);
                };
            }
Exemplo n.º 3
0
        public async Task MqttServerOnOtherPortReceivesMessage()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithDefaultEndpointPort(1337)
                          .Build();

            using (var mqttServer = await MqttServerHelper.Get(_logger, options))
                using (var jobHost = await JobHostHelper <SimpleMessageAnotherPortTestFunction> .RunFor(_testLoggerProvider))
                {
                    await mqttServer.PublishAsync(DefaultMessage);

                    await WaitFor(() => SimpleMessageAnotherPortTestFunction.CallCount >= 1);
                }

            Assert.Equal(1, SimpleMessageAnotherPortTestFunction.CallCount);
        }
Exemplo n.º 4
0
        static async void InitMqtt()
        {
            // Start a MQTT server.
            Console.WriteLine("Starting MQTT Server at: localhost:1883");
            // Configure MQTT server.
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(1883);

            var mqttServer = new MqttFactory().CreateMqttServer();
            await mqttServer.StartAsync(optionsBuilder.Build());

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
            await mqttServer.StopAsync();
        }
Exemplo n.º 5
0
        public static async Task RunAsync()
        {
            MqttNetConsoleLogger.ForwardToConsole();

            var factory = new MqttFactory();
            var server  = factory.CreateMqttServer();
            var client  = factory.CreateMqttClient();

            var serverOptions = new MqttServerOptionsBuilder().Build();
            await server.StartAsync(serverOptions);

            var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost").Build();
            await client.ConnectAsync(clientOptions);

            await Task.Delay(Timeout.Infinite);
        }
Exemplo n.º 6
0
        public static void Init()
        {
            Server = new MqttFactory().CreateMqttServer();

            IMqttServerOptions SrvOpt = new MqttServerOptionsBuilder().WithDefaultEndpointPort(1883).Build();

            Server.StartAsync(SrvOpt);

            Client = new MqttFactory().CreateMqttClient();
            Client.UseApplicationMessageReceivedHandler(OnMessageReceived);
            Client.UseConnectedHandler(OnConnected);

            IMqttClientOptions CliOpt = new MqttClientOptionsBuilder().WithClientId("SquidHome").WithTcpServer("127.0.0.1", 1883).WithCleanSession().Build();

            Client.ConnectAsync(CliOpt, CancellationToken.None);
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithoutDefaultEndpoint()
                                    .WithConnectionValidator(new Authenticators.HubAuthenticatorService(Configuration).Validate)
                                    .WithApplicationMessageInterceptor(c => { })
                                    .Build();

            services
            .AddHostedMqttServer(mqttServerOptions)
            .AddMqttConnectionHandler()
            .AddConnections();

            services.AddDbContext <HubDbContext>(options => options.UseSqlServer(
                                                     Configuration.GetConnectionString("HubDatabase")));
        }
Exemplo n.º 8
0
        public async Task TriggerAndOutputReuseConnection()
        {
            var mqttApplicationMessages = new List <MqttApplicationMessage>();
            var counnections            = 0;
            var options = new MqttServerOptionsBuilder()
                          .WithConnectionValidator(x =>
            {
                counnections += (x.ClientId != "IntegrationTest") ? 1 : 0;
            })
                          .Build();

            using (var mqttServer = await MqttServerHelper.Get(_logger, options))
                using (var mqttClient = await MqttClientHelper.Get(_logger))
                    using (var jobHost = await JobHostHelper <TriggerAndOutputWithSameConnectionTestFunction> .RunFor(_testLoggerProvider))
                    {
                        await mqttClient.SubscribeAsync("test/outtopic");

                        await mqttClient.SubscribeAsync("test/outtopic2");

                        await mqttServer.PublishAsync(DefaultMessage);

                        var firstMessage = await mqttClient.WaitForMessage();

                        if (firstMessage != null)
                        {
                            mqttApplicationMessages.Add(firstMessage);
                            var secondMessage = await mqttClient.WaitForMessage();

                            if (secondMessage != null)
                            {
                                mqttApplicationMessages.Add(secondMessage);
                            }
                        }
                        await WaitFor(() => TriggerAndOutputWithSameConnectionTestFunction.CallCount >= 1);
                    }

            Assert.Equal(1, TriggerAndOutputWithSameConnectionTestFunction.CallCount);
            Assert.Equal(1, counnections);

            Assert.Equal(2, mqttApplicationMessages.Count);
            Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic");
            Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic2");

            var bodyString = Encoding.UTF8.GetString(mqttApplicationMessages.First().Payload);

            Assert.Equal("{\"test\":\"message\"}", bodyString);
        }
Exemplo n.º 9
0
        public async Task Set_Session_Item()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                var serverOptions = new MqttServerOptionsBuilder()
                                    .WithConnectionValidator(delegate(MqttConnectionValidatorContext context)
                {
                    // Don't validate anything. Just set some session items.
                    context.SessionItems["can_subscribe_x"] = true;
                    context.SessionItems["default_payload"] = "Hello World";
                })
                                    .WithSubscriptionInterceptor(delegate(MqttSubscriptionInterceptorContext context)
                {
                    if (context.TopicFilter.Topic == "x")
                    {
                        context.AcceptSubscription = context.SessionItems["can_subscribe_x"] as bool? == true;
                    }
                })
                                    .WithApplicationMessageInterceptor(delegate(MqttApplicationMessageInterceptorContext context)
                {
                    context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(context.SessionItems["default_payload"] as string);
                });

                await testEnvironment.StartServer(serverOptions);

                string receivedPayload = null;

                var client = await testEnvironment.ConnectClient();

                client.UseApplicationMessageReceivedHandler(delegate(MqttApplicationMessageReceivedEventArgs args)
                {
                    receivedPayload = args.ApplicationMessage.ConvertPayloadToString();
                });

                var subscribeResult = await client.SubscribeAsync("x");

                Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS0, subscribeResult.Items[0].ResultCode);

                var client2 = await testEnvironment.ConnectClient();

                await client2.PublishAsync("x");

                await Task.Delay(1000);

                Assert.AreEqual("Hello World", receivedPayload);
            }
        }
Exemplo n.º 10
0
        private void InitServer()
        {
            IMqttNetLogger logger = new MqttNetLogger();

            serverOptionsBuilder = new MqttServerOptionsBuilder()
                                   .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(ip))
                                   .WithDefaultEndpointPort(port)
                                   .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(communicationTimeout))
                                   .WithEncryptionSslProtocol(sslProtocols);
            // connect verfication
            serverOptionsBuilder.WithConnectionValidator(valid =>
            {
                if (valid.ClientId.Length < 10)
                {
                    valid.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }
                if (!valid.Username.Equals(this.username))
                {
                    valid.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }
                if (!valid.Password.Equals(password))
                {
                    valid.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }
                valid.ReasonCode = MqttConnectReasonCode.Success;
            });
            serverOptions = serverOptionsBuilder.Build();

            mqttServer = (new MqttFactory()).CreateMqttServer(logger) as MqttServer;
            mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
            {
                ClientIds.Add(e.ClientId);
                Logger.Info($"clientID:{e.ClientId} connect success!");
            });
            mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(e =>
            {
                ClientIds.RemoveWhere(s => s.Equals(e.ClientId));
                Logger.Info($"clientID:{e.ClientId} disconnect!");
            });
            mqttServer.UseApplicationMessageReceivedHandler(e =>
            {
                AppMsgReceivedHandler?.Invoke(e.ClientId, e.ApplicationMessage);
            });
        }
Exemplo n.º 11
0
        public async Task Manage_Session_MaxParallel()
        {
            using (var testEnvironment = CreateTestEnvironment())
            {
                testEnvironment.IgnoreClientLogErrors = true;
                var serverOptions = new MqttServerOptionsBuilder();
                await testEnvironment.StartServer(serverOptions);

                var options = new MqttClientOptionsBuilder().WithClientId("1");

                var clients = await Task.WhenAll(Enumerable.Range(0, 10).Select(i => TryConnect(testEnvironment, options)));

                var connectedClients = clients.Where(c => c?.IsConnected ?? false).ToList();

                Assert.AreEqual(1, connectedClients.Count);
            }
        }
Exemplo n.º 12
0
        public async Task StartServerAsync()
        {
            try
            {
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithConnectionBacklog(100)
                                     .WithDefaultEndpointPort(1883);

                _mqttServer = new MqttFactory().CreateMqttServer();
                await _mqttServer.StartAsync(optionsBuilder.Build());
            }
            catch (Exception ex)
            {
                _logger.LogError("StartServerAsync error:\n" + ex.ToString());
                Console.ReadLine();
            }
        }
    public static async Task Validating_Connections()
    {
        /*
         * This sample starts a simple MQTT server which will check for valid credentials and client ID.
         *
         * See _Run_Minimal_Server_ for more information.
         */

        var mqttFactory = new MqttFactory();

        var mqttServerOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpoint()
                                .Build();

        using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions))
        {
            // Setup connection validation before starting the server so that there is
            // no change to connect without valid credentials.
            mqttServer.ValidatingConnectionAsync += e =>
            {
                if (e.ClientId != "ValidClientId")
                {
                    e.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                }

                if (e.Username != "ValidUser")
                {
                    e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }

                if (e.Password != "SecretPassword")
                {
                    e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }

                return(Task.CompletedTask);
            };

            await mqttServer.StartAsync();

            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();

            await mqttServer.StopAsync();
        }
    }
Exemplo n.º 14
0
        public void StartListening()
        {
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder()
                                                      .WithConnectionBacklog(100)
                                                      .WithDefaultEndpointPort(5656)
                                                      .WithApplicationMessageInterceptor(context =>
            {
                Console.WriteLine(Encoding.UTF8.GetString(context.ApplicationMessage.Payload, 0, context.ApplicationMessage.Payload.Length));
                Clients.All.notifyMessage(context.ApplicationMessage.Payload, 0, context.ApplicationMessage.Payload.Length);
                context.ApplicationMessage.Payload = null;
            });
            IMqttServer mqttServer = new MqttFactory().CreateMqttServer();

            mqttServer.StartAsync(optionsBuilder.Build());
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Exemplo n.º 15
0
        /// <summary>
        /// 开启服务
        /// </summary>
        private async Task <string> CreateMQTTServer(int port)
        {
            var optionsBuilder = new MqttServerOptionsBuilder();

            try
            {
                //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。
                optionsBuilder.WithConnectionValidator(c =>
                {
                    try
                    {
                        if (LoginEvent != null)
                        {
                            LoginEvent?.Invoke(c);
                        }
                        else
                        {
                            c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                        }
                    }
                    catch
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        return;
                    }
                });
                //指定端口
                optionsBuilder.WithDefaultEndpointPort(port);
                //连接记录数,默认 一般为2000
                //optionsBuilder.WithConnectionBacklog(2000);
                mqttServer = new MqttFactory().CreateMqttServer();
                //   客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件,用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。
                //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient,通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。
                mqttServer.ClientConnected    += MqttServer_ClientConnected;
                mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
                //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象,通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。
                mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
            }
            catch (Exception ex)
            {
                return("MQTT服务创建失败>" + ex.Message);
            }
            await mqttServer.StartAsync(optionsBuilder.Build());

            return("MQTT服务<0.0.0.0:" + port + ">已启动");
        }
Exemplo n.º 16
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var db = _serviceProvider.CreateScope().ServiceProvider.GetService <SmartServerContext>())
            {
                await db.Database.MigrateAsync(cancellationToken : cancellationToken);
            }
            _logger.LogInformation("Starting MqttBrokerService");
            var optionsBuilder = new MqttServerOptionsBuilder().WithDefaultEndpoint();
            await _mqttServer.StartAsync(optionsBuilder.Build());

            await _mqttTemperatureClientService.StartAsync();

            await _autodiscoverService.StartAsync();

            _mqttServer.ClientConnectedHandler    = new MqttServerClientConnectedHandlerDelegate(args => _logger.LogDebug("Client {0} connected.", args.ClientId));
            _mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(args => _logger.LogDebug("Client {0} disconnected ({1}).", args.ClientId, args.DisconnectType));
        }
Exemplo n.º 17
0
        private IMqttServerOptions ConfigBroker(int port = 1889)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(port)
                                 .WithConnectionValidator(c =>
            {
                c.ReasonCode    = MqttConnectReasonCode.BadUserNameOrPassword;
                var userAccount = (_accountManager.Login(c.Username, c.Password))?.Result;
                if (userAccount != null)
                {
                    c.ReasonCode = MqttConnectReasonCode.Success;
                }
            });

            return(optionsBuilder.Build());
        }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

#if ENABLE_MQTT_BROKER
            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithoutDefaultEndpoint()
                                    .Build();

            services
            .AddHostedMqttServer(mqttServerOptions)
            .AddMqttConnectionHandler()
            .AddConnections();
#endif
            MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(Configuration.GetConnectionString("mongodb"));

            var redisConfiguration = Configuration.GetSection("redis").Get <RedisConfiguration>();
            var mqttOptions        = Configuration.GetSection("MQTT").Get <MqttSubscribeConfig>();
            services.AddSingleton(mqttOptions);
            services.AddSingleton(redisConfiguration);
            services.AddSingleton <IRedisConnectionFactory, RedisConnectionFactory>();
            services.AddSingleton(client);
            queue_service = new MongoBackgroundTaskQueue(client);
            services.AddSingleton(queue_service);
            //IServiceCollection cols  = services.AddSingleton<IBackgroundMongoTaskQueue, MongoBackgroundTaskQueue>();
            //services.AddHostedService<MongoBackgroundHostService>();



            //byte[] file_array = File.ReadAllBytes("output.txt");

            //byte[] new_fileArray = new byte[file_array.Length + 8];
            //Array.Copy(file_array, new_fileArray, file_array.Length);
            //DaegunPacket packet = PacketParser.ByteToStruct<DaegunPacket>(new_fileArray);
            //packet.timestamp = DateTime.Now;
            //queue_service.QueueBackgroundWorkItem(packet);



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemplo n.º 19
0
        private static async Task StartMqttServer()
        {
            if (mqttServer == null)
            {
                // Configure MQTT server.
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithConnectionBacklog(100)
                                     .WithDefaultEndpointPort(8222)
                                     .WithConnectionValidator(c =>
                {
                    Dictionary <string, string> c_u = new Dictionary <string, string>();
                    c_u.Add("client001", "username001");
                    c_u.Add("client002", "username002");
                    Dictionary <string, string> u_psw = new Dictionary <string, string>();
                    u_psw.Add("username001", "psw001");
                    u_psw.Add("username002", "psw002");

                    if (c_u.ContainsKey(c.ClientId) && c_u[c.ClientId] == c.Username)
                    {
                        if (u_psw.ContainsKey(c.Username) && u_psw[c.Username] == c.Password)
                        {
                            c.ReasonCode = MqttConnectReasonCode.Success;
                        }
                        else
                        {
                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        }
                    }
                    else
                    {
                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    }
                });

                // Start a MQTT server.
                mqttServer = new MqttFactory().CreateMqttServer();
                mqttServer.UseApplicationMessageReceivedHandler(MqttServer_ApplicationMessageReceived);
                mqttServer.UseClientConnectedHandler(MqttServer_ClientConnected);
                mqttServer.UseClientDisconnectedHandler(MqttServer_ClientDisconnected);

                await mqttServer.StartAsync(optionsBuilder.Build());

                Console.WriteLine("MQTT服务启动成功!");
            }
        }
Exemplo n.º 20
0
        public async Task Publish_Special_Content()
        {
            var factory       = new MqttFactory();
            var server        = factory.CreateMqttServer();
            var serverOptions = new MqttServerOptionsBuilder().Build();

            var receivedMessages = new List <MqttApplicationMessage>();

            var client = factory.CreateMqttClient();

            try
            {
                await server.StartAsync(serverOptions);

                client.Connected += async(s, e) =>
                {
                    await client.SubscribeAsync("RCU/P1/H0001/R0003");

                    var msg = new MqttApplicationMessageBuilder()
                              .WithPayload("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|")
                              .WithTopic("RCU/P1/H0001/R0003");

                    await client.PublishAsync(msg.Build());
                };

                client.ApplicationMessageReceived += (s, e) =>
                {
                    lock (receivedMessages)
                    {
                        receivedMessages.Add(e.ApplicationMessage);
                    }
                };

                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());

                await Task.Delay(500);

                Assert.AreEqual(1, receivedMessages.Count);
                Assert.AreEqual("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|", receivedMessages.First().ConvertPayloadToString());
            }
            finally
            {
                await server.StopAsync();
            }
        }
Exemplo n.º 21
0
        public async Task <bool> StartAsync(int port)
        {
            if (server.IsStarted)
            {
                return(true);
            }

            Port = port;
            IMqttServerOptions options = new MqttServerOptionsBuilder()
                                         .WithApplicationMessageInterceptor(cv => { cv.AcceptPublish = true; })
                                         .WithConnectionValidator(cv =>
            {
                if (cv.ClientId.Length < 10)
                {
                    cv.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                if (!users.ContainsKey(cv.Username) ||
                    users[cv.Username] != cv.Password)
                {
                    cv.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                cv.ReasonCode = MqttConnectReasonCode.Success;
            })
                                         .WithEncryptionSslProtocol(System.Security.Authentication.SslProtocols.Tls12)
                                         .WithDefaultEndpointPort(port)
                                         .WithSubscriptionInterceptor(cv => { cv.AcceptSubscription = true; })
                                         .Build();

            try
            {
                await server.StartAsync(options);

                logger.Debug("Mqtt server is running at: {0}", port);
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(false);
            }
        }
Exemplo n.º 22
0
        private async void StartMqttServer()
        {
            ClientDispatcher = Dispatcher.CurrentDispatcher;
            SetStatus("Configuring");
            MqttFactory factory = new MqttFactory();
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder()
                                                      .WithDefaultCommunicationTimeout(new TimeSpan(0, 0, 0, 60, 0))
                                                      .WithDefaultEndpoint()
                                                      .WithDefaultEndpointPort(PlainPort)
                                                      .WithMaxPendingMessagesPerClient(2000)
            ;

            Server = factory.CreateMqttServer();

            Server.ApplicationMessageReceived += Server_ApplicationMessageReceived;
            Server.ClientConnected            += Server_ClientConnected;
            Server.ClientDisconnected         += Server_ClientDisconnected;
            Server.ClientSubscribedTopic      += Server_ClientSubscribedTopic;
            Server.ClientUnsubscribedTopic    += Server_ClientUnsubscribedTopic;
            Server.Started += Server_Started;

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Start(optionsBuilder.Build());
            }
            else
#endif
            await Server.StartAsync(optionsBuilder.Build());

            SetStatus("Started");
            // This will run the event queue forever, until we stop it
            Dispatcher.Run();

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Stop();
            }
            else
#endif
            Server.StopAsync().Wait();

            await Dispatcher.BeginInvoke((Action)(() => OnServerThreadStopped()));
        }
Exemplo n.º 23
0
        public static async Task RunClientAndServer()
        {
            try
            {
                var mqttFactory       = new MqttFactory();
                var mqttServerOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();
                var mqttServer        = mqttFactory.CreateMqttServer(mqttServerOptions);
                await mqttServer.StartAsync().ConfigureAwait(false);

                var options = new MqttClientOptions
                {
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "127.0.0.1"
                    }
                };

                var client = mqttFactory.CreateMqttClient();
                await client.ConnectAsync(options).ConfigureAwait(false);

                var message = new MqttApplicationMessageBuilder().WithTopic("t")
                              .Build();

                var stopwatch = new Stopwatch();

                for (var i = 0; i < 10; i++)
                {
                    stopwatch.Restart();

                    var sentMessagesCount = 0;
                    while (stopwatch.ElapsedMilliseconds < 1000)
                    {
                        await client.PublishAsync(message, CancellationToken.None).ConfigureAwait(false);

                        sentMessagesCount++;
                    }

                    Console.WriteLine($"Sending {sentMessagesCount} messages per second. #" + (i + 1));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Exemplo n.º 24
0
        public async Task TriggerAndOutputUseDifferentConnection()
        {
            MqttApplicationMessage mqttApplicationMessage = null;

            var connectionsCountServer1 = 0;
            var optionsServer1          = new MqttServerOptionsBuilder()
                                          .WithDefaultEndpointPort(1337)
                                          .WithConnectionValidator(x =>
            {
                connectionsCountServer1 += (x.ClientId != "IntegrationTest") ? 1 : 0;
            })
                                          .Build();

            var connectionsCountServer2 = 0;
            var optionsServer2          = new MqttServerOptionsBuilder()
                                          .WithConnectionValidator(x =>
            {
                connectionsCountServer2 += (x.ClientId != "IntegrationTest") ? 1 : 0;
            })
                                          .Build();

            using (var mqttServer1 = await MqttServerHelper.Get(_logger, optionsServer1))
                using (var mqttServer2 = await MqttServerHelper.Get(_logger, optionsServer2))
                    using (var mqttClientForServer2 = await MqttClientHelper.Get(_logger))
                        using (var jobHost = await JobHostHelper <TriggerAndOutputWithDifferentConnectionTestFunction> .RunFor(_testLoggerProvider))
                        {
                            await mqttClientForServer2.SubscribeAsync("test/outtopic");

                            await mqttServer1.PublishAsync(DefaultMessage);

                            mqttApplicationMessage = await mqttClientForServer2.WaitForMessage();
                            await WaitFor(() => TriggerAndOutputWithDifferentConnectionTestFunction.CallCount >= 1);
                        }

            Assert.Equal(1, TriggerAndOutputWithDifferentConnectionTestFunction.CallCount);
            Assert.Equal(1, connectionsCountServer1);
            Assert.Equal(1, connectionsCountServer2);

            Assert.NotNull(mqttApplicationMessage);
            Assert.Equal("test/outtopic", mqttApplicationMessage.Topic);

            var bodyString = Encoding.UTF8.GetString(mqttApplicationMessage.Payload);

            Assert.Equal("{\"test\":\"message\"}", bodyString);
        }
Exemplo n.º 25
0
        public async Task WhenTlsIsSetToTrueASecureConnectionIsMade()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithEncryptedEndpoint()
                          .WithEncryptionCertificate(new X509Certificate2(@"Certificates/myRootCA.pfx", "12345", X509KeyStorageFlags.Exportable))
                          .WithoutDefaultEndpoint()
                          .Build();

            using (var mqttServer = await MqttServerHelper.Get(_logger, options))
                using (var jobHost = await JobHostHelper <FunctionConnectingWithTlsEnabledTestFunction> .RunFor(_testLoggerProvider))
                {
                    await mqttServer.PublishAsync(DefaultMessage);

                    await WaitFor(() => FunctionConnectingWithTlsEnabledTestFunction.CallCount >= 1, 20);
                }

            Assert.Equal(1, FunctionConnectingWithTlsEnabledTestFunction.CallCount);
        }
Exemplo n.º 26
0
        public async Task Deny_Connection()
        {
            var serverOptions = new MqttServerOptionsBuilder().WithConnectionValidator(context =>
            {
                context.ReasonCode = MqttConnectReasonCode.NotAuthorized;
            });

            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                testEnvironment.IgnoreClientLogErrors = true;

                await testEnvironment.StartServerAsync(serverOptions);

                var connectingFailedException = await Assert.ThrowsExceptionAsync <MqttConnectingFailedException>(() => testEnvironment.ConnectClientAsync());

                Assert.AreEqual(MqttClientConnectResultCode.NotAuthorized, connectingFailedException.ResultCode);
            }
        }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var mqttOptions = new MqttServerOptionsBuilder()
                              .WithSubscriptionInterceptor(c => {
                // This callback area is not fired regardless tested using breakpoint and Console.WriteLine
                Console.WriteLine($"WithSubscriptionInterceptor: client id = {c.ClientId}");
                c.AcceptSubscription = false;
                c.CloseConnection    = true;
            })
                              // Other validation + interceptor
                              .Build();

            services.AddHostedMqttServer(mqttOptions);
            services.AddMqttTcpServerAdapter();
            services.AddMqttWebSocketServerAdapter();
        }
Exemplo n.º 28
0
        public async Task CustomConnectionWithClientIdIsReceived()
        {
            string clientId = string.Empty;
            var    options  = new MqttServerOptionsBuilder()
                              .WithConnectionValidator(x => clientId = x.ClientId)
                              .Build();

            using (var mqttServer = await MqttServerHelper.Get(_logger, options))
                using (var jobHost = await JobHostHelper <CustomConnectionStringWithClientIdTestFunction> .RunFor(_testLoggerProvider))
                {
                    await mqttServer.PublishAsync(DefaultMessage);

                    await WaitFor(() => CustomConnectionStringWithClientIdTestFunction.CallCount >= 1);
                }

            Assert.Equal(1, CustomConnectionStringWithClientIdTestFunction.CallCount);
            Assert.Equal("Custom", clientId);
        }
        public static IServiceCollection AddColtSmartMQTT(this IServiceCollection services, IConfiguration configuration)
        {
            var mqttOption = configuration.GetSection("MqttOption").Get <MqttOption>();

            var optionBuilder = new MqttServerOptionsBuilder().WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(mqttOption.HostIp))
                                .WithDefaultEndpointPort(mqttOption.HostPort)
                                .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(mqttOption.Timeout))
                                .WithEncryptedEndpoint()
                                .WithConnectionValidator(t =>
            {
                if (!string.IsNullOrWhiteSpace(t.Username) && !string.IsNullOrWhiteSpace(t.Password))
                {
                    var userService = EnjoyGlobals.ServiceProvider.GetService <IUserService>();

                    if (userService != null && userService.VerifyUser(t.Username, t.Password))
                    {
                        t.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                    }
                    else
                    {
                        t.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    }
                }
                else
                {
                    t.ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
                }
            });


            var options = optionBuilder.Build();

            //var certificate = new X509Certificate2(@"C:\certs\test\test.cer", "", X509KeyStorageFlags.Exportable);
            //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Pfx);
            //options.TlsEndpointOptions.IsEnabled = true;

            services.AddHostedMqttServer(options)
            .AddMqttConnectionHandler()
            .AddConnections();



            return(services);
        }
Exemplo n.º 30
0
        public async Task MqttServer_ConnectionDenied()
        {
            var server = new MqttFactory().CreateMqttServer();
            var client = new MqttFactory().CreateMqttClient();

            try
            {
                var options = new MqttServerOptionsBuilder().WithConnectionValidator(context =>
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
                }).Build();

                await server.StartAsync(options);


                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost").Build();

                try
                {
                    await client.ConnectAsync(clientOptions);

                    Assert.Fail("An exception should be raised.");
                }
                catch (Exception exception)
                {
                    if (exception is MqttConnectingFailedException)
                    {
                    }
                    else
                    {
                        Assert.Fail("Wrong exception.");
                    }
                }
            }
            finally
            {
                await client.DisconnectAsync();

                await server.StopAsync();

                client.Dispose();
            }
        }