You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

222 lines
7.7 KiB

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