2 3 - 迁移 IMqttServiceManager 接口到 DMS.Core 4 - 在 DataCenterService 中添加 MQTT 服务器和变量别名的加载逻辑 5 - 实现 MqttPublishProcessor 的核心处理逻辑 6 - 为 DTO 和 ViewModel 的 MqttAliases 属性提供默认空列表初始化 7 - 更新 AutoMapper 映射配置以支持 VariableMqttAliasDto
51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
using System.Threading.Tasks;
|
||
using AutoMapper;
|
||
using DMS.Application.Interfaces;
|
||
using DMS.Application.Models;
|
||
using DMS.Core.Interfaces.Services;
|
||
using DMS.Core.Models;
|
||
|
||
namespace DMS.Application.Services.Processors;
|
||
|
||
/// <summary>
|
||
/// 负责将变量数据发布到MQTT的处理器。
|
||
/// </summary>
|
||
public class MqttPublishProcessor : IVariableProcessor
|
||
{
|
||
private readonly IMapper _mapper;
|
||
private readonly IMqttServiceManager _mqttServiceManager;
|
||
|
||
public MqttPublishProcessor(IMapper mapper, IMqttServiceManager mqttServiceManager)
|
||
{
|
||
_mapper = mapper;
|
||
_mqttServiceManager = mqttServiceManager;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 处理单个变量上下文,如果有关联的MQTT配置,则将其推送到发送队列。
|
||
/// </summary>
|
||
/// <param name="context">包含变量及其元数据的上下文对象。</param>
|
||
public async Task ProcessAsync(VariableContext context)
|
||
{
|
||
var variable = context.Data;
|
||
if (variable?.MqttAliases == null || variable.MqttAliases.Count == 0)
|
||
{
|
||
return; // 没有关联的MQTT配置,直接返回
|
||
}
|
||
|
||
// 遍历所有关联的MQTT配置,并将其推入发送队列
|
||
foreach (var variableMqttAlias in variable.MqttAliases)
|
||
{
|
||
// 创建VariableMqtt对象
|
||
var variableMqtt = new VariableMqtt
|
||
{
|
||
Variable = _mapper.Map<Variable>(variable),
|
||
Mqtt = variableMqttAlias.MqttServer,
|
||
MqttId = variableMqttAlias.MqttServerId
|
||
};
|
||
|
||
// 发布变量数据到MQTT服务器
|
||
await _mqttServiceManager.PublishVariableDataAsync(variableMqtt);
|
||
}
|
||
}
|
||
} |