printServer/utils/cameraOsd.js
liufumingren 8fa511dfa1 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 断言仍全通过。
2026-09-15 22:03:22 +08:00

446 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 摄像头 OSD(屏幕叠加文字)处理工具
*
* 用法:
* import { setCameraOSD } from '../utils/cameraOsd.js';
* await setCameraOSD('rtsp://admin:pass@192.168.1.100:554/stream', '通道名称');
*/
import { createRequire } from 'module';
import { promisify, format } from 'util';
import fs from 'fs';
import path from 'path';
import os from 'os';
import http from 'http';
import crypto from 'crypto';
import { getAppDataDir } from './runtime.js';
const require = createRequire(import.meta.url);
const { Cam } = require('onvif');
// ─── 文件日志 ───
// 目录沿用项目约定 getAppDataDir()(同 frpc.js):Windows 打包版 = %ProgramData%\printServer,
// Linux / 开发态 = 项目根目录。之前自己拼 process.env.ProgramData 会让 Linux 写到
// 字面量目录 "/opt/printserver/C:/ProgramData/printServer/" 下。
function _logDir() {
const dir = getAppDataDir();
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
return dir;
}
function _writeLog(level, ...args) {
// 调用处用的是 %s/%d 占位符,必须走 util.format;直接 join 会把占位符原样打进日志
const msg = format(...args);
console.log(`[CameraOSD] ${msg}`);
try {
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
fs.appendFileSync(path.join(_logDir(), 'cameraOsd.log'), `[${ts}] [${level}] ${msg}\n`, 'utf-8');
} catch (_) { /* ignore */ }
}
const _log = (...a) => _writeLog('INFO', ...a);
const _err = (...a) => _writeLog('ERR', ...a);
/**
* 解析 RTSP URL 提取 [用户名, 密码, 主机, 通道号]
* 格式: rtsp://username:password@host:port/path
* 通道解析: /stream2 → 2;/Streaming/Channels/201 → 2;默认 1
* (cameraPtz.js 也复用本函数)
*/
export function extractRTSPInfo(rtspUrl) {
const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)(?::(\d+))?(\/\S*)?/);
if (!match) {
throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径');
}
let channel = 1;
const pathPart = match[5] || '';
// 海康风格 /Streaming/Channels/201(第1位数字=通道号)
const hc = pathPart.match(/\/Streaming\/Channels\/(\d)\d{2}/i);
if (hc) channel = parseInt(hc[1], 10);
else {
const sm = pathPart.match(/stream(\d+)/i);
if (sm) channel = parseInt(sm[1], 10);
}
return { username: match[1], password: match[2], host: match[3], channel };
}
/**
* 给摄像头设置 OSD 文字
* @param {string} rtspUrl - 摄像头 RTSP 地址
* @param {string} osdText - 要显示的 OSD 文字
* @returns {Promise<{ok: boolean, message: string}>}
*/
export async function setCameraOSD(rtspUrl, osdText, posX = -0.9, posY = 0.8) {
return _osdAction(rtspUrl, osdText, posX, posY, 'replace');
}
/**
* 清空 OSD(删除全部文本 OSD,不创建新的)
*/
export async function clearCameraOSD(rtspUrl) {
return _osdAction(rtspUrl, '', 0, 0, 'clear');
}
/**
* 海康 ISAPI 协议 OSD 设置(当 ONVIF 不可用时回退)
* 接口: GET/PUT /ISAPI/System/Video/inputs/channels/1/overlays/text
* 认证: Basic / Digest 自适应
* @returns {Promise<{ok: boolean, message: string}>}
*/
async function _osdActionIsapi(host, username, password, osdText, posX, posY, mode, channel = 1) {
_log('[ISAPI] 开始设置 OSD host=%s mode=%s', host, mode);
try {
let auth = await _isapiAuth(host, username, password, '/ISAPI/System/Video/inputs/channels/1/overlays/text');
if (!auth) {
return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
}
// 401 时自动重新握手并重试一次(nonce 过期/stale 场景)
const authedReq = async (method, uri, body) => {
let resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
if (resp.status === 401) {
const newAuth = await _isapiAuth(host, username, password, '/ISAPI/System/Video/inputs/channels/1/overlays/text');
if (newAuth) {
auth = newAuth;
resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
}
}
return resp;
};
// 嗅探设备全部通道(不依赖 rtspUrl 的通道号):全部通道都设置
let channels = [];
try {
const chListResp = await authedReq('GET', '/ISAPI/System/Video/inputs/channels', null);
const chIds = [...(chListResp.body || '').matchAll(/<VideoInputChannel[^>]*>[\s\S]*?<id>(\d+)<\/id>/g)].map(m => +m[1]);
if (chIds.length > 0) channels = chIds;
} catch (_) { /* 枚举失败则回退单通道 */ }
if (channels.length === 0) {
const ch = Number.isInteger(channel) && channel >= 1 ? channel : 1;
channels = [ch];
_log('[ISAPI] 通道枚举失败,回退单通道 %d', ch);
} else {
_log('[ISAPI] 设备通道列表: %s,将对全部通道执行 %s', JSON.stringify(channels), mode);
}
// 逐通道执行
const results = [];
for (const c of channels) {
const r = await _osdChannelIsapi(authedReq, c, osdText, posX, posY, mode);
results.push(r);
}
const okList = results.filter(r => r.ok);
const failList = results.filter(r => !r.ok);
if (okList.length === 0) {
return { ok: false, message: 'ISAPI 所有通道操作失败: ' + failList.map(r => `ch${r.channel}: ${r.message}`).join('; ') };
}
const msg = mode === 'clear'
? `OSD 已清空 (ISAPI),通道 ${okList.map(r => r.channel).join(',')}`
: `OSD 设置成功 (ISAPI): ${osdText},通道 ${okList.map(r => r.channel).join(',')}`;
_log('[ISAPI] 汇总: %s', msg);
const out = { ok: true, message: msg, count: okList.length };
if (failList.length) out.partialFail = failList.map(r => `ch${r.channel}: ${r.message}`);
return out;
} catch (e) {
_err('[ISAPI] 异常:', e.message);
return { ok: false, message: 'ISAPI OSD 操作异常: ' + e.message };
}
}
/**
* 对单个通道执行 OSD 设置/清空
* @returns {Promise<{ok: boolean, message: string, channel: number}>}
*/
async function _osdChannelIsapi(authedReq, ch, osdText, posX, posY, mode) {
const baseUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays/text`;
const mainUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays`;
// 1. 读取现有 OSD
const getResp = await authedReq('GET', baseUri, null);
_log('[ISAPI] ch%d GET overlays status=%s body=%s', ch, getResp.status, (getResp.body || '').slice(0, 300));
if (mode === 'clear') {
// 清空:提交空列表
const emptyXml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0"></TextOverlayList>';
const putResp = await authedReq('PUT', baseUri, emptyXml);
_log('[ISAPI] ch%d clear PUT status=%s body=%s', ch, putResp.status, (putResp.body || '').slice(0, 200));
if (putResp.status >= 200 && putResp.status < 300) {
_log('[ISAPI] ch%d 已清空', ch);
return { ok: true, message: '已清空', channel: ch };
}
return { ok: false, message: '清空失败: HTTP ' + putResp.status, channel: ch };
}
// 2. 设置文字:坐标系从 overlays 总接口读 normalizedScreenSize(实测 GV413 为 704x576,
// 与主码流分辨率无关)。Y 轴 bottom-up:ONVIF posY(-1=下,+1=上)→ py = (1-posY)/2*H
let width = 704, height = 576;
try {
const mainResp = await authedReq('GET', mainUri, null);
const wm = /<normalizedScreenWidth>(\d+)</.exec(mainResp.body || '');
const hm = /<normalizedScreenHeight>(\d+)</.exec(mainResp.body || '');
if (wm && hm) { width = +wm[1]; height = +hm[1]; }
} catch (_) { /* 用默认 704x576 */ }
// 重试链:normalized 坐标系 → 安全坐标(0,0)
const attempts = [
{ w: width, h: height },
{ w: 0, h: 0 }
];
let putResp = { status: 0, body: '' };
for (const a of attempts) {
let px, py;
if (a.w === 0) { px = 0; py = 0; }
else {
px = Math.max(0, Math.min(a.w - 8, Math.round((posX + 1) / 2 * a.w)));
py = Math.max(0, Math.min(a.h - 8, Math.round((1 - posY) / 2 * a.h)));
}
const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">\n' +
'<TextOverlay>\n<id>1</id>\n<enabled>true</enabled>\n' +
`<positionX>${px}</positionX>\n<positionY>${py}</positionY>\n` +
`<displayText>${_xmlEscape(osdText)}</displayText>\n` +
'<isPersistentText>true</isPersistentText>\n' +
'</TextOverlay>\n</TextOverlayList>';
putResp = await authedReq('PUT', baseUri, xml);
_log('[ISAPI] ch%d set PUT(%d,%d) status=%s body=%s', ch, px, py, putResp.status, (putResp.body || '').slice(0, 160));
if (putResp.status >= 200 && putResp.status < 300) break;
}
if (!(putResp.status >= 200 && putResp.status < 300)) {
return { ok: false, message: '设置失败: HTTP ' + putResp.status, channel: ch };
}
// 3. 回读验证(精确匹配 displayText 标签,避免短文本误命中)
const verifyResp = await authedReq('GET', baseUri, null);
const body = verifyResp.body || '';
_log('[ISAPI] ch%d verify GET status=%s body=%s', ch, verifyResp.status, body.slice(0, 300));
const escapedText = _xmlEscape(osdText);
if (body.includes(`<displayText>${escapedText}</displayText>`)) {
_log('[ISAPI] ch%d OK OSD 写入成功: %s', ch, osdText);
return { ok: true, message: '写入成功', channel: ch };
}
_err('[ISAPI] ch%d FAIL 回读验证失败: 期望="%s" body=%s', ch, osdText, body.slice(0, 300));
return { ok: false, message: '回读验证失败', channel: ch };
}
function _xmlEscape(s) {
return String(s ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/**
* ISAPI 认证握手:先无认证请求,401 后按 WWW-Authenticate 选择 Digest 或 Basic
* @returns {Promise<{headers:(method,uri)=>Object}|null>}
* (导出以供 cameraPtz.js 复用)
*/
export async function _isapiAuth(host, username, password, probeUri, port = 80) {
try {
const probe = await _isapiRequest(host, 'GET', probeUri, null, {}, 8000, port);
const wwwAuth = (probe.headers['www-authenticate'] || '') + ' ' + ((probe.body && probe.status === 401) ? '' : '');
_log('[ISAPI] 探测 status=%s WWW-Authenticate=%s', probe.status, (probe.headers['www-authenticate'] || '无').slice(0, 120));
// 有些设备直接返回 200(无认证)
if (probe.status !== 401 && probe.status !== 0) {
return { headers: () => ({}) };
}
const wa = probe.headers['www-authenticate'] || '';
if (/digest/i.test(wa)) {
const realm = /realm="([^"]*)"/i.exec(wa)?.[1] || '';
const nonce = /nonce="([^"]*)"/i.exec(wa)?.[1] || '';
const qop = /qop="([^"]*)"/i.exec(wa)?.[1] || 'auth';
const opaque = /opaque="([^"]*)"/i.exec(wa)?.[1] || '';
if (!realm || !nonce) return null;
return {
headers: (method, uri) => {
const cnonce = crypto.randomBytes(8).toString('hex');
const nc = '00000001';
const ha1 = _md5(`${username}:${realm}:${password}`);
const ha2 = _md5(`${method}:${uri}`);
const response = _md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
let h = `Digest username="${username}", realm="${realm}", nonce="${nonce}", uri="${uri}", response="${response}", qop=${qop}, nc=${nc}, cnonce="${cnonce}"`;
if (opaque) h += `, opaque="${opaque}"`;
return { Authorization: h };
}
};
}
// Basic
const basic = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
return { headers: () => ({ Authorization: basic }) };
} catch (e) {
_err('[ISAPI] 认证探测异常:', e.message);
return null;
}
}
function _md5(s) {
return crypto.createHash('md5').update(s, 'utf8').digest('hex');
}
/** 嗅探设备是否支持海康 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, port);
// 200 = 无需认证;401 = 接口存在需认证;404/其他 = 不支持
if (resp.status === 200 || resp.status === 401) {
_log('[ISAPI] 嗅探成功 host=%s status=%d', host, resp.status);
return true;
}
_log('[ISAPI] 嗅探不支持 host=%s status=%d', host, resp.status);
return false;
} catch (e) {
_log('[ISAPI] 嗅探失败 host=%s: %s', host, e.message);
return false;
}
}
/** 原生 HTTP 请求(带 Content-Length,避免 chunked 被设备拒绝;导出以供 cameraPtz.js 复用) */
export function _isapiRequest(host, method, uri, body, headers, timeoutMs = 8000, port = 80) {
return new Promise((resolve, reject) => {
const h = { ...headers };
if (body != null) {
h['Content-Type'] = 'application/xml';
h['Content-Length'] = Buffer.byteLength(body);
}
const req = http.request({ host, port, path: uri, method, headers: h, timeout: timeoutMs }, (res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data }));
});
req.on('timeout', () => { req.destroy(); reject(new Error('ISAPI 请求超时')); });
req.on('error', reject);
if (body != null) req.write(body);
req.end();
});
}
/**
* OSD 核心操作
* @param {string} mode - 'replace'=删旧建新, 'append'=叠加追加, 'clear'=只删不建
*/
async function _osdAction(rtspUrl, osdText, posX, posY, mode) {
_log('收到 OSD 请求, rtspUrl:', rtspUrl.replace(/:[^:@]+@/, ':****@'), 'text:', osdText, 'pos:', posX, posY, 'mode:', mode);
const info = extractRTSPInfo(rtspUrl);
_log('连接摄像头:', info.host, '用户:', info.username, '通道:', info.channel);
// 0. 先嗅探 ISAPI(海康系设备):可用则直接走 ISAPI,无需试 ONVIF
if (await _isapiProbe(info.host)) {
_log('探测到 ISAPI 协议(海康系设备),直接使用 ISAPI');
return _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel);
}
// 1. ONVIF 尝试:端口依次 80(标准)→ 2020(MIPC 等非标),全失败回退 ISAPI
return new Promise((resolve) => {
const onvifPorts = [80, 2020];
const tryPort = (idx) => {
_log('尝试 ONVIF 端口:', onvifPorts[idx]);
new Cam({
hostname: info.host,
username: info.username,
password: info.password,
port: onvifPorts[idx],
timeout: 6000,
preserveAddress: true
}, async function (err) {
if (err) {
_err('ONVIF 端口 %d 失败:', onvifPorts[idx], err.message);
if (idx + 1 < onvifPorts.length) { tryPort(idx + 1); return; }
_log('ONVIF 全部失败 → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
return;
}
// ONVIF 连接成功,执行原逻辑
const cam = this;
(async () => {
try {
// 转为 Promise 风格
const getOSDs = promisify(cam.getOSDs).bind(cam);
const createOSD = promisify(cam.createOSD).bind(cam);
const setOSD = promisify(cam.setOSD).bind(cam);
const token = cam.defaultProfile.videoSourceConfiguration.$.token;
_log('videoSourceConfigurationToken:', token);
// 检查是否已有文本 OSD(过滤掉时间 OSD 等非 Plain 类型)
let osdList = [];
try {
const resp = await getOSDs(token);
osdList = resp?.getOSDsResponse?.OSDs || [];
_log('已有 OSD 数量:', osdList.length, JSON.stringify(osdList));
} catch (e) {
_err('获取已有 OSD 失败:', e.message);
}
// 只取 Plain 类型的文本 OSD token
const textOSD = osdList.find(o => o.textString?.type === 'Plain');
const osdToken = textOSD?.$?.token;
const createOptions = {
videoSourceConfigurationToken: token,
plaintext: osdText,
position: { x: posX, y: posY }
};
if (mode === 'clear') {
// clear 模式:只删不建
_log('clear 模式,删除所有文本 OSD');
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
}
_log('clear 完成');
resolve({ ok: true, message: 'OSD 已清空', count: 0 });
return;
}
// replace 模式:删除已有文本 OSD,再创建新的
if (osdToken) {
_log('replace 模式,删除已有文本 OSD');
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
}
}
// 创建新 OSD,最多重试 3 次
_log('创建新 OSD, text:', osdText, 'pos:', posX, posY);
for (let i = 0; i < 3; i++) {
try {
await createOSD(createOptions);
_log('第', i + 1, '次尝试成功');
break;
} catch (e) {
_err('第', i + 1, '次尝试失败:', e.message);
if (i === 2) throw e;
}
}
// 验证写入
const verifyResp = await getOSDs(token);
const verifyList = verifyResp?.getOSDsResponse?.OSDs || [];
const textOSDs = verifyList.filter(o => o.textString?.type === 'Plain');
const verifyTexts = textOSDs.map(o => o.textString?.plainText || '').join(',');
_log('验证读取 OSD: 共', textOSDs.length, '个文本, texts=[', verifyTexts, ']');
const found = textOSDs.some(o => {
const txt = String(o?.textString?.plainText ?? '');
return txt === String(osdText) || txt.includes(String(osdText));
});
if (found) {
_log('OK OSD 写入成功:', osdText);
resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length });
} else {
_err('ONVIF FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + '] → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
} catch (e) {
_err('ONVIF 操作失败:', e.message, '→ 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
})();
});
};
tryPort(0);
});
}