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

84 lines
3.1 KiB
C#

3 months ago
using Infrastructure.CloudSdk.mqttmessagecenter;
2 months ago
using NPOI.SS.Formula.Functions;
using NuGet.Packaging;
using OpenAuth.App.ServiceApp;
2 months ago
using System.Security.Cryptography;
3 months ago
namespace OpenAuth.WebApi.Model.mqtt
{
public class MqttHostedService : IHostedService
{
private readonly IServiceProvider _serviceProvider;
private readonly MqttMessageCenter _mqttCenter;
private readonly AirportMaintenanceApp _app;
3 months ago
public MqttHostedService(IServiceProvider serviceProvider, MqttMessageCenter mqttCenter, AirportMaintenanceApp app)
3 months ago
{
_serviceProvider = serviceProvider;
_mqttCenter = mqttCenter;
_app = app;
3 months ago
}
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"];
3 months ago
await _mqttCenter.InitializeAsync(
3 months ago
handlers,
server: serverIp,
port: int.Parse(port),
2 months ago
clientId: Guid.NewGuid().ToString(),
username: username,
password: password
3 months ago
);
//查询网关,订阅主题
var topics = new List<string>();
3 months ago
var gatewayList = await _app.GetGatewaysnList();
3 months ago
foreach (var gateway in gatewayList)
{
topics.AddRange(new[]
{
3 months ago
$"thing/product/{gateway}/osd",
$"thing/product/{gateway}/events",
$"thing/product/{gateway}/requests",
$"thing/product/{gateway}/services_reply",
3 months ago
//$"thing/product/{gateway}/drc/up",
//$"thing/product/{gateway}/drc/down",
$"sys/product/{gateway}/status"
});
}
var snList = await _app.GetUavSn();
foreach (var sn in snList)
2 months ago
{
topics.AddRange(new[]
{
// $"thing/product/1581F8HGX254V00A0BUY/osd",
$"thing/product/{sn}/osd"
});
}
await _mqttCenter.ConnectAndSubscribeAsync(topics.ToArray());
3 months ago
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}