/**
* 摄像头云台(PTZ)ISAPI 控制工具
*
* 服务端通过 WS 下发的 method(入口在 services/camera.js):
* camera.ptz.control { rtspUrl, action, speed? } 开始(持续运动)
* camera.ptz.stop { rtspUrl, action } 停止(同一动作,数值置 0)
* camera.ptz.presetGoto { rtspUrl, presetId } 调用预置点
* camera.ptz.presetSet { rtspUrl, presetId, presetName? } 设置预置点
* camera.ptz.auto { rtspUrl, on } 自动巡航(autoPan)开关
*
* 用法:
* import { ptzControl, ptzStop } from '../utils/cameraPtz.js';
* await ptzControl(rtspUrl, 'left', 4);
* await ptzStop(rtspUrl, 'left');
*
* 接口路径、报文格式、速度换算均对齐海康官方无插件 SDK(webVideoCtrl.js):
* PUT /ISAPI/PTZCtrl/channels/{ch}/continuous 方向 / 变倍(IPC 直连或模拟通道)
* PUT /ISAPI/ContentMgmt/PTZCtrlProxy/channels/{ch}/continuous NVR 的 IP 通道(代理)
* PUT /ISAPI/Image/channels/{ch}/focus | iris 聚焦 / 光圈
* PUT /ISAPI/ContentMgmt/ImageProxy/channels/{ch}/focus | iris NVR 代理
* PUT /ISAPI/System/Video/inputs/channels/{ch}/focus | iris IPC 直连的聚焦 / 光圈变体
* PUT /ISAPI/PTZCtrl/channels/{ch}/presets/{id}[/goto] 预置点设置 / 调用
* PUT /ISAPI/PTZCtrl/channels/{ch}/autoPan 自动巡航
*
* 速度换算:speed < 7 → 15 * speed,否则 100(默认 speed=4 → 60);停止 = 0。
*/
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 同级)。
// ⚠️ 不要自己用 process.env.ProgramData 拼:Linux 下会得到一个字面量目录
// "/opt/printserver/C:/ProgramData/..."(cameraOsd 从 7 月底起就掉在那里)。
function _logDir() {
const dir = getAppDataDir();
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
return dir;
}
function _writeLog(level, ...args) {
// 调用处用的是 %s 占位符,必须走 util.format;直接 join 会把 %s 原样打进日志
const msg = format(...args.map(a => (typeof a === 'string' ? a : (() => {
try { return JSON.stringify(a); } catch (_) { return String(a); }
})())));
console.log(`[CameraPTZ] ${msg}`);
try {
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
fs.appendFileSync(path.join(_logDir(), 'cameraPtz.log'), `[${ts}] [${level}] ${msg}\n`, 'utf-8');
} catch (_) { /* ignore */ }
}
const _log = (...a) => _writeLog('INFO', ...a);
const _err = (...a) => _writeLog('ERR', ...a);
/** 方向符号:实测方向相反时改这里(pan: + 右 - 左;tilt: + 上 - 下) */
const SIGNS = { pan: 1, tilt: 1, zoom: 1, focus: 1, iris: 1 };
/**
* 动作表(对齐 SDK 的 iPTZIndex 1~15 语义)
* kind: ptz=方向(PTZData pan/tilt)/ zoom=变倍(PTZData zoom)/ focus / iris
*/
const ACTIONS = {
up: { kind: 'ptz', pan: 0, tilt: 1 },
down: { kind: 'ptz', pan: 0, tilt: -1 },
left: { kind: 'ptz', pan: -1, tilt: 0 },
right: { kind: 'ptz', pan: 1, tilt: 0 },
upleft: { kind: 'ptz', pan: -1, tilt: 1 },
downleft: { kind: 'ptz', pan: -1, tilt: -1 },
upright: { kind: 'ptz', pan: 1, tilt: 1 },
downright: { kind: 'ptz', pan: 1, tilt: -1 },
zoomin: { kind: 'zoom', zoom: 1 },
zoomout: { kind: 'zoom', zoom: -1 },
focusin: { kind: 'focus', focus: 1 },
focusout: { kind: 'focus', focus: -1 },
irisin: { kind: 'iris', iris: 1 },
irisout: { kind: 'iris', iris: -1 },
};
/** 兼容写法:驼峰 / 下划线 / SDK 的数字索引 */
const ACTION_ALIASES = {
upleft: 'upleft', upright: 'upright', downleft: 'downleft', downright: 'downright',
up_left: 'upleft', up_right: 'upright', down_left: 'downleft', down_right: 'downright',
zoomin: 'zoomin', zoomout: 'zoomout', zoom_in: 'zoomin', zoom_out: 'zoomout',
focusin: 'focusin', focusout: 'focusout', focus_in: 'focusin', focus_out: 'focusout',
focusfar: 'focusin', focusnear: 'focusout',
irisin: 'irisin', irisout: 'irisout', iris_in: 'irisin', iris_out: 'irisout',
1: 'up', 2: 'down', 3: 'left', 4: 'right',
5: 'upleft', 6: 'downleft', 7: 'upright', 8: 'downright',
10: 'zoomin', 11: 'zoomout', 12: 'focusin', 13: 'focusout', 14: 'irisin', 15: 'irisout',
};
/** 每种动作的候选 URI(按顺序尝试:先 IPC 直连/模拟通道,再 NVR 代理) */
const URI_BUILDERS = {
ptz: ch => [
`/ISAPI/PTZCtrl/channels/${ch}/continuous`,
`/ISAPI/ContentMgmt/PTZCtrlProxy/channels/${ch}/continuous`,
],
zoom: ch => [
`/ISAPI/PTZCtrl/channels/${ch}/continuous`,
`/ISAPI/ContentMgmt/PTZCtrlProxy/channels/${ch}/continuous`,
],
focus: ch => [
`/ISAPI/Image/channels/${ch}/focus`,
`/ISAPI/ContentMgmt/ImageProxy/channels/${ch}/focus`,
`/ISAPI/System/Video/inputs/channels/${ch}/focus`,
],
iris: ch => [
`/ISAPI/Image/channels/${ch}/iris`,
`/ISAPI/ContentMgmt/ImageProxy/channels/${ch}/iris`,
`/ISAPI/System/Video/inputs/channels/${ch}/iris`,
],
presetSet: (ch, id) => [
`/ISAPI/PTZCtrl/channels/${ch}/presets/${id}`,
`/ISAPI/ContentMgmt/PTZCtrlProxy/channels/${ch}/presets/${id}`,
],
presetGoto: (ch, id) => [
`/ISAPI/PTZCtrl/channels/${ch}/presets/${id}/goto`,
`/ISAPI/ContentMgmt/PTZCtrlProxy/channels/${ch}/presets/${id}/goto`,
],
autoPan: ch => [
`/ISAPI/PTZCtrl/channels/${ch}/autoPan`,
`/ISAPI/ContentMgmt/PTZCtrlProxy/channels/${ch}/autoPan`,
],
};
/**
* 某设备上已验证可用的【候选序号】缓存:host → { 'ptz:6': 0 }
* ⚠️ 必须存序号而不是完整 URI:预置点类 URI 里带 presetId,若缓存整条 URI,
* 换另一个预置点时首个候选会命中旧 id 的地址 → 调错预置点。
*/
const _routeCache = new Map();
/** 归一化动作名 */
function _normalizeAction(action) {
if (action === null || action === undefined) return null;
const raw = String(action).trim();
const key = (ACTION_ALIASES[raw] || ACTION_ALIASES[raw.toLowerCase()] || raw.toLowerCase());
return ACTIONS[key] ? key : null;
}
/** 速度档位 → ISAPI 数值(SDK 规则:<7 档 ×15,≥7 档 100) */
function _speedValue(speed) {
const s = Number(speed);
if (!Number.isFinite(s) || s <= 0) return 15 * 4; // 默认 4 档 → 60
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 解析),
* 缺哪项才回落到 rtspUrl。
*/
function _parseTarget(rtspUrl, opts = {}) {
let info = { host: '', username: '', password: '', channel: 1 };
if (rtspUrl) {
try {
info = extractRTSPInfo(rtspUrl);
} catch (e) {
// rtspUrl 不合法/缺账号时,靠显式字段补齐
_log('rtspUrl 解析失败,改用显式字段: %s', e.message);
}
}
let channel = Number(info.channel) || 1;
// 兼容 /Streaming/Channels/1201 这种通道号 ≥10 的写法(取末两位为码流号)
const m = String(rtspUrl || '').match(/\/Streaming\/Channels\/(\d+)/i);
if (m && m[1].length > 2) channel = Number(m[1].slice(0, -2));
// ── 摄像机地址:优先平台显式给的 camera.ip,其次 rtspUrl 的 host,最后才是 data.ip。
// ⚠️ 带录像机的报文里 data.ip 是【录像机】的地址(摄像机在 camera.ip),
// 拿它当摄像机会用摄像机的密码去连录像机 → 401。
const camBlock = opts.camera || {};
const camCh = Number(camBlock.channel_id);
if (Number.isInteger(camCh) && camCh > 0) channel = camCh;
const override = Number(opts.channel);
if (Number.isInteger(override) && override > 0) channel = override; // 顶层最优先
const host = _cleanHost(camBlock.ip) || _cleanHost(info.host) || _cleanHost(opts.ip);
if (!host) throw new Error('缺少设备地址(需 rtspUrl 或 ip)');
const p = Number(opts.port);
const target = {
host,
// ⚠️ 凭据【不能】优先用显式字段:实测平台在密码含 @ 时把它切给了 ip 字段
// (rtspUrl 是 admin:qwe2024@…,而下发的是 ip="@192.168.11.247" + password="qwe2024"),
// 用错密码会让 ONVIF 直接报 SOAP Fault: Authority failure。
// → 摄像机凭据以 rtspUrl 解析结果为准,显式字段只在 rtspUrl 缺项时兜底。
username: info.username || opts.username,
password: info.password || opts.password,
channel,
port: Number.isInteger(p) && p > 0 ? p : 80,
server: null,
};
// ── 录像机(平台下发的 server 块):仅作【兜底】目标。
// 实测 8.241(DS-7932N-R4)的 /ISAPI/ContentMgmt/PTZCtrlProxy/channels 里 16 个
// IP 通道全部 enabled=false、controlProtocol 为空(录像机没配云台),
// /ISAPI/PTZCtrl/channels 还一直 503 Device Busy → 走录像机基本没用,
// 真正能让云台动的是直连摄像机,所以摄像机永远优先。
const srv = opts.server;
const srvHost = _cleanHost(srv && (srv.internal_ip || srv.ip));
if (srvHost && srvHost !== host) {
const sp = Number(srv.internal_port);
target.server = {
host: srvHost,
username: srv.username || opts.username,
password: srv.password || opts.password,
channel,
port: Number.isInteger(sp) && sp > 0 ? sp : 80,
};
}
return target;
}
function _xmlEscape(s) {
return String(s === null || s === undefined ? '' : s)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"');
}
const _XML_HEAD = "";
/** 组装请求体:返回 { body, kind } */
function _buildBody(action, speed, stop) {
const def = ACTIONS[action];
const v = stop ? 0 : _speedValue(speed);
switch (def.kind) {
case 'ptz':
return _XML_HEAD +
'' + (def.pan || 0) * v * SIGNS.pan + '' +
'' + (def.tilt || 0) * v * SIGNS.tilt + '';
case 'zoom':
return _XML_HEAD + '' + (def.zoom || 0) * v * SIGNS.zoom + '';
case 'focus':
return _XML_HEAD + '' + (def.focus || 0) * v * SIGNS.focus + '';
case 'iris':
return _XML_HEAD + '' + (def.iris || 0) * v * SIGNS.iris + '';
default:
return null;
}
}
/** 建立认证会话(含 401 自动重握手),失败返回 null */
async function _openSession(host, username, password, port) {
let auth = await acquireIsapiAuth(host, username, password, '/ISAPI/System/deviceInfo', port);
if (!auth) return null;
return {
async put(uri, body) {
let resp = await isapiRequest(host, 'PUT', uri, body, auth.headers('PUT', uri), 5000, port);
if (resp.status === 401) {
_log('401 → 重新握手后重试 uri=%s', uri);
const fresh = await acquireIsapiAuth(host, username, password, '/ISAPI/System/deviceInfo', port);
if (fresh) {
auth = fresh;
resp = await isapiRequest(host, 'PUT', uri, body, auth.headers('PUT', uri), 5000, port);
}
}
return resp;
},
async get(uri) {
let resp = await isapiRequest(host, 'GET', uri, null, auth.headers('GET', uri), 5000, port);
if (resp.status === 401) {
const fresh = await acquireIsapiAuth(host, username, password, '/ISAPI/System/deviceInfo', port);
if (fresh) {
auth = fresh;
resp = await isapiRequest(host, 'GET', uri, null, auth.headers('GET', uri), 5000, port);
}
}
return resp;
},
};
}
/** host → { ids:number[], noPtzIds:number[] }(设备自报的 ISAPI PTZ 通道,只枚举一次) */
const _chCache = new Map();
/**
* 枚举设备自报的 PTZ 通道与云台能力。
* 实测 192.168.8.165(DS-2XD8F826E 双目 IPC):平台从 rtspUrl 的 /stream6 推出 channel=6,
* 而该机只有 PTZ 通道 1(发 6 → 403);且该机 panSupport/tiltSupport/zoomSupport 均为 false
* (压根没有云台机构,发通道 1 会回 200 但什么也不动)。
*/
async function _isapiChannelInfo(session, host) {
if (_chCache.has(host)) return _chCache.get(host);
let info = { ids: [], noPtzIds: [] };
try {
const resp = await session.get('/ISAPI/PTZCtrl/channels');
if (resp.status === 200) {
const ids = [];
const noPtzIds = [];
for (const m of String(resp.body || '').matchAll(/]([\s\S]*?)<\/PTZChannel>/g)) {
const block = m[1];
const id = Number(/(\d+)<\/id>/.exec(block)?.[1]);
if (!id) continue;
if (/false<\/enabled>/.test(block)) continue;
ids.push(id);
const flags = ['panSupport', 'tiltSupport', 'zoomSupport'];
const present = flags.filter(f => new RegExp(`<${f}>`).test(block));
if (present.length && present.every(f => new RegExp(`<${f}>false<\/${f}>`).test(block))) noPtzIds.push(id);
}
info = { ids, noPtzIds };
_log('设备 PTZ 通道 host=%s: ids=[%s] 无云台机构=[%s]', host, ids.join(','), noPtzIds.join(','));
} else {
_log('枚举 PTZ 通道失败 host=%s status=%s(沿用推导的通道号)', host, resp.status);
}
} catch (e) {
_err('枚举 PTZ 通道异常 host=%s: %s', host, e.message);
}
_chCache.set(host, info);
return info;
}
/**
* 决定实际要用的 PTZ 通道:
* 设备能枚举出通道时以设备为准(下发的编号在列表里就用它,否则用第一个);
* 枚举不到(如 NVR 不提供该接口)则沿用推导出的编号。
* @returns {Promise<{channel:number, noPtz:boolean}>}
*/
async function _resolveIsapiChannel(session, host, requested) {
const info = await _isapiChannelInfo(session, host);
if (!info.ids.length) return { channel: requested, noPtz: false };
if (info.ids.includes(requested)) return { channel: requested, noPtz: info.noPtzIds.includes(requested) };
_log('下发通道 %d 不在设备 PTZ 通道列表 [%s] 内(多为平台内部编号)→ 改用 %d', requested, info.ids.join(','), info.ids[0]);
return { channel: info.ids[0], noPtz: info.noPtzIds.includes(info.ids[0]) };
}
/**
* 按候选 URI 依次尝试,成功即缓存该设备可用的路径
* @returns {Promise<{ok:boolean, uri?:string, status?:number, body?:string, message?:string}>}
*/
async function _putWithFallback(session, host, cacheKey, uris, body) {
const cachedIdx = _routeCache.get(host)?.[cacheKey];
const ordered = (Number.isInteger(cachedIdx) && cachedIdx >= 0 && cachedIdx < uris.length)
? [uris[cachedIdx], ...uris.filter((_, i) => i !== cachedIdx)]
: uris.slice();
let last = { status: 0, body: '' };
for (const uri of ordered) {
try {
const resp = await session.put(uri, body);
_log('PUT %s → HTTP %s %s', uri, resp.status, (resp.body || '').slice(0, 160));
if (resp.status >= 200 && resp.status < 300) {
if (!_routeCache.has(host)) _routeCache.set(host, {});
_routeCache.get(host)[cacheKey] = uris.indexOf(uri);
return { ok: true, uri, status: resp.status };
}
last = resp;
// 只有"路径不对/不支持"类错误才值得换下一条;其它(如 401 已重试过)直接失败
if (![ 400, 403, 404, 405, 500, 501, 502, 503 ].includes(resp.status)) break;
} catch (e) {
_err('PUT %s 异常: %s', uri, e.message);
last = { status: 0, body: e.message };
}
}
return {
ok: false,
status: last.status,
body: last.body,
message: `全部候选接口失败(最后 HTTP ${last.status})${last.body ? ':' + String(last.body).slice(0, 120) : ''}`,
};
}
/** 候选路径排序:录像机(IP 通道)优先走 ContentMgmt 代理接口,摄像机直连优先 PTZCtrl */
function _urisFor(list, preferProxy) {
if (!preferProxy) return list;
const proxy = list.filter(u => u.includes('/ContentMgmt/'));
return [...proxy, ...list.filter(u => !u.includes('/ContentMgmt/'))];
}
/**
* 尝试顺序:摄像机直连优先,平台下发的录像机仅做兜底。
* @returns {Array<{host,username,password,port,channel,label,preferProxy}>}
*/
function _targets(target) {
const list = [{
host: target.host, username: target.username, password: target.password,
port: target.port, channel: target.channel, label: '摄像机', preferProxy: false,
}];
const s = target.server;
if (s && s.host && s.host !== target.host) {
list.push({
host: s.host, username: s.username, password: s.password,
port: s.port, channel: s.channel, label: '录像机', preferProxy: true,
});
}
return list;
}
/**
* 对单个目标执行一次云台操作(自动选 ISAPI / ONVIF)
* @param {object} t 目标
* @param {object} spec { label, verb, cacheKey, uris:(ch)=>string[], body, onvif:(t)=>Promise|null }
*/
async function _execOnce(t, spec) {
const proto = await _protocol(t);
if (proto === 'onvif') {
if (!spec.onvif) {
return { ok: false, protocol: 'onvif', message: `${spec.label} 在 ONVIF 协议下无对应接口(${t.host})` };
}
try {
const r = await _withOnvifRetry(t, spec.label, () => spec.onvif(t));
return { ...r, label: t.label, host: t.host };
} catch (e) {
_dropOnvif(t.host);
_err('ONVIF %s 异常: %s(%s %s)', spec.label, e.message, t.label, t.host);
return { ok: false, protocol: 'onvif', message: `${t.label}(${t.host})ONVIF 异常: ${e.message}` };
}
}
// ── ISAPI ──
try {
const session = await _openSession(t.host, t.username, t.password, t.port);
if (!session) {
return { ok: false, protocol: 'isapi', message: `${t.label}(${t.host})ISAPI 认证失败(Basic/Digest 均不可用)` };
}
const ch = await _resolveIsapiChannel(session, t.host, t.channel);
if (ch.noPtz) {
return {
ok: false, protocol: 'isapi', stopTrying: true,
message: `设备 PTZ 通道 ${ch.channel} 的 pan/tilt/zoom 能力均为 false(该摄像机没有云台机构),已跳过发送`,
};
}
const r = await _putWithFallback(session, t.host, `${spec.cacheKey}:${ch.channel}`, _urisFor(spec.uris(ch.channel), t.preferProxy), spec.body);
return r.ok
? { ok: true, protocol: 'isapi', uri: r.uri, status: r.status, message: `${spec.verb}成功(${t.label} HTTP ${r.status})` }
: { ok: false, protocol: 'isapi', message: `${t.label}(${t.host}):${r.message}` };
} catch (e) {
_err('%s ISAPI 异常: %s', spec.label, e.message);
return { ok: false, protocol: 'isapi', message: `${t.label}(${t.host})云台操作异常: ${e.message}` };
}
}
/** 按 摄像机 → 录像机 的顺序尝试,第一个成功即返回 */
async function _runChain(target, spec) {
const targets = _targets(target);
let last = null;
for (let i = 0; i < targets.length; i++) {
const t = targets[i];
const r = await _execOnce(t, spec);
if (r.ok || r.stopTrying) return r;
last = r;
if (targets[i + 1]) {
_log('%s%s 失败(%s)→ 改试%s %s', t.label, t.host, r.message, targets[i + 1].label, targets[i + 1].host);
}
}
return last;
}
// ═══════════════════════════════════════════════════════════════════════
// 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);
}
/**
* 同一台设备的云台操作串行执行。
* core/wsClient.js 是并发处理 WS 消息的,平台把 control/stop 挨得很近发过来时,
* 两个 SOAP 请求会同时打到同一台相机。实测 TP-Link 在并发下会返回
* `SOAP Fault: Authority failure` / `Parse Error` / 残缺 SOAP(8.85 一晚上 16 次)。
* 串行后设备侧同一时刻只看到一个请求,而且 control → stop 的顺序也有保障。
*/
const _hostChain = new Map();
function _serialize(host, fn) {
const prev = _hostChain.get(host) || Promise.resolve();
const run = prev.then(() => fn(), () => fn());
_hostChain.set(host, run.then(() => { }, () => { }));
return run;
}
/**
* 偶发错误(设备偶尔返回非 HTTP / 不完整的 SOAP 响应、连接被重置…):实测 TP-Link 在
* control/stop 连得很快时会偶发 "Parse Error: Expected HTTP/, RTSP/ or ICE/",
* 水星 MIPC332 那类设备会回 "Wrong ONVIF SOAP response"。
* 这类错误断开重连重试基本就好;而【丢掉 stop】= 云台一直转,代价远大于重试。
* 注意:SOAP Fault(Authority failure / Token does not exist 等)是设备明确的拒绝,不算偶发。
*/
function _isOnvifTransient(e) {
return /Parse Error|Wrong ONVIF SOAP response|ECONNRESET|socket hang up|EPIPE|ETIMEDOUT|timeout|ECONNREFUSED|not connected/i
.test(String(e && e.message ? e.message : e));
}
/** 偶发错误就断开重连重试(首次 + 最多 2 次);这些操作是幂等的(stop / 同速度运动 / 预置点) */
async function _withOnvifRetry(target, label, fn) {
const MAX = 3;
let lastErr;
for (let attempt = 1; attempt <= MAX; attempt++) {
try {
return await fn();
} catch (e) {
lastErr = e;
if (!_isOnvifTransient(e) || attempt === MAX) break;
_log('ONVIF %s 偶发错误(%s)→ 断开重连后第 %d 次重试', label, e.message, attempt);
_dropOnvif(target.host);
await new Promise(r => setTimeout(r, 150 * attempt));
}
}
throw lastErr;
}
/** 速度档位 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 });
_log('ONVIF 停止成功 profileToken=%s', profileToken);
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 });
_log('ONVIF 运动成功 x=%s y=%s (speed=%s profileToken=%s)', x, y, speed, profileToken);
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 });
_log('ONVIF 变倍成功 zoom=%s (speed=%s profileToken=%s)', zoom, speed, profileToken);
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 });
_log('ONVIF 预置点 %d 已调用(token=%s profileToken=%s)', id, token, profileToken);
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);
_log('ONVIF 预置点 %d 已设置(token=%s profileToken=%s)', id, token, profileToken);
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
* @param {string|number} action up/down/left/right/upLeft/.../zoomIn/zoomOut/focusIn/focusOut/irisIn/irisOut,或 SDK 索引 1~15
* @param {number} [speed=4] 1~7(<7 → 15×,≥7 → 100)
* @param {boolean} [stop=false] true 时数值置 0(同一个 action 用于停止)
* @param {object} [opts] { channel, port } 手动指定通道号 / ISAPI 端口(默认 80)
* @returns {Promise<{ok:boolean, action?:string, uri?:string, message:string}>}
*/
export async function ptzAction(rtspUrl, action, speed = 4, stop = false, opts = {}) {
const key = _normalizeAction(action);
if (!key) {
return { ok: false, message: `未知的云台动作: ${action}` };
}
const def = ACTIONS[key];
let target;
try {
target = _parseTarget(rtspUrl, opts);
} catch (e) {
return { ok: false, message: `设备信息无效: ${e.message}` };
}
_log('%s action=%s speed=%s ch=%d host=%s', stop ? '停止' : '开始', key, speed, target.channel, target.host);
const r = await _serialize(target.host, () => _runChain(target, {
label: `control(${key})`,
verb: stop ? '停止' : '执行',
cacheKey: def.kind,
uris: (ch) => URI_BUILDERS[def.kind](ch),
body: _buildBody(key, speed, stop),
onvif: (t) => _onvifAction(t, key, speed, stop),
}));
return { ...r, action: key };
}
/** 开始持续运动 */
export function ptzControl(rtspUrl, action, speed = 4, opts = {}) {
return ptzAction(rtspUrl, action, speed, false, opts);
}
/** 停止持续运动(同一个 action,数值置 0) */
export function ptzStop(rtspUrl, action, opts = {}) {
return ptzAction(rtspUrl, action, 0, true, opts);
}
/** 调用预置点 */
export async function ptzPresetGoto(rtspUrl, presetId, opts = {}) {
const id = Number(presetId);
if (!Number.isInteger(id) || id <= 0) return { ok: false, message: `预置点编号无效: ${presetId}` };
let target;
try {
target = _parseTarget(rtspUrl, opts);
} catch (e) {
return { ok: false, message: `设备信息无效: ${e.message}` };
}
_log('调用预置点 %d ch=%d host=%s', id, target.channel, target.host);
const r = await _serialize(target.host, () => _runChain(target, {
label: `presetGoto(${id})`,
verb: `预置点 ${id} 调用`,
cacheKey: 'presetGoto',
uris: (ch) => URI_BUILDERS.presetGoto(ch, id),
body: null, // SDK 调用预置点不带请求体
onvif: (t) => _onvifPresetGoto(t, id),
}));
return { ...r, presetId: id };
}
/** 设置(保存)预置点 */
export async function ptzPresetSet(rtspUrl, presetId, presetName, opts = {}) {
const id = Number(presetId);
if (!Number.isInteger(id) || id <= 0) return { ok: false, message: `预置点编号无效: ${presetId}` };
let target;
try {
target = _parseTarget(rtspUrl, opts);
} catch (e) {
return { ok: false, message: `设备信息无效: ${e.message}` };
}
const body = _XML_HEAD + '' + id + '' +
'' + _xmlEscape(presetName || `Preset${id}`) + '';
_log('设置预置点 %d (%s) ch=%d host=%s', id, presetName || '', target.channel, target.host);
const r = await _serialize(target.host, () => _runChain(target, {
label: `presetSet(${id})`,
verb: `预置点 ${id} 设置`,
cacheKey: 'presetSet',
uris: (ch) => URI_BUILDERS.presetSet(ch, id),
body,
onvif: (t) => _onvifPresetSet(t, id, presetName),
}));
return { ...r, presetId: id };
}
/** 自动巡航(autoPan)开关 */
export async function ptzAuto(rtspUrl, on, opts = {}) {
let target;
try {
target = _parseTarget(rtspUrl, opts);
} catch (e) {
return { ok: false, message: `设备信息无效: ${e.message}` };
}
const enabled = on === true || on === 1 || String(on).toLowerCase() === 'true' || String(on) === '1';
const body = _XML_HEAD + '' + (enabled ? 100 : 0) + '';
_log('%s 自动巡航 ch=%d host=%s', enabled ? '开启' : '关闭', target.channel, target.host);
return await _serialize(target.host, () => _runChain(target, {
label: 'auto',
verb: `自动巡航${enabled ? '开启' : '关闭'}`,
cacheKey: 'autoPan',
uris: (ch) => URI_BUILDERS.autoPan(ch),
body,
onvif: null, // ONVIF ver20 PTZ 没有 autoPan 对应接口(只有 PresetTour,该型号不支持)
}));
}