/**
* 摄像头云台(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 { getAppDataDir } from './runtime.js';
import {
extractRTSPInfo,
_isapiAuth as acquireIsapiAuth,
_isapiRequest as isapiRequest,
} from './cameraOsd.js';
// ─── 文件日志(独立文件,便于排查云台问题) ───
// 目录沿用项目约定 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;
}
/** 解析 RTSP URL → { host, username, password, channel, port } */
function _parseTarget(rtspUrl, channelOverride, portOverride) {
const info = extractRTSPInfo(rtspUrl);
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));
const override = Number(channelOverride);
if (Number.isInteger(override) && override > 0) channel = override;
const p = Number(portOverride);
return {
host: info.host,
username: info.username,
password: info.password,
channel,
port: Number.isInteger(p) && p > 0 ? p : 80,
};
}
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;
},
};
}
/**
* 按候选 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) : ''}`,
};
}
/**
* 方向 / 变倍 / 聚焦 / 光圈 —— 持续型动作
* @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.channel, opts.port);
} catch (e) {
return { ok: false, message: `RTSP 地址无效: ${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);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
const r = await _putWithFallback(session, target.host, `${def.kind}:${target.channel}`, uris, body);
return r.ok
? { ok: true, action: key, uri: r.uri, message: `${stop ? '停止' : '执行'}成功 (HTTP ${r.status})` }
: { ok: false, action: key, message: r.message };
} catch (e) {
_err('%s 异常: %s', key, e.message);
return { ok: false, action: key, message: `云台操作异常: ${e.message}` };
}
}
/** 开始持续运动 */
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.channel, opts.port);
} catch (e) {
return { ok: false, message: `RTSP 地址无效: ${e.message}` };
}
_log('调用预置点 %d ch=%d host=%s', id, target.channel, target.host);
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
// SDK 调用预置点不带请求体
const r = await _putWithFallback(session, target.host, `presetGoto:${target.channel}`, URI_BUILDERS.presetGoto(target.channel, id), null);
return r.ok
? { ok: true, presetId: id, uri: r.uri, message: `预置点 ${id} 已调用 (HTTP ${r.status})` }
: { ok: false, presetId: id, message: r.message };
} catch (e) {
_err('预置点调用异常: %s', e.message);
return { ok: false, presetId: id, message: `预置点调用异常: ${e.message}` };
}
}
/** 设置(保存)预置点 */
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.channel, opts.port);
} catch (e) {
return { ok: false, message: `RTSP 地址无效: ${e.message}` };
}
const body = _XML_HEAD + '' + id + '' +
'' + _xmlEscape(presetName || `Preset${id}`) + '';
_log('设置预置点 %d (%s) ch=%d host=%s', id, presetName || '', target.channel, target.host);
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
const r = await _putWithFallback(session, target.host, `presetSet:${target.channel}`, URI_BUILDERS.presetSet(target.channel, id), body);
return r.ok
? { ok: true, presetId: id, uri: r.uri, message: `预置点 ${id} 已设置 (HTTP ${r.status})` }
: { ok: false, presetId: id, message: r.message };
} catch (e) {
_err('预置点设置异常: %s', e.message);
return { ok: false, presetId: id, message: `预置点设置异常: ${e.message}` };
}
}
/** 自动巡航(autoPan)开关 */
export async function ptzAuto(rtspUrl, on, opts = {}) {
let target;
try {
target = _parseTarget(rtspUrl, opts.channel, opts.port);
} catch (e) {
return { ok: false, message: `RTSP 地址无效: ${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);
try {
const session = await _openSession(target.host, target.username, target.password, target.port);
if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
const r = await _putWithFallback(session, target.host, `autoPan:${target.channel}`, URI_BUILDERS.autoPan(target.channel), body);
return r.ok
? { ok: true, uri: r.uri, message: `自动巡航已${enabled ? '开启' : '关闭'} (HTTP ${r.status})` }
: { ok: false, message: r.message };
} catch (e) {
_err('自动巡航异常: %s', e.message);
return { ok: false, message: `自动巡航异常: ${e.message}` };
}
}