Files
Ayay/SHH.CameraService/Core/CmdClients/CommandDispatcher.cs
twice109 3d47c8f009 增加了通过网络主动上报图像的支持
增加了指令维护通道的支持
2026-01-07 10:59:03 +08:00

46 lines
1.4 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 Newtonsoft.Json.Linq;
namespace SHH.CameraService;
public class CommandDispatcher
{
// 路由表Key = ActionName, Value = Handler
private readonly Dictionary<string, ICommandHandler> _handlers;
// 通过依赖注入拿到所有实现了 ICommandHandler 的类
public CommandDispatcher(IEnumerable<ICommandHandler> handlers)
{
_handlers = handlers.ToDictionary(h => h.ActionName, h => h);
}
public async Task DispatchAsync(string jsonMessage)
{
try
{
var jObj = JObject.Parse(jsonMessage);
string action = jObj["Action"]?.ToString();
var payload = jObj["Payload"];
if (string.IsNullOrEmpty(action)) return;
// 1. 查找是否有对应的处理器
if (_handlers.TryGetValue(action, out var handler))
{
await handler.ExecuteAsync(payload);
}
else if (action == "ACK")
{
// ACK 是特殊的,可以直接在这里处理或者忽略
Console.WriteLine($"[指令] 握手成功: {jObj["Message"]}");
}
else
{
Console.WriteLine($"[警告] 未知的指令: {action}");
}
}
catch (Exception ex)
{
Console.WriteLine($"[分发错误] {ex.Message}");
}
}
}