fix(devices): Dahua snapshot channel is 1-based; add Dahua clock sync; wiki page for the bench IPC-HFW2549T
Build & push images / images (push) Successful in 3m25s

The dahua driver decremented the wizard's channel on the belief the CGI is
0-based. On real hardware (IPC-HFW2549T-AS-IL, fw V2.880, 2026-09-17)
snapshot.cgi?channel=0 answers HTTP 400 and channel=1 returns the 2880x1620
JPEG — so every Dahua assignment sat at degraded "HTTP 400". The channel is
now sent as entered (clamped >= 1) and the URL is pinned in camera.test.ts.

DahuaCamera.syncClock reads global.cgi getCurrentTime and, past the drift
limit, writes setCurrentTime with the host's naive local wall time (no offset):
the OSD burned into snapshots must match the booth clock; the camera's tz/DST
config is left alone. Verified live: a 2h-off set, set back, 1s drift -> no
write. The device monitor picks it up via isClockSyncable unchanged.

Wiki: new entities/dahua-ipc-hfw2549t.md (endpoint table, verbatim
eventManager attach parts — VideoMotion Start/Stop, VideoMotionInfo,
TimeChange — RealUTC is the camera's belief of UTC, 5-strike login lockout,
unit not factory-fresh); lpr-camera Dahua bullet corrected; runbook §3 Dahua
paragraph; index + log. The server-side attach-stream subscriber is not built.
This commit is contained in:
2026-10-08 08:03:50 +02:00
parent 4d1d245680
commit 4593a397dd
7 changed files with 348 additions and 16 deletions
+87 -2
View File
@@ -200,12 +200,97 @@ describe("hikvision syncClock — the 1970 power-cut recovery (ISAPI /System/tim
await expect(cam().syncClock(HOST_NOW, 60)).rejects.toThrow("clock set failed: HTTP 403");
});
it("the dahua driver does NOT claim the capability (no ISAPI time endpoint)", async () => {
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(false);
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).toEqual({ 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");
});
});
+78 -11
View File
@@ -18,8 +18,12 @@ import { digestGet, digestRequest } from "./http-digest.js";
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
// HTTP when an event fires; the bytes are stored and referenced from the signed
// event as an independent fraud-control record (the camera PULLS, it never pushes
// to us). Hikvision (ISAPI) and Dahua (CGI) differ only in the snapshot URL and
// channel encoding. Both use HTTP Digest auth (see ./http-digest.ts).
// to us). Hikvision (ISAPI) and Dahua (CGI) differ in the snapshot URL, the
// channel encoding and the clock endpoint. Both use HTTP Digest auth (see ./http-digest.ts).
//
// VERIFIED on hardware (2026-09-17): a Dahua IPC-HFW2549T-AS-IL (fw 2.880) at
// 10.0.10.11 returns a 2880×1620 JPEG from /cgi-bin/snapshot.cgi?channel=1 —
// and HTTP 400 for channel=0. See wiki/entities/dahua-ipc-hfw2549t.md.
//
// VERIFIED on hardware (2026-06-15): a Hikvision unit at 10.0.10.121 returns a
// 2688×1520 JPEG from /ISAPI/Streaming/channels/101/picture with Digest auth.
@@ -162,8 +166,8 @@ class HttpCamera implements CameraDevice {
});
}
/** Digest request against an arbitrary device path (ISAPI config reads/writes). */
protected isapi(method: "GET" | "PUT", path: string, body?: string) {
/** Digest request against an arbitrary device path (ISAPI / CGI config reads+writes). */
protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) {
return digestRequest({
host: this.#host,
port: this.#port,
@@ -197,7 +201,7 @@ class HikvisionCamera extends HttpCamera {
* explicit offset makes the instant unambiguous regardless of that config.
*/
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
const read = await this.isapi("GET", "/ISAPI/System/time");
const read = await this.deviceRequest("GET", "/ISAPI/System/time");
if (read.status !== 200) {
throw new Error(`clock read failed: HTTP ${read.status}`);
}
@@ -221,7 +225,7 @@ class HikvisionCamera extends HttpCamera {
`<Time><timeMode>manual</timeMode><localTime>${localIso}</localTime>` +
(timeZone ? `<timeZone>${timeZone}</timeZone>` : "") +
`</Time>`;
const put = await this.isapi("PUT", "/ISAPI/System/time", body);
const put = await this.deviceRequest("PUT", "/ISAPI/System/time", body);
if (put.status !== 200) {
throw new Error(`clock set failed: HTTP ${put.status}`);
}
@@ -230,6 +234,67 @@ class HikvisionCamera extends HttpCamera {
}
}
// --- Dahua clock sync (CGI global.cgi getCurrentTime / setCurrentTime) --------------
// Same problem, different surface. The Dahua CGI reads and writes the clock as a
// NAIVE local wall-time string ("2026-09-17 10:35:49", no offset) in whatever time
// zone / DST the camera is configured for. We deliberately write the HOST's local
// wall time verbatim: what must match the booth is the OSD timestamp burned into
// every snapshot and the event times, i.e. the wall clock — not the camera's idea
// of UTC. (The bench unit ran a year-round UTC+1 with DST off and NTP off; after
// this sync its OSD read the booth's time.) VERIFIED on hardware 2026-09-17:
// setCurrentTime answers 200 "OK" and getCurrentTime reads the new value back.
// See wiki/entities/dahua-ipc-hfw2549t.md.
const DAHUA_TIME_PATH = "/cgi-bin/global.cgi?action=getCurrentTime";
/** "2026-09-17T10:35:49+02:00" (host localIso, WITH offset) → "2026-09-17 10:35:49"
* (the naive wall time the Dahua CGI speaks). */
function naiveWallTime(localIso: string): string {
const m = localIso.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/);
if (!m) throw new Error(`syncClock: unparseable host time ${localIso}`);
return `${m[1]} ${m[2]}`;
}
/** Parse a naive "YYYY-MM-DD HH:MM:SS" as an instant in the HOST's zone — both sides
* of the drift comparison go through this, so the zone cancels out. */
function naiveMs(naive: string): number {
return Date.parse(naive.replace(" ", "T"));
}
class DahuaCamera extends HttpCamera {
async syncClock(localIso: string, maxDriftSec: number): Promise<ClockSyncResult> {
const read = await this.deviceRequest("GET", DAHUA_TIME_PATH);
if (read.status !== 200) {
throw new Error(`clock read failed: HTTP ${read.status}`);
}
// Reply body: "result=2026-09-17 09:35:51"
const cameraNaive =
read.body.toString("utf8").match(/result=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1] ?? null;
const hostNaive = naiveWallTime(localIso);
const cameraMs = cameraNaive ? naiveMs(cameraNaive) : NaN;
const driftSeconds = Number.isFinite(cameraMs)
? Math.round(Math.abs(naiveMs(hostNaive) - cameraMs) / 1000)
: null;
if (driftSeconds != null && driftSeconds <= maxDriftSec) {
return { driftSeconds, synced: false };
}
const set = await this.deviceRequest(
"GET",
`/cgi-bin/global.cgi?action=setCurrentTime&time=${encodeURIComponent(hostNaive)}`,
);
// Dahua answers 200 with a body of "OK"; a refused write is a non-200 or "Error".
if (set.status !== 200 || !/^OK/.test(set.body.toString("utf8").trim())) {
throw new Error(
`clock set failed: HTTP ${set.status} ${set.body.toString("utf8").trim().slice(0, 40)}`,
);
}
stubLog(this.driverId, `clock synced (was ${driftSeconds ?? "unparseable"}s off)`);
return { driftSeconds, synced: true };
}
}
const channelField: ConfigField = {
key: "channel",
label: "Channel",
@@ -329,15 +394,17 @@ export const dahuaDriver: CameraDriver = {
id: "dahua",
category: "camera",
label: "Dahua camera",
description: "Dahua snapshot via CGI (HTTP Digest).",
description: "Dahua snapshot via CGI (HTTP Digest) + clock sync.",
transports: ["tcp-ip"],
configFields: cameraConfigFields,
// Dahua channels are 0-based on the CGI; the admin enters 1-based. No stream in the
// path (the second arg is ignored — Dahua has no main/sub snapshot distinction here).
// snapshot.cgi channels are 1-BASED, exactly as the admin enters them (only Dahua's
// configManager TABLES are 0-indexed — the earlier `ch - 1` here drew a permanent
// HTTP 400 on real hardware, 2026-09-17). No stream in the path: `subtype` is
// ignored by snapshot.cgi, the still always comes off the main stream.
create: (c) =>
new HttpCamera(
new DahuaCamera(
"dahua",
c,
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(0, ch - 1)}`,
(ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(1, ch)}`,
),
};