Exemplo n.º 1
0
        private static async Task ConnectMqttServerAsync()
        {
            if (mqttServer == null)
            {
                var serveroptions = new MqttServerOptions
                {
                    DefaultEndpointOptions = { Port = port }
                };
                mqttServer = new MqttServerFactory().CreateMqttServer(serveroptions) as MqttServer;
                mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                mqttServer.ClientConnected            += MqttServer_Connected;
                mqttServer.ClientDisconnected         += MqttServer_Disconnected;
            }

            try
            {
                await mqttServer.StartAsync();

                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
            }
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Started Program to start broker...");

            var mqttOptions = new MqttConfiguration
            {
                BufferSize                   = 128 * 1024,
                Port                         = 1883,
                KeepAliveSecs                = 10,
                WaitTimeoutSecs              = 2,
                MaximumQualityOfService      = MqttQualityOfService.AtMostOnce,
                AllowWildcardsInTopicFilters = true,
                AllowLocationSubscription    = true
            };

            var broker = MqttServer.Create(mqttOptions, authenticationProvider: RedisAuthenticationProvider.Instance);

            /** use constructor with Create( MqttConfiguration configuration, IMqttServerBinding binding = null, IMqttAuthenticationProvider authenticationProvider = null) */
            try
            {
                broker.Start();
                Console.WriteLine("Press CTRL + C exit.");
                while (true)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                mqttServer = new MqttServer( );
                mqttServer.OnClientApplicationMessageReceive += MqttServer_OnClientApplicationMessageReceive;
                mqttServer.OnClientConnected += MqttServer_OnClientConnected;
                if (checkBox1.Checked)
                {
                    mqttServer.ClientVerification += MqttServer_ClientVerification;
                }

                mqttServer.ServerStart(int.Parse(textBox2.Text));
                mqttServer.LogNet = new HslCommunication.LogNet.LogNetSingle("");
                mqttServer.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
                button1.Enabled = false;
                button2.Enabled = true;
                panel2.Enabled  = true;
                MessageBox.Show("Start Success");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Start Failed : " + ex.Message);
            }
        }
Exemplo n.º 4
0
 public static async Task PublishAsync(this MqttServer mqtt, string SenderClientId, string topic, string _payload)
 {
     await mqtt.PublishAsync(SenderClientId, new MqttApplicationMessage()
     {
         Topic = topic, Payload = System.Text.Encoding.Default.GetBytes(_payload)
     });
 }
Exemplo n.º 5
0
 public static async Task PublishAsync(this MqttServer mqtt, string SenderClientId, string topic, byte[] _payload)
 {
     await mqtt.PublishAsync(SenderClientId, new MqttApplicationMessage()
     {
         Topic = topic, Payload = _payload
     });
 }
Exemplo n.º 6
0
 public static async Task PublishAsync <T>(this MqttServer mqtt, string SenderClientId, string topic, T _payload) where T : class
 {
     await mqtt.PublishAsync(SenderClientId, new MqttApplicationMessage()
     {
         Topic = topic, Payload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(_payload)
     });
 }
Exemplo n.º 7
0
        public RootController()
        {
            var service = ServiceLocator.Instance.GetService(typeof(MqttServer));

            Messager = (MqttServer)service;
            //typeof(MqttServer).IsInstanceOfType(server);
        }
Exemplo n.º 8
0
        public void Setup()
        {
            var factory   = new MqttFactory();
            var tcpServer = new MqttTcpServerAdapter();

            tcpServer.ClientHandler += args =>
            {
                _serverChannel =
                    (IMqttChannel)args.GetType().GetField("_channel",
                                                          System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
                    .GetValue(args);

                return(Task.CompletedTask);
            };

            var serverOptions = new MqttServerOptionsBuilder().Build();

            _mqttServer = factory.CreateMqttServer(serverOptions, new[] { tcpServer }, new MqttNetEventLogger());


            _mqttServer.StartAsync().GetAwaiter().GetResult();

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

            var tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions;

            _clientChannel = new MqttTcpChannel(new MqttClientOptions {
                ChannelOptions = tcpOptions
            });

            _clientChannel.ConnectAsync(CancellationToken.None).GetAwaiter().GetResult();
        }
Exemplo n.º 9
0
        public static async Task   PublishAsync(this MqttServer mqtt, string SenderClientId, MqttApplicationMessage message)
        {
            var clients = await mqtt.GetClientsAsync();

            var client = clients.FirstOrDefault(c => c.Id == SenderClientId);
            await client.Session.EnqueueApplicationMessageAsync(message);
        }
Exemplo n.º 10
0
        public async Task <ReuquestResult> StopServer()
        {
            if (mqttServer == null)
            {
                return new ReuquestResult {
                           Code = 404, Successful = false
                }
            }
            ;
            try
            {
                await mqttServer.StopAsync();

                mqttServer = null;
                LMLogs.NLog.Logger.Log(LMLogs.LogLevel.Exception, "MqttService", $"停止服务成功");
                return(new ReuquestResult {
                    Successful = true
                });
            }
            catch (Exception ex)
            {
                LMLogs.NLog.Logger.Log(LMLogs.LogLevel.Exception, "MqttService", $"停止服务异常:{ex.Message}");
                return(new ReuquestResult {
                    Successful = false, Code = 500
                });
            }
        }
    }
Exemplo n.º 11
0
        public DeviceMessageBrokerService(ILogService logService)
        {
            if (logService == null)
            {
                throw new ArgumentNullException(nameof(logService));
            }

            _log = logService.CreatePublisher(nameof(DeviceMessageBrokerService));

            var channelA = new MqttCommunicationAdapter();

            _clientCommunicationAdapter         = new MqttCommunicationAdapter();
            channelA.Partner                    = _clientCommunicationAdapter;
            _clientCommunicationAdapter.Partner = channelA;

            var mqttClientOptions = new MqttClientOptions {
                ClientId = "HA4IoT.Loopback"
            };

            _client = new MqttClient(mqttClientOptions, channelA);
            _client.ApplicationMessageReceived += ProcessIncomingMessage;

            var mqttServerOptions = new MqttServerOptions();

            _server = new MqttServerFactory().CreateMqttServer(mqttServerOptions);
            _server.ClientConnected += (s, e) => _log.Info($"MQTT client '{e.Identifier}' connected.");
        }
Exemplo n.º 12
0
        private async Task TestPublishAsync(
            string topic,
            MqttQualityOfServiceLevel qualityOfServiceLevel,
            string topicFilter,
            MqttQualityOfServiceLevel filterQualityOfServiceLevel,
            int expectedReceivedMessagesCount)
        {
            var s = new MqttServer(new MqttServerOptions(), new List <IMqttServerAdapter> {
                new TestMqttServerAdapter()
            });

            s.Start();

            var c1 = ConnectTestClient("c1", null, s);
            var c2 = ConnectTestClient("c2", null, s);

            var receivedMessagesCount = 0;

            c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;

            await c1.SubscribeAsync(new TopicFilter(topicFilter, filterQualityOfServiceLevel));

            await c2.PublishAsync(new MqttApplicationMessage(topic, new byte[0], qualityOfServiceLevel, false));

            await Task.Delay(500);

            await c1.Unsubscribe(topicFilter);

            await Task.Delay(500);

            s.Stop();

            Assert.AreEqual(expectedReceivedMessagesCount, receivedMessagesCount);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                siemens = new SiemensS7Net(SiemensPLCS.S1200, "127.0.0.1");
                siemens.SetPersistentConnection( );

                mqttServer = new MqttServer( );
                mqttServer.OnClientApplicationMessageReceive += MqttServer_OnClientApplicationMessageReceive;
                mqttServer.OnClientConnected += MqttServer_OnClientConnected;
                if (checkBox1.Checked)
                {
                    mqttServer.ClientVerification += MqttServer_ClientVerification;
                }

                mqttServer.RegisterMqttRpcApi("Account", this);
                mqttServer.RegisterMqttRpcApi("Siemens", siemens);                                 // 注册一个西门子PLC的服务接口的示例
                mqttServer.RegisterMqttRpcApi("TimeOut", typeof(HslTimeOut));                      // 注册的类的静态方法和静态属性
                mqttServer.RegisterMqttRpcApi("Fanuc", new HslCommunication.CNC.Fanuc.FanucSeries0i("127.0.0.1"));
                mqttServer.ServerStart(int.Parse(textBox2.Text));
                mqttServer.LogNet = new HslCommunication.LogNet.LogNetSingle("");
                mqttServer.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
                mqttServer.RegisterMqttRpcApi("Log", mqttServer.LogNet);
                button1.Enabled = false;
                button2.Enabled = true;
                panel2.Enabled  = true;
                MessageBox.Show("Start Success");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Start Failed : " + ex.Message);
            }
        }
Exemplo n.º 14
0
        public async void Start()
        {
            var configuration = new MqttConfiguration
            {
                BufferSize                   = 128 * 1024,
                Port                         = 55555,
                KeepAliveSecs                = 10,
                WaitTimeoutSecs              = 2,
                MaximumQualityOfService      = MqttQualityOfService.AtMostOnce,
                AllowWildcardsInTopicFilters = true,
            };
            //var     = await MqttClient.CreateAsync("192.168.1.10", configuration);

            IMqttServer mqttServer = MqttServer.Create(configuration);

            mqttServer.ClientConnected    += MqttServer_ClientConnected;
            mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
            mqttServer.MessageUndelivered += MqttServer_MessageUndelivered;
            mqttServer.Start();


            client = await mqttServer.CreateClientAsync();

            // client.PublishAsync();


            Console.WriteLine("Hello World!");
        }
Exemplo n.º 15
0
        public void Setup()
        {
            TopicGenerator.Generate(NumPublishers, NumTopicsPerPublisher, out var topicsByPublisher, out var singleWildcardTopicsByPublisher, out var multiWildcardTopicsByPublisher);
            _topics = topicsByPublisher.Values.First();

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

            var factory = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(serverOptions);
            _mqttClient = factory.CreateMqttClient();

            _mqttServer.StartAsync().GetAwaiter().GetResult();

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

            _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult();

            foreach (var topic in _topics)
            {
                var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
                                       .WithTopicFilter(topic)
                                       .Build();
                _mqttClient.SubscribeAsync(subscribeOptions).GetAwaiter().GetResult();
            }
        }
Exemplo n.º 16
0
 public void MqttServerInitialization( )
 {
     mqttServer = new MqttServer( );
     mqttServer.OnClientApplicationMessageReceive += MqttServer_OnClientApplicationMessageReceive;
     mqttServer.OnClientConnected += MqttServer_OnClientConnected;
     mqttServer.ServerStart(1883);
 }
 public string Post([FromBody] dynamic data, string deviceId)
 {
     data.name       = "";
     data.macAddress = "";
     MqttServer.processMqttMessage(data, deviceId);
     return("success");
 }
Exemplo n.º 18
0
            protected override void StopWork(String reason)
            {
                _Server.TryDispose();
                _Server = null;

                base.StopWork(reason);
            }
        public async Task InitializeAsync()
        {
            var factory = new MqttFactory();

            MqttServer  = factory.CreateMqttServer();
            MqttClient1 = factory.CreateMqttClient();
            MqttClient2 = factory.CreateMqttClient();
            MqttClient1.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Client1MessageReceived?.Invoke(this, args));
            MqttClient2.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Client2MessageReceived?.Invoke(this, args));

            var brokerIpAddress = IPAddress.Loopback;
            var brokerPort      = 1885;

            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithClientId("broker")
                                    .WithDefaultEndpointBoundIPAddress(brokerIpAddress)
                                    .WithDefaultEndpointPort(brokerPort)
                                    .Build();
            var mqttClient1Options = new MqttClientOptionsBuilder()
                                     .WithClientId("client1")
                                     .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                     .Build();
            var mqttClient2Options = new MqttClientOptionsBuilder()
                                     .WithClientId("client2")
                                     .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                     .Build();

            await MqttServer.StartAsync(mqttServerOptions).ConfigureAwait(false);

            var connectClient1Result = await MqttClient1.ConnectAsync(mqttClient1Options).ConfigureAwait(false);

            var connectClient2Result = await MqttClient2.ConnectAsync(mqttClient2Options).ConfigureAwait(false);
        }
Exemplo n.º 20
0
        public async Task MqttServer_ClearRetainedMessage()
        {
            var serverAdapter = new TestMqttServerAdapter();
            var s             = new MqttServer(new MqttServerOptions(), new List <IMqttServerAdapter> {
                serverAdapter
            });
            await s.StartAsync();

            var c1 = await serverAdapter.ConnectTestClient(s, "c1");

            await c1.PublishAsync(new MqttApplicationMessage("retained", new byte[3], MqttQualityOfServiceLevel.AtLeastOnce, true));

            await c1.PublishAsync(new MqttApplicationMessage("retained", new byte[0], MqttQualityOfServiceLevel.AtLeastOnce, true));

            await c1.DisconnectAsync();

            var c2 = await serverAdapter.ConnectTestClient(s, "c2");

            var receivedMessagesCount = 0;

            c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
            await c2.SubscribeAsync(new TopicFilter("retained", MqttQualityOfServiceLevel.AtLeastOnce));

            await Task.Delay(500);

            await s.StopAsync();

            Assert.AreEqual(0, receivedMessagesCount);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            Debug.WriteLine("Configuring Server...");

            var stopSignal = new ManualResetEventSlim();
            var config     = new MqttConfiguration
            {
                Port = port,
                MaximumQualityOfService      = MqttQualityOfService.AtLeastOnce,
                AllowWildcardsInTopicFilters = true,
                WaitTimeoutSecs = 10,
                KeepAliveSecs   = 15
            };
            var server = MqttServer.Create(config);

            Debug.WriteLine("Starting Server...");

            server.Stopped += (sender, e) =>
            {
                Debug.WriteLine("Server stopped. Finishing app...");
                stopSignal.Set();
            };
            server.ClientConnected    += (sender, e) => Debug.WriteLine($"New player connected: {e}");
            server.ClientDisconnected += (sender, e) => Debug.WriteLine($"Player disconnected: {e}");

            server.Start();

            Debug.WriteLine("Server started...");
            Debug.WriteLine("Listening for new players...");

            stopSignal.Wait();
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            SiemensS7Net plc = new SiemensS7Net(SiemensPLCS.S1200, "127.0.0.1"); // 此处拿了本地虚拟的PLC测试

            plc.SetPersistentConnection( );                                      // 设置了长连接

            MqttServer mqttServer = new MqttServer( );

            mqttServer.RegisterMqttRpcApi("MainPLC", plc);
            mqttServer.ServerStart(1883);

            while (true)
            {
                Thread.Sleep(1000);                   // 每秒读取一次
                OperateResult <short> read = plc.ReadInt16("M100");
                if (read.IsSuccess)
                {
                    // 读取成功后,进行业务处理,存入数据库,或是其他的分析
                    Console.WriteLine("读取成功,M100:" + read.Content);
                }
                else
                {
                    // 读取失败之后,显示下状态
                    Console.WriteLine("读取PLC失败,原因:" + read.Message);
                }
            }
        }
Exemplo n.º 23
0
        public async Task MqttServer_WillMessage()
        {
            var s = new MqttServer(new MqttServerOptions(), new List <IMqttServerAdapter> {
                new TestMqttServerAdapter()
            });

            s.Start();

            var willMessage = new MqttApplicationMessage("My/last/will", new byte[0], MqttQualityOfServiceLevel.AtMostOnce, false);
            var c1          = ConnectTestClient("c1", null, s);
            var c2          = ConnectTestClient("c2", willMessage, s);

            var receivedMessagesCount = 0;

            c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
            await c1.SubscribeAsync(new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce));

            await c2.DisconnectAsync();

            await Task.Delay(1000);

            s.Stop();

            Assert.AreEqual(1, receivedMessagesCount);
        }
Exemplo n.º 24
0
 protected void Application_Start()
 {
     MqttServer.ConfigureAndStart();
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
Exemplo n.º 25
0
 public CheckDevices(ILogger <CheckDevices> logger, IServiceScopeFactory scopeFactor, MqttServer serverEx
                     , IOptions <AppSettings> options)
 {
     _mcsetting   = options.Value.MqttClient;
     _logger      = logger;
     _scopeFactor = scopeFactor;
     _serverEx    = serverEx;
 }
 public LightPointsMenager(ISettings settings)
 {
     _settings = settings;
     // _logger = new Logger.Logger("HomeAutomationLocalServer");
     _mqttServer    = new MqttServer();
     _restClient    = new RestClient(_settings.HomeAutomationLightingSystemApi);
     _signalRClient = new SignalRClient();
 }
        /// <summary>
        /// Returns true if OgcDataStreamInfo instances are equal
        /// </summary>
        /// <param name="other">Instance of OgcDataStreamInfo to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(OgcDataStreamInfo other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     DataStreamId == other.DataStreamId ||
                     DataStreamId != null &&
                     DataStreamId.Equals(other.DataStreamId)
                     ) &&
                 (
                     MqttTopic == other.MqttTopic ||
                     MqttTopic != null &&
                     MqttTopic.Equals(other.MqttTopic)
                 ) &&
                 (
                     MqttServer == other.MqttServer ||
                     MqttServer != null &&
                     MqttServer.Equals(other.MqttServer)
                 ) &&
                 (
                     ExternalId == other.ExternalId ||
                     ExternalId != null &&
                     ExternalId.Equals(other.ExternalId)
                 ) &&
                 (
                     Metadata == other.Metadata ||
                     Metadata != null &&
                     Metadata.Equals(other.Metadata)
                 ) &&
                 (
                     SensorType == other.SensorType ||
                     SensorType != null &&
                     SensorType.Equals(other.SensorType)
                 ) &&
                 (
                     UnitOfMeasurement == other.UnitOfMeasurement ||
                     UnitOfMeasurement != null &&
                     UnitOfMeasurement.Equals(other.UnitOfMeasurement)
                 ) &&
                 (
                     fixedLatitude == other.fixedLatitude ||
                     fixedLatitude != null &&
                     fixedLatitude.Equals(other.fixedLatitude)
                 ) && (
                     fixedLongitude == other.fixedLongitude ||
                     fixedLongitude != null &&
                     fixedLongitude.Equals(other.fixedLongitude)
                     ));
        }
Exemplo n.º 28
0
 public Form()
 {
     InitializeComponent();
     Server = new MqttServer();
     Server.attach(this);
     StartServer();
     Client = new MqttClient();
     Control.CheckForIllegalCrossThreadCalls = false;
 }
Exemplo n.º 29
0
        public static async void StartMqttServer(IHubContext <ChartDataHub> hub)
        {
            _hub = hub;

            if (mqttServer == null)
            {
                string hostIP   = "127.0.0.1";
                int    hostPort = 1883;
                int    timeOut  = 120;
                string userName = "******";
                string password = "******";

                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithDefaultEndpoint()
                                     .WithDefaultEndpointPort(hostPort)
                                     .WithDefaultCommunicationTimeout(new TimeSpan(0, 0, timeOut))
                                     .WithConnectionValidator(
                    c =>
                {
                    if (c.Username != userName)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }

                    if (c.Password != password)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }

                    c.ReasonCode = MqttConnectReasonCode.Success;
                }).WithSubscriptionInterceptor(
                    c =>
                {
                    c.AcceptSubscription = true;
                }).WithApplicationMessageInterceptor(
                    c =>
                {
                    c.AcceptPublish = true;
                });

                mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
                mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(OnMqttServerStarted);
                mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(OnMqttServerStopped);

                mqttServer.ClientConnectedHandler            = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
                mqttServer.ClientDisconnectedHandler         = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
                mqttServer.ClientSubscribedTopicHandler      = new MqttServerClientSubscribedHandlerDelegate(OnMqttServerClientSubscribedTopic);
                mqttServer.ClientUnsubscribedTopicHandler    = new MqttServerClientUnsubscribedTopicHandlerDelegate(OnMqttServerClientUnsubscribedTopic);
                mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMqttServer_ApplicationMessageReceived);


                await mqttServer.StartAsync(optionsBuilder.Build());
            }
        }
Exemplo n.º 30
0
        //static void Main(string[] args)
        //{
        //    //MqttNetTrace.TraceMessagePublished += MqttNetTrace_TraceMessagePublished;
        //    new Thread(StartMqttServer).Start();

        //    while (true)
        //    {
        //        var inputString = Console.ReadLine().ToLower().Trim();

        //        if (inputString == "exit")
        //        {
        //            mqttServer?.StopAsync();
        //            Console.WriteLine("MQTT服务异步停止...");
        //            break;
        //        }
        //        else if (inputString == "clients")
        //        {
        //            foreach (var item in mqttServer.GetClientStatusAsync().Result)
        //            {
        //                Console.WriteLine($"客户端标识:{item.ClientId},协议版本:{item.ProtocolVersion}");
        //            }
        //        }
        //        else if (inputString == "publish")
        //        {
        //            Console.WriteLine("Please key in your topic:");
        //            string topic = Console.ReadLine();
        //            Console.WriteLine("Please key in your payload:");
        //            string payload = Console.ReadLine();
        //            PublishMqttTopic(topic, payload);
        //            Console.WriteLine($"主题消息[{topic}]发布成功!");
        //        }
        //        else
        //        {
        //            Console.WriteLine($"命令[{inputString}]无效!");
        //        }
        //    }
        //}

        public static async void StartMqttServer()
        {
            if (mqttServer == null)
            {
                var config         = ReadConfiguration();
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithDefaultEndpoint().WithDefaultEndpointPort(int.Parse(config["Port"].ToString())).WithConnectionValidator(
                    c =>
                {
                    var currentUser = config["Users"][0]["UserName"].ToString();
                    var currentPWD  = config["Users"][0]["Password"].ToString();

                    if (currentUser == null || currentPWD == null)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }

                    if (c.Username != currentUser)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }

                    if (c.Password != currentPWD)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }

                    c.ReasonCode = MqttConnectReasonCode.Success;
                }).WithSubscriptionInterceptor(
                    c =>
                {
                    c.AcceptSubscription = true;
                }).WithApplicationMessageInterceptor(
                    c =>
                {
                    c.AcceptPublish = true;
                });

                mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
                mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(OnMqttServerStarted);
                mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(OnMqttServerStopped);

                mqttServer.ClientConnectedHandler            = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
                mqttServer.ClientDisconnectedHandler         = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
                mqttServer.ClientSubscribedTopicHandler      = new MqttServerClientSubscribedHandlerDelegate(OnMqttServerClientSubscribedTopic);
                mqttServer.ClientUnsubscribedTopicHandler    = new MqttServerClientUnsubscribedTopicHandlerDelegate(OnMqttServerClientUnsubscribedTopic);
                mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMqttServer_ApplicationMessageReceived);


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