7b29331f52
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.
367 lines
17 KiB
TypeScript
367 lines
17 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { DigestGetResult } from "./http-digest.js";
|
|
|
|
// The HTTP layer is mocked so the camera driver's RETRY logic is tested without a
|
|
// network. Hikvision returns 503 "Device Busy" (sometimes 500) transiently when its
|
|
// snapshot encoder is occupied — captureSnapshot must retry those and succeed, but
|
|
// fail FAST on a config error (401 auth / 404 path). See camera.ts.
|
|
|
|
const digestGet = vi.fn<(...a: unknown[]) => Promise<DigestGetResult>>();
|
|
const digestRequest = vi.fn<(...a: unknown[]) => Promise<DigestGetResult>>();
|
|
vi.mock("./http-digest.js", () => ({
|
|
digestGet: (...a: unknown[]) => digestGet(...a),
|
|
digestRequest: (...a: unknown[]) => digestRequest(...a),
|
|
}));
|
|
|
|
// Import the driver AFTER the mock is registered.
|
|
const { hikvisionDriver } = await import("./camera.js");
|
|
|
|
function reply(status: number, body = "jpeg-bytes"): DigestGetResult {
|
|
return { status, contentType: "image/jpeg", body: Buffer.from(body) };
|
|
}
|
|
|
|
function makeCamera() {
|
|
return hikvisionDriver.create({ host: "10.0.10.12", port: 80, username: "admin", password: "x", channel: 1 });
|
|
}
|
|
|
|
beforeEach(() => {
|
|
digestGet.mockReset();
|
|
digestRequest.mockReset();
|
|
vi.useFakeTimers();
|
|
});
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe("hikvision captureSnapshot — 503 Device Busy retry", () => {
|
|
it("retries a transient 503 and succeeds", async () => {
|
|
digestGet
|
|
.mockResolvedValueOnce(reply(503))
|
|
.mockResolvedValueOnce(reply(503))
|
|
.mockResolvedValueOnce(reply(200, "the-frame"));
|
|
const cam = makeCamera();
|
|
const p = cam.captureSnapshot({ direction: "entry" });
|
|
await vi.runAllTimersAsync(); // let the backoff sleeps fire
|
|
const shot = await p;
|
|
expect(shot.bytes.toString()).toBe("the-frame");
|
|
expect(digestGet).toHaveBeenCalledTimes(3); // 503, 503, 200
|
|
});
|
|
|
|
it("also retries a transient 500", async () => {
|
|
digestGet.mockResolvedValueOnce(reply(500)).mockResolvedValueOnce(reply(200));
|
|
const cam = makeCamera();
|
|
const p = cam.captureSnapshot({ direction: "entry" });
|
|
await vi.runAllTimersAsync();
|
|
await p;
|
|
expect(digestGet).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("gives up after the attempt cap, naming it 'device busy'", async () => {
|
|
digestGet.mockResolvedValue(reply(503)); // always busy
|
|
const cam = makeCamera();
|
|
// Attach the rejection assertion BEFORE flushing timers so the rejection always
|
|
// has a handler (no unhandled-rejection noise), then drive the backoff sleeps.
|
|
const assertion = expect(cam.captureSnapshot({ direction: "entry" })).rejects.toThrow(/HTTP 503 \(device busy\)/);
|
|
await vi.runAllTimersAsync();
|
|
await assertion;
|
|
expect(digestGet).toHaveBeenCalledTimes(4); // SNAPSHOT_MAX_ATTEMPTS
|
|
});
|
|
|
|
it("does NOT retry a 401 (auth error self-won't-heal) — fails fast", async () => {
|
|
digestGet.mockResolvedValue(reply(401));
|
|
const cam = makeCamera();
|
|
const assertion = expect(cam.captureSnapshot({ direction: "entry" })).rejects.toThrow(/HTTP 401/);
|
|
await vi.runAllTimersAsync();
|
|
await assertion;
|
|
expect(digestGet).toHaveBeenCalledTimes(1); // no retry
|
|
});
|
|
|
|
it("does NOT retry a 404 (wrong path/channel) — fails fast", async () => {
|
|
digestGet.mockResolvedValue(reply(404));
|
|
const cam = makeCamera();
|
|
const assertion = expect(cam.captureSnapshot({ direction: "entry" })).rejects.toThrow(/HTTP 404/);
|
|
await vi.runAllTimersAsync();
|
|
await assertion;
|
|
expect(digestGet).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("succeeds first try with no retry on a clean 200", async () => {
|
|
digestGet.mockResolvedValue(reply(200));
|
|
const cam = makeCamera();
|
|
const shot = await cam.captureSnapshot({ direction: "entry" });
|
|
expect(shot.contentType).toBe("image/jpeg");
|
|
expect(digestGet).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe("hikvision snapshot stream selection (main vs sub)", () => {
|
|
function pathFor(config: Record<string, unknown>): string {
|
|
digestGet.mockReset();
|
|
digestGet.mockResolvedValue(reply(200));
|
|
hikvisionDriver.create(config as never).captureSnapshot({ direction: "entry" });
|
|
return String((digestGet.mock.calls[0]![0] as { path: string }).path);
|
|
}
|
|
|
|
it("defaults to the MAIN stream (…/channels/101/picture) — back-compat", () => {
|
|
expect(pathFor({ host: "1.2.3.4", channel: 1 })).toBe("/ISAPI/Streaming/channels/101/picture");
|
|
});
|
|
|
|
it("stream=2 selects the SUB stream (…/channels/102/picture) — the G3H 503 fix", () => {
|
|
expect(pathFor({ host: "1.2.3.4", channel: 1, stream: 2 })).toBe("/ISAPI/Streaming/channels/102/picture");
|
|
});
|
|
|
|
it("honours the channel number with the stream (ch2 sub = 202)", () => {
|
|
expect(pathFor({ host: "1.2.3.4", channel: 2, stream: 2 })).toBe("/ISAPI/Streaming/channels/202/picture");
|
|
});
|
|
|
|
it("an invalid stream falls back to main (1)", () => {
|
|
expect(pathFor({ host: "1.2.3.4", channel: 1, stream: 9 })).toBe("/ISAPI/Streaming/channels/101/picture");
|
|
});
|
|
});
|
|
|
|
describe("healthCheck detail is a STABLE size bucket (log-noise fix, 2026-07-05)", () => {
|
|
// The device monitor logs + re-emits whenever the detail string changes. JPEG
|
|
// frame size differs on every frame, so an exact byte count made healthy cameras
|
|
// "change" on nearly every poll. The detail must stay identical across ordinary
|
|
// frame-size jitter and only move on a real shift (different stream/res, tiny body).
|
|
it("frames of similar size land in the same bucket", async () => {
|
|
const cam = makeCamera();
|
|
digestGet.mockResolvedValueOnce(reply(200, "x".repeat(16_716)));
|
|
const a = await cam.healthCheck();
|
|
digestGet.mockResolvedValueOnce(reply(200, "x".repeat(17_902)));
|
|
const b = await cam.healthCheck();
|
|
expect(a).toEqual({ status: "ready", detail: "snapshot ≈16 KB" });
|
|
expect(b.detail).toBe(a.detail); // jitter does NOT change the detail
|
|
});
|
|
|
|
it("a genuinely different size (sub vs main stream) lands in a different bucket", async () => {
|
|
const cam = makeCamera();
|
|
digestGet.mockResolvedValueOnce(reply(200, "x".repeat(299_395)));
|
|
const big = await cam.healthCheck();
|
|
expect(big.detail).toBe("snapshot ≈256 KB");
|
|
});
|
|
|
|
it("an empty-ish 200 body is flagged, not bucketed away", async () => {
|
|
const cam = makeCamera();
|
|
digestGet.mockResolvedValueOnce(reply(200, "xx"));
|
|
const tiny = await cam.healthCheck();
|
|
expect(tiny.detail).toBe("snapshot <1 KB");
|
|
});
|
|
});
|
|
|
|
describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/time)", () => {
|
|
const timeXml = (localTime: string) =>
|
|
reply(
|
|
200,
|
|
`<?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";
|
|
|
|
function cam() {
|
|
return makeCamera() as unknown as {
|
|
syncClock(localIso: string, maxDriftSec: number): Promise<{ driftSeconds: number | null; synced: boolean }>;
|
|
};
|
|
}
|
|
|
|
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, zoneChanged: false, timeZone: "CST-2:00:00" });
|
|
expect(digestRequest).toHaveBeenCalledTimes(1); // GET only
|
|
});
|
|
|
|
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/>"));
|
|
const r = await cam().syncClock(HOST_NOW, 60);
|
|
expect(r.synced).toBe(true);
|
|
expect(r.driftSeconds).toBeGreaterThan(1_000_000_000); // ~56 years
|
|
const put = digestRequest.mock.calls[1]![0] as { method: string; path: string; body: string };
|
|
expect(put.method).toBe("PUT");
|
|
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:00</timeZone>"); // the host's current offset, never the camera's DST rule
|
|
});
|
|
|
|
it("unparseable camera time = infinite drift → syncs", async () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(reply(200, "<Time><localTime>garbage</localTime></Time>"))
|
|
.mockResolvedValueOnce(reply(200, "<ResponseStatus/>"));
|
|
const r = await cam().syncClock(HOST_NOW, 60);
|
|
expect(r).toMatchObject({ driftSeconds: null, synced: true });
|
|
});
|
|
|
|
it("a failed set surfaces as an error (monitor logs it, backstop retries)", async () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(timeXml("1970-01-01T01:00:00+01:00"))
|
|
.mockResolvedValueOnce(reply(403, "denied"));
|
|
await expect(cam().syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 403");
|
|
});
|
|
|
|
it("both camera drivers claim the capability (Dahua via global.cgi since 2026-09-17)", async () => {
|
|
const { dahuaDriver, hikvisionDriver } = await import("./camera.js");
|
|
const { isClockSyncable } = await import("../interfaces.js");
|
|
const mk = (d: typeof dahuaDriver) =>
|
|
d.create({ host: "10.0.10.12", port: 80, username: "admin", password: "x", channel: 1 });
|
|
expect(isClockSyncable(mk(dahuaDriver))).toBe(true);
|
|
expect(isClockSyncable(mk(hikvisionDriver))).toBe(true);
|
|
});
|
|
});
|
|
|
|
// Dahua — verified against an IPC-HFW2549T-AS-IL (fw 2.880) on 2026-09-17. The CGI
|
|
// numbers snapshot channels from 1 (channel=0 → HTTP 400), ignores any stream
|
|
// selector, and speaks NAIVE local wall time on global.cgi. See camera.ts and
|
|
// wiki/entities/dahua-ipc-hfw2549t.md.
|
|
describe("dahua snapshot URL — channel is 1-BASED, no stream selector", () => {
|
|
async function pathFor(config: Record<string, unknown>): Promise<string> {
|
|
const { dahuaDriver } = await import("./camera.js");
|
|
digestGet.mockReset();
|
|
digestGet.mockResolvedValue(reply(200));
|
|
dahuaDriver.create(config as never).captureSnapshot({ direction: "entry" });
|
|
return String((digestGet.mock.calls[0]![0] as { path: string }).path);
|
|
}
|
|
|
|
it("channel 1 as entered → channel=1 (the old `ch - 1` sent 0 → HTTP 400 on hardware)", async () => {
|
|
expect(await pathFor({ host: "1.2.3.4", channel: 1 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
|
});
|
|
|
|
it("defaults to channel 1 when none is configured", async () => {
|
|
expect(await pathFor({ host: "1.2.3.4" })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
|
});
|
|
|
|
it("channel 2 passes through; a stream setting is ignored", async () => {
|
|
expect(await pathFor({ host: "1.2.3.4", channel: 2, stream: 2 })).toBe("/cgi-bin/snapshot.cgi?channel=2");
|
|
});
|
|
|
|
it("a zero/negative channel is clamped to 1 rather than sent as-is", async () => {
|
|
expect(await pathFor({ host: "1.2.3.4", channel: 0 })).toBe("/cgi-bin/snapshot.cgi?channel=1");
|
|
});
|
|
});
|
|
|
|
describe("dahua syncClock — global.cgi getCurrentTime/setCurrentTime, naive wall time", () => {
|
|
const HOST_NOW = "2026-09-17T10:35:49+02:00";
|
|
const timeReply = (naive: string) => reply(200, `result=${naive}\r\n`);
|
|
|
|
async function cam() {
|
|
const { dahuaDriver } = await import("./camera.js");
|
|
return dahuaDriver.create({ host: "10.0.10.11", port: 80, username: "admin", password: "x", channel: 1 }) as unknown as {
|
|
syncClock(localIso: string, maxDriftSec: number): Promise<{ driftSeconds: number | null; synced: boolean }>;
|
|
};
|
|
}
|
|
|
|
it("in-sync camera: reads, does NOT set", async () => {
|
|
digestRequest.mockResolvedValueOnce(timeReply("2026-09-17 10:35:40"));
|
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
|
expect(r).toEqual({ driftSeconds: 9, synced: false });
|
|
expect(digestRequest).toHaveBeenCalledTimes(1);
|
|
const get = digestRequest.mock.calls[0]![0] as { method: string; path: string };
|
|
expect(get.method).toBe("GET");
|
|
expect(get.path).toBe("/cgi-bin/global.cgi?action=getCurrentTime");
|
|
});
|
|
|
|
it("an hour behind (the bench unit: DST off, NTP off) → sets the HOST wall time, no offset", async () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(timeReply("2026-09-17 09:35:51"))
|
|
.mockResolvedValueOnce(reply(200, "OK\r\n"));
|
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
|
expect(r).toEqual({ driftSeconds: 3598, synced: true });
|
|
const set = digestRequest.mock.calls[1]![0] as { method: string; path: string };
|
|
expect(set.method).toBe("GET");
|
|
expect(set.path).toBe("/cgi-bin/global.cgi?action=setCurrentTime&time=2026-09-17%2010%3A35%3A49");
|
|
});
|
|
|
|
it("unparseable camera reply = infinite drift → syncs", async () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(reply(200, "Error\r\nBad Request!"))
|
|
.mockResolvedValueOnce(reply(200, "OK"));
|
|
const r = await (await cam()).syncClock(HOST_NOW, 60);
|
|
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 () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
|
|
.mockResolvedValueOnce(reply(200, "Error\r\nInvalid Argument!"));
|
|
await expect((await cam()).syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 200 Error");
|
|
});
|
|
|
|
it("a non-200 set surfaces as an error", async () => {
|
|
digestRequest
|
|
.mockResolvedValueOnce(timeReply("1970-01-01 01:00:00"))
|
|
.mockResolvedValueOnce(reply(401, "denied"));
|
|
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>");
|
|
});
|
|
});
|