Files
Ayay/SHH.CameraService/GrpcImpls/Handlers/TimeSyncHandler.cs

79 lines
2.7 KiB
C#
Raw Permalink 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 Ayay.SerilogLogs;
using Newtonsoft.Json.Linq;
using Serilog;
using SHH.CameraSdk;
using SHH.Contracts;
namespace SHH.CameraService;
/// <summary>
/// 设备时间同步处理器
/// 响应 gRpc 指令ProtocolCodes.Time_Sync
/// </summary>
public class TimeSyncHandler : ICommandHandler
{
private readonly ILogger _sysLog = Log.ForContext("SourceContext", LogModules.Core);
private readonly CameraManager _cameraManager;
// Optimized: 需在 ProtocolCodes 中定义此常量,确保与网关下发的 CmdCode 对应
public string ActionName => ProtocolCodes.Device_TimeSync;
public TimeSyncHandler(CameraManager cameraManager)
{
_cameraManager = cameraManager ?? throw new ArgumentNullException(nameof(cameraManager));
}
public async Task ExecuteAsync(JToken payload)
{
// 1. 解析基础参数
var deviceId = payload["DeviceId"]?.Value<int>() ?? 0;
var method = payload["Method"]?.Value<string>()?.ToLower(); // "get" 或 "set"
if (deviceId <= 0)
{
_sysLog.Warning("[TimeSync] 无效指令设备ID非法");
return;
}
// 2. 获取设备并校验能力
var device = _cameraManager.GetDevice(deviceId);
if (device == null)
{
_sysLog.Warning($"[TimeSync] 设备 {deviceId} 不存在");
return;
}
// Modified: 根据 ISyncFeature.cs 校验是否实现 ITimeSyncFeature 接口
if (!(device is ITimeSyncFeature syncFeature))
{
_sysLog.Warning($"[TimeSync] 设备 {deviceId} 不支持时间同步功能");
return;
}
// 3. 业务逻辑分支
try
{
if (method == "set")
{
// 解析待设置的时间,若无则默认使用服务器当前系统时间
var targetTime = payload["SyncTime"]?.Value<DateTime>() ?? DateTime.Now;
// 调用接口设置时间
await syncFeature.SetTimeAsync(targetTime);
_sysLog.Information($"[TimeSync] 设备 {deviceId} 时间已同步为: {targetTime:yyyy-MM-dd HH:mm:ss}");
}
else
{
// 执行获取时间
var deviceTime = await syncFeature.GetTimeAsync();
_sysLog.Information($"[TimeSync] 获取设备 {deviceId} 当前时间成功: {deviceTime:yyyy-MM-dd HH:mm:ss}");
// TODO: 若需要将结果返回给网关,需在此处调用 GatewayService 异步回传
}
}
catch (Exception ex)
{
_sysLog.Error(ex, $"[TimeSync] 设备 {deviceId} 操作失败 ({method})");
}
}
}