Пример #1
0
        private void btn_ServerStart_Click(object sender, EventArgs e)
        {
            IMqttServerOptions options = new MqttServerOptions()
            {
                ConnectionValidator = new MqttServerConnectionValidatorDelegate(ConnectEventAction),
            };

            server.StartAsync(options);
            if (server.IsStarted)
            {
                MessageBox.Show("Server Connect Success");
            }
            else
            {
                MessageBox.Show("Server Connect Fail");
            }
        }
Пример #2
0
        public void Start(MqttServerOptions options)
        {
            if (_socket != null)
            {
                throw new InvalidOperationException("Server is already started.");
            }

            _cancellationTokenSource = new CancellationTokenSource();

            _socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind(new IPEndPoint(IPAddress.Any, options.Port));
            _socket.Listen(options.ConnectionBacklog);

            Task.Run(async() => await AcceptConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);

            _x590Certificate2 = new X509Certificate2(options.CertificatePath);
        }
Пример #3
0
        /// <summary>
        /// The method that handles the button click to start the server.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private async void ButtonServerStartClick(object sender, EventArgs e)
        {
            if (this._mqttServer != null)
            {
                return;
            }

            var storage = new JsonServerStorage();

            storage.Clear();
            this._mqttServer = new MqttFactory().CreateMqttServer();
            var options = new MqttServerOptions();

            options.DefaultEndpointOptions.Port = int.Parse(this.TextBoxPort.Text);
            options.Storage = storage;
            options.EnablePersistentSessions = true;
            options.ConnectionValidator      = new MqttServerConnectionValidatorDelegate(
                c =>
            {
                if (c.Username != "username")
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

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

                c.ReasonCode = MqttConnectReasonCode.Success;
            });

            try
            {
                await this._mqttServer.StartAsync(options);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Occurs", MessageBoxButtons.OK, MessageBoxIcon.Error);
                await this._mqttServer.StopAsync();

                this._mqttServer = null;
            }
        }
Пример #4
0
        public async Task MqttServer_InterceptMessage()
        {
            void Interceptor(MqttApplicationMessageInterceptorContext context)
            {
                context.ApplicationMessage.Payload = Encoding.ASCII.GetBytes("extended");
            }

            var serverAdapter = new TestMqttServerAdapter();
            var s             = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());

            try
            {
                var options = new MqttServerOptions {
                    ApplicationMessageInterceptor = Interceptor
                };

                await s.StartAsync(options);

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

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

                await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("test").Build());

                var isIntercepted = false;
                c2.ApplicationMessageReceived += (sender, args) =>
                {
                    isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(args.ApplicationMessage.Payload), StringComparison.Ordinal) == 0;
                };

                var m = new MqttApplicationMessageBuilder().WithTopic("test").Build();
                await c1.PublishAsync(m);

                await c1.DisconnectAsync();

                await Task.Delay(500);

                Assert.IsTrue(isIntercepted);
            }
            finally
            {
                await s.StopAsync();
            }
        }
Пример #5
0
        private static void RunServerAsync(string[] arguments)
        {
            MqttTrace.TraceMessagePublished += (s, e) =>
            {
                Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
                if (e.Exception != null)
                {
                    Console.WriteLine(e.Exception);
                }
            };

            try
            {
                var options = new MqttServerOptions
                {
                    ConnectionValidator = p =>
                    {
                        if (p.ClientId == "SpecialClient")
                        {
                            if (p.Username != "USER" || p.Password != "PASS")
                            {
                                return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                            }
                        }

                        return(MqttConnectReturnCode.ConnectionAccepted);
                    }
                };

                var mqttServer = new MqttServerFactory().CreateMqttServer(options);
                mqttServer.Start();

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                mqttServer.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
Пример #6
0
        public MqttTcpServerListener(
            AddressFamily addressFamily,
            MqttServerOptions serverOptions,
            MqttServerTcpEndpointBaseOptions tcpEndpointOptions,
            X509Certificate2 tlsCertificate,
            IMqttNetLogger logger)
        {
            _addressFamily  = addressFamily;
            _serverOptions  = serverOptions ?? throw new ArgumentNullException(nameof(serverOptions));
            _options        = tcpEndpointOptions ?? throw new ArgumentNullException(nameof(tcpEndpointOptions));
            _tlsCertificate = tlsCertificate;
            _rootLogger     = logger;
            _logger         = logger.WithSource(nameof(MqttTcpServerListener));

            if (_options is MqttServerTlsTcpEndpointOptions tlsOptions)
            {
                _tlsOptions = tlsOptions;
            }
        }
Пример #7
0
        public void Start()
        {
            if (_broker != null)
            {
                throw new InvalidOperationException("Broker is already running");
            }

            _broker = new MqttFactory().CreateMqttServer();
            _broker.UseClientConnectedHandler(new MqttServerClientConnectedHandlerDelegate((args => Log.Debug($"Robot {args.ClientId} connected"))));
            _broker.UseClientDisconnectedHandler(new MqttServerClientDisconnectedHandlerDelegate((args => Log.Debug($"Robot {args.ClientId} disconnected"))));

            var options = new MqttServerOptions();

            options.DefaultEndpointOptions.Port = Port;

            Log.Information($"MQTTBroker: Starting on port {IPAddress}:{Port}");
            _broker.StartAsync(options).Wait();
            Log.Information("MQTTBroker: Started");
        }
        public Task StartAsync(MqttServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (_isRunning)
            {
                throw new InvalidOperationException("Server is already started.");
            }
            _isRunning = true;

            _cancellationTokenSource = new CancellationTokenSource();

            if (options.DefaultEndpointOptions.IsEnabled)
            {
                _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                _defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
                _defaultEndpointSocket.Listen(options.ConnectionBacklog);

                Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
            }

            if (options.TlsEndpointOptions.IsEnabled)
            {
                if (options.TlsEndpointOptions.Certificate == null)
                {
                    throw new ArgumentException("TLS certificate is not set.");
                }

                _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);

                _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                _tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
                _tlsEndpointSocket.Listen(options.ConnectionBacklog);

                Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
            }

            return(Task.FromResult(0));
        }
Пример #9
0
        private static void StartMqttServer()
        {
            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = c =>
                        {
                            //if (c.ClientId.Length < 10)
                            //{
                            //    c.ReturnCode= MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                            //}

                            if (c.Username != "admin" || c.Password != "123")
                            {
                                c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                            }
                            c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                        }
                    };

                    mqttServer = new MqttFactory().CreateMqttServer(new MqttNetLogger()) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected            += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected         += MqttServer_ClientDisconnected;
                    mqttServer.ClientSubscribedTopic      += MqttServer_ClientSubscribedTopic;
                    mqttServer.ClientUnsubscribedTopic    += MqttServer_ClientUnsubscribedTopic;

                    mqttServer.StartAsync(options).Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }


            Console.WriteLine("MQTT服务启动成功!");
        }
 private static IServiceCollection AddHostedMqttServerEx(this IServiceCollection services)
 {
     services.AddSingleton <MqttHostedServerEx>();
     services.AddSingleton <IHostedService>(s => s.GetService <MqttHostedServerEx>());
     services.AddTransient <IMqttNetLogger, MqttNetLogger>();
     services.AddSingleton <IMqttServerEx>(s =>
     {
         var mhse  = s.GetService <MqttHostedServerEx>();
         var store = s.GetService <IMqttServerStorage>();
         MqttServerOptions options   = (MqttServerOptions)mhse.Options;
         options.ConnectionValidator = mhse.ConnectionValidator;
         if (options.Storage == null)
         {
             options.Storage = store;
         }
         return(mhse);
     }
                                           );
     return(services);
 }
Пример #11
0
        private static void StartMQTTServer()
        {
            try
            {
                var mqttFactory = new MqttFactory();
                var server      = mqttFactory.CreateMqttServer();
                server.ApplicationMessageReceived += Server_ApplicationMessageReceived;
                server.ClientConnected            += Server_ClientConnected;
                server.ClientDisconnected         += Server_ClientDisconnected;
                var mqOptions = new MqttServerOptions();
                server.StartAsync(mqOptions);
                Console.WriteLine("服务成功开启");
                Console.ReadLine();
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 private static IServiceCollection AddHostedMqttServerEx(this IServiceCollection services)
 {
     var logger = new MqttNetLogger();
     var childLogger = logger.CreateChildLogger();
     services.AddSingleton<IMqttNetLogger>(logger);
     services.AddSingleton(childLogger);
     services.AddSingleton<MqttHostedServerEx>();
     services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServerEx>());
     services.AddSingleton<IMqttServerEx>(s =>
     {
         var mhse = s.GetService<MqttHostedServerEx>();
         var store = s.GetService<IMqttServerStorage>();
         MqttServerOptions options = (MqttServerOptions)mhse.Options;
         options.ConnectionValidator = mhse.ConnectionValidator;
         if (options.Storage == null) options.Storage = store;
         return mhse;
     }
     );
     return services;
 }
Пример #13
0
        public DeviceMessageBrokerService(ILogService logService, IScriptingService scriptingService)
        {
            if (scriptingService == null)
            {
                throw new ArgumentNullException(nameof(scriptingService));
            }
            _log = logService?.CreatePublisher(nameof(DeviceMessageBrokerService)) ?? throw new ArgumentNullException(nameof(logService));

            MqttTrace.TraceMessagePublished += (s, e) =>
            {
                if (e.Level == MqttTraceLevel.Warning)
                {
                    _log.Warning(e.Exception, e.Message);
                }
                else if (e.Level == MqttTraceLevel.Error)
                {
                    _log.Error(e.Exception, e.Message);
                }
            };

            var channelA = new MqttCommunicationAdapter();

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

            var mqttClientOptions = new MqttClientOptions {
                ClientId = "HA4IoT.Loopback", KeepAlivePeriod = TimeSpan.FromHours(1)
            };

            _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.");

            scriptingService.RegisterScriptProxy(s => new DeviceMessageBrokerScriptProxy(this, s));
        }
        private static void StartMqttServer()
        {
            //while (true)
            //{
            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            if (p.ClientId == "c001")
                            {
                                if (p.Username != "u001" || p.Password != "p001")
                                {
                                    return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                                }
                            }
                            return(MqttConnectReturnCode.ConnectionAccepted);
                        }
                    };
                    options.DefaultEndpointOptions.Port = int.Parse(ConfigurationManager.AppSettings.Get("MqttPort"));
                    mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;

                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected            += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected         += MqttServer_ClientDisconnected;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            mqttServer.StartAsync();
            Thread.Sleep(int.MaxValue);
            //Console.WriteLine("MQTT服务启动成功!");
            //}
        }
        static async System.Threading.Tasks.Task Main()
        {
            /*************************************************************
            *                    User Configuration                     *
            *************************************************************/
            var user     = "******";
            var password = "******";


            //  Setup client validator                       !!! chua ket hop option builder nay vo dc
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(99)
                                 .WithDefaultEndpointPort(1884);

            //  Setup client validator
            var options = new MqttServerOptions();

            options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
            {
                if (c.Username != user)
                {
                    c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                if (c.Password != password)
                {
                    c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionAccepted;
            });

            //  Start Server
            var mqttServer = new MqttFactory().CreateMqttServer();
            await mqttServer.StartAsync(options);

            Console.WriteLine("Server is running... \r\n\nPress Enter to exit.");
            Console.ReadLine();
            await mqttServer.StopAsync();
        }
Пример #16
0
        public void ServerStart()
        {
            mqttServer.StopAsync().Wait();
            MqttServerOptionsBuilder optionBuilder = new MqttServerOptionsBuilder()
                                                     .WithConnectionBacklog(1000)
                                                     .WithDefaultEndpointPort(ServerPort);
            MqttServerOptions option = optionBuilder.Build() as MqttServerOptions;

            option.EnablePersistentSessions    = true;
            option.MaxPendingMessagesPerClient = 1000;
            option.ConnectionValidator         = new MqttServerConnectionValidatorDelegate((MqttConnectionValidatorContext c) =>
            {
                if (c.Username == "test")
                {
                    c.ReasonCode = MqttConnectReasonCode.Success;
                }
                else
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }
            }
                                                                                           );
            mqttServer.StartAsync(option).Wait();
            ServerActive = true;
            //SManager.TextBoxAutoScrollPrintLine(txtReceiveMessage, "服务端已打开!");
            mqttServer.UseApplicationMessageReceivedHandler((MqttApplicationMessageReceivedEventArgs ee) =>
            {
                Invoke(new Action(() =>
                {
                    if (ServerOnHandleMessage != null)
                    {
                        ServerOnHandleMessage.Invoke(ee.ApplicationMessage.Topic, ee.ApplicationMessage.ConvertPayloadToString());
                    }
                    SManager.TextBoxAutoScrollPrintLine(txtReceiveMessage, "服务端收到消息:" + Encoding.UTF8.GetString(ee.ApplicationMessage.Payload));
                }));
            }
                                                            );
        }
Пример #17
0
        public static void StartMqttServer()
        {
            if (obj_mqttServer == null)//如果尚未创建mqtt服务器
            {
                try
                {
                    MqttServerOptions options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            if (p.ClientId == "c001")
                            {
                                if (p.Username != "u001" || p.Password != "p001")
                                {
                                    return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                                }
                            }

                            return(MqttConnectReturnCode.ConnectionAccepted);
                        }
                    };

                    obj_mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;   //采用MqttServerFactory对象的CreateMqttServer方法创建一个mqttServer 服务端
                    obj_mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived; //消息接收处理事件
                    obj_mqttServer.ClientConnected            += MqttServer_ClientConnected;            //客户端连接处理事件
                    obj_mqttServer.ClientDisconnected         += MqttServer_ClientDisconnected;         //客户端断开连接处理事件
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            obj_mqttServer.StartAsync();   //异步启动mqttServer
            Console.WriteLine("MQTT服务启动成功!");
            changeTxt("MQTT服务启动成功!");
        }
Пример #18
0
        public static void StartMqttServer()
        {
            DeviceContext devices = new DeviceContext();

            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            DeviceModel device = devices.Devices.SingleOrDefault(x => x.DeviceKey == p.Password);
                            if ((device.Name == p.Username) || (device.User == p.Username))
                            {
                                return(MqttConnectReturnCode.ConnectionAccepted);
                            }

                            return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                        }
                    };

                    mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected            += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected         += MqttServer_ClientDisconnected;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            mqttServer.StartAsync();
            Console.WriteLine("MQTT服务启动成功!");
        }
Пример #19
0
        private static void StartMqttServer()
        {
            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            //if (p.ClientId != "c001")
                            //{
                            //    if (p.Username != "u001" || p.Password != "p001")
                            //    {
                            //        return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                            //    }
                            //}

                            return(MqttConnectReturnCode.ConnectionAccepted);
                        }
                    };

                    mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected            += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected         += MqttServer_ClientDisconnected;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            mqttServer.StartAsync();
            Console.WriteLine("MQTT服务启动成功!");
        }
        public void TestMethod1()
        {
            var options = new MqttServerOptions
            {
                ConnectionValidator = c =>
                {
                    if (c.ClientId.Length < 10)
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                    }

                    if (c.Username != "xxx" || c.Password != "xxx")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                    }

                    return(MqttConnectReturnCode.ConnectionAccepted);
                }
            };

            var mqttServer = new MqttServerFactory().CreateMqttServer(options);

            mqttServer.StartAsync();
        }
Пример #21
0
        // This code is for the Wiki at GitHub!
        // ReSharper disable once UnusedMember.Local
        private async Task WikiCode()
        {
            {
                // Write all trace messages to the console window.
                MqttNetGlobalLog.LogMessagePublished += (s, e) =>
                {
                    Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
                    if (e.TraceMessage.Exception != null)
                    {
                        Console.WriteLine(e.TraceMessage.Exception);
                    }
                };
            }

            {
                // Use a custom identifier for the trace messages.
                var clientOptions = new MqttClientOptionsBuilder()
                                    .Build();
            }

            {
                // Create a new MQTT client.
                var factory    = new MqttFactory();
                var mqttClient = factory.CreateMqttClient();

                {
                    // Create TCP based options using the builder.
                    var options = new MqttClientOptionsBuilder()
                                  .WithClientId("Client1")
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithCredentials("bud", "%spencer%")
                                  .WithTls()
                                  .WithCleanSession()
                                  .Build();

                    await mqttClient.ConnectAsync(options);
                }

                {
                    // Use TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com", 1883) // Port is optional
                                  .Build();
                }

                {
                    // Use secure TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithTls()
                                  .Build();
                }

                {
                    // Use WebSocket connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                                  .Build();

                    await mqttClient.ConnectAsync(options);
                }

                {
                    // Create TCP based options manually
                    var options = new MqttClientOptions
                    {
                        ClientId    = "Client1",
                        Credentials = new MqttClientCredentials
                        {
                            Username = "******",
                            Password = "******"
                        },
                        ChannelOptions = new MqttClientTcpOptions
                        {
                            Server     = "broker.hivemq.org",
                            TlsOptions = new MqttClientTlsOptions
                            {
                                UseTls = true
                            }
                        },
                    };
                }

                {
                    // Subscribe to a topic
                    await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                    // Unsubscribe from a topic
                    await mqttClient.UnsubscribeAsync("my/topic");

                    // Publish an application message
                    var applicationMessage = new MqttApplicationMessageBuilder()
                                             .WithTopic("A/B/C")
                                             .WithPayload("Hello World")
                                             .WithAtLeastOnceQoS()
                                             .Build();

                    await mqttClient.PublishAsync(applicationMessage);
                }
            }

            // ----------------------------------
            {
                var options = new MqttServerOptions();

                options.ConnectionValidator = c =>
                {
                    if (c.ClientId.Length < 10)
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                    }

                    if (c.Username != "mySecretUser")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                    }

                    if (c.Password != "mySecretPassword")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                    }

                    return(MqttConnectReturnCode.ConnectionAccepted);
                };

                var factory    = new MqttFactory();
                var mqttServer = factory.CreateMqttServer();
                await mqttServer.StartAsync(options);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                await mqttServer.StopAsync();
            }

            // ----------------------------------

            // For UWP apps:
            MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
            {
                if (o.Server == "server_with_revoked_cert")
                {
                    return(new[] { ChainValidationResult.Revoked });
                }

                return(new ChainValidationResult[0]);
            };

            {
                // Start a MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(new MqttServerOptions());

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                await mqttServer.StopAsync();
            }

            {
                // Configure MQTT server.
                var options = new MqttServerOptions
                {
                    ConnectionBacklog = 100
                };

                options.DefaultEndpointOptions.Port = 1884;
                options.ConnectionValidator         = packet =>
                {
                    if (packet.ClientId != "Highlander")
                    {
                        return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                    }

                    return(MqttConnectReturnCode.ConnectionAccepted);
                };

                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(options);
            }

            {
                // Setup client validator.
                var options = new MqttServerOptions
                {
                    ConnectionValidator = c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                        }

                        if (c.Username != "mySecretUser")
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                        }

                        if (c.Password != "mySecretPassword")
                        {
                            return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
                        }

                        return(MqttConnectReturnCode.ConnectionAccepted);
                    }
                };
            }

            {
                // Create a new MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
            }

            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Client1")
                                                 .WithTcpServer("broker.hivemq.com")
                                                 .WithTls().Build())
                              .Build();

                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                await mqttClient.StartAsync(options);
            }
        }
Пример #22
0
        public Press()
        {
            Thickness marginer = new Thickness();

            marginer.Bottom = marginer.Left = marginer.Right = marginer.Top = 2;
            Thickness Tmarginer = new Thickness();

            Tmarginer.Left = Tmarginer.Right = 32;
            Tmarginer.Top  = Tmarginer.Bottom = 17;
            _mqttServer    = new MqttFactory().CreateMqttServer();
            var options = new MqttServerOptions();

            options.DefaultEndpointOptions.Port = 1883;
            Starter(options);

            this.InitializeComponent();
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
            for (int i = 0; i < 40; i++)
            {
                Texter[i] = new TextBlock
                {
                    Text   = (i + 1).ToString(),
                    Margin = Tmarginer,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Foreground          = new SolidColorBrush(Windows.UI.Colors.Indigo),
                    VerticalAlignment   = VerticalAlignment.Center,
                    FontWeight          = Windows.UI.Text.FontWeights.Bold,
                    FontSize            = 16
                };
                Liner[i] = new Rectangle
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Height            = 50,
                    VerticalAlignment = VerticalAlignment.Center,
                    Width             = 78,
                    Fill   = new SolidColorBrush(Windows.UI.Colors.LightSteelBlue),
                    Margin = marginer
                };
                Liner[i].Fill.Opacity = .67;
                if (i < 8)
                {
                    Line1.Children.Add(Liner[i]);
                    Line1Text.Children.Add(Texter[i]);
                }
                else if (i < 12)
                {
                    Line2.Children.Add(Liner[i]);
                    Line2Text.Children.Add(Texter[i]);
                }
                else if (i == 12)
                {
                    Line2A.Children.Add(Liner[i]);
                    Line2AText.Children.Add(Texter[i]);
                }
                else if (i < 21)
                {
                    Line3.Children.Add(Liner[i]);
                    Line3Text.Children.Add(Texter[i]);
                }
                else if (i < 25)
                {
                    Line4.Children.Add(Liner[i]);
                    Line4Text.Children.Add(Texter[i]);
                }
                else if (i < 29)
                {
                    Line5.Children.Add(Liner[i]);
                    Line5Text.Children.Add(Texter[i]);
                }
                else if (i == 29)
                {
                    Line5A.Children.Add(Liner[i]);
                    Line5AText.Children.Add(Texter[i]);
                }
                else if (i == 30)
                {
                    Line5B.Children.Add(Liner[i]);
                    Line5BText.Children.Add(Texter[i]);
                }
                else if (i < 35)
                {
                    Line6.Children.Add(Liner[i]);
                    Line6Text.Children.Add(Texter[i]);
                }
                else if (i == 35)
                {
                    Line6B.Children.Add(Liner[i]);
                    Line6BText.Children.Add(Texter[i]);
                }
                else
                {
                    Line7.Children.Add(Liner[i]);
                    Line7Text.Children.Add(Texter[i]);
                }
                //< Rectangle x: Name = "p1" HorizontalAlignment = "Center" Height = "78" VerticalAlignment = "Center" Width = "78" Fill = "#FFDFC6C6" Margin = "1,1,1,1" />
            }
        }
Пример #23
0
        public async void Starter(MqttServerOptions options)
        {
            EasClientDeviceInformation CurrentDeviceInfor = new EasClientDeviceInformation();
            var machiner = CurrentDeviceInfor.FriendlyName;
            await _mqttServer.StartAsync(options);

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options2 = new MqttClientOptions {
                ClientId = ""
            };


            options2.ChannelOptions = new MqttClientTcpOptions
            {
                Server     = machiner,
                Port       = 1883,
                TlsOptions = tlsOptions
            };

            if (options2.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            /*options.Credentials = new MqttClientCredentials
             * {
             *  Username = User.Text,
             *  Password = Password.Text
             * };*/

            options2.CleanSession    = true;
            options2.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            try
            {
                if (_mqttClient != null)
                {
                    await _mqttClient.DisconnectAsync();

                    _mqttClient.ApplicationMessageReceived -= OnApplicationMessageReceived;
                }

                var factory = new MqttFactory();
                _mqttClient = factory.CreateMqttClient();
                _mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;

                await _mqttClient.ConnectAsync(options2);
            }
            catch (Exception exception)
            {
                //Trace.Text += exception + Environment.NewLine;
            }

            if (_mqttClient == null)
            {
                return;
            }
            var qos = MqttQualityOfServiceLevel.ExactlyOnce;
            await _mqttClient.SubscribeAsync(new TopicFilter("luxProto2", qos));
        }
 public Task StartAsync(MqttServerOptions options)
 {
     return(Task.CompletedTask);
 }
Пример #25
0
#pragma warning disable IDE0051 // Remove unused private members
        private async Task WikiCode()
#pragma warning restore IDE0051 // Remove unused private members
        {
            {
                // Use a custom identifier for the trace messages.
                var clientOptions = new MqttClientOptionsBuilder()
                                    .Build();
            }

            {
                // Create a new MQTT client.
                var factory = new MqttFactory();
                var client  = factory.CreateMqttClient();

                // Create TCP based options using the builder.
                var options = new MqttClientOptionsBuilder()
                              .WithClientId("Client1")
                              .WithTcpServer("broker.hivemq.com")
                              .WithCredentials("bud", "%spencer%")
                              .WithTls()
                              .WithCleanSession()
                              .Build();

                await client.ConnectAsync(options);

                // Reconnecting

                client.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    try
                    {
                        await client.ConnectAsync(options);
                    }
                    catch
                    {
                        Console.WriteLine("### RECONNECTING FAILED ###");
                    }
                });

                // Consuming messages

                client.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                    Console.WriteLine();
                });

                void Handler(MqttApplicationMessageReceivedEventArgs args)
                {
                    //...
                }

                client.UseApplicationMessageReceivedHandler(e => Handler(e));

                // Subscribe after connect

                client.UseConnectedHandler(async e =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");

                    // Subscribe to a topic
                    await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                    Console.WriteLine("### SUBSCRIBED ###");
                });

                // Subscribe to a topic
                await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                // Unsubscribe from a topic
                await client.UnsubscribeAsync("my/topic");

                // Publish an application message
                var applicationMessage = new MqttApplicationMessageBuilder()
                                         .WithTopic("A/B/C")
                                         .WithPayload("Hello World")
                                         .WithAtLeastOnceQoS()
                                         .Build();

                await client.PublishAsync(applicationMessage);
            }

            {
                {
                    // Use TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com", 1883) // Port is optional
                                  .Build();
                }

                {
                    // Use secure TCP connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer("broker.hivemq.com")
                                  .WithTls()
                                  .Build();
                }

                {
                    // Use WebSocket connection.
                    var options = new MqttClientOptionsBuilder()
                                  .WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                                  .Build();
                }

                {
                    // Create TCP based options manually
                    var options = new MqttClientOptions
                    {
                        ClientId    = "Client1",
                        Credentials = new MqttClientCredentials
                        {
                            Username = "******",
                            Password = Encoding.UTF8.GetBytes("%spencer%")
                        },
                        ChannelOptions = new MqttClientTcpOptions
                        {
                            Server     = "broker.hivemq.org",
                            TlsOptions = new MqttClientTlsOptions
                            {
                                UseTls = true
                            }
                        },
                    };
                }
            }

            // ----------------------------------
            {
                var options = new MqttServerOptions
                {
                    ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                            return;
                        }

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

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

                        c.ReasonCode = MqttConnectReasonCode.Success;
                    })
                };

                var factory    = new MqttFactory();
                var mqttServer = factory.CreateMqttServer();
                await mqttServer.StartAsync(options);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                await mqttServer.StopAsync();
            }

            // ----------------------------------

            // For UWP apps:
            MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
            {
                if (o.Server == "server_with_revoked_cert")
                {
                    return(new[] { ChainValidationResult.Revoked });
                }

                return(Array.Empty <ChainValidationResult>());
            };

            {
                // Start a MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
                await mqttServer.StartAsync(new MqttServerOptions());

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                await mqttServer.StopAsync();
            }

            {
                // Configure MQTT server.
                var optionsBuilder = new MqttServerOptionsBuilder()
                                     .WithConnectionBacklog(100)
                                     .WithDefaultEndpointPort(1884);

                var options = new MqttServerOptions
                {
                };

                options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                {
                    if (c.ClientId != "Highlander")
                    {
                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                        return;
                    }

                    c.ReasonCode = MqttConnectReasonCode.Success;
                });

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

            {
                // Setup client validator.
                var options = new MqttServerOptions
                {
                    ConnectionValidator = new MqttServerConnectionValidatorDelegate(c =>
                    {
                        if (c.ClientId.Length < 10)
                        {
                            c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                            return;
                        }

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

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

                        c.ReasonCode = MqttConnectReasonCode.Success;
                    })
                };
            }

            {
                // Create a new MQTT server.
                var mqttServer = new MqttFactory().CreateMqttServer();
            }

            {
                // Setup application message interceptor.
                var options = new MqttServerOptionsBuilder()
                              .WithApplicationMessageInterceptor(context =>
                {
                    if (context.ApplicationMessage.Topic == "my/custom/topic")
                    {
                        context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes("The server injected payload.");
                    }

                    // It is also possible to read the payload and extend it. For example by adding a timestamp in a JSON document.
                    // This is useful when the IoT device has no own clock and the creation time of the message might be important.
                })
                              .Build();
            }

            {
                // Setup subscription interceptor.
                var options = new MqttServerOptionsBuilder()
                              .WithSubscriptionInterceptor(context =>
                {
                    if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
                    {
                        context.AcceptSubscription = false;
                    }

                    if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
                    {
                        context.AcceptSubscription = false;
                        context.CloseConnection    = true;
                    }
                })
                              .Build();
            }

            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Client1")
                                                 .WithTcpServer("broker.hivemq.com")
                                                 .WithTls().Build())
                              .Build();

                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());

                await mqttClient.StartAsync(options);
            }

            {
                // Use a custom log ID for the logger.
                var factory = new MqttFactory();
                var client  = factory.CreateMqttClient(new MqttNetLogger("MyCustomId"));
            }

            {
                var client = new MqttFactory().CreateMqttClient();

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic("MyTopic")
                              .WithPayload("Hello World")
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                await client.PublishAsync(message);
            }

            {
                // Write all trace messages to the console window.
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.LogMessage.Timestamp:O}] [{e.LogMessage.ThreadId}] [{e.LogMessage.Source}] [{e.LogMessage.Level}]: {e.LogMessage.Message}";
                    if (e.LogMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.LogMessage.Exception.ToString();
                    }

                    Console.WriteLine(trace);
                };
            }
        }
 public Task StartAsync(MqttServerOptions options)
 {
     return(Task.FromResult(0));
 }
Пример #27
0
        public Task StartAsync(MqttServerOptions options, IMqttNetLogger logger)
        {
            _serverOptions = options;

            return(Task.CompletedTask);
        }
Пример #28
0
        public static async Task RunAsync()
        {
            try
            {
                var options = new MqttServerOptions
                {
                    ConnectionValidator = new MqttServerConnectionValidatorDelegate(p =>
                    {
                        if (p.ClientId == "SpecialClient")
                        {
                            if (p.Username != "USER" || p.Password != "PASS")
                            {
                                p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                            }
                        }
                    }),

                    Storage = new RetainedMessageHandler(),

                    ApplicationMessageInterceptor = new MqttServerApplicationMessageInterceptorDelegate(context =>
                    {
                        if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
                        {
                            // Replace the payload with the timestamp. But also extending a JSON
                            // based payload with the timestamp is a suitable use case.
                            context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
                        }

                        if (context.ApplicationMessage.Topic == "not_allowed_topic")
                        {
                            context.AcceptPublish   = false;
                            context.CloseConnection = true;
                        }
                    }),

                    SubscriptionInterceptor = new MqttServerSubscriptionInterceptorDelegate(context =>
                    {
                        if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
                        {
                            context.AcceptSubscription = false;
                        }

                        if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
                        {
                            context.AcceptSubscription = false;
                            context.CloseConnection    = true;
                        }
                    })
                };

                // Extend the timestamp for all messages from clients.
                // Protect several topics from being subscribed from every client.

                //var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
                //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
                //options.ConnectionBacklog = 5;
                //options.DefaultEndpointOptions.IsEnabled = true;
                //options.TlsEndpointOptions.IsEnabled = false;

                var mqttServer = new MqttFactory().CreateMqttServer();

                mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
                {
                    MqttNetConsoleLogger.PrintToConsole(
                        $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'",
                        ConsoleColor.Magenta);
                });

                //options.ApplicationMessageInterceptor = c =>
                //{
                //    if (c.ApplicationMessage.Payload == null || c.ApplicationMessage.Payload.Length == 0)
                //    {
                //        return;
                //    }

                //    try
                //    {
                //        var content = JObject.Parse(Encoding.UTF8.GetString(c.ApplicationMessage.Payload));
                //        var timestampProperty = content.Property("timestamp");
                //        if (timestampProperty != null && timestampProperty.Value.Type == JTokenType.Null)
                //        {
                //            timestampProperty.Value = DateTime.Now.ToString("O");
                //            c.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(content.ToString());
                //        }
                //    }
                //    catch (Exception)
                //    {
                //    }
                //};

                mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
                {
                    Console.Write("Client disconnected event fired.");
                });

                await mqttServer.StartAsync(options);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();

                await mqttServer.StopAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
Пример #29
0
        public static void AddAutomaticaCoreService(this IServiceCollection services, IConfiguration configuration, bool isElectronActive)
        {
            services.AddAutomaticaDrivers();
            services.AddDispatcher();

            services.AddSingleton <ILocalizationProvider>(new LocalizationProvider(SystemLogger.Instance));

            services.AddSingleton <IVisualisationFactory, VisuTempInit>();
            services.AddSingleton <ITelegramMonitor, TelegramMonitor>();
            services.AddSingleton <IServerCloudApi, CloudApi>();
            services.AddSingleton <ICloudApi, CloudApi>();
            services.AddSingleton <ILicenseContext, AllowAllLicenseContext>();
            services.AddSingleton <ILicenseContract>(provider => provider.GetService <ILicenseContext>());
            services.AddSingleton <ILearnMode, LearnMode>();
            services.AddAutomaticaPushServices(configuration, isElectronActive);

            services.AddSingleton <IPluginInstaller, PluginInstaller>();

            if (!isElectronActive)
            {
                services.AddSingleton <IDriverNodesStoreInternal, DriverNodesStoreInternal>();
                services.AddSingleton <INodeInstanceStore, NodeInstanceStore>();
                services.AddSingleton <ILogicInstancesStore, LogicInstanceStore>();

                services.AddSingleton <LogicStore, LogicStore>();
                services.AddSingleton <ILogicStore>(a => a.GetService <LogicStore>());
                services.AddSingleton <IRuleDataHandler>(a => a.GetService <LogicStore>());

                services.AddSingleton <LoadedNodeInstancesStore, LoadedNodeInstancesStore>();
                services.AddSingleton <INodeInstanceStateHandler>(a => a.GetService <LoadedNodeInstancesStore>());
                services.AddSingleton <ILoadedNodeInstancesStore>(a => a.GetService <LoadedNodeInstancesStore>());

                services.AddSingleton <NativeUpdateHandler, NativeUpdateHandler>();
                services.AddSingleton <IUpdateHandler>(a => a.GetService <NativeUpdateHandler>());
                services.AddSingleton <IAutoUpdateHandler>(a => a.GetService <NativeUpdateHandler>());

                services.AddSingleton <ILoadedStore, LoadedStore>();
                services.AddSingleton <ILogicFactoryStore, LogicFactoryStore>();
                services.AddSingleton <IDriverFactoryStore, DriverFactoryStore>();

                services.AddSingleton <IDriverLoader, DriverLoader>();
                services.AddSingleton <ILogicLoader, LogicLoader>();

                services.AddSingleton <MqttService, MqttService>();
                services.AddSingleton <IRemoteHandler>(provider => provider.GetService <MqttService>());
                services.AddSingleton <IRemoteServerHandler>(provider => provider.GetService <MqttService>());
                services.AddSingleton <IRemoteSender, MqttPublishService>();


                services.AddSingleton <PluginHandler, PluginHandler>();
                services.AddSingleton <IPluginHandler>(a => a.GetService <PluginHandler>());
                services.AddSingleton <IPluginLoader>(a => a.GetService <PluginHandler>());

                services.AddSingleton <IRuleInstanceVisuNotify, RuleInstanceVisuNotifier>();

                services.AddSingleton <CoreServer, CoreServer>();
                services.AddSingleton <IHostedService>(provider => provider.GetService <CoreServer>());
                services.AddSingleton <ICoreServer>(provider => provider.GetService <CoreServer>());

                services.AddSingleton <INotifyDriver, NotifyDriverHandler>();
                services.AddSingleton <IRuleEngineDispatcher, RuleEngineDispatcher>();

                services.AddSingleton <IDataBroadcast, DataBroadcastService>();

                services.AddSingleton <DatabaseTrendingValueStore, DatabaseTrendingValueStore>();
            }


            var mqttServerOptions = new MqttServerOptions()
            {
                ConnectionValidator = new MqttServerConnectionValidatorDelegate(a => MqttService.ValidateConnection(a, configuration, SystemLogger.Instance))
            };

            mqttServerOptions.DefaultEndpointOptions.BoundInterNetworkAddress   = IPAddress.Any;
            mqttServerOptions.DefaultEndpointOptions.BoundInterNetworkV6Address = IPAddress.None;
            mqttServerOptions.DefaultEndpointOptions.IsEnabled         = true;
            mqttServerOptions.DefaultEndpointOptions.Port              = 1883;
            mqttServerOptions.DefaultEndpointOptions.ConnectionBacklog = 1000;

            services.AddHostedMqttServer(mqttServerOptions);

            services.AddAutomaticaVisualization(configuration);
            services.AddInternals(configuration);
        }
Пример #30
0
        public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, MqttServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            services.AddSingleton(options);
            services.AddSingleton <IMqttNetLogger>(new MqttNetLogger());
            services.AddSingleton <MqttHostedServer>();
            services.AddSingleton <IHostedService>(s => s.GetService <MqttHostedServer>());
            services.AddSingleton <IMqttServer>(s => s.GetService <MqttHostedServer>());

            services.AddSingleton <MqttWebSocketServerAdapter>();
            services.AddSingleton <IMqttServerAdapter>(s => s.GetService <MqttWebSocketServerAdapter>());

            return(services);
        }