namespace ClassNotify.Server.Services; public interface IDevicePresenceService { bool IsOnline(string deviceId, DateTimeOffset? lastHeartbeatAt); } public sealed class DevicePresenceService : IDevicePresenceService { private readonly ISecurityService _securityService; public DevicePresenceService(ISecurityService securityService) { _securityService = securityService; } public bool IsOnline(string deviceId, DateTimeOffset? lastHeartbeatAt) { if (string.IsNullOrWhiteSpace(deviceId)) { return false; } // 1. Primary source of truth: Active SignalR device connection var connId = _securityService.GetDeviceConnectionId(deviceId); if (!string.IsNullOrEmpty(connId)) { return true; } // 2. Secondary heartbeat threshold check (within 60s) if (lastHeartbeatAt.HasValue && (DateTimeOffset.UtcNow - lastHeartbeatAt.Value).TotalSeconds <= 60) { return true; } return false; } }