using AutoMapper;
using DMS.Application.DTOs;
using DMS.Application.DTOs.Events;
using DMS.Core.Models;
using DMS.Application.Interfaces;
using DMS.Core.Interfaces;
using DMS.Core.Enums;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
namespace DMS.Application.Services;
///
/// MQTT管理服务,负责MQTT相关的业务逻辑。
///
public class MqttManagementService
{
private readonly IMqttAppService _mqttAppService;
private readonly ConcurrentDictionary _mqttServers;
///
/// 当MQTT服务器数据发生变化时触发
///
public event EventHandler MqttServerChanged;
public MqttManagementService(IMqttAppService mqttAppService,
ConcurrentDictionary mqttServers)
{
_mqttAppService = mqttAppService;
_mqttServers = mqttServers;
}
///
/// 异步根据ID获取MQTT服务器DTO。
///
public async Task GetMqttServerByIdAsync(int id)
{
return await _mqttAppService.GetMqttServerByIdAsync(id);
}
///
/// 异步获取所有MQTT服务器DTO列表。
///
public async Task> GetAllMqttServersAsync()
{
return await _mqttAppService.GetAllMqttServersAsync();
}
///
/// 异步创建一个新的MQTT服务器。
///
public async Task CreateMqttServerAsync(MqttServerDto mqttServerDto)
{
return await _mqttAppService.CreateMqttServerAsync(mqttServerDto);
}
///
/// 异步更新一个已存在的MQTT服务器。
///
public async Task UpdateMqttServerAsync(MqttServerDto mqttServerDto)
{
await _mqttAppService.UpdateMqttServerAsync(mqttServerDto);
}
///
/// 异步删除一个MQTT服务器。
///
public async Task DeleteMqttServerAsync(int id)
{
await _mqttAppService.DeleteMqttServerAsync(id);
}
///
/// 在内存中添加MQTT服务器
///
public void AddMqttServerToMemory(MqttServerDto mqttServerDto)
{
if (_mqttServers.TryAdd(mqttServerDto.Id, mqttServerDto))
{
OnMqttServerChanged(new MqttServerChangedEventArgs(DataChangeType.Added, mqttServerDto));
}
}
///
/// 在内存中更新MQTT服务器
///
public void UpdateMqttServerInMemory(MqttServerDto mqttServerDto)
{
_mqttServers.AddOrUpdate(mqttServerDto.Id, mqttServerDto, (key, oldValue) => mqttServerDto);
OnMqttServerChanged(new MqttServerChangedEventArgs(DataChangeType.Updated, mqttServerDto));
}
///
/// 在内存中删除MQTT服务器
///
public void RemoveMqttServerFromMemory(int mqttServerId)
{
if (_mqttServers.TryRemove(mqttServerId, out var mqttServerDto))
{
OnMqttServerChanged(new MqttServerChangedEventArgs(DataChangeType.Deleted, mqttServerDto));
}
}
///
/// 触发MQTT服务器变更事件
///
protected virtual void OnMqttServerChanged(MqttServerChangedEventArgs e)
{
MqttServerChanged?.Invoke(this, e);
}
}