继续修改报警系统

This commit is contained in:
2025-09-14 09:03:07 +08:00
parent 58c9340640
commit 25cd43d436
4 changed files with 85 additions and 9 deletions

View File

@@ -80,5 +80,5 @@ public class DeviceDto
/// <summary>
/// 设备关联的变量表集合
/// </summary>
public List<VariableTableDto> VariableTables { get; set; }
public List<VariableTableDto> VariableTables { get; set; }=new List<VariableTableDto>();
}

View File

@@ -1,3 +1,4 @@
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.Core.Events;
using DMS.Core.Interfaces.Repositories;
@@ -10,12 +11,16 @@ namespace DMS.Application.EventHandlers
{
private readonly ILogger<AlarmEventHandler> _logger;
private readonly IAlarmHistoryRepository _alarmHistoryRepository;
// 可以注入其他服务,如 IEmailService, ISmsService 等
private readonly IEmailAppService _emailAppService; // 注入邮件服务
public AlarmEventHandler(ILogger<AlarmEventHandler> logger, IAlarmHistoryRepository alarmHistoryRepository)
public AlarmEventHandler(
ILogger<AlarmEventHandler> logger,
IAlarmHistoryRepository alarmHistoryRepository,
IEmailAppService emailAppService) // 添加邮件服务依赖
{
_logger = logger;
_alarmHistoryRepository = alarmHistoryRepository;
_emailAppService = emailAppService;
}
public async void HandleAlarm(object sender, AlarmEventArgs e)
@@ -50,9 +55,52 @@ namespace DMS.Application.EventHandlers
_logger.LogError(ex, $"保存报警记录时发生错误: {ex.Message}");
}
// 在这里添加其他报警处理逻辑
// 发送邮件通知
try
{
// 获取默认邮件账户
var emailAccounts = await _emailAppService.GetAllEmailAccountsAsync();
var defaultAccount = emailAccounts.FirstOrDefault(); // 简单选择第一个账户
if (defaultAccount != null)
{
// 构建邮件内容
var emailRequest = new SendEmailRequest
{
EmailAccountId = defaultAccount.Id,
To = "peigangwei@qq.com", // 这里应该从配置或用户信息中获取
Subject = $"设备报警通知 - {e.VariableName}",
Body = $@"
<html>
<body>
<h2>设备报警通知</h2>
<p><strong>报警时间:</strong> {e.Timestamp:yyyy-MM-dd HH:mm:ss}</p>
<p><strong>变量名称:</strong> {e.VariableName}</p>
<p><strong>当前值:</strong> {e.CurrentValue}</p>
<p><strong>阈值:</strong> {e.ThresholdValue}</p>
<p><strong>报警类型:</strong> {e.AlarmType}</p>
<p><strong>报警消息:</strong> {e.Message}</p>
</body>
</html>",
IsHtml = true
};
// 发送邮件
await _emailAppService.SendEmailAsync(emailRequest);
_logger.LogInformation($"报警邮件已发送: {e.Message}");
}
else
{
_logger.LogWarning("未配置邮件账户,无法发送报警邮件");
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"发送报警邮件时发生错误: {ex.Message}");
}
// 在这里可以添加其他报警处理逻辑
// 例如:
// 2. 发送邮件或短信通知
// 3. 触发其他操作
}
}

View File

@@ -78,10 +78,16 @@ public class VariableTableManagementService : IVariableTableManagementService
/// </summary>
public void AddVariableTableToMemory(VariableTableDto variableTableDto)
{
// 添加null检查
if (variableTableDto == null)
return;
DeviceDto deviceDto = null;
if (_appDataStorageService.Devices.TryGetValue(variableTableDto.DeviceId, out var device))
{
deviceDto = device;
// 确保VariableTables不为null
device.VariableTables ??= new List<VariableTableDto>();
device.VariableTables.Add(variableTableDto);
variableTableDto.Device = device;
}