using System.Diagnostics;
using System.Globalization;
using AttendanceHub.Sync.Domain;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using zkemkeeper;
namespace AttendanceHub.Sync.Com;
///
/// Exclusive COM session for one device, backed by :
/// one dedicated STA owner thread + permanent message pump + one CZKEMClass RCW that is
/// created / used / released ONLY on that owner. Every SDK operation is routed through the
/// worker's command queue (never ThreadPool, Task.Run, or ad-hoc STA threads).
/// The application layer talks to IZkComSession and never sees the RCW.
/// Interop note: zkemkeeper 1.0.2 exposes COM [out] params as C# ref — callers pre-init locals.
///
public sealed class ComSession : IZkComSession
{
private static readonly TimeSpan DefaultOpTimeout = TimeSpan.FromSeconds(30);
private readonly DeviceSessionWorker _worker;
private readonly ILogger _log;
private readonly string _deviceId;
private readonly string _ip;
private readonly int _port;
private readonly int _machineNumber;
private readonly bool _performsReadOperations;
private bool _connected;
private int _sessionEpoch;
private DateTimeOffset? _connectedAt;
private DateTimeOffset? _disconnectedAt;
private int _eventMask;
private bool _disposed;
private _IZKEMEvents_OnAttTransactionExEventHandler? _onAttEx;
private _IZKEMEvents_OnAttTransactionEventHandler? _onAtt;
private _IZKEMEvents_OnConnectedEventHandler? _onConnected;
private _IZKEMEvents_OnDisConnectedEventHandler? _onDisconnected;
public event Action? AttendanceReceived;
public int Generation => _worker.Generation;
public bool IsConnected => _connected;
public int OwnerThreadId => _worker.OwnerThreadId;
public bool PumpAlive => _worker.PumpAlive;
// Owner-context / event-dispatch instrumentation (proof counters).
private long _eventsDirectOnOwner;
private long _eventsHandedToOwner;
private long _eventsDropped;
private int _staleRejected;
/// Realtime events that executed directly on the COM owner thread (pump dispatch).
public long EventsDirectOnOwner => Interlocked.Read(ref _eventsDirectOnOwner);
/// Realtime events captured on a foreign thread and handed to the owner context.
public long EventsHandedToOwner => Interlocked.Read(ref _eventsHandedToOwner);
/// Realtime events dropped because the owner was unavailable (always logged).
public long EventsDropped => Interlocked.Read(ref _eventsDropped);
public int StaleGenerationRejections => _staleRejected;
/// Diagnostic view of the underlying worker (owner identity, pump heartbeat, counters).
public DeviceSessionWorker Worker => _worker;
///
/// LIVE production sessions pass false: they must never execute read APIs
/// (ReadGeneralLogData / probes / functional-health reads), including during recreate.
/// Defaults to true for READ sessions and existing test tooling.
///
public ComSession(string deviceId, string ip, int port, int machineNumber, int commTimeoutSeconds,
ILogger? log = null, bool performsReadOperations = true)
{
_deviceId = deviceId;
_ip = ip;
_port = port;
_machineNumber = machineNumber;
_performsReadOperations = performsReadOperations;
_log = log ?? NullLogger.Instance;
_worker = new DeviceSessionWorker(deviceId, machineNumber, commTimeoutSeconds, _log);
_worker.RegisterEventSinks(AttachEventSinks, DetachEventSinks);
}
private void AssertReadAllowed(string api)
{
if (_performsReadOperations) return;
_log.LogError("LIVE_SESSION_READ_FORBIDDEN device={Device} api={Api} generation={Gen} ownerTid={OwnerTid} — LIVE sessions never execute reads",
_deviceId, api, _worker.Generation, _worker.OwnerThreadId);
throw new InvalidOperationException($"LIVE_SESSION_READ_FORBIDDEN api={api} device={_deviceId}");
}
public ZkSessionInfo Info => new(
Environment.ProcessId,
_deviceId,
_worker.OwnerThreadId,
_worker.ApartmentState,
_worker.Generation,
_worker.SdkVersion,
_worker.RcwCreatedAt,
_connectedAt,
_disconnectedAt);
public Task InitializeAsync(CancellationToken cancellationToken = default)
=> _worker.StartAsync(cancellationToken);
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
var result = await _worker.ConnectAsync(_ip, _port, cancellationToken).ConfigureAwait(false);
_connected = result.Success;
if (result.Success)
{
_connectedAt = DateTimeOffset.UtcNow;
_disconnectedAt = null;
}
return result;
}
public async Task RegEventAsync(int eventMask, CancellationToken cancellationToken = default)
{
await _worker.RegEventAsync(eventMask, cancellationToken).ConfigureAwait(false);
_eventMask = eventMask;
}
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
await _worker.DisconnectAsync(cancellationToken).ConfigureAwait(false);
_connected = false;
_disconnectedAt = DateTimeOffset.UtcNow;
}
public Task ProbeCapabilityAsync(CancellationToken cancellationToken = default)
{
AssertReadAllowed("ProbeCapability");
return InvokeAsync("CapabilityProbe", zk => ProbeCore(zk, out _), DefaultOpTimeout, cancellationToken);
}
///
/// Liveness probe — device-info round trip, NOT a log read, therefore allowed on LIVE sessions
/// too. Short timeout so a wedged socket is detected quickly instead of being trusted forever.
///
public async Task PingAsync(CancellationToken cancellationToken = default)
{
if (!_connected)
return false;
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
var ok = await InvokeAsync("LivenessPing", PingCore, TimeSpan.FromSeconds(10), timeout.Token).ConfigureAwait(false);
if (!ok)
_log.LogWarning("LIVENESS_PING_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} — session still flagged connected",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
return ok;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
_log.LogWarning("LIVENESS_PING_TIMEOUT device={Device} generation={Gen} — no answer within 10s",
_deviceId, _worker.Generation);
return false;
}
catch (Exception ex)
{
_log.LogWarning(ex, "LIVENESS_PING_ERROR device={Device} generation={Gen}", _deviceId, _worker.Generation);
return false;
}
}
/// Executed on the owner thread: cheap device-info call, no attendance-log read.
private bool PingCore(CZKEMClass zk)
{
int userCount = -1;
var ok = zk.GetDeviceInfo(_machineNumber, 2, ref userCount);
if (ok && userCount >= 0)
return true;
// Some firmwares answer the serial instead of user counts — either proves the pipe is alive.
return zk.GetSerialNumber(_machineNumber, out var serial) && !string.IsNullOrEmpty(serial);
}
public Task GetFunctionalHealthAsync(CancellationToken cancellationToken = default)
{
AssertReadAllowed("GetFunctionalHealth");
return InvokeAsync("FunctionalHealth", zk =>
{
var cap = ProbeCore(zk, out var deviceInfoOk);
var sw = Stopwatch.StartNew();
string readApi = "none";
int logs = 0;
bool readOk = false;
string? sdkErr = null;
try
{
// Live-first: this probe only has to prove the read channel still ANSWERS, so it must
// stay cheap. Without tryTimeWindow it silently fell back to a full-buffer
// ReadGeneralLogData — measured at 47s / 56s / 361s on busy devices — i.e. the health
// check itself was a major source of device load. allowFallback:false bounds it: a
// rejected window fails fast (-> SESSION_RECREATE_HEALTH_DEGRADED warning only)
// instead of costing a multi-10k full pass. The scheduled read cycle owns the real work.
var result = ReadAttendanceCore(zk, DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddMinutes(1),
AttendanceReadMode.Auto, maxRecords: 5, allowFallback: false, tryTimeWindow: true);
readApi = result.ApiUsed;
logs = result.Records.Count;
readOk = result.Status is AttendanceReadStatus.Success or AttendanceReadStatus.TrueEmpty;
if (!readOk)
sdkErr = $"{result.Status}: {result.Error ?? result.LastError?.ToString()}";
}
finally
{
sw.Stop();
}
var health = new FunctionalHealth(_connected, deviceInfoOk, readOk, readApi, logs, sw.ElapsedMilliseconds, sdkErr, cap);
_log.LogInformation(
"FUNCTIONAL_HEALTH device={Device} connected={C} info={I} read={R} api={Api} logs={Logs} ms={Ms} sdkErr={Err} generation={Gen}",
_deviceId, health.Connected, health.DeviceInfoOk, health.FunctionalReadOk, health.ReadApiUsed,
health.LogsEnumerated, health.ReadDurationMs, health.SdkError, _worker.Generation);
return health;
}, DefaultOpTimeout, cancellationToken);
}
public Task ReadAttendanceAsync(AttendanceReadRequest request, CancellationToken cancellationToken = default)
{
AssertReadAllowed("ReadAttendance");
return InvokeAsync("ReadAttendance", zk =>
ReadAttendanceCore(zk, request.Start, request.End, request.Mode, request.MaxRecords, request.AllowFallback, request.TryTimeWindow),
TimeSpan.FromMinutes(5), cancellationToken);
}
public async Task RecreateSessionAsync(CancellationToken cancellationToken = default)
{
_log.LogWarning("SESSION_RECREATE_BEGIN device={Device} oldGeneration={Gen}", _deviceId, _worker.Generation);
var oldEpoch = _sessionEpoch;
Interlocked.Increment(ref _sessionEpoch);
// Full lifecycle (stop old owner → unsubscribe → disconnect/release → terminate pump →
// start new owner → create → connect → RegEvent → generation++) lives in the worker.
//
// _connected MUST be re-synchronised even when the recreate throws: the worker bumps the
// generation in its own finally, and a stale `_connected == true` here is exactly what made
// a dead session look healthy forever (reconnect gate + read cycle both keyed off it).
try
{
await _worker.RecreateAsync(_ip, _port, _eventMask == 0 ? 1 : _eventMask, cancellationToken).ConfigureAwait(false);
}
finally
{
_connected = _worker.RcwConnected;
_connectedAt = _connected ? DateTimeOffset.UtcNow : _connectedAt;
_disconnectedAt = _connected ? null : DateTimeOffset.UtcNow;
}
_log.LogInformation("SESSION_TEARDOWN device={Device} oldEpoch={E} generation={Gen} connected={C}", _deviceId, oldEpoch, _worker.Generation, _connected);
if (_performsReadOperations)
{
var health = await GetFunctionalHealthAsync(cancellationToken).ConfigureAwait(false);
if (!health.FunctionalReadOk)
_log.LogWarning("SESSION_RECREATE_HEALTH_DEGRADED readErr={Err}", health.SdkError);
}
else
{
// LIVE sessions must never execute reads — including the recreate-time functional probe.
_log.LogInformation(
"SESSION_RECREATE_HEALTH_SKIPPED device={Device} generation={Gen} reason=live_session_no_reads",
_deviceId, _worker.Generation);
}
_log.LogInformation("SESSION_RECREATE_OK device={Device} newGeneration={Gen}", _deviceId, _worker.Generation);
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
try
{
await DisconnectAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogError(ex,
"COM_DISPOSE_DISCONNECT_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} — continuing teardown",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
}
try
{
await _worker.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogError(ex,
"COM_DISPOSE_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
}
}
private Task InvokeAsync(string api, Func body, TimeSpan timeout, CancellationToken ct = default)
=> _worker.InvokeAsync(api, body, timeout, ct);
/// Explicit owner guard used by event sink attach/detach (subscription must be on the owner).
private void AssertOwnerThread(string apiName)
{
var current = Environment.CurrentManagedThreadId;
if (current != _worker.OwnerThreadId)
{
throw new InvalidOperationException(
$"COM_ACCESS_VIOLATION api={apiName} currentThread={current} ownerThread={_worker.OwnerThreadId} name={_deviceId}");
}
}
private int? GetLastErrorCode(CZKEMClass zk)
{
try
{
int err = 0;
zk.GetLastError(ref err);
return err;
}
catch (Exception ex)
{
_log.LogDebug(ex,
"COM_NATIVE_ERROR_QUERY_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
return null;
}
}
// ------------------------------------------------------------------
// Realtime event sinks — attach/detach ALWAYS on the owner thread;
// handlers execute in the owner context (direct when already on the owner,
// otherwise posted to the owner queue). No SQLite, no upload, no SDK re-entry.
// ------------------------------------------------------------------
private void AttachEventSinks(CZKEMClass zk)
{
AssertOwnerThread("AttachEventSinks");
DetachEventSinks(zk);
var epoch = _sessionEpoch;
_onAttEx = (enrollNumber, isInvalid, attState, verifyMethod, year, month, day, hour, minute, second, workcode) =>
HandleAttEvent(epoch, enrollNumber ?? "", isInvalid, attState, verifyMethod, year, month, day, hour, minute, second, workcode, "OnAttTransactionEx");
_onAtt = (enrollNumber, isInvalid, attState, verifyMethod, year, month, day, hour, minute, second) =>
HandleAttEvent(epoch, enrollNumber.ToString(), isInvalid, attState, verifyMethod, year, month, day, hour, minute, second, 0, "OnAttTransaction");
_onConnected = () => _log.LogInformation("RT OnConnected device={Device} generation={Gen}", _deviceId, _worker.Generation);
_onDisconnected = () =>
{
_connected = false;
_log.LogInformation("RT OnDisConnected device={Device} generation={Gen}", _deviceId, _worker.Generation);
};
zk.OnAttTransactionEx += _onAttEx;
zk.OnAttTransaction += _onAtt;
zk.OnConnected += _onConnected;
zk.OnDisConnected += _onDisconnected;
_log.LogInformation(
"COM_EVENT_SINK_ATTACHED device={Device} epoch={Epoch} generation={Gen} ownerTid={OwnerTid} api=OnAttTransactionEx+OnAttTransaction+OnConnected+OnDisConnected",
_deviceId, epoch, _worker.Generation, _worker.OwnerThreadId);
}
private void DetachEventSinks(CZKEMClass zk)
{
AssertOwnerThread("DetachEventSinks");
try
{
if (_onAttEx is not null) zk.OnAttTransactionEx -= _onAttEx;
if (_onAtt is not null) zk.OnAttTransaction -= _onAtt;
if (_onConnected is not null) zk.OnConnected -= _onConnected;
if (_onDisconnected is not null) zk.OnDisConnected -= _onDisconnected;
_log.LogInformation(
"COM_EVENT_SINK_DETACHED device={Device} epoch={Epoch} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _sessionEpoch, _worker.Generation, _worker.OwnerThreadId);
}
catch (Exception ex)
{
_log.LogError(ex,
"COM_DETACH_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} execTid={ExecTid}",
_deviceId, _worker.Generation, _worker.OwnerThreadId, Environment.CurrentManagedThreadId);
}
_onAttEx = null;
_onAtt = null;
_onConnected = null;
_onDisconnected = null;
}
///
/// Raw COM callback entry. Captures metadata only, then executes the normalized dispatch in the
/// owner context (direct if already on the owner, otherwise posted to the owner queue).
///
private void HandleAttEvent(
int epoch,
string enrollNumber,
long isInvalid,
long attState,
long verifyMethod,
long year, long month, long day, long hour, long minute, long second,
long workcode,
string sourceApi)
{
if (_disposed)
{
Interlocked.Increment(ref _eventsDropped);
_log.LogWarning(
"RT_EVENT_DROPPED device={Device} source={Src} reason=disposed generation={Gen}",
_deviceId, sourceApi, _worker.Generation);
return;
}
if (Environment.CurrentManagedThreadId == _worker.OwnerThreadId && _worker.IsRunning)
{
DispatchRealtimeOnOwner(epoch, enrollNumber, isInvalid, attState, verifyMethod,
year, month, day, hour, minute, second, workcode, sourceApi);
Interlocked.Increment(ref _eventsDirectOnOwner);
return;
}
if (_worker.TryPost(
() => DispatchRealtimeOnOwner(epoch, enrollNumber, isInvalid, attState, verifyMethod,
year, month, day, hour, minute, second, workcode, sourceApi),
"RT_" + sourceApi))
{
Interlocked.Increment(ref _eventsHandedToOwner);
_log.LogDebug(
"RT_EVENT_HANDOFF_TO_OWNER device={Device} source={Src} callbackTid={CbTid} ownerTid={OwnerTid} generation={Gen}",
_deviceId, sourceApi, Environment.CurrentManagedThreadId, _worker.OwnerThreadId, _worker.Generation);
}
else
{
Interlocked.Increment(ref _eventsDropped);
_log.LogWarning(
"RT_EVENT_DROPPED device={Device} source={Src} reason=owner_unavailable generation={Gen}",
_deviceId, sourceApi, _worker.Generation);
}
}
private void DispatchRealtimeOnOwner(
int epoch,
string enrollNumber,
long isInvalid,
long attState,
long verifyMethod,
long year, long month, long day, long hour, long minute, long second,
long workcode,
string sourceApi)
{
try
{
if (_disposed)
{
Interlocked.Increment(ref _eventsDropped);
_log.LogWarning(
"RT_EVENT_DROPPED device={Device} source={Src} reason=disposed generation={Gen}",
_deviceId, sourceApi, _worker.Generation);
return;
}
if (epoch != _sessionEpoch)
{
Interlocked.Increment(ref _staleRejected);
_log.LogWarning(
"STALE_GENERATION_REJECTED source={Src} eventGen={G} eventEpoch={E} currentGen={CG} currentEpoch={CE}",
sourceApi, _worker.Generation, epoch, _worker.Generation, _sessionEpoch);
return;
}
var generation = _worker.Generation;
var dto = new RawAttendanceEvent(
generation,
enrollNumber,
isInvalid != 0,
(int)attState,
(int)verifyMethod,
(int)year, (int)month, (int)day, (int)hour, (int)minute, (int)second,
(int)workcode,
sourceApi,
DateTimeOffset.UtcNow);
// Lightweight only: subscribers must enqueue and return (no SQLite / no upload / no SDK).
AttendanceReceived?.Invoke(dto);
}
catch (Exception ex)
{
_log.LogError(ex, "RT_EVENT_HANDLER_FAILURE source={Src} generation={Gen}", sourceApi, _worker.Generation);
}
}
// ------------------------------------------------------------------
// Capability probe + read core (executed on the owner thread only —
// every path is wrapped by DeviceSessionWorker.InvokeAsync which asserts ownership).
// ------------------------------------------------------------------
private DeviceCapability ProbeCore(CZKEMClass zk, out bool deviceInfoOk)
{
deviceInfoOk = false;
var probed = new List();
try
{
probed.Add("GetDeviceInfo(2)");
int userCount = -1;
var usersOk = zk.GetDeviceInfo(_machineNumber, 2, ref userCount);
deviceInfoOk = usersOk && userCount >= 0;
string Serial() { probed.Add("GetSerialNumber"); return zk.GetSerialNumber(_machineNumber, out var s) ? s : null!; }
string Mac() { probed.Add("GetDeviceMAC"); string s = ""; return zk.GetDeviceMAC(_machineNumber, ref s) ? s : null!; }
string Product() { probed.Add("GetProductCode"); return zk.GetProductCode(_machineNumber, out var s) ? s : null!; }
string Fw()
{
probed.Add("GetDeviceFirmwareVersion");
string s = "";
if (zk.GetDeviceFirmwareVersion(_machineNumber, ref s) && !string.IsNullOrEmpty(s)) return s;
probed.Add("GetFirmwareVersion");
s = "";
return zk.GetFirmwareVersion(_machineNumber, ref s) ? s : null!;
}
string Platform() { probed.Add("GetPlatform"); string s = ""; return zk.GetPlatform(_machineNumber, ref s) ? s : null!; }
string Ip() { probed.Add("GetDeviceIP"); string s = ""; return zk.GetDeviceIP(_machineNumber, ref s) ? s : null!; }
bool NewFw()
{
probed.Add("IsNewFirmwareMachine");
try { return zk.IsNewFirmwareMachine(_machineNumber); }
catch (Exception ex)
{
_log.LogDebug(ex, "COM_PROBE_API_FAILED device={Device} api=IsNewFirmwareMachine generation={Gen} ownerTid={OwnerTid}",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
return false;
}
}
int Status(int id)
{
probed.Add($"GetDeviceStatus({id})");
int v = -1;
return zk.GetDeviceStatus(_machineNumber, id, ref v) ? v : -1;
}
var isNew = NewFw();
string sdk = _worker.SdkVersion;
if (string.IsNullOrEmpty(sdk))
{
probed.Add("GetSDKVersion");
string sv = "";
sdk = zk.GetSDKVersion(ref sv) ? sv : "";
}
return new DeviceCapability(
Serial(), Mac(), Product(), Fw(),
isNew ? "new-architecture" : "legacy",
sdk,
Platform(), Ip(), isNew,
Status(6), Status(9), Status(12),
usersOk ? userCount : -1,
isNew ? "ReadTimeGLogData" : "ReadGeneralLogData",
"RegEvent(1)+OnAttTransactionEx",
probed);
}
catch (Exception ex)
{
_log.LogError(ex, "ProbeCore failed device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _worker.Generation, _worker.OwnerThreadId);
return new DeviceCapability(null, null, null, null, "unknown", _worker.SdkVersion, null, null, false, -1, -1, -1, -1, "ReadGeneralLogData", "RegEvent(1)", probed);
}
}
private AttendanceReadResult ReadAttendanceCore(
CZKEMClass zk,
DateTimeOffset start,
DateTimeOffset end,
AttendanceReadMode mode,
int maxRecords,
bool allowFallback = true,
bool tryTimeWindow = false)
{
// DeviceSessionWorker.InvokeAsync has already asserted the owner thread.
var ownerTid = _worker.OwnerThreadId;
_log.LogInformation(
"COM_READ_OWNER_THREAD=ONLY_OWNER device={Device} ownerThread={Tid} generation={Gen} mode={Mode} start={Start} end={End}",
_deviceId, ownerTid, _worker.Generation, mode, start, end);
var sw = Stopwatch.StartNew();
var records = new List();
string loadApi = "none";
string drainApi = "none";
var windowed = false;
try
{
if (!_connected)
{
sw.Stop();
return new AttendanceReadResult(AttendanceReadStatus.Disconnected, loadApi, null, records, sw.ElapsedMilliseconds, null, "not connected");
}
var isNew = false;
try { isNew = zk.IsNewFirmwareMachine(_machineNumber); }
catch (Exception ex)
{
_log.LogDebug(ex, "COM_PROBE_API_FAILED device={Device} api=IsNewFirmwareMachine generation={Gen} ownerTid={OwnerTid}",
_deviceId, _worker.Generation, ownerTid);
isNew = false;
}
var loadOk = false;
// Window policy:
// * TimeWindow mode always uses the windowed ReadTimeGLogData path.
// * Auto mode uses it ONLY when the caller opted in (request.TryTimeWindow) and the
// caller validates the result against a full-read baseline before trusting it
// (DeviceWorker window-state machine); otherwise Auto goes straight to full-buffer.
// CULTURE: the SDK expects GREGORIAN "yyyy-MM-dd HH:mm:ss" in device-local time. On a
// fa-IR host the default calendar is Jalali, so formatting WITHOUT InvariantCulture
// produced strings like "1405-07-16 ..." and the device rejected the window (lastError=0)
// — which is exactly why windowed reads silently fell back to the 50s full-buffer read.
if (mode == AttendanceReadMode.TimeWindow)
{
loadApi = "ReadTimeGLogData";
drainApi = "SSR_GetGeneralLogData";
var st = start.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
var en = end.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
loadOk = zk.ReadTimeGLogData(_machineNumber, st, en);
if (!loadOk)
{
var primaryErr = GetLastErrorCode(zk);
if (!allowFallback)
{
sw.Stop();
_log.LogError(
"READ_FAILURE api=ReadTimeGLogData ok=False lastError={Err} elapsedMs={Ms} status=CapabilityUnsupported-or-ReadFailure allowFallback=false",
primaryErr, sw.ElapsedMilliseconds);
return new AttendanceReadResult(AttendanceReadStatus.ReadFailure, "ReadTimeGLogData", drainApi, records,
sw.ElapsedMilliseconds, primaryErr, $"ReadTimeGLogData returned false (NOT empty); fallback disabled; lastError={primaryErr}");
}
// Observed on live device BRC7205060126: IsNewFirmwareMachine=true but ReadTimeGLogData=false.
// Phase-1/2 compatibility fallback (documented, not silent): full-buffer load + SSR drain.
_log.LogWarning(
"READ_API_FALLBACK from=ReadTimeGLogData to=ReadGeneralLogData generation={Gen} lastError={Err}",
_worker.Generation, primaryErr);
loadApi = "ReadTimeGLogData->ReadGeneralLogData";
drainApi = "SSR_GetGeneralLogData";
loadOk = zk.ReadGeneralLogData(_machineNumber);
}
}
else if (mode == AttendanceReadMode.NewOnly)
{
loadApi = "ReadNewGLogData";
drainApi = "SSR_GetGeneralLogData";
loadOk = zk.ReadNewGLogData(_machineNumber);
if (!loadOk)
{
if (!allowFallback)
{
sw.Stop();
var nerr = GetLastErrorCode(zk);
return new AttendanceReadResult(AttendanceReadStatus.ReadFailure, "ReadNewGLogData", drainApi, records,
sw.ElapsedMilliseconds, nerr, $"ReadNewGLogData returned false (NOT empty); fallback disabled; lastError={nerr}");
}
_log.LogWarning("READ_API_FALLBACK from=ReadNewGLogData to=ReadGeneralLogData generation={Gen}", _worker.Generation);
loadApi = "ReadNewGLogData->ReadGeneralLogData";
loadOk = zk.ReadGeneralLogData(_machineNumber);
}
}
else
{
// Auto may FIRST try the device-side windowed load: the device then only hands back
// records inside [start,end] (tens/hundreds instead of the whole multi-10k buffer),
// which is the difference between a ~50s and a sub-second read. When the firmware
// rejects the API we fall back to the proven full-buffer load — one extra cheap call
// and exactly the legacy behaviour (never a regression).
var windowedAttempt = mode == AttendanceReadMode.Auto && tryTimeWindow;
if (windowedAttempt)
{
var st = start.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
var en = end.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
if (zk.ReadTimeGLogData(_machineNumber, st, en))
{
windowed = true;
loadOk = true;
loadApi = "ReadTimeGLogData";
drainApi = "SSR_GetGeneralLogData";
}
else
{
var winErr = GetLastErrorCode(zk);
_log.LogWarning(
"READ_TIME_WINDOW_REJECTED device={Device} windowLocal=[{S} .. {E}] lastError={Err} generation={Gen} — falling back to full-buffer read",
_deviceId, st, en, winErr, _worker.Generation);
}
}
if (!windowed)
{
if (windowedAttempt && !allowFallback)
{
// Bounded probe (recreate-time functional check / capability probe): a rejected
// window must NOT silently become a full-buffer ReadGeneralLogData. Fail fast so
// the probe stays sub-second; the scheduled read cycle owns the real read.
sw.Stop();
var winFallbackErr = GetLastErrorCode(zk);
_log.LogWarning(
"READ_WINDOW_FALLBACK_DISABLED api=ReadTimeGLogData lastError={Err} elapsedMs={Ms} generation={Gen}",
winFallbackErr, sw.ElapsedMilliseconds, _worker.Generation);
return new AttendanceReadResult(AttendanceReadStatus.ReadFailure, "ReadTimeGLogData", "none", records,
sw.ElapsedMilliseconds, winFallbackErr, $"windowed load rejected (lastError={winFallbackErr}); full-buffer fallback disabled by caller");
}
loadApi = windowedAttempt ? "ReadTimeGLogData->ReadGeneralLogData" : "ReadGeneralLogData";
// Auto enumerates exclusively via SSR_GetGeneralLogData (fixed architecture);
// LegacyFull keeps its legacy isNew-based drain selection.
drainApi = (mode == AttendanceReadMode.Auto || isNew) ? "SSR_GetGeneralLogData" : "GetGeneralExtLogData";
loadOk = zk.ReadGeneralLogData(_machineNumber);
}
}
if (!loadOk)
{
sw.Stop();
var err = GetLastErrorCode(zk);
_log.LogError(
"READ_FAILURE api={Api} ok=False lastError={Err} elapsedMs={Ms} ownerThread={Tid} generation={Gen} status=ReadFailure",
loadApi, err, sw.ElapsedMilliseconds, ownerTid, _worker.Generation);
return new AttendanceReadResult(AttendanceReadStatus.ReadFailure, loadApi, drainApi, records, sw.ElapsedMilliseconds, err,
$"{loadApi} returned false (NOT empty)");
}
while (records.Count < maxRecords)
{
if (drainApi == "SSR_GetGeneralLogData")
{
string pin;
int verify, inout, y, mo, d, h, mi, s, wc = 0;
if (!zk.SSR_GetGeneralLogData(_machineNumber, out pin, out verify, out inout, out y, out mo, out d, out h, out mi, out s, ref wc))
break;
records.Add(new RawAttendanceEvent(_worker.Generation, pin, false, inout, verify, y, mo, d, h, mi, s, wc, drainApi, DateTimeOffset.UtcNow));
}
else
{
int enroll = 0, verify = 0, inout = 0, y = 0, mo = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0, reserved = 0;
if (!zk.GetGeneralExtLogData(_machineNumber, ref enroll, ref verify, ref inout, ref y, ref mo, ref d, ref h, ref mi, ref s, ref wc, ref reserved))
break;
records.Add(new RawAttendanceEvent(_worker.Generation, enroll.ToString(), false, inout, verify, y, mo, d, h, mi, s, wc, drainApi, DateTimeOffset.UtcNow));
}
}
sw.Stop();
var status = records.Count == 0 ? AttendanceReadStatus.TrueEmpty : AttendanceReadStatus.Success;
_log.LogInformation(
"READ_OK status={Status} loadApi={Load} drainApi={Drain} windowed={W} count={Count} elapsedMs={Ms} ownerThread={Tid} generation={Gen} windowStart={S} windowEnd={E}",
status, loadApi, drainApi, windowed, records.Count, sw.ElapsedMilliseconds, ownerTid, _worker.Generation,
start.ToString("o"), end.ToString("o"));
return new AttendanceReadResult(status, loadApi, drainApi, records, sw.ElapsedMilliseconds, GetLastErrorCode(zk), null, windowed);
}
catch (System.Runtime.InteropServices.COMException ex)
{
sw.Stop();
_log.LogError(ex, "READ_COM_EXCEPTION elapsedMs={Ms} generation={Gen}", sw.ElapsedMilliseconds, _worker.Generation);
return new AttendanceReadResult(AttendanceReadStatus.ComException, loadApi, drainApi, records, sw.ElapsedMilliseconds, ex.HResult, ex.Message);
}
catch (System.Runtime.InteropServices.SEHException ex)
{
sw.Stop();
_log.LogError(ex, "READ_SEH_EXCEPTION elapsedMs={Ms} generation={Gen}", sw.ElapsedMilliseconds, _worker.Generation);
return new AttendanceReadResult(AttendanceReadStatus.ComException, loadApi, drainApi, records, sw.ElapsedMilliseconds, ex.HResult, ex.Message);
}
catch (Exception ex)
{
sw.Stop();
_log.LogError(ex, "READ_EXCEPTION elapsedMs={Ms} generation={Gen}", sw.ElapsedMilliseconds, _worker.Generation);
return new AttendanceReadResult(AttendanceReadStatus.ComException, loadApi, drainApi, records, sw.ElapsedMilliseconds, null, ex.Message);
}
}
}