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
+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 };
}
}