2025-09-12 14:59:32 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
2025-10-01 19:16:47 +08:00
|
|
|
using DMS.Application.Events;
|
2025-09-12 14:59:32 +08:00
|
|
|
using DMS.Application.Interfaces;
|
2025-09-16 14:42:23 +08:00
|
|
|
using DMS.Core.Events;
|
2025-09-12 14:59:32 +08:00
|
|
|
using DMS.Core.Models;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace DMS.Application.Services;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 设备监视服务实现类,用于监视设备的状态变化
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class DeviceMonitoringService : IDeviceMonitoringService, IDisposable
|
|
|
|
|
{
|
|
|
|
|
private readonly ILogger<DeviceMonitoringService> _logger;
|
|
|
|
|
private readonly IEventService _eventService;
|
2025-10-22 14:06:16 +08:00
|
|
|
private readonly IAppDataService _appDataService;
|
2025-10-18 17:18:09 +08:00
|
|
|
private readonly IAppCenterService _appCenterService;
|
2025-09-12 14:59:32 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 初始化DeviceMonitoringService类的新实例
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="logger">日志记录器</param>
|
|
|
|
|
/// <param name="deviceAppService">设备应用服务</param>
|
|
|
|
|
public DeviceMonitoringService(ILogger<DeviceMonitoringService> logger, IEventService eventService,
|
2025-10-22 14:06:16 +08:00
|
|
|
IAppDataService appStorageService,
|
2025-10-18 17:18:09 +08:00
|
|
|
IAppCenterService appCenterService)
|
2025-09-12 14:59:32 +08:00
|
|
|
{
|
|
|
|
|
_logger = logger;
|
|
|
|
|
_eventService = eventService;
|
2025-10-22 14:06:16 +08:00
|
|
|
_appDataService = appStorageService;
|
2025-10-18 17:18:09 +08:00
|
|
|
_appCenterService = appCenterService;
|
2025-10-01 18:41:05 +08:00
|
|
|
_eventService.OnDeviceStateChanged += OnDeviceStateChanged;
|
2025-09-12 14:59:32 +08:00
|
|
|
}
|
|
|
|
|
|
2025-10-01 18:41:05 +08:00
|
|
|
private void OnDeviceStateChanged(object? sender, DeviceStateChangedEventArgs e)
|
2025-09-12 14:59:32 +08:00
|
|
|
{
|
2025-10-01 18:41:05 +08:00
|
|
|
// 只处理激活状态变化事件
|
|
|
|
|
if (e.StateType == Core.Enums.DeviceStateType.Active)
|
2025-09-12 14:59:32 +08:00
|
|
|
{
|
2025-10-22 14:06:16 +08:00
|
|
|
if (_appDataService.Devices.TryGetValue(e.DeviceId, out var device))
|
2025-10-01 18:09:30 +08:00
|
|
|
{
|
2025-10-01 18:41:05 +08:00
|
|
|
// 更新设备激活状态 - 同时更新数据库和内存
|
|
|
|
|
_ = Task.Run(async () =>
|
|
|
|
|
{
|
2025-10-18 17:18:09 +08:00
|
|
|
await _appCenterService.DeviceManagementService.UpdateDeviceAsync(device);
|
2025-10-01 18:41:05 +08:00
|
|
|
});
|
|
|
|
|
}
|
2025-09-12 14:59:32 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
2025-10-01 18:41:05 +08:00
|
|
|
_eventService.OnDeviceStateChanged -= OnDeviceStateChanged;
|
2025-09-12 14:59:32 +08:00
|
|
|
}
|
|
|
|
|
}
|