fix(devices): Hikvision clock sync owns the time zone (fixed offset, re-set at DST edges)

park-2's cameras burned Beijing time into every frame: factory zone CST-8,
and the sync compared instants only, so zero drift meant the zone was never
touched. The G3H firmware also accepts a POSIX zone with a DST rule, echoes
it back, and ignores the rule.

syncClock now derives the site's current UTC offset as a fixed Hikvision
zone (hikvisionFixedZone) and rewrites it when it differs, sending the clock
with it. The device monitor adds a third trigger beside offline->ready and
the 24h backstop: the moment the site's UTC offset changes, so a DST switch
is handled within one poll. ClockSyncResult reports zoneChanged/timeZone.

Both park-2 cameras were set to CST-2:00:00 by hand on 2026-10-09; this
must be deployed there before 2026-10-25 or the OSD reads 1h ahead from
that day until it is.
This commit is contained in:
2026-10-11 18:17:25 +02:00
parent 9332802e5d
commit 7b29331f52
5 changed files with 163 additions and 31 deletions
+18 -6
View File
@@ -27,8 +27,10 @@ const POLL_MS = Number(process.env.DEVICE_POLL_MS ?? 8000);
// Camera clock sync (Hikvision loses its clock on power cuts — reboots at the 1970
// epoch until a human logs into its web UI). The monitor re-syncs from the HOST
// clock (the site's offline time authority) at the offline→ready edge — exactly the
// power-restored moment — plus a daily backstop; drift under the threshold is left
// alone. See wiki/entities/lpr-camera.md (clock sync).
// power-restored moment — plus a daily backstop, plus the moment the site's UTC offset
// changes (a DST switch: the camera's zone is a FIXED offset the host rewrites, see
// HikvisionCamera.syncClock); drift under the threshold is left alone. See
// wiki/entities/lpr-camera.md (clock sync).
const CLOCK_SYNC_BACKSTOP_MS = 24 * 60 * 60 * 1000;
const CLOCK_MAX_DRIFT_SEC = 60;
@@ -201,18 +203,26 @@ export class DeviceMonitor {
}
// Camera clock re-sync at the power-restored edge (prev offline/unknown →
// ready) + a daily backstop. Stamped BEFORE the async attempt so a failing
// camera is retried at backstop cadence, never every poll.
// ready) + a daily backstop + the site's UTC-offset edge (DST switch). Stamped
// BEFORE the async attempt so a failing camera is retried at backstop cadence,
// never every poll.
if (row.category === "camera" && next.state === "ready" && device && isClockSyncable(device)) {
const prev = this.#latest.get(row.id);
const cameBack = !prev || prev.state === "offline";
const last = this.#clockSyncedAt.get(row.id) ?? 0;
if (cameBack || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
const nowIso = localIsoWithOffset(siteTz(this.#db));
const offset = nowIso.slice(-6);
const offsetChanged = this.#clockSyncedOffset.get(row.id) !== offset;
if (cameBack || offsetChanged || Date.now() - last > CLOCK_SYNC_BACKSTOP_MS) {
this.#clockSyncedAt.set(row.id, Date.now());
this.#clockSyncedOffset.set(row.id, offset);
const cam = device;
void (async () => {
try {
const r = await cam.syncClock(localIsoWithOffset(siteTz(this.#db)), CLOCK_MAX_DRIFT_SEC);
const r = await cam.syncClock(nowIso, CLOCK_MAX_DRIFT_SEC);
if (r.zoneChanged) {
this.#log.warn(`device-monitor: camera ${row.id} time zone set to ${r.timeZone ?? "?"} (site offset ${offset})`);
}
if (r.synced) {
// A large jump is the 1970 power-cut signature — warn (persisted) so
// the reboot stays visible; a small correction is routine info.
@@ -249,6 +259,8 @@ export class DeviceMonitor {
/** Per-camera timestamp of the last clock-sync ATTEMPT (backstop pacing). */
readonly #clockSyncedAt = new Map<string, number>();
/** Per-camera site UTC offset ("+02:00") at the last attempt — a change (DST) re-syncs. */
readonly #clockSyncedOffset = new Map<string, string>();
/** Cache + emit a status, but only when it CHANGED (state or detail). */
#publish(id: string, next: DeviceStatusEvent): void {
+76 -6
View File
@@ -153,7 +153,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
const timeXml = (localTime: string) =>
reply(
200,
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00DST01:00:00</timeZone></Time>`,
`<?xml version="1.0"?><Time><timeMode>NTP</timeMode><localTime>${localTime}</localTime><timeZone>CST-2:00:00</timeZone></Time>`,
);
const HOST_NOW = "2026-07-07T12:00:00+02:00";
@@ -166,11 +166,11 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
it("in-sync camera: reads, does NOT set", async () => {
digestRequest.mockResolvedValueOnce(timeXml("2026-07-07T12:00:10+02:00"));
const r = await cam().syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: 10, synced: false });
expect(r).toEqual({ driftSeconds: 10, synced: false, zoneChanged: false, timeZone: "CST-2:00:00" });
expect(digestRequest).toHaveBeenCalledTimes(1); // GET only
});
it("1970 camera: PUTs manual time with the host instant, echoing the camera's timeZone", async () => {
it("1970 camera: PUTs manual time with the host instant and the site's fixed-offset zone", async () => {
digestRequest
.mockResolvedValueOnce(timeXml("1970-01-01T03:12:44+01:00"))
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
@@ -182,7 +182,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
expect(put.path).toBe("/ISAPI/System/time");
expect(put.body).toContain("<timeMode>manual</timeMode>");
expect(put.body).toContain(`<localTime>${HOST_NOW}</localTime>`);
expect(put.body).toContain("<timeZone>CST-2:00:00DST01:00:00</timeZone>"); // echoed, never invented
expect(put.body).toContain("<timeZone>CST-2:00:00</timeZone>"); // the host's current offset, never the camera's DST rule
});
it("unparseable camera time = infinite drift → syncs", async () => {
@@ -190,7 +190,7 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
.mockResolvedValueOnce(reply(200, "<Time><localTime>garbage</localTime></Time>"))
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
const r = await cam().syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: null, synced: true });
expect(r).toMatchObject({ driftSeconds: null, synced: true });
});
it("a failed set surfaces as an error (monitor logs it, backstop retries)", async () => {
@@ -277,7 +277,7 @@ describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wa
.mockResolvedValueOnce(reply(200, "Error\r\nBad Request!"))
.mockResolvedValueOnce(reply(200, "OK"));
const r = await (await cam()).syncClock(HOST_NOW, 60);
expect(r).toEqual({ driftSeconds: null, synced: true });
expect(r).toMatchObject({ driftSeconds: null, synced: true });
});
it("a 200 whose body is not OK is still a failed set (Dahua's 'Error' convention)", async () => {
@@ -294,3 +294,73 @@ describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wa
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 401");
});
});
// --- Hikvision clock sync: the zone is the host's FIXED current offset -------------
// park-2 2026-10-09: both cameras sat on the factory CST-8 (Beijing) — instant right,
// OSD six hours off — and this firmware ignores the DST rule in a POSIX zone string. So
// the sync rewrites the zone to the site's current fixed offset and re-sends the clock
// with it; a camera already on the right zone with small drift is left alone.
const { hikvisionFixedZone } = await import("./camera.js");
function timeXml(localTime: string, timeZone: string) {
return (
`<?xml version="1.0" encoding="UTF-8"?><Time version="2.0"><timeMode>manual</timeMode>` +
`<localTime>${localTime}</localTime><timeZone>${timeZone}</timeZone></Time>`
);
}
function xmlReply(status: number, body: string): DigestGetResult {
return { status, contentType: "application/xml", body: Buffer.from(body) };
}
function putCalls() {
return digestRequest.mock.calls
.map((c) => c[0] as { method: string; path: string; body?: string })
.filter((c) => c.method === "PUT");
}
describe("hikvisionFixedZone", () => {
it("inverts the sign the POSIX way and keeps minutes", () => {
expect(hikvisionFixedZone("2026-10-09T19:01:08+02:00")).toBe("CST-2:00:00");
expect(hikvisionFixedZone("2026-12-09T18:01:08+01:00")).toBe("CST-1:00:00");
expect(hikvisionFixedZone("2026-10-09T09:01:08-05:30")).toBe("CST+5:30:00");
expect(hikvisionFixedZone("2026-10-09T17:01:08+00:00")).toBe("CST0:00:00");
});
it("refuses a host time without an offset", () => {
expect(() => hikvisionFixedZone("2026-10-09T19:01:08")).toThrow(/utc offset/);
});
});
describe("hikvision syncClock — zone", () => {
it("rewrites a factory CST-8 zone even when the instant is right", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean; timeZone?: string; driftSeconds: number | null }> };
// Same instant as the host (17:01:08Z), shown in Beijing time.
digestRequest
.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-10T01:01:08+08:00", "CST-8:00:00")))
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: true, zoneChanged: true, timeZone: "CST-2:00:00", driftSeconds: 0 });
const puts = putCalls();
expect(puts).toHaveLength(1);
expect(puts[0].path).toBe("/ISAPI/System/time");
expect(puts[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
expect(puts[0].body).toContain("<localTime>2026-10-09T19:01:08+02:00</localTime>");
});
it("leaves a camera on the right zone with small drift alone", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
digestRequest.mockResolvedValueOnce(xmlReply(200, timeXml("2026-10-09T19:01:20+02:00", "CST-2:00:00")));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: false, zoneChanged: false });
expect(putCalls()).toHaveLength(0);
});
it("re-sets the clock (same zone) when drift exceeds the threshold", async () => {
const cam = makeCamera() as unknown as { syncClock(iso: string, max: number): Promise<{ synced: boolean; zoneChanged?: boolean }> };
digestRequest
.mockResolvedValueOnce(xmlReply(200, timeXml("1970-01-01T08:00:00+02:00", "CST-2:00:00")))
.mockResolvedValueOnce(xmlReply(200, "<ResponseStatus><statusCode>1</statusCode></ResponseStatus>"));
const r = await cam.syncClock("2026-10-09T19:01:08+02:00", 60);
expect(r).toMatchObject({ synced: true, zoneChanged: false });
expect(putCalls()[0].body).toContain("<timeZone>CST-2:00:00</timeZone>");
});
});
+41 -11
View File
@@ -189,15 +189,40 @@ class HttpCamera implements CameraDevice {
// ANPR pushes. So the host (the site's time authority — offline-first, no NTP
// dependency) re-syncs the camera over the same Digest-auth ISAPI used for
// snapshots. The device monitor calls this at the offline→ready edge (the
// power-restored moment) + a daily backstop. See wiki/entities/lpr-camera.md.
// power-restored moment), a daily backstop, and whenever the site's UTC offset
// changes (DST). See wiki/entities/lpr-camera.md.
//
// TIME ZONE: the OSD shows the camera's LOCAL time = instant + its `timeZone` setting.
// park-2 (2026-10-09) ran both cameras on the factory CST-8 (Beijing): the instant was
// right, the burned-in time six hours off, and a correct-instant sync never touched it.
// This firmware (DS-2CD1047G3H) also ignores the DST rule in a POSIX-style zone string
// ("CET-1:00:00DST01:00:00,M3.5.0/02:00:00,M10.5.0/03:00:00" was accepted, echoed back,
// and NOT applied — OSD stayed on +01:00 in October). So the host owns DST too: the zone
// is written as a FIXED offset equal to the site's CURRENT offset ("CST-2:00:00" in summer,
// "CST-1:00:00" in winter — Hikvision's inverted POSIX sign) and rewritten at the next
// sync after the site's offset changes. The abbreviation is cosmetic (the camera renames
// whatever we send to "CST").
/** The Hikvision `timeZone` string for a FIXED offset equal to `localIso`'s UTC offset:
* "+02:00" → "CST-2:00:00", "-05:30" → "CST+5:30:00", "+00:00" → "CST0:00:00". */
export function hikvisionFixedZone(localIso: string): string {
const m = localIso.match(/([+-])(\d{2}):(\d{2})$/);
if (!m) throw new Error(`syncClock: host time has no utc offset: ${localIso}`);
const hours = Number(m[2]);
const minutes = m[3];
if (hours === 0 && minutes === "00") return "CST0:00:00";
// POSIX (and Hikvision) sign is inverted: east of UTC is negative.
const sign = m[1] === "+" ? "-" : "+";
return `CST${sign}${hours}:${minutes}:00`;
}
class HikvisionCamera extends HttpCamera {
/**
* Read the camera clock; when it drifts more than `maxDriftSec` from `localIso`
* (the site's wall-clock now, WITH utc offset), set it via
* PUT /ISAPI/System/time. The camera's own `timeZone` string is echoed back
* verbatim — we correct the CLOCK, never fight the tz/DST config; `localIso`'s
* explicit offset makes the instant unambiguous regardless of that config.
* Read the camera clock + zone. Rewrite the zone when it is not the site's current
* fixed offset (see above); otherwise set the clock only when it drifts more than
* `maxDriftSec` from `localIso` (the site's wall-clock now, WITH utc offset). The PUT
* always carries both: `localIso`'s explicit offset makes the instant unambiguous
* regardless of the zone the camera applies to it.
*/
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
const read = await this.deviceRequest("GET", "/ISAPI/System/time");
@@ -207,6 +232,8 @@ class HikvisionCamera extends HttpCamera {
const xml = read.body.toString("utf8");
const cameraTime = xml.match(/<localTime>([^<]+)<\/localTime>/)?.[1]?.trim() ?? null;
const timeZone = xml.match(/<timeZone>([^<]+)<\/timeZone>/)?.[1]?.trim() ?? "";
const wantZone = hikvisionFixedZone(localIso);
const zoneChanged = timeZone !== wantZone;
// Drift: parse both sides as instants. A camera reply without a UTC offset (or
// otherwise unparseable) can't be trusted → treat as infinite drift and sync.
@@ -215,21 +242,24 @@ class HikvisionCamera extends HttpCamera {
const driftSeconds = Number.isFinite(cameraMs)
? Math.round(Math.abs(hostMs - cameraMs) / 1000)
: null;
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false };
if (!zoneChanged && driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false, zoneChanged: false, timeZone };
}
const body =
`<?xml version="1.0" encoding="UTF-8"?>` +
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
(timeZone ? `<timeZone>${timeZone}</timeZone>` : "") +
`<timeZone>${wantZone}</timeZone>` +
`</Time>`;
const put = await this.deviceRequest("PUT", "/ISAPI/System/time", body);
if (put.status !== 200) {
throw new Error(`clock set failed: HTTP ${put.status}`);
}
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
return { driftSeconds, synced: true };
stubLog(
this.driverId,
`clock synced (was ${driftSeconds ?? "unparseable"}s off${zoneChanged ? `; zone ${timeZone || "unset"} → ${wantZone}` : ""})`,
);
return { driftSeconds, synced: true, zoneChanged, timeZone: wantZone };
}
}
+7 -1
View File
@@ -203,8 +203,14 @@ export interface ClockSyncResult {
/** Camera-vs-host drift in whole seconds at check time; null = the camera's
* reply was unparseable (treated as infinite drift → sync). */
readonly driftSeconds: number | null;
/** True when the camera clock was actually set (drift exceeded the threshold). */
/** True when the camera clock was actually set (drift exceeded the threshold, or the
* zone was rewritten — the clock is always re-sent with a zone change). */
readonly synced: boolean;
/** True when the camera's time-ZONE setting was rewritten to the site's current UTC
* offset (Hikvision only; see HikvisionCamera.syncClock). */
readonly zoneChanged?: boolean;
/** The camera's zone string after the call (Hikvision only), for the log line. */
readonly timeZone?: string;
}
/** Optional capability: a device whose clock the HOST can read + set. Hikvision
+21 -7
View File
@@ -231,14 +231,28 @@ Built: the HOST is the site's time authority (offline-first — no NTP infra dep
device monitor re-syncs each Hikvision camera over the same Digest-auth ISAPI used for snapshots:
- **Trigger:** the camera's **offline → ready transition** (exactly the power-restored moment) +
a **24h backstop**; the attempt timestamp is stamped BEFORE the async call, so a failing camera
retries at backstop cadence, never every 8s poll.
- **Mechanics** (`HikvisionCamera.syncClock`): `GET /ISAPI/System/time`, parse `localTime`; drift ≤
60s → leave alone. Beyond that → `PUT /ISAPI/System/time` with `timeMode=manual`, the site's
a **24h backstop** + **the site's UTC-offset edge** (a DST switch, checked every poll from
`localIsoWithOffset(siteTz)`); the attempt timestamp is stamped BEFORE the async call, so a
failing camera retries at backstop cadence, never every 8s poll.
- **Mechanics** (`HikvisionCamera.syncClock`): `GET /ISAPI/System/time`, parse `localTime` and
`timeZone`. The wanted zone is the site's **current offset as a fixed zone**
(`hikvisionFixedZone`: `+02:00` → `CST-2:00:00`, `+01:00` → `CST-1:00:00`; Hikvision's inverted
POSIX sign; the abbreviation is cosmetic — the camera renames whatever is sent to `CST`). Zone
differs → `PUT /ISAPI/System/time` with `timeMode=manual`, the wanted zone, and the site's
wall-clock now WITH explicit utc offset (`localIsoWithOffset(siteTz)`, e.g.
`2026-07-07T15:30:22+02:00` — the offset makes the instant unambiguous), and the camera's own
`timeZone` string **echoed back verbatim** (we correct the clock, never fight its tz/DST config).
An unparseable camera reply counts as infinite drift → sync.
`2026-07-07T15:30:22+02:00` — the offset makes the instant unambiguous whatever zone the
camera applies). Zone right and drift ≤ 60s → leave alone; drift beyond → the same PUT. An
unparseable camera reply counts as infinite drift → sync. The result carries `zoneChanged` +
`timeZone`; the monitor logs a zone rewrite at **warn**.
- **Why the host owns the zone (2026-10-09, park-2):** both cameras ran the **factory `CST-8:00:00`
(Beijing)** — the instant was right, so the drift check never fired, while the OSD burned into
every snapshot read **six hours ahead** of the booth (the operator's "barrier opened by itself"
claim was argued against camera footage stamped 21:45 for a 15:45 event). The earlier design
"echo the camera's zone verbatim" could never fix that. And this firmware (DS-2CD1047G3H)
**ignores the DST rule in a POSIX zone string**: `CET-1:00:00DST01:00:00,M3.5.0/02:00:00,M10.5.0/03:00:00`
was accepted and echoed back, but `localTime` and the OSD stayed on +01:00 in October. Hence a
fixed offset rewritten by the host at each DST edge, not a camera-side rule. Applied by hand to
both park-2 cameras the same day (`PUT` with `CST-2:00:00`); the deploy keeps it so.
- **Visibility:** a sync after a big jump (>1h — the power-cut signature) logs at **warn**
(persisted to app_logs); small corrections log info. Failures log warn.
- **Scope:** Hikvision only (`isClockSyncable` capability guard); the Dahua driver's CGI has no