LASAPlatform/OpenAuth.WebApi/Model/mqtt/MqttHostedService.cs

66 lines
2.5 KiB
C#

using Infrastructure.CloudSdk.mqttmessagecenter;
using NPOI.SS.Formula.Functions;
using NuGet.Packaging;
using OpenAuth.App.ServiceApp;
using System.Security.Cryptography;
namespace OpenAuth.WebApi.Model.mqtt
{
public class MqttHostedService : IHostedService
{
private readonly IServiceProvider _serviceProvider;
private readonly MqttMessageCenter _mqttCenter;
private readonly AirportMaintenanceApp _app;
public MqttHostedService(IServiceProvider serviceProvider, MqttMessageCenter mqttCenter, AirportMaintenanceApp app)
{
_serviceProvider = serviceProvider;
_mqttCenter = mqttCenter;
_app = app;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = _serviceProvider.CreateScope();
var handlers = scope.ServiceProvider.GetServices<IMqttMessageHandler>();
// 创建配置构建器
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
optional: true)
.AddEnvironmentVariables();
// 构建配置
var configuration = builder.Build();
// 读取连接字符串
var serverIp = configuration["MQTT:Server"];
var port = configuration["MQTT:Port"];
var username = configuration["MQTT:UserName"];
var password = configuration["MQTT:Password"];
await _mqttCenter.InitializeAsync(
handlers,
server: serverIp,
port: int.Parse(port),
clientId: Guid.NewGuid().ToString(),
username: username,
password: password
);
string[] topicList =
{
"thing/product/+/services_reply",
"thing/product/+/events",
"thing/product/+/requests",
"thing/product/+/osd",
"sys/product/+/status",
"thing/product/+/control-operation"
};
await _mqttCenter.SubscribeAsync(topicList);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}