Files
DMS/DMS.WPF/Services/MqttDataService.cs

87 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.ObjectModel;
using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.WPF.Interfaces;
using DMS.WPF.ViewModels.Items;
namespace DMS.WPF.Services;
/// <summary>
/// MQTT数据服务类负责管理MQTT服务器相关的数据和操作。
/// </summary>
public class MqttDataService : IMqttDataService
{
private readonly IMapper _mapper;
private readonly IAppDataCenterService _appDataCenterService;
private readonly IDataStorageService _dataStorageService;
private readonly IMqttAppService _mqttAppService;
/// <summary>
/// MqttDataService类的构造函数。
/// </summary>
/// <param name="mapper">AutoMapper 实例。</param>
/// <param name="mqttAppService">MQTT应用服务实例。</param>
public MqttDataService(IMapper mapper,IAppDataCenterService appDataCenterService,IDataStorageService dataStorageService, IMqttAppService mqttAppService)
{
_mapper = mapper;
_appDataCenterService = appDataCenterService;
_dataStorageService = dataStorageService;
_mqttAppService = mqttAppService;
}
/// <summary>
/// 加载所有MQTT服务器数据。
/// </summary>
public async Task LoadMqttServers()
{
try
{
// 加载MQTT服务器数据
_dataStorageService.MqttServers = _mapper.Map<ObservableCollection<MqttServerItemViewModel>>(_appDataCenterService.MqttServers.Values);
}
catch (Exception ex)
{
// 记录异常或处理错误
Console.WriteLine($"加载MQTT服务器数据时发生错误: {ex.Message}");
}
}
/// <summary>
/// 添加MQTT服务器。
/// </summary>
public async Task<MqttServerItemViewModel> AddMqttServer(MqttServerItemViewModel mqttServer)
{
var dto = _mapper.Map<MqttServerDto>(mqttServer);
var id = await _mqttAppService.CreateMqttServerAsync(dto);
dto.Id = id;
var mqttServerItem = _mapper.Map<MqttServerItemViewModel>(dto);
_dataStorageService.MqttServers.Add(mqttServerItem);
return mqttServerItem;
}
/// <summary>
/// 更新MQTT服务器。
/// </summary>
public async Task<bool> UpdateMqttServer(MqttServerItemViewModel mqttServer)
{
var dto = _mapper.Map<MqttServerDto>(mqttServer);
await _mqttAppService.UpdateMqttServerAsync(dto);
return true;
}
/// <summary>
/// 删除MQTT服务器。
/// </summary>
public async Task<bool> DeleteMqttServer(MqttServerItemViewModel mqttServer)
{
await _mqttAppService.DeleteMqttServerAsync(mqttServer.Id);
_dataStorageService.MqttServers.Remove(mqttServer);
return true;
}
}