feat(camera): 云台支持 ONVIF,兼容非海康设备(实测 TP-Link 可动)

背景:平台下发的 camera.ptz.* 目标实测是 TP-Link TL-IPC682P-A4(192.168.9.226 /
192.168.11.247),设备没有 ISAPI(/ISAPI/System/deviceInfo 404,PUT 返回 405 +
{"error_code":-10000} 的 JSON),纯 ISAPI 实现必然全失败(线上 20 条指令 0 成功)。

- 协议选路:先探海康 ISAPI(_isapiProbe),不通则走 ONVIF;结果按 host 缓存,
  不会每条指令都多一次探测往返
- ONVIF 实现:continuousMove(方向用 onlySendPanTilt、变倍用 onlySendZoom,
  速度档 1~7 → 0.15~1)/ stop / gotoPreset / setPreset;
  聚焦、光圈、autoPan 在 ONVIF 下无对应接口,明确返回不支持(而不是静默失败)
- 新增 ONVIF_MOVE_TIMEOUT_MS=30s 兜底:ONVIF 的 ContinuousMove 不带 Timeout 时
  设备会一直转,服务端漏发 stop 就停不下来;设 0 可关闭以与 ISAPI 行为完全一致
- 预置点:契约里的 presetId 先按 token 匹配、再按 Preset{id} / preset_{id} 名字匹配;
  setPreset 优先指定 token,设备不接受时让它自行分配并把实际 token 写进日志
- 平台下发的 ip 字段实测是 "@192.168.11.247"(多一个前导 @),新增 _cleanHost
  统一清洗,并兼容误传完整 rtsp:// 的情况
- utils/cameraOsd.js 导出 _isapiProbe 并支持自定义 port(默认 80,原调用行为不变)

真机实测(192.168.11.247,与生产同一台):协议探测 → ONVIF,会话 profileToken=profile_1,
left 1 秒后位置 x 由 0.6766 → 0.5717(Δx=0.1049,方向正确),设备预置点 token 1~8。
离线回归 38 断言仍全通过。
This commit is contained in:
liufumingren 2026-09-15 22:03:22 +08:00
parent 13872b0514
commit 8fa511dfa1
2 changed files with 271 additions and 5 deletions

View File

@ -278,10 +278,10 @@ function _md5(s) {
return crypto.createHash('md5').update(s, 'utf8').digest('hex');
}
/** 嗅探设备是否支持海康 ISAPI 协议(快速 GET /ISAPI/System/deviceInfo) */
async function _isapiProbe(host) {
/** 嗅探设备是否支持海康 ISAPI 协议(快速 GET /ISAPI/System/deviceInfo,导出以供 cameraPtz.js 做协议选路) */
export async function _isapiProbe(host, port = 80) {
try {
const resp = await _isapiRequest(host, 'GET', '/ISAPI/System/deviceInfo', null, {}, 2500);
const resp = await _isapiRequest(host, 'GET', '/ISAPI/System/deviceInfo', null, {}, 2500, port);
// 200 = 无需认证;401 = 接口存在需认证;404/其他 = 不支持
if (resp.status === 200 || resp.status === 401) {
_log('[ISAPI] 嗅探成功 host=%s status=%d', host, resp.status);

View File

@ -28,13 +28,18 @@
import fs from 'fs';
import path from 'path';
import { format } from 'util';
import { createRequire } from 'module';
import { getAppDataDir } from './runtime.js';
import {
extractRTSPInfo,
_isapiAuth as acquireIsapiAuth,
_isapiRequest as isapiRequest,
_isapiProbe as isapiProbe,
} from './cameraOsd.js';
const require = createRequire(import.meta.url);
const { Cam } = require('onvif');
// ─── 文件日志(独立文件,便于排查云台问题) ───
// 目录沿用项目约定 getAppDataDir():Windows 打包版 = %ProgramData%\printServer;
// Linux / 开发态 = 项目根目录(和 frpc.log、run.log 同级)。
@ -152,6 +157,21 @@ function _speedValue(speed) {
return s < 7 ? 15 * Math.round(s) : 100;
}
/**
* 清洗服务端下发的 host:实测平台会下发 "@192.168.11.247"(前面多一个 @),
* 也兼容误传完整 rtsp:// 地址的情况。
*/
function _cleanHost(v) {
let s = String(v === null || v === undefined ? '' : v).trim();
if (/^rtsp:\/\//i.test(s)) {
try { return extractRTSPInfo(s).host || ''; } catch (_) { /* 继续下面的清洗 */ }
}
s = s.replace(/^rtsp:\/\//i, '').replace(/^@+/, '').trim();
const at = s.lastIndexOf('@');
if (at >= 0) s = s.slice(at + 1); // user:pass@host → host
return s.split('/')[0].split(':')[0]; // host:port/path → host
}
/**
* 解析目标设备 → { host, username, password, channel, port }
* 优先用服务端显式下发的 ip / username / password / channel(推荐,不依赖 rtspUrl 解析),
@ -175,7 +195,7 @@ function _parseTarget(rtspUrl, opts = {}) {
const override = Number(opts.channel);
if (Number.isInteger(override) && override > 0) channel = override;
const host = opts.ip || info.host;
const host = _cleanHost(opts.ip || info.host);
if (!host) throw new Error('缺少设备地址(需 rtspUrl 或 ip)');
const p = Number(opts.port);
@ -274,6 +294,208 @@ async function _putWithFallback(session, host, cacheKey, uris, body) {
};
}
// ═══════════════════════════════════════════════════════════════════════
// ONVIF 通道(给非海康设备用;实测车队里是 TP-Link TL-IPC682P-A4)
// 选路策略与 cameraOsd.js 一致:先探海康 ISAPI → 探不通过就走 ONVIF
// ═══════════════════════════════════════════════════════════════════════
/**
* 连续运动的兜底超时(毫秒)。
* ONVIF 的 ContinuousMove 不写 Timeout 时设备会一直转,服务端漏发 stop 就停不下来;
* 这里给个上限,最多转这么久。设 0 = 不发 Timeout(行为与 ISAPI 路径完全一致)。
*/
const ONVIF_MOVE_TIMEOUT_MS = 30000;
/** host → 'isapi' | 'onvif'(一台设备只探一次,避免每条指令都多一个往返) */
const _protoCache = new Map();
/** host → { cam, profileToken, port }(ONVIF 会话复用;库内部每次请求新建 HTTP,复用安全) */
const _onvifCache = new Map();
function _dropOnvif(host) {
_onvifCache.delete(host);
}
/** 速度档位 1~7 → ONVIF 速度 0.15~1(默认 4 档 → 0.57) */
function _speedNormalized(speed) {
const s = Number(speed);
const v = (Number.isFinite(s) && s > 0 ? s : 4) / 7;
return Math.max(0.15, Math.min(1, Math.round(v * 100) / 100));
}
/** 探测设备协议(结果永久缓存) */
async function _protocol(target) {
if (_protoCache.has(target.host)) return _protoCache.get(target.host);
let proto = 'onvif';
try {
proto = (await isapiProbe(target.host, target.port)) ? 'isapi' : 'onvif';
} catch (e) {
_err('协议探测异常 host=%s: %s(按 ONVIF 处理)', target.host, e.message);
}
_log('协议探测 host=%s:%d → %s', target.host, target.port, proto.toUpperCase());
_protoCache.set(target.host, proto);
return proto;
}
/** onvif 库的 promise 化封装(签名已核对:除 getProfiles 外均为 (options, callback)) */
function _onvifCall(cam, name, options) {
return new Promise((resolve, reject) => {
const f = cam[name];
if (typeof f !== 'function') { reject(new Error(`onvif 库缺少方法 ${name}`)); return; }
try {
f.call(cam, options || {}, (e, d) => (e ? reject(e) : resolve(d)));
} catch (e) {
reject(e);
}
});
}
/** 建立 ONVIF 连接(设备不在线/不支持时返回 null,不抛) */
function _onvifConnect(target, port) {
return new Promise((resolve) => {
let settled = false;
const timer = setTimeout(() => {
if (!settled) { settled = true; _err('ONVIF 连接超时 %s:%d', target.host, port); resolve(null); }
}, 8000);
const cam = new Cam({
hostname: target.host,
username: target.username,
password: target.password,
port,
timeout: 6000,
preserveAddress: true,
}, (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (err) { _err('ONVIF 连接失败 %s:%d: %s', target.host, port, err.message); resolve(null); return; }
resolve(cam);
});
cam.on('error', () => { /* 交给 callback 处理 */ });
});
}
/** 取 profileToken:优先 defaultProfile,兜底 getProfiles() 的第一个 */
function _onvifProfileToken(cam) {
const fromDefault = cam.defaultProfile?.$?.token || cam.activeSource?.profileToken;
if (fromDefault) return Promise.resolve(fromDefault);
return new Promise((resolve) => {
cam.getProfiles((err, profiles) => {
if (err) { resolve(null); return; }
const list = Array.isArray(profiles) ? profiles : (profiles?.profiles || []);
resolve(list[0]?.$?.token || null);
});
});
}
/** 建立/复用 ONVIF 会话 → { cam, profileToken, port } 或 null */
async function _onvifSession(target) {
const cached = _onvifCache.get(target.host);
if (cached) return cached;
// 先试平台给的口(默认 80),再试非标的 2020
const ports = [target.port, 2020].filter((p, i, a) => a.indexOf(p) === i);
for (const port of ports) {
const cam = await _onvifConnect(target, port);
if (!cam) continue;
const profileToken = await _onvifProfileToken(cam);
if (!profileToken) { _err('ONVIF 已连上但取不到 profileToken %s:%d', target.host, port); continue; }
const sess = { cam, profileToken, port };
_onvifCache.set(target.host, sess);
_log('ONVIF 会话就绪 host=%s:%d profileToken=%s', target.host, port, profileToken);
return sess;
}
return null;
}
/** 拉设备上的预置点表(token → preset 对象) */
async function _onvifPresets(cam, profileToken) {
const r = await _onvifCall(cam, 'getPresets', { profileToken });
if (r && typeof r === 'object' && Object.keys(r).length) return r;
return cam.presets || {};
}
/** 把契约里的 presetId 映射到设备实际 token(先按 token,再按 Preset{id} / preset_{id} 名字) */
function _resolvePresetToken(table, id) {
const keys = Object.keys(table || {});
if (keys.includes(String(id))) return String(id);
const want = [`preset_${id}`, `Preset${id}`].map(s => s.toLowerCase());
const hit = keys.find(k => want.includes(String(table[k]?.name || '').toLowerCase()));
return hit || null;
}
/** ONVIF:方向 / 变倍 / 停止 */
async function _onvifAction(target, action, speed, stop) {
const sess = await _onvifSession(target);
if (!sess) return { ok: false, protocol: 'onvif', message: `ONVIF 连接失败(${target.host}:${target.port})` };
const { cam, profileToken } = sess;
const def = ACTIONS[action];
if (stop) {
await _onvifCall(cam, 'stop', { profileToken, panTilt: true, zoom: true });
return { ok: true, protocol: 'onvif', message: '停止成功 (ONVIF Stop)' };
}
const timeout = ONVIF_MOVE_TIMEOUT_MS > 0 ? { timeout: ONVIF_MOVE_TIMEOUT_MS } : {};
if (def.kind === 'ptz') {
const v = _speedNormalized(speed);
const x = (def.pan || 0) * v * SIGNS.pan;
const y = (def.tilt || 0) * v * SIGNS.tilt;
// onlySendPanTilt:该设备的 zoom 范围是 0~0,不同时发 zoom,避免被拒
await _onvifCall(cam, 'continuousMove', { profileToken, x, y, onlySendPanTilt: true, ...timeout });
return { ok: true, protocol: 'onvif', message: `执行成功 (ONVIF ContinuousMove x=${x} y=${y})` };
}
if (def.kind === 'zoom') {
const zoom = (def.zoom || 0) * _speedNormalized(speed) * SIGNS.zoom;
await _onvifCall(cam, 'continuousMove', { profileToken, zoom, onlySendZoom: true, ...timeout });
return { ok: true, protocol: 'onvif', message: `执行成功 (ONVIF Zoom=${zoom})` };
}
return { ok: false, protocol: 'onvif', action, message: `${action} 在 ONVIF 协议下无对应接口(${def.kind} 不支持)` };
}
/** ONVIF:调用预置点 */
async function _onvifPresetGoto(target, id) {
const sess = await _onvifSession(target);
if (!sess) return { ok: false, protocol: 'onvif', presetId: id, message: `ONVIF 连接失败(${target.host}:${target.port})` };
const { cam, profileToken } = sess;
const table = await _onvifPresets(cam, profileToken);
const token = _resolvePresetToken(table, id);
if (!token) {
return {
ok: false, protocol: 'onvif', presetId: id,
message: `设备上没有预置点 ${id}(现有: ${Object.keys(table).join(',') || '无'})`,
};
}
await _onvifCall(cam, 'gotoPreset', { profileToken, preset: token });
return { ok: true, protocol: 'onvif', presetId: id, token, message: `预置点 ${id}(token=${token}) 已调用 (ONVIF GotoPreset)` };
}
/** ONVIF:设置(保存)预置点 */
async function _onvifPresetSet(target, id, presetName) {
const sess = await _onvifSession(target);
if (!sess) return { ok: false, protocol: 'onvif', presetId: id, message: `ONVIF 连接失败(${target.host}:${target.port})` };
const { cam, profileToken } = sess;
const name = presetName || `Preset${id}`;
const table = await _onvifPresets(cam, profileToken);
const existing = _resolvePresetToken(table, id);
const pickToken = (r) => r?.setPresetResponse?.presetToken || r?.presetToken || r?.$?.presetToken || null;
try {
// 已存在则覆盖同名 token;不存在则请求设备用该编号作 token
const r = await _onvifCall(cam, 'setPreset', { profileToken, presetName: name, presetToken: existing || String(id) });
const token = pickToken(r) || existing || String(id);
if (String(token) !== String(id)) _log('注意:设备给回的 token=%s ≠ 请求的 presetId=%s', token, id);
return { ok: true, protocol: 'onvif', presetId: id, token, message: `预置点 ${id} 已设置(token=${token},ONVIF SetPreset)` };
} catch (e) {
if (existing) throw e; // 覆盖已知 token 都失败 → 真实错误,抛出交给上层
// 设备不接受指定 token → 让它自行分配(此时设备分配的 token 可能与 presetId 不一致)
const r = await _onvifCall(cam, 'setPreset', { profileToken, presetName: name });
const token = pickToken(r);
_log('设备自行分配 token=%s(≠ 请求的 presetId=%s)', token, id);
return { ok: true, protocol: 'onvif', presetId: id, token, message: `预置点已设置(设备分配 token=${token},与请求的 ${id} 不一致,请以 token 为准)` };
}
}
/**
* 方向 / 变倍 / 聚焦 / 光圈 —— 持续型动作
* @param {string} rtspUrl
@ -296,9 +518,22 @@ export async function ptzAction(rtspUrl, action, speed = 4, stop = false, opts =
return { ok: false, message: `设备信息无效: ${e.message}` };
}
_log('%s action=%s speed=%s ch=%d host=%s', stop ? '停止' : '开始', key, speed, target.channel, target.host);
// 协议选路:ISAPI 探测不通过(非海康设备)→ 走 ONVIF
const proto = await _protocol(target);
if (proto === 'onvif') {
try {
return await _onvifAction(target, key, speed, stop);
} catch (e) {
_dropOnvif(target.host);
_err('ONVIF %s 异常: %s', key, e.message);
return { ok: false, action: key, protocol: 'onvif', message: `ONVIF 云台操作异常: ${e.message}` };
}
}
const body = _buildBody(key, speed, stop);
const uris = URI_BUILDERS[def.kind](target.channel);
_log('%s action=%s speed=%s ch=%d host=%s', stop ? '停止' : '开始', key, speed, target.channel, target.host);
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
@ -334,6 +569,18 @@ export async function ptzPresetGoto(rtspUrl, presetId, opts = {}) {
return { ok: false, message: `设备信息无效: ${e.message}` };
}
_log('调用预置点 %d ch=%d host=%s', id, target.channel, target.host);
const proto = await _protocol(target);
if (proto === 'onvif') {
try {
return await _onvifPresetGoto(target, id);
} catch (e) {
_dropOnvif(target.host);
_err('ONVIF 预置点调用异常: %s', e.message);
return { ok: false, protocol: 'onvif', presetId: id, message: `ONVIF 预置点调用异常: ${e.message}` };
}
}
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
@ -361,6 +608,18 @@ export async function ptzPresetSet(rtspUrl, presetId, presetName, opts = {}) {
const body = _XML_HEAD + '<PTZPreset><id>' + id + '</id>' +
'<presetName>' + _xmlEscape(presetName || `Preset${id}`) + '</presetName></PTZPreset>';
_log('设置预置点 %d (%s) ch=%d host=%s', id, presetName || '', target.channel, target.host);
const proto = await _protocol(target);
if (proto === 'onvif') {
try {
return await _onvifPresetSet(target, id, presetName);
} catch (e) {
_dropOnvif(target.host);
_err('ONVIF 预置点设置异常: %s', e.message);
return { ok: false, protocol: 'onvif', presetId: id, message: `ONVIF 预置点设置异常: ${e.message}` };
}
}
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
@ -385,6 +644,13 @@ export async function ptzAuto(rtspUrl, on, opts = {}) {
const enabled = on === true || on === 1 || String(on).toLowerCase() === 'true' || String(on) === '1';
const body = _XML_HEAD + '<autoPanData><autoPan>' + (enabled ? 100 : 0) + '</autoPan></autoPanData>';
_log('%s 自动巡航 ch=%d host=%s', enabled ? '开启' : '关闭', target.channel, target.host);
const proto = await _protocol(target);
if (proto === 'onvif') {
// ONVIF ver20 PTZ 没有 autoPan 对应接口(只有 PresetTour,该型号不支持)
return { ok: false, protocol: 'onvif', message: '自动巡航在 ONVIF 协议下不支持(无 autoPan 接口)' };
}
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };