提交 015ed47f 编写于 作者: 麦壳饼's avatar 麦壳饼

修正和内置mqtt客户端相关的配置问题

上级 f4230c7f
...@@ -21,17 +21,17 @@ namespace IoTSharp ...@@ -21,17 +21,17 @@ namespace IoTSharp
/// mqtt client settings /// mqtt client settings
/// </summary> /// </summary>
public MqttClientSetting MqttClient { get; set; } public MqttClientSetting MqttClient { get; set; }
public string JwtAudience { get; set; }
} }
public class MqttClientSetting public class MqttClientSetting
{ {
/// <summary> /// <summary>
/// built-in or IP、HostName /// built-in or IP、HostName
/// </summary> /// </summary>
public string MqttBroker { get; set; } = "built-in"; public string MqttBroker { get; set; }
public string UserName { get; set; } = ""; public string UserName { get; set; }
public string Password { get; set; } = ""; public string Password { get; set; }
public int Port { get; set; } = 1883; public int Port { get; set; }
} }
public class MqttBrokerSetting public class MqttBrokerSetting
{ {
...@@ -40,6 +40,6 @@ namespace IoTSharp ...@@ -40,6 +40,6 @@ namespace IoTSharp
public bool EnableTls { get; set; } = false; public bool EnableTls { get; set; } = false;
public string Certificate { get; set; } public string Certificate { get; set; }
public SslProtocols SslProtocol { get; set; } = SslProtocols.None; public SslProtocols SslProtocol { get; set; } = SslProtocols.None;
public bool PersistRetainedMessages { get; internal set; } public bool PersistRetainedMessages { get; set; }
} }
} }
...@@ -24,13 +24,12 @@ namespace IoTSharp ...@@ -24,13 +24,12 @@ namespace IoTSharp
public static class MqttExtension public static class MqttExtension
{ {
//static private IMqttServer _mqttServer; //static private IMqttServer _mqttServer;
public static void AddIoTSharpMqttServer(this IServiceCollection services, MqttBrokerSetting setting) public static void AddIoTSharpMqttServer(this IServiceCollection services, MqttBrokerSetting broker)
{ {
services.AddMqttTcpServerAdapter(); services.AddMqttTcpServerAdapter();
services.AddHostedMqttServerEx(options => services.AddHostedMqttServerEx(options =>
{ {
var broker = setting;
if (broker == null) broker = new MqttBrokerSetting();
options.WithDefaultEndpointPort(broker.Port).WithDefaultEndpoint(); options.WithDefaultEndpointPort(broker.Port).WithDefaultEndpoint();
if (broker.EnableTls) if (broker.EnableTls)
{ {
...@@ -102,10 +101,10 @@ namespace IoTSharp ...@@ -102,10 +101,10 @@ namespace IoTSharp
public static void AddMqttClient(this IServiceCollection services, MqttClientSetting setting) public static void AddMqttClient(this IServiceCollection services, MqttClientSetting setting)
{ {
if (setting == null) setting = new MqttClientSetting();
services.AddSingleton(options => new MQTTnet.MqttFactory().CreateMqttClient()); services.AddSingleton(options => new MQTTnet.MqttFactory().CreateMqttClient());
services.AddTransient(options => new MqttClientOptionsBuilder() services.AddTransient(options => new MqttClientOptionsBuilder()
.WithClientId("buind-in") .WithClientId(setting.MqttBroker)
.WithTcpServer((setting.MqttBroker == "built-in" || string.IsNullOrEmpty(setting.MqttBroker)) ? "127.0.0.1" : setting.MqttBroker, setting.Port) .WithTcpServer((setting.MqttBroker == "built-in" || string.IsNullOrEmpty(setting.MqttBroker)) ? "127.0.0.1" : setting.MqttBroker, setting.Port)
.WithCredentials(setting.UserName, setting.Password) .WithCredentials(setting.UserName, setting.Password)
.WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500) .WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500)
......
...@@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore; ...@@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet; using MQTTnet;
using MQTTnet.AspNetCoreEx; using MQTTnet.AspNetCoreEx;
using MQTTnet.Server; using MQTTnet.Server;
...@@ -27,13 +28,16 @@ namespace IoTSharp.Handlers ...@@ -27,13 +28,16 @@ namespace IoTSharp.Handlers
readonly ILogger<MQTTServerHandler> _logger; readonly ILogger<MQTTServerHandler> _logger;
readonly ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
readonly IMqttServerEx _serverEx; readonly IMqttServerEx _serverEx;
readonly IServiceScope scope;
readonly MqttClientSetting _mcsetting;
public MQTTServerHandler(ILogger<MQTTServerHandler> logger, IServiceScopeFactory scopeFactor,IMqttServerEx serverEx, DiagnosticsService diagnosticsService, public MQTTServerHandler(ILogger<MQTTServerHandler> logger, IServiceScopeFactory scopeFactor,IMqttServerEx serverEx, DiagnosticsService diagnosticsService,
RuntimeStatusHandler systemStatusService RuntimeStatusHandler systemStatusService, IOptions <AppSettings> options
) )
{ {
_mcsetting = options.Value.MqttClient;
_logger = logger; _logger = logger;
_dbContext = scopeFactor.CreateScope().ServiceProvider.GetRequiredService<ApplicationDbContext>(); scope = scopeFactor.CreateScope();
_dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
_serverEx = serverEx; _serverEx = serverEx;
InboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.inbound_rate"); InboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.inbound_rate");
OutboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.outbound_rate"); OutboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.outbound_rate");
...@@ -337,32 +341,41 @@ namespace IoTSharp.Handlers ...@@ -337,32 +341,41 @@ namespace IoTSharp.Handlers
public static string MD5Sum(string text) => BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", ""); public static string MD5Sum(string text) => BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
internal void Server_ClientConnectionValidator(object sender, MqttServerClientConnectionValidatorEventArgs e) internal void Server_ClientConnectionValidator(object sender, MqttServerClientConnectionValidatorEventArgs e)
{ {
var _dbContextcv = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
MqttConnectionValidatorContext obj = e.Context; MqttConnectionValidatorContext obj = e.Context;
Uri uri = new Uri("mqtt://" + obj.Endpoint); Uri uri = new Uri("mqtt://" + obj.Endpoint);
_logger.LogInformation($"ClientId={obj.ClientId},Endpoint={obj.Endpoint},Username={obj.Username},Password={obj.Password},WillMessage={obj.WillMessage?.ConvertPayloadToString()}"); if (uri.IsLoopback && !string.IsNullOrEmpty(e.Context.ClientId) && e.Context.ClientId == _mcsetting.MqttBroker && !string.IsNullOrEmpty(e.Context.Username) && e.Context.Username == _mcsetting.UserName && e.Context.Password == _mcsetting.Password)
var mcr = _dbContext.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc => (mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username) {
|| (mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.Username && mc.IdentityValue == obj.Password)); obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionAccepted;
if (mcr != null) }
else
{ {
try _logger.LogInformation($"ClientId={obj.ClientId},Endpoint={obj.Endpoint},Username={obj.Username},Password={obj.Password},WillMessage={obj.WillMessage?.ConvertPayloadToString()}");
var mcr = _dbContextcv.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc =>
(mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username) ||
(mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.Username && mc.IdentityValue == obj.Password));
if (mcr != null)
{ {
var device = mcr.Device; try
if (!Devices.ContainsKey(e.Context.ClientId)) {
var device = mcr.Device;
if (!Devices.ContainsKey(e.Context.ClientId))
{
Devices.Add(e.Context.ClientId, device);
}
}
catch (Exception ex)
{ {
Devices.Add(e.Context.ClientId, device); _logger.LogError(ex, "ConnectionRefusedServerUnavailable {0}", ex.Message);
obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedServerUnavailable;
} }
} }
catch (Exception ex) else
{ {
_logger.LogError(ex, "ConnectionRefusedServerUnavailable {0}", ex.Message); obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedServerUnavailable; _logger.LogInformation($"Bad username or password {obj.Username},connection {obj.Endpoint} refused");
} }
} }
else
{
obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
_logger.LogInformation($"Bad username or password {obj.Username},connection {obj.Endpoint} refused");
}
} }
public List<string> GetTopicImportUids() public List<string> GetTopicImportUids()
......
...@@ -9,7 +9,7 @@ using Microsoft.AspNetCore; ...@@ -9,7 +9,7 @@ using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MQTTnet.AspNetCore;
namespace IoTSharp namespace IoTSharp
{ {
public class Program public class Program
......
...@@ -40,10 +40,15 @@ namespace IoTSharp ...@@ -40,10 +40,15 @@ namespace IoTSharp
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration)
{ {
Configuration = configuration; Configuration = configuration;
AppSettings = Configuration.Get<AppSettings>(); settings = Configuration.Get<AppSettings>();
if (settings.MqttBroker == null) settings.MqttBroker = new MqttBrokerSetting();
if (settings.MqttClient == null) settings.MqttClient = new MqttClientSetting();
if (string.IsNullOrEmpty(settings.MqttClient.MqttBroker)) settings.MqttClient.MqttBroker = "built-in";
if (string.IsNullOrEmpty(settings.MqttClient.Password)) settings.MqttClient.Password = Guid.NewGuid().ToString();
if (string.IsNullOrEmpty(settings.MqttClient.UserName)) settings.MqttClient.UserName = Guid.NewGuid().ToString();
if (settings.MqttClient.Port == 0) settings.MqttClient.Port = 1883;
} }
private AppSettings settings;
public AppSettings AppSettings { get; }
public IConfiguration Configuration { get; private set; } public IConfiguration Configuration { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
...@@ -62,11 +67,15 @@ namespace IoTSharp ...@@ -62,11 +67,15 @@ namespace IoTSharp
{ {
configuration.RootPath = "ClientApp/dist"; configuration.RootPath = "ClientApp/dist";
}); });
services.AddOptions();
services.Configure<AppSettings>(Configuration); services.Configure((Action<AppSettings>)(setting =>
{
Configuration.Bind(setting);
setting.MqttBroker = settings.MqttBroker;
setting.MqttClient = settings.MqttClient;
}));
services.AddLogging(loggingBuilder => loggingBuilder.AddConsole()); services.AddLogging(loggingBuilder => loggingBuilder.AddConsole());
services.AddIoTSharpHub(Configuration); services.AddIoTSharpHub(Configuration);
// Enable the Gzip compression especially for Kestrel // Enable the Gzip compression especially for Kestrel
services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal); services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
...@@ -80,7 +89,7 @@ namespace IoTSharp ...@@ -80,7 +89,7 @@ namespace IoTSharp
.AddRoleManager<RoleManager<IdentityRole>>() .AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders() .AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>(); .AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureJwtAuthentication(Configuration["JwtIssuer"], Configuration["JwtAudience"], Configuration["JwtKey"], TimeSpan.FromDays(Convert.ToInt32(Configuration["JwtExpireDays"]))); services.ConfigureJwtAuthentication(settings.JwtIssuer , settings.JwtAudience, settings.JwtKey, TimeSpan.FromDays(Convert.ToInt32(settings.JwtExpireDays)));
services.Configure<ForwardedHeadersOptions>(options => services.Configure<ForwardedHeadersOptions>(options =>
{ {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
...@@ -95,8 +104,8 @@ namespace IoTSharp ...@@ -95,8 +104,8 @@ namespace IoTSharp
configure.Description = description?.Description; configure.Description = description?.Description;
}); });
services.AddTransient<ApplicationDBInitializer>(); services.AddTransient<ApplicationDBInitializer>();
services.AddIoTSharpMqttServer(AppSettings.MqttBroker); services.AddIoTSharpMqttServer(settings.MqttBroker);
services.AddMqttClient(AppSettings.MqttClient); services.AddMqttClient(settings.MqttClient);
services.AddHostedService<CoAPService>(); services.AddHostedService<CoAPService>();
services.AddHostedService<MQTTMessageService>(); services.AddHostedService<MQTTMessageService>();
services.AddSingleton<DiagnosticsService>(); services.AddSingleton<DiagnosticsService>();
...@@ -105,6 +114,7 @@ namespace IoTSharp ...@@ -105,6 +114,7 @@ namespace IoTSharp
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册