Startup.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. using Microsoft.AspNetCore.Authentication;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Net.Http.Headers;
  7. using Microsoft.OpenApi.Models;
  8. using Microsoft.Scripting.Utils;
  9. using MQTTnet.Server.Configuration;
  10. using MQTTnet.Server.Logging;
  11. using MQTTnet.Server.Mqtt;
  12. using MQTTnet.Server.Scripting;
  13. using MQTTnet.Server.Scripting.DataSharing;
  14. using Newtonsoft.Json.Converters;
  15. using Swashbuckle.AspNetCore.SwaggerUI;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Net;
  20. using MQTTnet.AspNetCore;
  21. namespace MQTTnet.Server.Web
  22. {
  23. public class Startup
  24. {
  25. public Startup(IConfiguration configuration)
  26. {
  27. var builder = new ConfigurationBuilder()
  28. .AddJsonFile("appsettings.json")
  29. .AddEnvironmentVariables();
  30. Configuration = builder.Build();
  31. }
  32. public IConfigurationRoot Configuration { get; }
  33. public void Configure(
  34. IApplicationBuilder application,
  35. MqttServerService mqttServerService,
  36. PythonScriptHostService pythonScriptHostService,
  37. DataSharingService dataSharingService,
  38. MqttSettingsModel mqttSettings)
  39. {
  40. application.UseHsts();
  41. application.UseRouting();
  42. application.UseCors(x => x
  43. .AllowAnyOrigin()
  44. .AllowAnyMethod()
  45. .AllowAnyHeader());
  46. application.UseAuthentication();
  47. application.UseAuthorization();
  48. application.UseStaticFiles();
  49. application.UseEndpoints(endpoints =>
  50. {
  51. endpoints.MapControllers();
  52. });
  53. ConfigureWebSocketEndpoint(application, mqttServerService, mqttSettings);
  54. dataSharingService.Configure();
  55. pythonScriptHostService.Configure();
  56. mqttServerService.Configure();
  57. application.UseSwagger(o => o.RouteTemplate = "/api/{documentName}/swagger.json");
  58. application.UseSwaggerUI(o =>
  59. {
  60. o.RoutePrefix = "api";
  61. o.DocumentTitle = "MQTTnet.Server API";
  62. o.SwaggerEndpoint("/api/v1/swagger.json", "MQTTnet.Server API v1");
  63. o.DisplayRequestDuration();
  64. o.DocExpansion(DocExpansion.List);
  65. o.DefaultModelRendering(ModelRendering.Model);
  66. });
  67. }
  68. public void ConfigureServices(IServiceCollection services)
  69. {
  70. services.AddCors();
  71. services.AddControllers();
  72. services.AddMvc()
  73. .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
  74. .AddNewtonsoftJson(o =>
  75. {
  76. o.SerializerSettings.Converters.Add(new StringEnumConverter());
  77. });
  78. ReadMqttSettings(services);
  79. services.AddSingleton<PythonIOStream>();
  80. services.AddSingleton<PythonScriptHostService>();
  81. services.AddSingleton<DataSharingService>();
  82. services.AddSingleton<MqttNetLoggerWrapper>();
  83. services.AddSingleton<CustomMqttFactory>();
  84. services.AddSingleton<MqttServerService>();
  85. services.AddSingleton<MqttServerStorage>();
  86. services.AddSingleton<MqttClientConnectedHandler>();
  87. services.AddSingleton<MqttClientDisconnectedHandler>();
  88. services.AddSingleton<MqttClientSubscribedTopicHandler>();
  89. services.AddSingleton<MqttClientUnsubscribedTopicHandler>();
  90. services.AddSingleton<MqttServerConnectionValidator>();
  91. services.AddSingleton<MqttSubscriptionInterceptor>();
  92. services.AddSingleton<MqttUnsubscriptionInterceptor>();
  93. services.AddSingleton<MqttApplicationMessageInterceptor>();
  94. services.AddSwaggerGen(c =>
  95. {
  96. var securityScheme = new OpenApiSecurityScheme
  97. {
  98. Scheme = "Basic",
  99. Name = HeaderNames.Authorization,
  100. Type = SecuritySchemeType.Http,
  101. In = ParameterLocation.Header
  102. };
  103. c.AddSecurityDefinition("Swagger", securityScheme);
  104. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  105. {
  106. [securityScheme] = new List<string>()
  107. });
  108. c.SwaggerDoc("v1", new OpenApiInfo
  109. {
  110. Title = "MQTTnet.Server API",
  111. Version = "v1",
  112. Description = "The public API for the MQTT broker MQTTnet.Server.",
  113. License = new OpenApiLicense
  114. {
  115. Name = "MIT",
  116. Url = new Uri("https://github.com/chkr1011/MQTTnet/blob/master/README.md")
  117. },
  118. Contact = new OpenApiContact
  119. {
  120. Name = "MQTTnet.Server",
  121. Email = string.Empty,
  122. Url = new Uri("https://github.com/chkr1011/MQTTnet")
  123. },
  124. });
  125. });
  126. services.AddAuthentication("Basic")
  127. .AddScheme<AuthenticationSchemeOptions, AuthenticationHandler>("Basic", null)
  128. .AddCookie();
  129. }
  130. void ReadMqttSettings(IServiceCollection services)
  131. {
  132. var mqttSettings = new MqttSettingsModel();
  133. Configuration.Bind("MQTT", mqttSettings);
  134. services.AddSingleton(mqttSettings);
  135. var scriptingSettings = new ScriptingSettingsModel();
  136. Configuration.Bind("Scripting", scriptingSettings);
  137. services.AddSingleton(scriptingSettings);
  138. }
  139. static void ConfigureWebSocketEndpoint(
  140. IApplicationBuilder application,
  141. MqttServerService mqttServerService,
  142. MqttSettingsModel mqttSettings)
  143. {
  144. if (mqttSettings?.WebSocketEndPoint?.Enabled != true)
  145. {
  146. return;
  147. }
  148. if (string.IsNullOrEmpty(mqttSettings.WebSocketEndPoint.Path))
  149. {
  150. return;
  151. }
  152. var webSocketOptions = new WebSocketOptions
  153. {
  154. KeepAliveInterval = TimeSpan.FromSeconds(mqttSettings.WebSocketEndPoint.KeepAliveInterval),
  155. ReceiveBufferSize = mqttSettings.WebSocketEndPoint.ReceiveBufferSize
  156. };
  157. if (mqttSettings.WebSocketEndPoint.AllowedOrigins?.Any() == true)
  158. {
  159. webSocketOptions.AllowedOrigins.AddRange(mqttSettings.WebSocketEndPoint.AllowedOrigins);
  160. }
  161. application.UseWebSockets(webSocketOptions);
  162. application.Use(async (context, next) =>
  163. {
  164. if (context.Request.Path == mqttSettings.WebSocketEndPoint.Path)
  165. {
  166. if (context.WebSockets.IsWebSocketRequest)
  167. {
  168. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false))
  169. {
  170. await mqttServerService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false);
  171. }
  172. }
  173. else
  174. {
  175. context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
  176. }
  177. }
  178. else
  179. {
  180. await next().ConfigureAwait(false);
  181. }
  182. });
  183. }
  184. }
  185. }