using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ZKTecoSyncService.Models;
using ZKTecoSyncService.Protocol;
namespace ZKTecoSyncService.Services;
///
/// High-level protocol wrapper for ZKTeco device communication.
/// Uses COM Interop (zkemkeeper.CZKEMClass) — the same SDK used by StandaloneSDKDemo.
/// Same public API as before — DeviceConnectionService requires minimal changes.
///
public class ZKTecoProtocol : IDisposable
{
private zkemkeeper.CZKEMClass? _zkem;
private readonly string _ip;
private readonly int _port;
private readonly int _commKey;
private readonly int _machineNumber;
private readonly int _connectTimeoutMs;
private readonly int _readTimeoutMs;
private readonly ProtocolLogger? _logger;
private readonly DeviceTimeNormalizer _deviceTimeNormalizer;
private readonly object _sessionLock = new();
private volatile bool _connected;
private Action? _onLivePunch;
// ─── Failure trap diagnostic ──────────────────────────────────────
///
/// Invoked when reader enumeration failure is detected:
/// ReadGeneralLogData=TRUE + SSR_GetGeneralLogData(first)=FALSE + GetLogCount>0.
/// The snapshot uses the EXISTING _zkem instance — no new COM session is created.
///
public Action? OnReaderEnumerationFailure { get; set; }
// ─── Health telemetry ────────────────────────────────────────────────
public DateTime? LastConnectionSuccessAt { get; private set; }
public DateTime? LastSuccessfulReadAt { get; private set; }
public int ConsecutiveConnectionFailures { get; private set; }
public int ConsecutiveReadFailures { get; private set; }
public long ParseFailureCount { get; private set; }
public string? LastError { get; private set; }
public DateTime? LastErrorAt { get; private set; }
public bool IsConnected => _connected && _zkem != null;
// ─── Event listener lifecycle ────────────────────────────────────────
private bool _eventListenerActive;
private Action? _onEventListenerStopped;
///
/// Timestamp of the last live event received from this device.
/// Used to detect silently dead event listeners (COM callback dropped without error).
///
public DateTime? LastEventReceivedAt { get; private set; }
///
/// COM callback model: listener is "running" if callback is registered AND session is alive.
/// No Task to monitor — COM fires callbacks directly.
///
public bool IsEventListenerRunning => _eventListenerActive && _connected && _zkem != null;
public ZKTecoProtocol(string ip, int port, int commKey = 0, int machineNumber = 1,
int connectTimeoutMs = 5000, int readTimeoutMs = 10000,
ProtocolLogger? logger = null, DeviceTimeNormalizer? deviceTimeNormalizer = null)
{
_ip = ip;
_port = port;
_commKey = commKey;
_machineNumber = machineNumber;
_connectTimeoutMs = connectTimeoutMs;
_readTimeoutMs = readTimeoutMs;
_logger = logger;
_deviceTimeNormalizer = deviceTimeNormalizer ?? new DeviceTimeNormalizer("Local", null);
}
// ═════════════════════════════════════════════════════════════════════
// STA THREAD HELPER — retained for non-connect COM calls
// (GetDeviceInfo, GetLogCount, TestConnection, CleanLogData)
// Connect_Net MUST NOT use this — cross-apartment proxy fails (Scenario E).
// ═════════════════════════════════════════════════════════════════════
private bool RunOnStaThread(Action action, int timeoutMs)
{
Exception? captured = null;
var done = new ManualResetEventSlim(false);
var thread = new Thread(() =>
{
try { action(); }
catch (Exception ex) { captured = ex; }
finally { done.Set(); }
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
if (!done.Wait(timeoutMs))
{
try { thread.Interrupt(); } catch { }
return false;
}
if (captured != null) throw captured;
return true;
}
private (bool success, T value) RunOnStaThread(Func func, int timeoutMs)
{
T value = default!;
Exception? captured = null;
var done = new ManualResetEventSlim(false);
var thread = new Thread(() =>
{
try { value = func(); }
catch (Exception ex) { captured = ex; }
finally { done.Set(); }
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
if (!done.Wait(timeoutMs))
{
try { thread.Interrupt(); } catch { }
return (false, default!);
}
if (captured != null) throw captured;
return (true, value);
}
// ═════════════════════════════════════════════════════════════════════
// CONNECT / DISCONNECT
// ═════════════════════════════════════════════════════════════════════
public bool Connect()
{
lock (_sessionLock)
{
DisconnectInternal();
try
{
_zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) _zkem.SetCommPassword(_commKey);
// COM THREAD MATRIX FIX: Call Connect_Net directly on calling thread (MTA).
// Matrix result: MTA→MTA same-thread succeeds (Scenario A, 111s).
// RunOnStaThread created cross-apartment proxy (MTA→STA) which fails
// when STA is true (Scenario E, 0ms). Do NOT wrap in RunOnStaThread.
var sw = Stopwatch.StartNew();
bool connectResult = _zkem.Connect_Net(_ip, _port);
sw.Stop();
if (!connectResult)
{
int nativeError = -1;
try { _zkem.GetLastError(ref nativeError); } catch { }
int threadId = Environment.CurrentManagedThreadId;
string aptState = Thread.CurrentThread.GetApartmentState().ToString();
_connected = false;
LastError = $"Connect_Net=false elapsed={sw.ElapsedMilliseconds}ms nativeError={nativeError} thread={threadId} apt={aptState}";
LastErrorAt = DateTime.UtcNow;
ConsecutiveConnectionFailures++;
DisposeSessionUnsafe();
return false;
}
_connected = true;
LastConnectionSuccessAt = DateTime.UtcNow;
ConsecutiveConnectionFailures = 0;
LastError = null;
return true;
}
catch (Exception ex)
{
_connected = false;
ConsecutiveConnectionFailures++;
LastError = ex.Message;
LastErrorAt = DateTime.UtcNow;
DisposeSessionUnsafe();
return false;
}
}
}
public Task ConnectAsync(CancellationToken ct = default)
{
return Task.FromResult(Connect());
}
public void Disconnect()
{
lock (_sessionLock)
{
DisableRealTimeEvents();
DisconnectInternal();
}
}
public Task DisconnectAsync()
{
Disconnect();
return Task.CompletedTask;
}
private void DisconnectInternal()
{
// CRITICAL: Do NOT call _zkem.Disconnect() — corrupts COM state.
// Properly release COM reference instead.
_connected = false;
if (_zkem != null)
{
try { System.Runtime.InteropServices.Marshal.ReleaseComObject(_zkem); } catch { }
_zkem = null;
}
}
private void DisposeSessionUnsafe()
{
DisableRealTimeEvents();
_connected = false;
_zkem = null;
}
// ═════════════════════════════════════════════════════════════════════
// READ LOGS (Incremental — buffers every 500 records)
// ═════════════════════════════════════════════════════════════════════
///
/// Read all logs from device, invoking callback for each batch of records.
/// Progress-based timeout: if records are still arriving, never timeout.
/// Only times out if no records arrive for _readTimeoutMs.
/// Returns total count of records read.
///
public int ReadAllLogsIncremental(Action> onBatch, CancellationToken ct = default)
{
lock (_sessionLock)
{
if (!IsConnected || _zkem == null) return 0;
int totalRead = 0;
Exception? readException = null;
var readComplete = new ManualResetEventSlim(false);
var sessionStarted = DateTime.UtcNow;
var thread = new Thread(() =>
{
try
{
// ─── DIAGNOSTIC: ReadGeneralLogData with GetLastError ───
var readSw = Stopwatch.StartNew();
bool readResult = _zkem.ReadGeneralLogData(_machineNumber);
readSw.Stop();
int readErr = -999;
_zkem.GetLastError(ref readErr);
// ─── DIAGNOSTIC: SSR first call (failure detection only) ───
// This call reads the first record from the COM enumeration cursor.
// If healthy, we process it below. If failure, we trap and return.
var ssrFirstSw = Stopwatch.StartNew();
string enrollNumber = ""; int verifyMode = 0, inOutMode = 0;
int y = 0, m = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0;
bool ssrFirst = readResult && _zkem.SSR_GetGeneralLogData(_machineNumber,
out enrollNumber, out verifyMode, out inOutMode,
out y, out m, out d, out h, out mi, out s, ref wc);
ssrFirstSw.Stop();
int ssrFirstErr = -999;
_zkem.GetLastError(ref ssrFirstErr);
// ─── FAILURE TRAP: detect enumeration failure signature ───
if (readResult && !ssrFirst)
{
int logCountAtFailure = 0;
_zkem.GetDeviceStatus(_machineNumber, 6, ref logCountAtFailure);
if (logCountAtFailure > 0)
{
var detectedAt = DateTime.UtcNow;
int threadId = Environment.CurrentManagedThreadId;
string aptState = Thread.CurrentThread.GetApartmentState().ToString();
string comId = $"COM_{_zkem.GetHashCode()}(0x{RuntimeHelpers.GetHashCode(_zkem):X8})";
string fw = "", mac = "", plat = "", sn = "";
int uc = 0;
try
{
_zkem.GetFirmwareVersion(_machineNumber, ref fw);
_zkem.GetDeviceMAC(_machineNumber, ref mac);
_zkem.GetPlatform(_machineNumber, ref plat);
_zkem.GetSerialNumber(_machineNumber, out sn);
_zkem.GetDeviceStatus(_machineNumber, 2, ref uc);
}
catch { }
var snapshot = new ReaderFailureSnapshot
{
SchemaVersion = "1.0",
TrapId = $"TRAP_{detectedAt:yyyyMMdd_HHmmss}_{_ip.Replace(".", "")}",
Device = new SnapshotDevice
{
Ip = _ip, Port = _port,
Firmware = fw, Platform = plat,
Serial = sn, Mac = mac, UserCount = uc
},
Failure = new SnapshotFailure
{
Signature = "GetLogCount>0 AND ReadGeneralLogData=TRUE AND SSR_FIRST=FALSE",
DetectedAtUtc = detectedAt,
GetLogCount = logCountAtFailure,
ReadGeneralResult = true,
ReadGeneralGetLastError = readErr,
SsrFirstResult = false,
SsrFirstGetLastError = ssrFirstErr,
IsEnumerationFailure = true
},
ComSession = new SnapshotComSession
{
ComInstanceId = comId,
ComHashCode = RuntimeHelpers.GetHashCode(_zkem),
ThreadId = threadId,
ApartmentState = aptState,
SessionAgeMs = (long)(detectedAt - sessionStarted).TotalMilliseconds,
ConnectionState = _connected ? "CONNECTED" : "DISCONNECTED",
IsConnected = _connected,
EventListenerRunning = _eventListenerActive,
SessionStartUtc = sessionStarted
},
ReadDiagnostics = new SnapshotReadDiagnostics
{
ReadDurationMs = readSw.ElapsedMilliseconds,
SsrFirstDurationMs = ssrFirstSw.ElapsedMilliseconds,
LastReadSuccessAtUtc = LastSuccessfulReadAt,
LastReadPunchTime = null,
ReadSuccessCount = 0,
ReadFailureCount = 1,
ConsecutiveReadFailures = ConsecutiveReadFailures + 1,
LastReadError = $"READER_ENUMERATION_FAILURE: Read=TRUE({readErr}) SSR_FIRST=FALSE({ssrFirstErr}) LogCount={logCountAtFailure}",
LastReadErrorAt = detectedAt,
ParseFailureCount = ParseFailureCount
},
LiveCorrelation = new SnapshotLiveCorrelation
{
LastEventReceivedAt = LastEventReceivedAt,
LastEnrollNumber = "",
LastEventDeviceTime = "",
EventsActive = _eventListenerActive,
ConsecutiveEventFailures = 0,
TotalDroppedCapacityFull = 0
},
ProductionState = new SnapshotProductionState
{
IsOnline = _connected,
ReconnectCount = 0,
LastSuccessfulConnection = LastConnectionSuccessAt,
LastSuccessfulSync = null,
LastPunchTime = "",
InitialReadPending = true,
StateMachine = "Faulted"
},
Environment = new SnapshotEnvironment
{
TimestampUtc = detectedAt,
OsVersion = Environment.OSVersion.ToString(),
DotnetVersion = Environment.Version.ToString(),
ProcessId = Process.GetCurrentProcess().Id,
MachineName = Environment.MachineName
}
};
try { OnReaderEnumerationFailure?.Invoke(snapshot); } catch { }
LastError = snapshot.Failure.Signature;
LastErrorAt = detectedAt;
return;
}
}
// ─── NORMAL PATH: SSR enumeration ───
// ssrFirst already consumed the first record from the COM cursor.
// Process it here so it is NOT lost. Then continue reading the rest.
var batch = new List(500);
bool ssrFirstRead = false;
while (true)
{
if (!ssrFirst || ssrFirstRead)
{
// Read next record (or first time if diagnostic SSR was not called)
if (!_zkem.SSR_GetGeneralLogData(_machineNumber, out enrollNumber, out verifyMode, out inOutMode, out y, out m, out d, out h, out mi, out s, ref wc))
break;
}
ssrFirstRead = true;
ct.ThrowIfCancellationRequested();
var punchTime = _deviceTimeNormalizer.NormalizeToUtc(y, m, d, h, mi, s);
batch.Add(new AttendanceLog
{
DeviceIp = _ip, DevicePort = _port,
PersonnelCode = enrollNumber?.Trim() ?? string.Empty,
PunchTime = punchTime,
PunchType = inOutMode == 0 ? "in" : "out",
VerifyMode = MapVerifyMode(verifyMode),
WorkCode = wc,
});
if (batch.Count >= 500)
{
onBatch(batch);
totalRead += batch.Count;
batch = new List(500);
}
}
if (batch.Count > 0)
{
onBatch(batch);
totalRead += batch.Count;
}
}
catch (Exception ex) { readException = ex; }
finally { readComplete.Set(); }
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
try { while (!readComplete.Wait(5000)) { ct.ThrowIfCancellationRequested(); } }
catch (OperationCanceledException) { LastError = "ReadAllLogs cancelled"; LastErrorAt = DateTime.UtcNow; return totalRead; }
if (readException != null) { ConsecutiveReadFailures++; LastError = readException.Message; LastErrorAt = DateTime.UtcNow; DisposeSessionUnsafe(); return totalRead; }
LastSuccessfulReadAt = DateTime.UtcNow;
ConsecutiveReadFailures = 0;
LastError = null;
return totalRead;
}
}
public List ReadAllLogs()
{
var allLogs = new List();
ReadAllLogsIncremental(batch => allLogs.AddRange(batch));
return allLogs;
}
public Task> ReadAllLogsAsync(CancellationToken ct = default)
{
return Task.FromResult(ReadAllLogs());
}
// ═════════════════════════════════════════════════════════════════════
// REAL-TIME EVENTS (COM Interop)
// ═════════════════════════════════════════════════════════════════════
public void SetEventListenerStoppedCallback(Action callback)
{
_onEventListenerStopped = callback;
}
public bool EnableRealTimeEvents(Action onLivePunch)
{
lock (_sessionLock)
{
if (_zkem == null || !_connected) return false;
if (_onLivePunch != null) return true;
try
{
_onLivePunch = onLivePunch;
_zkem.OnAttTransactionEx += OnAttTransactionExHandler;
var ok = _zkem.RegEvent(_machineNumber, 65535);
if (!ok) { DisableRealTimeEvents(); return false; }
_eventListenerActive = true;
return true;
}
catch (Exception ex)
{
Console.WriteLine($"[{_ip}] RegEvent failed: {ex.Message}");
DisableRealTimeEvents();
return false;
}
}
}
public Task EnableRealTimeEventsAsync(Action onLivePunch, CancellationToken ct = default)
{
return Task.FromResult(EnableRealTimeEvents(onLivePunch));
}
public void DisableRealTimeEvents()
{
try { if (_zkem != null && _onLivePunch != null) _zkem.OnAttTransactionEx -= OnAttTransactionExHandler; } catch { }
_onLivePunch = null;
_eventListenerActive = false;
}
public Task StopEventListenerAsync()
{
DisableRealTimeEvents();
return Task.CompletedTask;
}
private void OnAttTransactionExHandler(string enrollNumber, int isInValid, int attState,
int verifyMethod, int year, int month, int day, int hour, int minute, int second, int workCode)
{
try
{
LastEventReceivedAt = DateTime.UtcNow;
var punchTime = _deviceTimeNormalizer.NormalizeToUtc(year, month, day, hour, minute, second);
var log = new AttendanceLog
{
DeviceIp = _ip, DevicePort = _port,
PersonnelCode = enrollNumber?.Trim() ?? string.Empty,
PunchTime = punchTime,
PunchType = attState == 1 ? "out" : "in",
VerifyMode = MapVerifyMode(verifyMethod),
WorkCode = workCode,
};
_onLivePunch?.Invoke(log);
}
catch { }
}
// ═════════════════════════════════════════════════════════════════════
// DEVICE INFO
// ═════════════════════════════════════════════════════════════════════
public DeviceStatus? GetDeviceInfo()
{
lock (_sessionLock)
{
if (!IsConnected || _zkem == null) return null;
try
{
var (ok, deviceResult) = RunOnStaThread(() =>
{
string fw = "", mac = "", plat = "", sn = "";
_zkem.GetFirmwareVersion(_machineNumber, ref fw);
_zkem.GetDeviceMAC(_machineNumber, ref mac);
_zkem.GetPlatform(_machineNumber, ref plat);
_zkem.GetSerialNumber(_machineNumber, out sn);
int uc = 0, lc = 0;
_zkem.GetDeviceStatus(_machineNumber, 2, ref uc);
_zkem.GetDeviceStatus(_machineNumber, 6, ref lc);
return new DeviceStatus
{
DeviceIp = _ip, DevicePort = _port,
DeviceSerial = sn, Status = "online",
FirmwareVersion = fw, UserCount = uc, LogCount = lc,
};
}, _readTimeoutMs + 2000);
if (!ok)
{
LastError = $"GetDeviceInfo timeout ({_readTimeoutMs}ms)";
LastErrorAt = DateTime.UtcNow;
DisposeSessionUnsafe();
return new DeviceStatus { DeviceIp = _ip, DevicePort = _port, Status = "error" };
}
return deviceResult;
}
catch
{
DisposeSessionUnsafe();
return new DeviceStatus { DeviceIp = _ip, DevicePort = _port, Status = "error" };
}
}
}
public Task GetDeviceInfoAsync(CancellationToken ct = default)
{
return Task.FromResult(GetDeviceInfo());
}
public int GetLogCount()
{
lock (_sessionLock)
{
if (!IsConnected || _zkem == null) return -1;
try
{
var (ok, logCount) = RunOnStaThread(() =>
{
int lc = 0;
return _zkem.GetDeviceStatus(_machineNumber, 6, ref lc) ? lc : -1;
}, _readTimeoutMs + 2000);
if (!ok)
{
ConsecutiveReadFailures++;
LastError = $"GetLogCount timeout ({_readTimeoutMs}ms)";
LastErrorAt = DateTime.UtcNow;
DisposeSessionUnsafe();
return -1;
}
return logCount;
}
catch
{
DisposeSessionUnsafe();
return -1;
}
}
}
public Task GetLogCountAsync(CancellationToken ct = default)
{
return Task.FromResult(GetLogCount());
}
public bool TestConnection()
{
lock (_sessionLock)
{
if (!IsConnected || _zkem == null) return false;
try
{
var (ok, testResult) = RunOnStaThread(() =>
{
string sn = "";
return _zkem.GetSerialNumber(_machineNumber, out sn);
}, _readTimeoutMs + 2000);
if (!ok || !testResult)
{
LastError = !ok ? $"TestConnection timeout ({_readTimeoutMs}ms)" : "TestConnection returned false";
LastErrorAt = DateTime.UtcNow;
DisposeSessionUnsafe();
return false;
}
LastConnectionSuccessAt = DateTime.UtcNow;
return true;
}
catch (Exception ex)
{
LastError = $"TestConnection error: {ex.Message}";
LastErrorAt = DateTime.UtcNow;
DisposeSessionUnsafe();
return false;
}
}
}
public Task TestConnectionAsync(CancellationToken ct = default)
{
return Task.FromResult(TestConnection());
}
// ═════════════════════════════════════════════════════════════════════
// CLEAN DEVICE LOG
// ═════════════════════════════════════════════════════════════════════
///
/// Clear device attendance log after successful sync.
/// MUST only be called after ALL records are confirmed in MySQL.
///
public bool CleanLogData()
{
lock (_sessionLock)
{
if (!IsConnected || _zkem == null) return false;
try
{
var (ok, cleanResult) = RunOnStaThread(() => _zkem.ClearData(_machineNumber, 1), _readTimeoutMs + 2000); // 1 = attendance log
if (!ok)
{
LastError = $"CleanData timeout ({_readTimeoutMs}ms)";
LastErrorAt = DateTime.UtcNow;
return false;
}
return cleanResult;
}
catch (Exception ex)
{
LastError = ex.Message;
LastErrorAt = DateTime.UtcNow;
return false;
}
}
}
// ═════════════════════════════════════════════════════════════════════
// RESET / DISPOSE
// ═════════════════════════════════════════════════════════════════════
public void ResetSession()
{
lock (_sessionLock)
{
DisposeSessionUnsafe();
ConsecutiveReadFailures = 0;
}
}
public void EnableDevice()
{
if (_zkem != null && _connected) try { _zkem.EnableDevice(_machineNumber, true); } catch { }
}
public void Dispose()
{
lock (_sessionLock)
{
DisableRealTimeEvents();
DisposeSessionUnsafe();
}
GC.SuppressFinalize(this);
}
// ═════════════════════════════════════════════════════════════════════
// HELPERS
// ═════════════════════════════════════════════════════════════════════
private static string MapVerifyMode(int mode) => mode switch
{
0 => "password", 1 => "fingerprint", 2 => "card",
3 => "fingerprint_password", 15 => "face", 25 => "face_card",
_ => $"mode_{mode}"
};
}