using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace ZKTecoSyncService.Tests;
///
/// Reader Failure Diagnostic Tests
///
/// Controlled tests to determine the actual failure mechanism when:
/// - Connect_Net remains healthy
/// - GetDeviceInfo works
/// - GetLogCount reports correct device record count
/// - ReadGeneralLogData returns TRUE
/// - SSR_GetGeneralLogData returns 0 records
/// - New attendance records exist on device but are not imported
/// - Windows Service restart immediately restores previously missed records
///
/// Target: 172.20.30.221 (preferred, if currently in bad state)
///
/// Usage:
/// dotnet test --filter "FullyQualifiedName~TEST2_ReaderFailureDiagnostic"
/// dotnet test --filter "FullyQualifiedName~TEST2_ReaderFailureDiagnostic.Test1"
/// dotnet test --filter "FullyQualifiedName~TEST2_ReaderFailureDiagnostic.RunAll_Sequential"
///
/// Env: TestDevice:Ip (default 172.20.30.221), TestDevice:Port (4370)
///
public class TEST2_ReaderFailureDiagnostic
{
private readonly string _ip;
private readonly int _port;
private readonly int _commKey;
private readonly int _machine;
public TEST2_ReaderFailureDiagnostic()
{
_ip = Environment.GetEnvironmentVariable("TestDevice:Ip") ?? "172.20.30.221";
_port = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:Port"), out var p) ? p : 4370;
_commKey = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:CommKey"), out var k) ? k : 0;
_machine = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:MachineNumber"), out var m) ? m : 1;
}
private static int GetError(zkemkeeper.CZKEMClass zkem)
{
int err = -999;
zkem.GetLastError(ref err);
return err;
}
private static int EnumerateSSR(zkemkeeper.CZKEMClass zkem, int machine, int maxRecords = 100000)
{
string enroll = ""; int vm = 0, io = 0, y = 0, m = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0;
int count = 0;
while (count < maxRecords && zkem.SSR_GetGeneralLogData(machine, out enroll, out vm, out io, out y, out m, out d, out h, out mi, out s, ref wc))
count++;
return count;
}
// =================================================================
// TEST 1 - GetLastError after empty enumeration
// =================================================================
[Fact]
public void Test1_GetLastError_After_Empty_Enumeration()
{
Console.WriteLine($"TEST 1: GetLastError after enumeration | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Does the SDK report an error or just 'no more'?\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [0] Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
int lc = 0; zkem.GetDeviceStatus(_machine, 6, ref lc);
Console.WriteLine($" [1] GetLogCount: {lc}");
bool readOk = zkem.ReadGeneralLogData(_machine);
Console.WriteLine($" [2] ReadGeneralLogData: {readOk}");
int errAfterRead = GetError(zkem);
Console.WriteLine($" [3] GetLastError after Read: {errAfterRead}");
string enroll = ""; int vm = 0, io = 0, y = 0, m = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0;
bool ssrFirst = zkem.SSR_GetGeneralLogData(_machine, out enroll, out vm, out io, out y, out m, out d, out h, out mi, out s, ref wc);
Console.WriteLine($" [4] SSR_GetGeneralLogData (first): {ssrFirst}");
if (ssrFirst)
Console.WriteLine($" Record: enroll={enroll} verify={vm} io={io} time={y}-{m:D2}-{d:D2} {h:D2}:{mi:D2}:{s:D2} wc={wc}");
int errAfterSsr1 = GetError(zkem);
Console.WriteLine($" [5] GetLastError after SSR (first): {errAfterSsr1}");
int ssrCount = ssrFirst ? 1 : 0;
if (ssrFirst)
{
while (zkem.SSR_GetGeneralLogData(_machine, out enroll, out vm, out io, out y, out m, out d, out h, out mi, out s, ref wc))
ssrCount++;
}
Console.WriteLine($" [6] SSR completed: {ssrCount} records enumerated");
int errAfterSsrEx = GetError(zkem);
Console.WriteLine($" [7] GetLastError after SSR exhausted: {errAfterSsrEx}");
Console.WriteLine($@"
=== TEST 1 RESULTS ===
GetLogCount: {lc}
ReadGeneralLogData: {readOk}
GetLastError after Read: {errAfterRead}
SSR first call: {ssrFirst}
SSR records enumerated: {ssrCount}
GetLastError after SSR 1: {errAfterSsr1}
GetLastError after SSR ex:{errAfterSsrEx}
INTERPRETATION:
GetLastError=0 after SSR returns false with 0 records:
-> SDK thinks enumeration is normal (internal cursor/reader corruption)
GetLastError!=0:
-> SDK knows something is wrong but does not propagate it to caller
KEY: When device is in bad state, does GetLastError show error or 0?
");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 2 - Repeat ReadGeneralLogData without reconnect
//
// A: GetLogCount -> ReadGeneralLogData -> SSR enumeration
// B: ReadGeneralLogData again -> SSR enumeration again
// Do NOT disconnect between A and B.
//
// B returns records -> stale internal enumeration buffer/cursor
// B returns zero while GetLogCount > 0 -> unhealthy SDK/session state
// =================================================================
[Fact]
public void Test2_Repeat_ReadGeneralLogData_No_Reconnect()
{
Console.WriteLine($"TEST 2: Repeat ReadGeneralLogData without reconnect | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Stale buffer vs unhealthy SDK/session state\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
Console.WriteLine("\n --- ROUND A ---");
int lcA = 0; zkem.GetDeviceStatus(_machine, 6, ref lcA);
bool readA = zkem.ReadGeneralLogData(_machine);
int countA = readA ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" A: GetLogCount={lcA}, ReadGeneralLogData={readA}, SSR={countA}");
// NO DISCONNECT/RECONNECT
Console.WriteLine("\n --- ROUND B (immediate, no reconnect) ---");
int lcB = 0; zkem.GetDeviceStatus(_machine, 6, ref lcB);
bool readB = zkem.ReadGeneralLogData(_machine);
int countB = readB ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" B: GetLogCount={lcB}, ReadGeneralLogData={readB}, SSR={countB}");
string interp = countA == 0 && countB > 0 ? "STALE_CURSOR: B found records A missed" :
countA == 0 && countB == 0 && lcA > 0 ? "UNHEALTHY_SDK: both return 0 but count > 0" :
countA > 0 ? "NORMAL: A consumed all records" : "NO_RECORDS: device is empty";
Console.WriteLine($"\n Interpretation: {interp}");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 3 - Re-register events without reconnect
//
// Baseline -> RegEvent(65535) -> probe again
// Determine whether re-registration changes reader behavior.
// =================================================================
[Fact]
public void Test3_ReRegister_Events_No_Reconnect()
{
Console.WriteLine($"TEST 3: Re-register events without reconnect | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Does RegEvent(65535) change reader behavior?\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
Console.WriteLine("\n --- BASELINE (before RegEvent) ---");
int lcBefore = 0; zkem.GetDeviceStatus(_machine, 6, ref lcBefore);
bool readBefore = zkem.ReadGeneralLogData(_machine);
int countBefore = readBefore ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" Before: GetLogCount={lcBefore}, Read={readBefore}, SSR={countBefore}");
Console.WriteLine("\n --- RegEvent(65535) ---");
bool regResult = zkem.RegEvent(_machine, 65535);
Console.WriteLine($" RegEvent(65535): {regResult}");
Console.WriteLine("\n --- AFTER RegEvent ---");
int lcAfter = 0; zkem.GetDeviceStatus(_machine, 6, ref lcAfter);
bool readAfter = zkem.ReadGeneralLogData(_machine);
int countAfter = readAfter ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" After: GetLogCount={lcAfter}, Read={readAfter}, SSR={countAfter}");
string interp = countBefore == 0 && countAfter > 0 ? "REGEVENT_FIXES: reader restored" :
countBefore == 0 && countAfter == 0 ? "REGEVENT_NO_EFFECT: reader still broken" :
countBefore > 0 ? "HEALTHY_DEVICE: not in bad state" : "NO_RECORDS";
Console.WriteLine($"\n Interpretation: {interp}");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 4 - Disconnect/Reconnect only (same CZKEMClass)
//
// Disconnect -> no new CZKEMClass -> Connect again -> probe
// Determine whether the SAME CZKEMClass recovers.
// =================================================================
[Fact]
public void Test4_Disconnect_Reconnect_Same_Instance()
{
Console.WriteLine($"TEST 4: Disconnect/Reconnect same instance | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Does same CZKEMClass recover after reconnect?\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [INITIAL] Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
int lcInit = 0; zkem.GetDeviceStatus(_machine, 6, ref lcInit);
Console.WriteLine($" [INITIAL] GetLogCount: {lcInit}");
Console.WriteLine("\n [DISCONNECT] Calling Disconnect()...");
zkem.Disconnect();
Thread.Sleep(1000);
Console.WriteLine(" [RECONNECT] Calling Connect_Net() on same instance...");
connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [RECONNECT] Connect_Net: {connected}");
if (!connected)
{
Console.WriteLine(" RECONNECT FAILED - cannot continue");
return;
}
bool regOk = zkem.RegEvent(_machine, 65535);
Console.WriteLine($" [POST-RECONNECT] RegEvent(65535): {regOk}");
int lcReconnect = 0; zkem.GetDeviceStatus(_machine, 6, ref lcReconnect);
bool readReconnect = zkem.ReadGeneralLogData(_machine);
int countReconnect = readReconnect ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" [POST-RECONNECT] GetLogCount={lcReconnect}, Read={readReconnect}, SSR={countReconnect}");
string interp = countReconnect > 0 ? "RECONNECT_WORKS: same instance recovered" :
countReconnect == 0 && lcReconnect > 0 ? "RECONNECT_FAILS: same instance still broken" :
"NO_RECORDS";
Console.WriteLine($"\n Interpretation: {interp}");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 5 - Dispose/Recreate CZKEMClass
//
// Release old instance -> new CZKEMClass -> Connect -> probe
// Determine whether recreation is the recovery boundary.
// =================================================================
[Fact]
public void Test5_Dispose_Recreate_CZKEMClass()
{
Console.WriteLine($"TEST 5: Dispose/Recreate CZKEMClass | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Is COM object recreation the recovery boundary?\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [OLD] Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
int lcOld = 0; zkem.GetDeviceStatus(_machine, 6, ref lcOld);
Console.WriteLine($" [OLD] GetLogCount: {lcOld}");
Console.WriteLine("\n [DISPOSE] Marshal.ReleaseComObject...");
try { Marshal.ReleaseComObject(zkem); } catch { }
zkem = null;
Thread.Sleep(1000);
Console.WriteLine(" [CREATE] new CZKEMClass()...");
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [NEW] Connect_Net: {connected}");
if (!connected) { Console.WriteLine(" NEW CONNECT FAILED"); return; }
bool regOk = zkem.RegEvent(_machine, 65535);
Console.WriteLine($" [NEW] RegEvent(65535): {regOk}");
int lcNew = 0; zkem.GetDeviceStatus(_machine, 6, ref lcNew);
bool readNew = zkem.ReadGeneralLogData(_machine);
int countNew = readNew ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" [NEW] GetLogCount={lcNew}, Read={readNew}, SSR={countNew}");
string interp = countNew > 0 ? "RECREATE_WORKS: fresh COM object restored reader" :
countNew == 0 && lcNew > 0 ? "RECREATE_FAILS: even fresh COM cannot read" :
"NO_RECORDS";
Console.WriteLine($"\n Interpretation: {interp}");
Console.WriteLine(" NOTE: This matches production behavior (service restart = new COM object)");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 6 - Live event health during reader failure
//
// While device is in bad reader state, perform one physical punch.
// Observe: OnAttTransactionEx, callback thread/timestamp,
// GetLogCount increment, SSR visibility of new record.
//
// Distinguishes: A) reader-only B) reader+event C) app pipeline
//
// ACTION REQUIRED: Perform ONE physical punch within 120 seconds
// =================================================================
[Fact]
public void Test6_Live_Event_Health_During_Reader_Failure()
{
Console.WriteLine($"TEST 6: Live event health during reader failure | Device: {_ip}:{_port}");
Console.WriteLine("ACTION: Perform ONE physical punch within 120 seconds\n");
zkemkeeper.CZKEMClass? zkem = null;
var eventReceived = new ManualResetEventSlim(false);
int cbThreadId = 0;
ApartmentState cbApartment = ApartmentState.Unknown;
bool cbIsThreadPool = false;
DateTime cbTimestamp = DateTime.MinValue;
string? cbPersonnel = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Connect_Net: {connected}");
Assert.True(connected, "Connect_Net failed");
int lcBefore = 0; zkem.GetDeviceStatus(_machine, 6, ref lcBefore);
bool readBefore = zkem.ReadGeneralLogData(_machine);
int ssrBefore = readBefore ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" BASELINE: GetLogCount={lcBefore}, SSR={ssrBefore}\n");
zkem.OnAttTransactionEx += (string enrollNumber, int isInValid, int attState,
int verifyMethod, int year, int month, int day, int hour, int minute, int second, int workCode) =>
{
cbThreadId = Thread.CurrentThread.ManagedThreadId;
cbApartment = Thread.CurrentThread.GetApartmentState();
cbIsThreadPool = Thread.CurrentThread.IsThreadPoolThread;
cbTimestamp = DateTime.UtcNow;
cbPersonnel = enrollNumber;
eventReceived.Set();
Console.WriteLine($" [CALLBACK] Thread {cbThreadId} ({cbApartment}) - {enrollNumber}");
};
bool regOk = zkem.RegEvent(_machine, 65535);
Console.WriteLine($" RegEvent(65535): {regOk}");
Console.WriteLine("\n Waiting for punch (120s)...");
bool gotEvent = eventReceived.Wait(TimeSpan.FromSeconds(120));
int lcAfter = 0; zkem.GetDeviceStatus(_machine, 6, ref lcAfter);
bool readAfter = zkem.ReadGeneralLogData(_machine);
int ssrAfter = readAfter ? EnumerateSSR(zkem, _machine) : 0;
bool logCountIncremented = lcAfter > lcBefore;
bool ssrCanSeeNewRecord = ssrAfter > ssrBefore;
string classification;
if (gotEvent && !logCountIncremented && !ssrCanSeeNewRecord)
classification = "A) READER-ONLY FAILURE - events work, SSR broken";
else if (!gotEvent && !logCountIncremented && !ssrCanSeeNewRecord)
classification = "B) READER + EVENT FAILURE - both broken";
else if (gotEvent && logCountIncremented && ssrCanSeeNewRecord)
classification = "HEALTHY - all components working (not in bad state)";
else
classification = "MIXED - partial failure state";
Console.WriteLine($@"
=== TEST 6 RESULTS ===
Event fired: {gotEvent}
Callback thread: {cbThreadId} ({cbApartment})
Callback timestamp: {cbTimestamp:O}
Callback personnel: {cbPersonnel ?? "N/A"}
Log count before: {lcBefore} after: {lcAfter} incremented: {logCountIncremented}
SSR before: {ssrBefore} after: {ssrAfter} sees new: {ssrCanSeeNewRecord}
CLASSIFICATION: {classification}");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 7 - Inspect COM error handling
//
// Confirm whether production calls GetLastError.
// For every critical COM method: return value + SDK GetLastError.
// =================================================================
[Fact]
public void Test7_Inspect_COM_Error_Handling()
{
Console.WriteLine($"TEST 7: Inspect COM error handling | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Audit what production actually checks\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" [1] Connect_Net: {connected}, GetLastError={GetError(zkem)}");
string sn = ""; bool snOk = zkem.GetSerialNumber(_machine, out sn);
Console.WriteLine($" [2] GetSerialNumber: {snOk} (sn={sn}), GetLastError={GetError(zkem)}");
string fw = ""; bool fwOk = zkem.GetFirmwareVersion(_machine, ref fw);
Console.WriteLine($" [3] GetFirmwareVersion: {fwOk} (fw={fw}), GetLastError={GetError(zkem)}");
string mac = ""; bool macOk = zkem.GetDeviceMAC(_machine, ref mac);
Console.WriteLine($" [4] GetDeviceMAC: {macOk} (mac={mac}), GetLastError={GetError(zkem)}");
string plat = ""; bool platOk = zkem.GetPlatform(_machine, ref plat);
Console.WriteLine($" [5] GetPlatform: {platOk} (plat={plat}), GetLastError={GetError(zkem)}");
int lc = 0; bool lcOk = zkem.GetDeviceStatus(_machine, 6, ref lc);
Console.WriteLine($" [6] GetDeviceStatus(6): {lcOk} (count={lc}), GetLastError={GetError(zkem)}");
int uc = 0; bool ucOk = zkem.GetDeviceStatus(_machine, 2, ref uc);
Console.WriteLine($" [7] GetDeviceStatus(2): {ucOk} (users={uc}), GetLastError={GetError(zkem)}");
bool readOk = zkem.ReadGeneralLogData(_machine);
Console.WriteLine($" [8] ReadGeneralLogData: {readOk}, GetLastError={GetError(zkem)}");
string enroll = ""; int vm = 0, io = 0, y = 0, m = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0;
bool ssrOk = zkem.SSR_GetGeneralLogData(_machine, out enroll, out vm, out io, out y, out m, out d, out h, out mi, out s, ref wc);
Console.WriteLine($" [9] SSR_GetGeneralLogData: {ssrOk}, GetLastError={GetError(zkem)}");
bool regOk = zkem.RegEvent(_machine, 65535);
Console.WriteLine($" [10] RegEvent(65535): {regOk}, GetLastError={GetError(zkem)}");
Console.WriteLine(@"
=== TEST 7 RESULTS - COM Error Handling Audit ===
PRODUCTION CODE ANALYSIS (ZKTecoProtocol.cs):
GetLastError is NEVER called in production code.
Production relies ONLY on:
- Return values (bool) of each COM method
- Timeout detection via RunOnStaThread
- Exception handling
CRITICAL FINDING:
If a COM method returns TRUE but the operation actually failed
(e.g., ReadGeneralLogData returns TRUE but SSR returns 0 records),
production has NO WAY to detect this because GetLastError is never called.
The SDK MAY be setting an error code that production never reads.
This could explain why ReadGeneralLogData returns TRUE but records
are not accessible - the error is available but unobserved.
RECOMMENDATION:
After ReadGeneralLogData, check GetLastError before SSR enumeration.
If GetLastError != 0, treat as read failure.");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// TEST 8 - Verify worker health independently
//
// CODE AUDIT: Is heartbeat from same worker or different task?
// For device 221, prove code continues executing after each read.
// =================================================================
[Fact]
public void Test8_Verify_Worker_Health_Independently()
{
Console.WriteLine($"TEST 8: Verify worker health independently | Device: {_ip}:{_port}");
Console.WriteLine("Purpose: Is heartbeat from same worker or different task?\n");
Console.WriteLine("CODE AUDIT: Worker Architecture");
Console.WriteLine(" DeviceConnectionService.cs creates one DeviceConnection per device.");
Console.WriteLine(" Each DeviceConnection runs in its own Task.Run() (line 79-87).");
Console.WriteLine(" Within each DeviceConnection, the main loop does BOTH:");
Console.WriteLine(" 1. Read logs (ReadAllLogsIncremental)");
Console.WriteLine(" 2. Send heartbeat (GetDeviceInfo + SendHeartbeatAsync)");
Console.WriteLine(" These are SEQUENTIAL in the same while loop iteration.\n");
Console.WriteLine("HEARTBEAT BELONGS TO: Same device worker task.");
Console.WriteLine(" The heartbeat is NOT from a separate task or thread.\n");
Console.WriteLine("KEY ARCHITECTURAL OBSERVATIONS:");
Console.WriteLine(" 1. Heartbeat comes AFTER log read (lines 449-613)");
Console.WriteLine(" 2. If log read hangs (STA timeout), heartbeat still fires");
Console.WriteLine(" because RunOnStaThread returns false -> heartbeat runs");
Console.WriteLine(" 3. If SSR_GetGeneralLogData returns 0 records:");
Console.WriteLine(" - Production logs READ_ALL_LOGS_EMPTY (line 532)");
Console.WriteLine(" - _lastSuccessfulReadAt is STILL updated (line 533)");
Console.WriteLine(" - Watchdog is NOT triggered");
Console.WriteLine(" - Heartbeat continues normally");
Console.WriteLine(" 4. Watchdog only triggers on STA thread timeout");
Console.WriteLine(" (RunOnStaThread false -> DisposeSessionUnsafe -> IsConnected=false)\n");
Console.WriteLine("CRITICAL FINDING:");
Console.WriteLine(" When SSR returns 0 but GetLogCount > 0:");
Console.WriteLine(" - Production logs READ_ALL_LOGS_EMPTY");
Console.WriteLine(" - Updates _lastSuccessfulReadAt = DateTime.UtcNow");
Console.WriteLine(" - Watchdog NEVER triggers");
Console.WriteLine(" - Heartbeat continues normally");
Console.WriteLine(" - Worker appears healthy from all telemetry");
Console.WriteLine(" - Records are silently lost\n");
Console.WriteLine("RUNTIME VERIFICATION:\n");
zkemkeeper.CZKEMClass? zkem = null;
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Connect_Net: {connected}");
if (!connected) return;
var swLc = Stopwatch.StartNew();
int lc = 0; zkem.GetDeviceStatus(_machine, 6, ref lc);
swLc.Stop();
Console.WriteLine($" Step 1 - GetLogCount: {lc} ({swLc.ElapsedMilliseconds}ms)");
var swRead = Stopwatch.StartNew();
bool readOk = zkem.ReadGeneralLogData(_machine);
swRead.Stop();
Console.WriteLine($" Step 2 - ReadGeneralLogData: {readOk} ({swRead.ElapsedMilliseconds}ms)");
var swSsr = Stopwatch.StartNew();
int ssrCount = readOk ? EnumerateSSR(zkem, _machine) : 0;
swSsr.Stop();
Console.WriteLine($" Step 3 - SSR_GetGeneralLogData: {ssrCount} records ({swSsr.ElapsedMilliseconds}ms)");
var swHb = Stopwatch.StartNew();
string fw = "", mac = "", plat = "", sn = "";
zkem.GetFirmwareVersion(_machine, ref fw);
zkem.GetDeviceMAC(_machine, ref mac);
zkem.GetPlatform(_machine, ref plat);
zkem.GetSerialNumber(_machine, out sn);
swHb.Stop();
Console.WriteLine($" Step 4 - GetDeviceInfo: fw={fw} sn={sn} ({swHb.ElapsedMilliseconds}ms)");
Console.WriteLine($@"
Total cycle: {swLc.ElapsedMilliseconds + swRead.ElapsedMilliseconds + swSsr.ElapsedMilliseconds + swHb.ElapsedMilliseconds}ms
CRITICAL CHECK:
If Step 3 returns 0 records but Step 1 shows count > 0:
-> Production logs READ_ALL_LOGS_EMPTY
-> Updates _lastSuccessfulReadAt
-> Watchdog NOT triggered
-> Worker appears healthy
-> Records silently lost
This confirms the failure mechanism:
SDK ReadGeneralLogData/SSR path becomes unhealthy while
GetDeviceInfo/GetDeviceStatus path remains healthy.
These are DIFFERENT SDK internal paths.");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
}
// =================================================================
// COMPREHENSIVE SEQUENTIAL RUNNER
//
// Runs all tests in sequence on same device session.
// Useful when device is currently in the bad state.
//
// Usage:
// dotnet test --filter "FullyQualifiedName~TEST2_ReaderFailureDiagnostic.RunAll_Sequential"
// =================================================================
[Fact]
public void RunAll_Sequential()
{
Console.WriteLine($"COMPREHENSIVE SEQUENTIAL DIAGNOSTIC | Device: {_ip}:{_port}\n");
zkemkeeper.CZKEMClass? zkem = null;
var results = new List();
try
{
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool connected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Connect_Net: {connected}");
if (!connected) { Console.WriteLine(" CANNOT PROCEED"); return; }
// TEST 1: GetLastError
Console.WriteLine("\n=== TEST 1: GetLastError After Enumeration ===");
{
int lc = 0; zkem.GetDeviceStatus(_machine, 6, ref lc);
bool readOk = zkem.ReadGeneralLogData(_machine);
int errAfterRead = GetError(zkem);
int ssrCount = readOk ? EnumerateSSR(zkem, _machine) : 0;
int errAfterSsr = GetError(zkem);
Console.WriteLine($" GetLogCount={lc}, ReadGeneralLogData={readOk}");
Console.WriteLine($" GetLastError after Read: {errAfterRead}");
Console.WriteLine($" SSR records: {ssrCount}");
Console.WriteLine($" GetLastError after SSR: {errAfterSsr}");
results.Add($"T1: LC={lc} Read={readOk} ErrRead={errAfterRead} SSR={ssrCount} ErrSSR={errAfterSsr}");
}
// TEST 2: Repeat without reconnect
Console.WriteLine("\n=== TEST 2: Repeat ReadGeneralLogData ===");
{
int lcA = 0; zkem.GetDeviceStatus(_machine, 6, ref lcA);
bool readA = zkem.ReadGeneralLogData(_machine);
int countA = readA ? EnumerateSSR(zkem, _machine) : 0;
int lcB = 0; zkem.GetDeviceStatus(_machine, 6, ref lcB);
bool readB = zkem.ReadGeneralLogData(_machine);
int countB = readB ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" Round A: LC={lcA} Read={readA} SSR={countA}");
Console.WriteLine($" Round B: LC={lcB} Read={readB} SSR={countB}");
string interp = countA == 0 && countB > 0 ? "STALE_CURSOR" :
countA == 0 && countB == 0 && lcA > 0 ? "UNHEALTHY_SDK" :
countA > 0 ? "NORMAL" : "NO_RECORDS";
Console.WriteLine($" Interpretation: {interp}");
results.Add($"T2: A={countA} B={countB} interp={interp}");
}
// TEST 3: Re-register events
Console.WriteLine("\n=== TEST 3: Re-register Events ===");
{
bool readBefore = zkem.ReadGeneralLogData(_machine);
int countBefore = readBefore ? EnumerateSSR(zkem, _machine) : 0;
bool regOk = zkem.RegEvent(_machine, 65535);
bool readAfter = zkem.ReadGeneralLogData(_machine);
int countAfter = readAfter ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" Before: SSR={countBefore}, RegEvent={regOk}, After: SSR={countAfter}");
string interp = countBefore == 0 && countAfter > 0 ? "REGEVENT_FIXES" : "REGEVENT_NO_EFFECT";
Console.WriteLine($" Interpretation: {interp}");
results.Add($"T3: Before={countBefore} Reg={regOk} After={countAfter} interp={interp}");
}
// TEST 4: Disconnect/Reconnect same instance
Console.WriteLine("\n=== TEST 4: Disconnect/Reconnect Same Instance ===");
{
zkem.Disconnect();
Thread.Sleep(1000);
bool reconnected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" Reconnect: {reconnected}");
if (reconnected)
{
zkem.RegEvent(_machine, 65535);
int lc = 0; zkem.GetDeviceStatus(_machine, 6, ref lc);
bool readOk = zkem.ReadGeneralLogData(_machine);
int count = readOk ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" After: LC={lc} Read={readOk} SSR={count}");
results.Add($"T4: Reconnect=TRUE SSR={count}");
}
else
{
results.Add("T4: Reconnect=FALSE");
}
}
// TEST 5: Dispose/Recreate
Console.WriteLine("\n=== TEST 5: Dispose/Recreate CZKEMClass ===");
{
try { Marshal.ReleaseComObject(zkem); } catch { }
zkem = null;
Thread.Sleep(1000);
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
bool newConnected = zkem.Connect_Net(_ip, _port);
Console.WriteLine($" New instance connect: {newConnected}");
if (newConnected)
{
zkem.RegEvent(_machine, 65535);
int lc = 0; zkem.GetDeviceStatus(_machine, 6, ref lc);
bool readOk = zkem.ReadGeneralLogData(_machine);
int count = readOk ? EnumerateSSR(zkem, _machine) : 0;
Console.WriteLine($" New: LC={lc} Read={readOk} SSR={count}");
results.Add($"T5: Connected=TRUE LC={lc} SSR={count}");
}
else
{
results.Add("T5: Connected=FALSE");
}
}
// TEST 7: GetLastError audit
Console.WriteLine("\n=== TEST 7: GetLastError Audit ===");
{
string s1 = ""; bool r1 = zkem.GetSerialNumber(_machine, out s1);
Console.WriteLine($" GetSerialNumber: {r1}, GetLastError={GetError(zkem)}");
string s2 = ""; bool r2 = zkem.GetFirmwareVersion(_machine, ref s2);
Console.WriteLine($" GetFirmwareVersion: {r2}, GetLastError={GetError(zkem)}");
int v = 0; bool r3 = zkem.GetDeviceStatus(_machine, 6, ref v);
Console.WriteLine($" GetDeviceStatus(6): {r3}, GetLastError={GetError(zkem)}");
bool r4 = zkem.ReadGeneralLogData(_machine);
Console.WriteLine($" ReadGeneralLogData: {r4}, GetLastError={GetError(zkem)}");
results.Add("T7: See above for per-method GetLastError values");
}
// TEST 8: Worker health
Console.WriteLine("\n=== TEST 8: Worker Health Architecture ===");
Console.WriteLine(" Heartbeat = same DeviceConnection worker task (CODE AUDIT)");
Console.WriteLine(" Watchdog only triggers on STA timeout (IsConnected=false)");
results.Add("T8: CODE AUDIT - heartbeat = same worker");
}
finally
{
if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } }
}
Console.WriteLine("\n=== FINAL RESULTS MATRIX ===");
foreach (var r in results)
Console.WriteLine($" {r}");
Console.WriteLine(@"
=== ANSWERS TO FINAL QUESTIONS ===
(See individual test outputs above for data-driven answers)
1. Does GetLastError report error during bad state?
-> Test 1 shows exact GetLastError codes after each operation
2. Does second ReadGeneralLogData recover without reconnect?
-> Test 2 shows Round A vs Round B comparison
3. Does RegEvent recover it?
-> Test 3 shows before/after RegEvent comparison
4. Does Disconnect/Reconnect recover it?
-> Test 4 shows same-instance reconnect result
5. Does Dispose/Recreate recover it?
-> Test 5 shows fresh COM object result (recovery boundary)
6. Does live OnAttTransactionEx work during bad state?
-> Test 6 shows callback vs reader divergence
7. Is failure reader-only, event+reader, or app pipeline?
-> Test 6 classification determines this
8. What exact state appears broken?
-> Synthesized from Tests 1-5 + code audit in Test 8
9. What event/action first puts SDK into that state?
-> Correlates across tests; requires long-running observation
10. Smallest production change for auto-detect + recovery?
-> Test 7 shows GetLastError is never checked; Test 8 shows
the watchdog gap when SSR returns 0 but GetLogCount > 0");
}
private class CallbackCapture
{
public int ThreadId;
public ApartmentState Apartment;
public bool IsThreadPool;
public DateTime Timestamp;
public string? PersonnelCode;
}
}