using AttendanceHub.Sync.Domain;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Com;
///
/// Dual-session device access: independent Live (RegEvent only) and Read (SSR) CZKEM sessions.
/// Each session has its own STA owner, RCW, pump, and generation. No shared COM objects.
/// Phase 2E: decouple long attendance reads from OnAttTransactionEx dispatch.
///
public sealed class DualComDevice : IAsyncDisposable
{
public string DeviceKey { get; }
public ComSession Live { get; }
public ComSession Read { get; }
private readonly ILogger _log;
public DualComDevice(
string deviceKey,
string ip,
int port,
int machineNumber,
int commTimeoutSeconds,
ILogger? log = null)
{
DeviceKey = deviceKey;
_log = log ?? NullLogger.Instance;
// Distinct worker/owner names — never share RCWs across sessions.
Live = new ComSession(deviceKey + ":live", ip, port, machineNumber, commTimeoutSeconds, _log);
Read = new ComSession(deviceKey + ":read", ip, port, machineNumber, commTimeoutSeconds, _log);
}
public event Action? AttendanceReceived
{
add => Live.AttendanceReceived += value;
remove => Live.AttendanceReceived -= value;
}
public async Task ConnectBothAsync(CancellationToken ct = default)
{
await Live.InitializeAsync(ct).ConfigureAwait(false);
await Read.InitializeAsync(ct).ConfigureAwait(false);
var liveConn = await Live.ConnectAsync(ct).ConfigureAwait(false);
var readConn = await Read.ConnectAsync(ct).ConfigureAwait(false);
bool regOk = false;
string? regErr = null;
if (liveConn.Success)
{
try
{
await Live.RegEventAsync(1, ct).ConfigureAwait(false);
regOk = true;
}
catch (Exception ex)
{
regErr = ex.Message;
}
}
_log.LogInformation(
"DUAL_CONNECT device={Dev} liveOwner={LO} readOwner={RO} liveOk={L} readOk={R} regEvent={G} err={E}",
DeviceKey, Live.OwnerThreadId, Read.OwnerThreadId, liveConn.Success, readConn.Success, regOk, regErr);
return new DualSessionConnectResult(
DeviceKey,
Live.OwnerThreadId,
Read.OwnerThreadId,
Live.Info.ApartmentState,
Read.Info.ApartmentState,
Live.Generation,
Read.Generation,
liveConn,
readConn,
regOk,
regErr);
}
/// Long SSR read on the READ session only — does not touch the LIVE owner.
public Task ReadAttendanceAsync(AttendanceReadRequest request, CancellationToken ct = default)
=> Read.ReadAttendanceAsync(request, ct);
public Task RecreateReadAsync(CancellationToken ct = default) => Read.RecreateSessionAsync(ct);
public Task RecreateLiveAsync(CancellationToken ct = default) => Live.RecreateSessionAsync(ct);
public async ValueTask DisposeAsync()
{
await Live.DisposeAsync().ConfigureAwait(false);
await Read.DisposeAsync().ConfigureAwait(false);
}
}
public sealed record DualSessionConnectResult(
string DeviceKey,
int LiveOwnerThreadId,
int ReadOwnerThreadId,
string LiveApartment,
string ReadApartment,
int LiveGeneration,
int ReadGeneration,
ConnectResult LiveConnect,
ConnectResult ReadConnect,
bool RegEventOk,
string? RegEventError);