import re, sqlite3, datetime, collections, os LOG = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\logs\attendancehub_sync.log" LOG1 = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\logs\attendancehub_sync.log.1" DB = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\attendancehub_v2.db" # RT log line: # 23:44:07.398 info: ... RT device=172.30.70.5 channel=LIVE gen=1 pin=96670 state=0 # verify=1 time=2026-10-10 13:00:52 src=OnAttTransactionEx RX = re.compile( r"^(?P\d\d):(?P\d\d):(?P\d\d)\.(?P\d+)\s+\w+:\s+.*?\bRT device=(?P\S+) " r"channel=(?P\w+) .*?pin=(?P\S+) .*?time=(?P\d{4})-(?P\d\d)-(?P\d\d) " r"(?P\d\d):(?P\d\d):(?P\d\d)") def scan(path): out = [] try: f = open(path, "r", encoding="utf-8", errors="replace") except FileNotFoundError: return out with f: for ln in f: g = RX.match(ln) if g: out.append(g.groupdict()) return out ev = scan(LOG1) + scan(LOG) print(f"parsed RT lines = {len(ev)}") # host clock only carries HH:MM:SS.mmm -> use the DEVICE date, then normalise host midnight rollover def host_instant(d): lab = datetime.datetime(int(d["y"]), int(d["mo"]), int(d["d"]), int(d["H"]), int(d["M"]), int(d["S"])) host = datetime.datetime(lab.year, lab.month, lab.day, int(d["h"]), int(d["m"]), int(d["s"]), int(d["ms"]) * 1000) delta = host - lab if delta < datetime.timedelta(hours=-12): host += datetime.timedelta(days=1) elif delta > datetime.timedelta(hours=12): host -= datetime.timedelta(days=1) return lab, host per = collections.defaultdict(list) # dev -> [device_offset_seconds] pipe = collections.defaultdict(list) # dev -> [first_seen - host_at_callback] pairs = 0 samples = collections.defaultdict(list) for d in ev: lab, host = host_instant(d) off = (host - lab).total_seconds() per[d["dev"]].append(off) if len(samples[d["dev"]]) < 3: samples[d["dev"]].append((d["ch"], d["pin"], lab.strftime("%m-%d %H:%M:%S"), host.strftime("%m-%d %H:%M:%S.%f")[:-3], off)) # join against SQLite to get OUR pipeline delay (callback log ts -> first_seen_at) con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=20) def parse_ts(s): if not s: return None s = s.rstrip("Z") w, _, fr = s.partition(".") fr = (fr + "0000000")[:7] return (datetime.datetime.fromisoformat(w).replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(microseconds=int(fr) / 10)) rows = con.execute("SELECT device_id, personnel_code, punch_time, first_seen_at FROM punches").fetchall() lut = {} for dev, pin, pt, fs in rows: lut[(dev, pin, pt)] = parse_ts(fs) for d in ev: lab, host = host_instant(d) key = (d["dev"], d["pin"], lab.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")) fs = lut.get(key) if fs: # first_seen_at is UTC; host above is local wall clock (UTC+3:30) pipe[d["dev"]].append((fs - (host - datetime.timedelta(hours=3, minutes=30)) .replace(tzinfo=datetime.timezone.utc)).total_seconds()) pairs += 1 con.close() print(f"\n=== A) DEVICE CLOCK OFFSET vs HOST (host_at_callback - device_label) ===") print(" positive => device clock is BEHIND the host by that much\n") print(f"{'device':<16} {'n':>5} {'min':>8} {'p50':>8} {'max':>8} spread") print("-" * 62) for dev in sorted(per): v = sorted(per[dev]) n = len(v) p50 = v[n // 2] print(f"{dev:<16} {n:>5} {v[0]:>7.0f}s {p50:>7.0f}s {v[-1]:>7.0f}s {v[-1]-v[0]:.0f}s") print("\n=== B) OUR PIPELINE (log_at_callback -> SQLite first_seen_at) ===") print(" this is what the service itself adds AFTER the COM callback\n") print(f"{'device':<16} {'n':>5} {'min':>8} {'p50':>8} {'max':>8}") print("-" * 52) for dev in sorted(pipe): v = sorted(pipe[dev]) n = len(v) print(f"{dev:<16} {n:>5} {v[0]:>7.1f}s {v[n//2]:>7.1f}s {v[-1]:>7.1f}s") print(f"\n rows joined to SQLite = {pairs}") print("\n=== C) samples (device label vs host at raw callback) ===") for dev in sorted(samples): for ch, pin, lab, host, off in samples[dev]: print(f" {dev:<16} {ch:<5} pin={pin:<8} device={lab} host={host} offset={off:.0f}s")