From efeed362a404c156bf1eb9fec571d99215288306 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 16 Sep 2026 17:07:56 +0800 Subject: [PATCH] =?UTF-8?q?fix(camera):=20=E4=BA=91=E5=8F=B0=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E7=9B=B4=E8=BF=9E=E6=91=84=E5=83=8F=E6=9C=BA=EF=BC=88?= =?UTF-8?q?NVR=20=E6=8A=A5=E6=96=87=E9=87=8C=20data.ip=20=E6=98=AF?= =?UTF-8?q?=E5=BD=95=E5=83=8F=E6=9C=BA=EF=BC=8C=E4=B8=8D=E6=98=AF=E6=91=84?= =?UTF-8?q?=E5=83=8F=E6=9C=BA=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 线上整夜实测 215 条指令、13 台设备,暴露两个问题: 1) 带录像机的报文全打错设备(77 次 401) 平台对"挂在录像机上的摄像机"下发的形状是: data.ip / username / password = 录像机;camera.ip = 摄像机;server.* = 录像机详情 (实测例:camera.ip=192.168.8.86,而 data.ip=192.168.8.241、password=ky666888) 原来把 data.ip 当摄像机地址,又用 rtspUrl 里的摄像机密码去连录像机 → 401 HTML。 现在 _parseTarget 的目标是【摄像机】(camera.ip → rtspUrl 的 host → data.ip 兜底), 凭据取 rtspUrl;录像机(server 块)只作兜底:摄像机失败才改试,且优先走 ContentMgmt 代理路径。 为什么录像机只能是兜底:实测 8.241(DS-7932N-R4) 的 /ISAPI/ContentMgmt/PTZCtrlProxy/channels 里 16 个 IP 通道全部 enabled=false、controlProtocol 为空(录像机没配云台), /ISAPI/PTZCtrl/channels 还一直 503 Device Busy —— 走录像机根本驱动不了云台。 2) ONVIF 偶发错误重试不足 "Wrong ONVIF SOAP response" 没被识别为偶发错误(水星 MIPC332 那台会回这个),且只重试 1 次。 现在纳入偶发集合(Parse Error / Wrong ONVIF SOAP response / 连接重置类), 改为首次 + 最多 2 次重试、间隔递增;SOAP Fault(设备明确的拒绝)仍不重试。 顺带把 4 个动作的执行路径统一到 _runChain/_execOnce(原先每个函数各写一遍协议分支), 去掉明显重复。 真机验证(平台原报文形状):目标主机由 192.168.8.241 变为 192.168.8.86,ONVIF 认证通过, 左转 0.8 秒 Δx=-0.0867。离线回归 46 断言全通过(新增"摄像机优先 / 录像机兜底"4 条)。 --- utils/cameraPtz.js | 285 +++++++++++++++++++++++++++------------------ 1 file changed, 174 insertions(+), 111 deletions(-) diff --git a/utils/cameraPtz.js b/utils/cameraPtz.js index 32cea22..c37100e 100644 --- a/utils/cameraPtz.js +++ b/utils/cameraPtz.js @@ -192,24 +192,51 @@ function _parseTarget(rtspUrl, opts = {}) { // 兼容 /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(opts.channel); - if (Number.isInteger(override) && override > 0) channel = override; - const host = _cleanHost(opts.ip || info.host); + // ── 摄像机地址:优先平台显式给的 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); - return { + const target = { host, // ⚠️ 凭据【不能】优先用显式字段:实测平台在密码含 @ 时把它切给了 ip 字段 // (rtspUrl 是 admin:qwe2024@…,而下发的是 ip="@192.168.11.247" + password="qwe2024"), // 用错密码会让 ONVIF 直接报 SOAP Fault: Authority failure。 - // → 以 rtspUrl 解析结果为准,显式字段只在 rtspUrl 缺项时兜底。 + // → 摄像机凭据以 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) { @@ -362,6 +389,93 @@ async function _putWithFallback(session, host, cacheKey, uris, body) { }; } +/** 候选路径排序:录像机(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 @@ -385,25 +499,33 @@ function _dropOnvif(host) { } /** - * 偶发传输层错误(设备偶尔返回非 HTTP 响应、连接被重置…):实测 TP-Link 在 - * control/stop 连得很快时会偶发 "Parse Error: Expected HTTP/, RTSP/ or ICE/"。 - * 这类错误断开重连一次基本就好;而【丢掉 stop】= 云台一直转,代价远大于重试。 + * 偶发错误(设备偶尔返回非 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|ECONNRESET|socket hang up|EPIPE|ETIMEDOUT|timeout|ECONNREFUSED|not connected/i + 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)); } -/** 偶发错误就断开重连重试一次;重试仍是幂等的(stop / 同一速度的运动 / 预置点) */ +/** 偶发错误就断开重连重试(首次 + 最多 2 次);这些操作是幂等的(stop / 同速度运动 / 预置点) */ async function _withOnvifRetry(target, label, fn) { - try { - return await fn(); - } catch (e) { - if (!_isOnvifTransient(e)) throw e; - _log('ONVIF %s 偶发传输错误(%s)→ 断开重连后重试一次', label, e.message); - _dropOnvif(target.host); - return await 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) */ @@ -615,35 +737,15 @@ export async function ptzAction(rtspUrl, action, speed = 4, stop = false, opts = _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 _withOnvifRetry(target, key, () => _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); - - try { - const session = await _openSession(target.host, target.username, target.password, target.port); - if (!session) return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' }; - const ch = await _resolveIsapiChannel(session, target.host, target.channel); - if (ch.noPtz) { - return { ok: false, action: key, protocol: 'isapi', message: `设备 PTZ 通道 ${ch.channel} 的 pan/tilt/zoom 能力均为 false(该摄像机没有云台机构),已跳过发送` }; - } - const r = await _putWithFallback(session, target.host, `${def.kind}:${ch.channel}`, URI_BUILDERS[def.kind](ch.channel), 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}` }; - } + const r = await _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 }; } /** 开始持续运动 */ @@ -668,30 +770,15 @@ export async function ptzPresetGoto(rtspUrl, presetId, opts = {}) { } _log('调用预置点 %d ch=%d host=%s', id, target.channel, target.host); - const proto = await _protocol(target); - if (proto === 'onvif') { - try { - return await _withOnvifRetry(target, `presetGoto(${id})`, () => _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 均不可用)' }; - const ch = await _resolveIsapiChannel(session, target.host, target.channel); - // SDK 调用预置点不带请求体 - const r = await _putWithFallback(session, target.host, `presetGoto:${ch.channel}`, URI_BUILDERS.presetGoto(ch.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}` }; - } + const r = await _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 }; } /** 设置(保存)预置点 */ @@ -708,29 +795,15 @@ export async function ptzPresetSet(rtspUrl, presetId, presetName, opts = {}) { '' + _xmlEscape(presetName || `Preset${id}`) + ''; _log('设置预置点 %d (%s) ch=%d host=%s', id, presetName || '', target.channel, target.host); - const proto = await _protocol(target); - if (proto === 'onvif') { - try { - return await _withOnvifRetry(target, `presetSet(${id})`, () => _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 均不可用)' }; - const ch = await _resolveIsapiChannel(session, target.host, target.channel); - const r = await _putWithFallback(session, target.host, `presetSet:${ch.channel}`, URI_BUILDERS.presetSet(ch.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}` }; - } + const r = await _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)开关 */ @@ -745,22 +818,12 @@ export async function ptzAuto(rtspUrl, on, opts = {}) { const body = _XML_HEAD + '' + (enabled ? 100 : 0) + ''; _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 均不可用)' }; - const ch = await _resolveIsapiChannel(session, target.host, target.channel); - const r = await _putWithFallback(session, target.host, `autoPan:${ch.channel}`, URI_BUILDERS.autoPan(ch.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}` }; - } + return await _runChain(target, { + label: 'auto', + verb: `自动巡航${enabled ? '开启' : '关闭'}`, + cacheKey: 'autoPan', + uris: (ch) => URI_BUILDERS.autoPan(ch), + body, + onvif: null, // ONVIF ver20 PTZ 没有 autoPan 对应接口(只有 PresetTour,该型号不支持) + }); }