Пример #1
0
        void ReadMqttSettings(IServiceCollection services)
        {
            var mqttSettings = new MqttSettingsModel();

            Configuration.Bind("MQTT", mqttSettings);
            services.AddSingleton(mqttSettings);
        }
Пример #2
0
        private static void ReadSettings(IConfiguration configuration, IServiceCollection services)
        {
            var mqttSettings = new MqttSettingsModel();

            configuration.Bind("MQTT", mqttSettings);
            services.AddSingleton(mqttSettings);
        }
Пример #3
0
        public MqttServerService(
            MqttSettingsModel mqttSettings,
            CustomMqttFactory mqttFactory,
            MqttClientConnectedHandler mqttClientConnectedHandler,
            MqttClientDisconnectedHandler mqttClientDisconnectedHandler,
            MqttClientSubscribedTopicHandler mqttClientSubscribedTopicHandler,
            MqttClientUnsubscribedTopicHandler mqttClientUnsubscribedTopicHandler,
            MqttServerConnectionValidator mqttConnectionValidator,
            MqttApplicationMessageReceivedHandler messageHandler,
            MqttApplicationMessageInterceptor messageInterceptor,
            MqttServerStorage mqttServerStorage,
            ILogger <MqttServerService> logger
            )
        {
            this._settings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
            this._mqttClientConnectedHandler         = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
            this._mqttClientDisconnectedHandler      = mqttClientDisconnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientDisconnectedHandler));
            this._mqttClientSubscribedTopicHandler   = mqttClientSubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientSubscribedTopicHandler));
            this._mqttClientUnsubscribedTopicHandler = mqttClientUnsubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientUnsubscribedTopicHandler));
            this._messageHandler          = messageHandler ?? throw new ArgumentNullException(nameof(messageHandler));
            this._mqttConnectionValidator = mqttConnectionValidator ?? throw new ArgumentNullException(nameof(mqttConnectionValidator));
            this._messageInterceptor      = messageInterceptor ?? throw new ArgumentNullException(nameof(messageInterceptor));
            this._mqttServerStorage       = mqttServerStorage ?? throw new ArgumentNullException(nameof(mqttServerStorage));
            this._logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _mqttServer = mqttFactory.CreateMqttServer();
        }
Пример #4
0
        public CustomMqttFactory(MqttSettingsModel settings, ILogger <MqttServer> logger)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            // It is important to avoid injecting the logger wrapper to ensure that no
            // unused log messages are generated by the MQTTnet library. Debug logging
            // has a huge performance impact.
            if (settings.EnableDebugLogging)
            {
                var mqttNetLogger = new MqttNetLoggerWrapper(logger);
                _mqttFactory = new MqttFactory(mqttNetLogger);

                logger.LogWarning("Debug logging is enabled. Performance of MQTTnet Server is decreased!");
            }
            else
            {
                _mqttFactory = new MqttFactory();
            }

            Logger = _mqttFactory.DefaultLogger;
        }
Пример #5
0
        static void ConfigureWebSocketEndpoint(
            IApplicationBuilder application,
            MqttServerService mqttServerService,
            MqttSettingsModel mqttSettings)
        {
            if (mqttSettings?.WebSocketEndPoint?.Enabled != true)
            {
                return;
            }

            if (string.IsNullOrEmpty(mqttSettings.WebSocketEndPoint.Path))
            {
                return;
            }

            var webSocketOptions = new WebSocketOptions
            {
                KeepAliveInterval = TimeSpan.FromSeconds(mqttSettings.WebSocketEndPoint.KeepAliveInterval),
                ReceiveBufferSize = mqttSettings.WebSocketEndPoint.ReceiveBufferSize
            };

            if (mqttSettings.WebSocketEndPoint.AllowedOrigins?.Any() == true)
            {
                webSocketOptions.AllowedOrigins.AddRange(mqttSettings.WebSocketEndPoint.AllowedOrigins);
            }

            application.UseWebSockets(webSocketOptions);

            application.Use(async(context, next) =>
            {
                if (context.Request.Path == mqttSettings.WebSocketEndPoint.Path)
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        string subProtocol = null;
                        if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
                        {
                            subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues);
                        }

                        using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false))
                        {
                            await mqttServerService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                }
                else
                {
                    await next().ConfigureAwait(false);
                }
            });
        }
Пример #6
0
        private void ReadMqttSettings(IServiceCollection services)
        {
            var mqttSettings = new MqttSettingsModel();

            Configuration.Bind("MQTT", mqttSettings);
            services.AddSingleton(mqttSettings);

            var scriptingSettings = new ScriptingSettingsModel();

            Configuration.Bind("Scripting", scriptingSettings);
            services.AddSingleton(scriptingSettings);
        }
Пример #7
0
        public void Configure(
            IApplicationBuilder application,
            IHostingEnvironment environment,
            MqttServerService mqttServerService,
            PythonScriptHostService pythonScriptHostService,
            DataSharingService dataSharingService,
            MqttSettingsModel mqttSettings)
        {
            if (environment.IsDevelopment())
            {
                application.UseDeveloperExceptionPage();
            }
            else
            {
                application.UseHsts();
            }

            application.UseCors(x => x
                                .AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .AllowCredentials());

            application.UseAuthentication();

            application.UseStaticFiles();

            application.UseHttpsRedirection();
            application.UseMvc();

            ConfigureWebSocketEndpoint(application, mqttServerService, mqttSettings);

            dataSharingService.Configure();
            pythonScriptHostService.Configure();

            mqttServerService.Configure();

            application.UseSwagger(o => o.RouteTemplate = "/api/{documentName}/swagger.json");

            application.UseSwaggerUI(o =>
            {
                o.RoutePrefix   = "api";
                o.DocumentTitle = "MQTTnet.Server API";
                o.SwaggerEndpoint("/api/v1/swagger.json", "MQTTnet.Server API v1");
                o.DisplayRequestDuration();
                o.DocExpansion(DocExpansion.List);
                o.DefaultModelRendering(ModelRendering.Model);
            });
        }
Пример #8
0
        public MqttClientService(
            Lazy <IMessageSession> eventBusSession,
            ILogger <MqttClient> logger,
            MqttSettingsModel settings,
            CustomMqttFactory mqttFactory,
            MqttClientConnectedHandler mqttClientConnectedHandler,
            MqttApplicationMessageReceivedHandler mqttApplicationMessageReceivedHandler)
        {
            this._eventBusSession                       = eventBusSession;
            this._logger                                = logger ?? throw new ArgumentNullException(nameof(logger));
            this._settings                              = settings ?? throw new ArgumentNullException(nameof(settings));
            this._mqttFactory                           = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
            this._mqttClientConnectedHandler            = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
            this._mqttApplicationMessageReceivedHandler = mqttApplicationMessageReceivedHandler ?? throw new ArgumentNullException(nameof(mqttApplicationMessageReceivedHandler));

            // Create a new MQTT client.
            _mqttClient = _mqttFactory.CreateMqttClient();
        }
Пример #9
0
        public void Configure(
            IApplicationBuilder application,
            MqttServerService mqttServerService,
            PythonScriptHostService pythonScriptHostService,
            DataSharingService dataSharingService,
            MqttSettingsModel mqttSettings)
        {
            application.UseDefaultFiles();
            application.UseStaticFiles();

            application.UseHsts();
            application.UseRouting();
            application.UseCors(x => x
                                .AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowAnyHeader());

            application.UseAuthentication();
            application.UseAuthorization();

            application.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            ConfigureWebSocketEndpoint(application, mqttServerService, mqttSettings);

            dataSharingService.Configure();
            pythonScriptHostService.Configure();

            mqttServerService.Configure();

            application.UseSwagger(o => o.RouteTemplate = "/api/{documentName}/swagger.json");

            application.UseSwaggerUI(o =>
            {
                o.RoutePrefix   = "api";
                o.DocumentTitle = "MQTTnet.Server API";
                o.SwaggerEndpoint("/api/v1/swagger.json", "MQTTnet.Server API v1");
                o.DisplayRequestDuration();
                o.DocExpansion(DocExpansion.List);
                o.DefaultModelRendering(ModelRendering.Model);
            });
        }
Пример #10
0
        public void Configure(
            IApplicationBuilder application,
            MqttServerService mqttServerService,
            MqttSettingsModel mqttSettings)
        {
            application.UseDefaultFiles();
            application.UseStaticFiles();
            application.UseHsts();

            application.UseCors(x => x
                                .AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowAnyHeader());

            application.UseAuthentication();

            ConfigureWebSocketEndpoint(application, mqttServerService, mqttSettings);

            mqttServerService.Configure();
        }
Пример #11
0
        public MqttServerService(
            MqttSettingsModel mqttSettings,
            CustomMqttFactory mqttFactory,
            MqttClientConnectedHandler mqttClientConnectedHandler,
            MqttClientDisconnectedHandler mqttClientDisconnectedHandler,
            MqttClientSubscribedTopicHandler mqttClientSubscribedTopicHandler,
            MqttClientUnsubscribedTopicHandler mqttClientUnsubscribedTopicHandler,
            MqttServerConnectionValidator mqttConnectionValidator,
            MqttSubscriptionInterceptor mqttSubscriptionInterceptor,
            MqttUnsubscriptionInterceptor mqttUnsubscriptionInterceptor,
            MqttApplicationMessageInterceptor mqttApplicationMessageInterceptor,
            MqttServerStorage mqttServerStorage,
            PythonScriptHostService pythonScriptHostService,
            ILogger <MqttServerService> logger)
        {
            _settings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
            _mqttClientConnectedHandler         = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
            _mqttClientDisconnectedHandler      = mqttClientDisconnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientDisconnectedHandler));
            _mqttClientSubscribedTopicHandler   = mqttClientSubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientSubscribedTopicHandler));
            _mqttClientUnsubscribedTopicHandler = mqttClientUnsubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientUnsubscribedTopicHandler));
            _mqttConnectionValidator            = mqttConnectionValidator ?? throw new ArgumentNullException(nameof(mqttConnectionValidator));
            _mqttSubscriptionInterceptor        = mqttSubscriptionInterceptor ?? throw new ArgumentNullException(nameof(mqttSubscriptionInterceptor));
            _mqttUnsubscriptionInterceptor      = mqttUnsubscriptionInterceptor ?? throw new ArgumentNullException(nameof(mqttUnsubscriptionInterceptor));
            _mqttApplicationMessageInterceptor  = mqttApplicationMessageInterceptor ?? throw new ArgumentNullException(nameof(mqttApplicationMessageInterceptor));
            _mqttServerStorage       = mqttServerStorage ?? throw new ArgumentNullException(nameof(mqttServerStorage));
            _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _webSocketServerAdapter = new MqttWebSocketServerAdapter(mqttFactory.Logger);

            var adapters = new List <IMqttServerAdapter>
            {
                new MqttTcpServerAdapter(mqttFactory.Logger)
                {
                    TreatSocketOpeningErrorAsWarning = true // Opening other ports than for HTTP is not allows in Azure App Services.
                },
                _webSocketServerAdapter
            };

            _mqttServer = mqttFactory.CreateMqttServer(adapters);
        }
Пример #12
0
        public MqttServerService(
            MqttSettingsModel mqttSettings,
            MqttClientConnectedHandler mqttClientConnectedHandler,
            MqttClientDisconnectedHandler mqttClientDisconnectedHandler,
            MqttClientSubscribedTopicHandler mqttClientSubscribedTopicHandler,
            MqttClientUnsubscribedTopicHandler mqttClientUnsubscribedTopicHandler,
            MqttServerConnectionValidator mqttConnectionValidator,
            MqttSubscriptionInterceptor mqttSubscriptionInterceptor,
            MqttUnsubscriptionInterceptor mqttUnsubscriptionInterceptor,
            MqttApplicationMessageInterceptor mqttApplicationMessageInterceptor,
            ILogger <MqttServerService> logger)
        {
            _settings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
            _mqttClientConnectedHandler         = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
            _mqttClientDisconnectedHandler      = mqttClientDisconnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientDisconnectedHandler));
            _mqttClientSubscribedTopicHandler   = mqttClientSubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientSubscribedTopicHandler));
            _mqttClientUnsubscribedTopicHandler = mqttClientUnsubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientUnsubscribedTopicHandler));
            _mqttConnectionValidator            = mqttConnectionValidator ?? throw new ArgumentNullException(nameof(mqttConnectionValidator));
            _mqttSubscriptionInterceptor        = mqttSubscriptionInterceptor ?? throw new ArgumentNullException(nameof(mqttSubscriptionInterceptor));
            _mqttUnsubscriptionInterceptor      = mqttUnsubscriptionInterceptor ?? throw new ArgumentNullException(nameof(mqttUnsubscriptionInterceptor));
            _mqttApplicationMessageInterceptor  = mqttApplicationMessageInterceptor ?? throw new ArgumentNullException(nameof(mqttApplicationMessageInterceptor));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            var mqttFactory = new MqttFactory();

            _webSocketServerAdapter = new MqttWebSocketServerAdapter(mqttFactory.DefaultLogger);
            var adapters = new List <IMqttServerAdapter>
            {
                new MqttTcpServerAdapter(mqttFactory.DefaultLogger)
                {
                    TreatSocketOpeningErrorAsWarning = true
                },
                _webSocketServerAdapter
            };

            _mqttServer = mqttFactory.CreateMqttServer(adapters);

            // Make this object available to message interceptor class avoiding
            // circular references created when using dependency injection.
            _mqttApplicationMessageInterceptor.SetServerService(this);
        }
Пример #13
0
        public MqttSettingsModel XMLReader()
        {
            MqttSettingsModel mqtt = new MqttSettingsModel();

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(Directory.GetCurrentDirectory() + "\\Config.xml");

            XmlElement xRoot = xmldoc.DocumentElement;

            foreach (XmlNode xnode in xRoot)
            {
                foreach (XmlNode fchildnode in xRoot.ChildNodes)
                {
                    if (fchildnode.Name == "MqttConnectSettings")
                    {
                        foreach (XmlNode childnode in fchildnode.ChildNodes)
                        {
                            if (childnode.Name == "hostName")
                            {
                                mqtt.HostName = childnode.InnerText;
                            }
                            if (childnode.Name == "port")
                            {
                                mqtt.Port = childnode.InnerText;
                            }
                            if (childnode.Name == "topic")
                            {
                                mqtt.Topic = childnode.InnerText;
                            }
                        }
                    }
                }
            }
            return(mqtt);
        }
Пример #14
0
 /// <summary>
 /// Conncet to server Mqtt for this param.
 /// (host = broker.hivemq.com, port = 1883, topic = exz/lora, qosLevel = 2).
 /// </summary>
 public void MqttConnect(MqttSettingsModel settings)
 {
     try
     {
         this.client = new MqttClient(settings.HostName);
         byte code = this.client.Connect(Guid.NewGuid().ToString());
         if (client.IsConnected)
         {
             Console.WriteLine("Connected to Mqtt: \n"); //BLEKFIEFF exz/lora
             Console.WriteLine("Connected to DB:  \n");
             ushort msgId = this.client.Subscribe(new string[] { settings.Topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
             this.client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(pubMessage.EventPublished);
         }
         else
         {
             Console.WriteLine("Cannot connect to Mqtt. Reload.");
             this.client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error :" + ex.Message);
     }
 }
Пример #15
0
        public MqttServerService(
            MqttSettingsModel mqttSettings,
            CustomMqttFactory mqttFactory,
            MqttClientConnectedHandler mqttClientConnectedHandler,
            MqttClientDisconnectedHandler mqttClientDisconnectedHandler,
            MqttClientSubscribedTopicHandler mqttClientSubscribedTopicHandler,
            MqttClientUnsubscribedTopicHandler mqttClientUnsubscribedTopicHandler,
            MqttServerConnectionValidator mqttConnectionValidator,
            MqttSubscriptionInterceptor mqttSubscriptionInterceptor,
            MqttApplicationMessageInterceptor mqttApplicationMessageInterceptor,
            MqttServerStorage mqttServerStorage,
            PythonScriptHostService pythonScriptHostService,
            ILogger <MqttServerService> logger)
        {
            _settings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
            _mqttClientConnectedHandler         = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
            _mqttClientDisconnectedHandler      = mqttClientDisconnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientDisconnectedHandler));
            _mqttClientSubscribedTopicHandler   = mqttClientSubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientSubscribedTopicHandler));
            _mqttClientUnsubscribedTopicHandler = mqttClientUnsubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientUnsubscribedTopicHandler));
            _mqttConnectionValidator            = mqttConnectionValidator ?? throw new ArgumentNullException(nameof(mqttConnectionValidator));
            _mqttSubscriptionInterceptor        = mqttSubscriptionInterceptor ?? throw new ArgumentNullException(nameof(mqttSubscriptionInterceptor));
            _mqttApplicationMessageInterceptor  = mqttApplicationMessageInterceptor ?? throw new ArgumentNullException(nameof(mqttApplicationMessageInterceptor));
            _mqttServerStorage       = mqttServerStorage ?? throw new ArgumentNullException(nameof(mqttServerStorage));
            _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _webSocketServerAdapter = new MqttWebSocketServerAdapter(mqttFactory.Logger.CreateChildLogger());

            var adapters = new List <IMqttServerAdapter>
            {
                new MqttTcpServerAdapter(mqttFactory.Logger.CreateChildLogger()),
                _webSocketServerAdapter
            };

            _mqttServer = mqttFactory.CreateMqttServer(adapters);
        }
Пример #16
0
 public MqttServerStorage(MqttSettingsModel mqttSettings, ILogger <MqttServerStorage> logger)
 {
     _mqttSettings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
     _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Пример #17
0
 public MqttServerConnectionValidator(MqttSettingsModel settings, ILogger <MqttServerConnectionValidator> logger)
 {
     this._settings = settings ?? throw new ArgumentNullException(nameof(settings));
     this._logger   = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Пример #18
0
 public MqttServerConnectionValidator(MqttSettingsModel mqttSettingsModel, ILogger <MqttServerConnectionValidator> logger)
 {
     _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     _mqttSettingsModel = mqttSettingsModel ?? throw new ArgumentNullException(nameof(logger));
 }