diff --git a/utils/cameraOsd.js b/utils/cameraOsd.js index d4f37fa..f996ee4 100644 --- a/utils/cameraOsd.js +++ b/utils/cameraOsd.js @@ -11,6 +11,8 @@ import { promisify } from 'util'; import fs from 'fs'; import path from 'path'; import os from 'os'; +import http from 'http'; +import crypto from 'crypto'; const require = createRequire(import.meta.url); const { Cam } = require('onvif'); @@ -34,15 +36,25 @@ const _log = (...a) => _writeLog('INFO', ...a); const _err = (...a) => _writeLog('ERR', ...a); /** - * 解析 RTSP URL 提取 [用户名, 密码, 主机] + * 解析 RTSP URL 提取 [用户名, 密码, 主机, 通道号] * 格式: rtsp://username:password@host:port/path + * 通道解析: /stream2 → 2;/Streaming/Channels/201 → 2;默认 1 */ function extractRTSPInfo(rtspUrl) { - const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)/); + const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)(?::(\d+))?(\/\S*)?/); if (!match) { throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径'); } - return { username: match[1], password: match[2], host: match[3] }; + 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 }; } /** @@ -62,6 +74,207 @@ 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 channel=%d', host, mode, channel); + try { + const ch = Number.isInteger(channel) && channel >= 1 ? channel : 1; + const baseUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays/text`; + const mainUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays`; + let auth = await _isapiAuth(host, username, password, baseUri); + 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, baseUri); + if (newAuth) { + auth = newAuth; + resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri)); + } + } + return resp; + }; + + // 1. 读取现有 OSD + const getResp = await authedReq('GET', baseUri, null); + _log('[ISAPI] GET overlays status=%s body=%s', getResp.status, (getResp.body || '').slice(0, 500)); + + if (mode === 'clear') { + // 清空:提交空列表 + const emptyXml = '\n' + + ''; + const putResp = await authedReq('PUT', baseUri, emptyXml); + _log('[ISAPI] clear PUT status=%s body=%s', putResp.status, (putResp.body || '').slice(0, 300)); + if (putResp.status >= 200 && putResp.status < 300) { + return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 }; + } + return { ok: false, message: 'ISAPI 清空 OSD 失败: HTTP ' + putResp.status }; + } + + // 2. 设置文字:设备字段兼容 positionX/positionY/displayText(回读确认过) + // 坐标系:从 overlays 总接口读 normalizedScreenSize(实测 GV413 为 704x576, + // 与主码流 1920x1080 无关)。Y 轴方向:实测该设备 positionY 小=靠底部(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 = /(\d+)(\d+)\n' + + '\n' + + '\n1\ntrue\n' + + `${px}\n${py}\n` + + `${_xmlEscape(osdText)}\n` + + 'true\n' + + '\n'; + putResp = await authedReq('PUT', baseUri, xml); + _log('[ISAPI] set PUT(%d,%d) status=%s body=%s', px, py, putResp.status, (putResp.body || '').slice(0, 200)); + if (putResp.status >= 200 && putResp.status < 300) break; + } + if (!(putResp.status >= 200 && putResp.status < 300)) { + return { ok: false, message: 'ISAPI 设置 OSD 失败: HTTP ' + putResp.status + ' ' + (putResp.body || '').slice(0, 100) }; + } + + // 3. 回读验证 + const verifyResp = await authedReq('GET', baseUri, null); + const body = verifyResp.body || ''; + _log('[ISAPI] verify GET status=%s body=%s', verifyResp.status, body.slice(0, 500)); + if (mode === 'clear') { + return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 }; + } + const found = body.includes(_xmlEscape(osdText)) || body.includes(osdText); + if (found) { + _log('[ISAPI] OK OSD 写入成功:', osdText); + return { ok: true, message: 'OSD 设置成功 (ISAPI): ' + osdText, count: 1 }; + } + _err('[ISAPI] FAIL 回读验证失败: 期望="' + osdText + '" body=' + body.slice(0, 300)); + return { ok: false, message: 'ISAPI OSD 写入验证失败' }; + } catch (e) { + _err('[ISAPI] 异常:', e.message); + return { ok: false, message: 'ISAPI OSD 操作异常: ' + e.message }; + } +} + +function _xmlEscape(s) { + return String(s ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +/** + * ISAPI 认证握手:先无认证请求,401 后按 WWW-Authenticate 选择 Digest 或 Basic + * @returns {Promise<{headers:(method,uri)=>Object}|null>} + */ +async function _isapiAuth(host, username, password, probeUri) { + try { + const probe = await _isapiRequest(host, 'GET', probeUri, null, {}); + 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) */ +async function _isapiProbe(host) { + try { + const resp = await _isapiRequest(host, 'GET', '/ISAPI/System/deviceInfo', null, {}, 2500); + // 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 被设备拒绝) */ +function _isapiRequest(host, method, uri, body, headers, timeoutMs = 8000) { + 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: 80, 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'=只删不建 @@ -69,24 +282,38 @@ export async function clearCameraOSD(rtspUrl) { 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); + _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) => { - new Cam({ - hostname: info.host, - username: info.username, - password: info.password, - port: 2020, - timeout: 10000, - preserveAddress: true - }, async function (err) { - if (err) { - _err('连接失败:', err.message); - return resolve({ ok: false, message: `连接摄像头失败: ${err.message}` }); - } - - const cam = this; - try { + 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); @@ -163,13 +390,16 @@ async function _osdAction(rtspUrl, osdText, posX, posY, mode) { _log('OK OSD 写入成功:', osdText); resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length }); } else { - _err('FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + ']'); - resolve({ ok: false, message: 'OSD 写入验证失败' }); + _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('操作失败:', e.message); - resolve({ ok: false, message: `OSD 操作失败: ${e.message}` }); - } - }); + } catch (e) { + _err('ONVIF 操作失败:', e.message, '→ 回退海康 ISAPI 协议'); + resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel)); + } + })(); + }); + }; + tryPort(0); }); }