- 退件拆包: 参照散单 Web returnUnpackwork 移植(returnUnpack.*/stock.warehouse.search/order.detail 反查对照), 扫码指令条码(jsbarcode renderjs)、快扫串行队列+乐观累加、明细扫描行置顶、左右分栏原单对照汇总(未退回/一致/差异)、备注下拉选项本地持久化 - 摄像头: camera.ts(camera.list/setOsd、camera_server.*、getLiveStreamUrl 本地 MJPEG 代理), 设置弹窗+浮动预览窗(拖拽/全屏/最小化胶囊)、OSD 单号条码推送、fetch 探测 502 内网->公网回退 - exe 内置海康取流服务 electron/hikvision-live.js: 监听 127.0.0.1:17320(与 printServer 17311 隔离), ISAPI digest 登录+快照轮询 multipart MJPEG(~5fps, 零 npm 依赖); 端口候选回退 httpPort->port->80(NVR port 常为 RTSP 554); 通道号映射 0/1->主码流 101/2->子 102(100 无效通道 NVR 返回 503); writeHead 后 flushHeaders(否则首帧前响应头不 flush); 登录限时 3.5s; 登录失败 502 兜底图与 printServer 行为一致 - 全局 401 处理: 非 skipAuth 请求 code/status=401 清 token 回登录(3s 去抖), 工作台 token 请求由 packaging 页自处理 - 菜单路径别名: menuRouteMap 兼容后端短路径(/order)与完整路径(/pages/xxx/index); index 页 rawPath 未定义引用修复; 布局样式微调 - 已验证: 17320 起服务/config 200/真实 NVR(192.168.8.241 ch2, port=554)回退 80 出流 7 帧/端口占用 blocked; 通道1 Device Busy 为车间占流非代码问题
529 lines
18 KiB
JavaScript
529 lines
18 KiB
JavaScript
/**
|
||
* WMS 内置海康取流服务(HTTP 快照模式,监听 127.0.0.1:17320)
|
||
*
|
||
* 协议与 printServer(打印电脑服务)的 live-stream 一致,但端口独立:
|
||
* printServer 用 17311(被占时回退 17312/17313),WMS 用 17320,互不冲突。
|
||
* 前端 src/api/camera.ts 的 getLiveStreamUrl() 固定请求
|
||
* http://localhost:17320/api/hikvision/live-stream,因此 WMS exe 单机即可
|
||
* 预览退件摄像头,无需另装 printServer。
|
||
*
|
||
* 端口策略:仅绑定 127.0.0.1 回环(不暴露局域网);17320 被占用时放弃并告警。
|
||
*
|
||
* 仅使用 Node 标准库(http/net/crypto),无第三方依赖,兼容
|
||
* electron-builder "dependencies 为空、不打 node_modules" 的打包配置。
|
||
*/
|
||
|
||
'use strict'
|
||
|
||
const http = require('http')
|
||
const net = require('net')
|
||
const crypto = require('crypto')
|
||
|
||
const PORT = 17320
|
||
const SNAPSHOT_INTERVAL_MS = 200
|
||
const LOGIN_CACHE_TTL_MS = 20 * 60 * 1000
|
||
const REQ_TIMEOUT_MS = 10000
|
||
|
||
/** printServer 无 ffmpeg 时的兜底错误图(1x1 JPEG),保持 502 行为与之一致 */
|
||
const FALLBACK_JPEG = Buffer.from(
|
||
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBAUEBAYFBQUGBgYHCQ4JCQgICRINDgoRFWGBEXFBUWFhcbHR8lJx4eHiAhIyUoKSkrLC0tHyE3NTcoNSooKSv/2wBDAQcHBwkJCRYJCQ0XFhUWFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxf/wAARCAABAAEDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AKwA//9k=',
|
||
'base64'
|
||
)
|
||
|
||
/** 简单 XML 文本提取(海康 ISAPI XML 字段,支持命名空间前缀,大小写敏感与 printServer 一致) */
|
||
function xmlText(xml, tag) {
|
||
if (!xml) return ''
|
||
const re = new RegExp(
|
||
'<(?:[\\w.-]+:)?' + tag + '(?:\\s[^>]*)?>([\\s\\S]*?)<\\/(?:[\\w.-]+:)?' + tag + '\\s*>'
|
||
)
|
||
const m = xml.match(re)
|
||
return m ? m[1].trim() : ''
|
||
}
|
||
|
||
function sha256Hex(text) {
|
||
return crypto.createHash('sha256').update(text, 'utf-8').digest('hex')
|
||
}
|
||
|
||
function sendJson(res, code, obj) {
|
||
const body = Buffer.from(JSON.stringify(obj), 'utf-8')
|
||
res.writeHead(code, {
|
||
'Content-Type': 'application/json; charset=utf-8',
|
||
'Content-Length': body.length,
|
||
'Access-Control-Allow-Origin': '*',
|
||
'Cache-Control': 'no-cache',
|
||
})
|
||
res.end(body)
|
||
}
|
||
|
||
/** 创建海康认证/请求服务实例(含登录缓存与并发锁) */
|
||
function createHikvisionService() {
|
||
const loginCache = new Map() // key `${ip}:${port}` -> { ts, httpBase, cookieJar, sessionTag }
|
||
const loginLocks = new Map() // key -> Promise
|
||
|
||
/** 通用 HTTP 请求(复刻 printServer services/hikvision.js _req) */
|
||
function _req(method, url, body, headers, cookieJar, binary = false, agent = null) {
|
||
const u = new URL(url)
|
||
const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null
|
||
const cookies = Object.entries(cookieJar || {})
|
||
.map(([k, v]) => `${k}=${v}`)
|
||
.join('; ')
|
||
const hdrs = { Accept: '*/*', 'User-Agent': 'Mozilla/5.0', ...headers }
|
||
if (cookies) hdrs['Cookie'] = cookies
|
||
if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length
|
||
|
||
return new Promise((resolve, reject) => {
|
||
const reqOpts = {
|
||
hostname: u.hostname,
|
||
port: u.port || 80,
|
||
path: u.pathname + u.search,
|
||
method,
|
||
headers: hdrs,
|
||
timeout: REQ_TIMEOUT_MS,
|
||
}
|
||
if (agent) reqOpts.agent = agent
|
||
const req = http.request(reqOpts, (res) => {
|
||
const chunks = []
|
||
res.on('data', (c) => chunks.push(c))
|
||
res.on('end', () => {
|
||
const raw = Buffer.concat(chunks)
|
||
const bodyOut = binary ? raw : raw.toString('utf-8')
|
||
if (res.headers['set-cookie'] && cookieJar) {
|
||
const list = Array.isArray(res.headers['set-cookie'])
|
||
? res.headers['set-cookie']
|
||
: [res.headers['set-cookie']]
|
||
list.forEach((sc) => {
|
||
const m = sc.match(/^([^=;]+)=([^;]*)/)
|
||
if (m) cookieJar[m[1]] = m[2]
|
||
})
|
||
}
|
||
resolve({ statusCode: res.statusCode, headers: res.headers, body: bodyOut })
|
||
})
|
||
})
|
||
req.on('error', reject)
|
||
req.on('timeout', () => {
|
||
req.destroy()
|
||
reject(new Error('请求超时'))
|
||
})
|
||
if (bodyBuf) req.write(bodyBuf)
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
/** 获取一次性 token(需要已有 session) */
|
||
async function _getToken(httpBase, sessionTag, cookieJar) {
|
||
const tokenHeaders = sessionTag ? { SessionTag: sessionTag } : {}
|
||
const tokenRes = await _req(
|
||
'GET',
|
||
`${httpBase}/ISAPI/Security/token?format=json`,
|
||
null,
|
||
tokenHeaders,
|
||
cookieJar
|
||
)
|
||
if (!String(tokenRes.body || '').includes('"Token"')) {
|
||
throw new Error(`Token获取失败(session失效,status=${tokenRes.statusCode})`)
|
||
}
|
||
try {
|
||
return JSON.parse(tokenRes.body).Token.value
|
||
} catch (e) {
|
||
throw new Error(`Token解析失败(status=${tokenRes.statusCode})`)
|
||
}
|
||
}
|
||
|
||
/** 完整 digest 登录(复刻 printServer _doLogin,XML 解析用正则替代 @xmldom) */
|
||
async function _doLogin(ip, httpPort, user, pass) {
|
||
const httpBase = `http://${ip}:${httpPort}`
|
||
const cookieJar = {}
|
||
|
||
const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${encodeURIComponent(user)}&random:${String(Date.now()).slice(-8)}`
|
||
const capsRes = await _req('GET', capsUrl, null, {}, cookieJar)
|
||
if (capsRes.statusCode !== 200) {
|
||
throw Object.assign(new Error(`获取登录能力失败: HTTP ${capsRes.statusCode}`), {
|
||
statusCode: capsRes.statusCode,
|
||
})
|
||
}
|
||
const capsBody = String(capsRes.body || '')
|
||
const sid = xmlText(capsBody, 'sessionID')
|
||
const challenge = xmlText(capsBody, 'challenge')
|
||
const salt = xmlText(capsBody, 'salt')
|
||
const itr = parseInt(xmlText(capsBody, 'iterations')) || 1
|
||
const ver = xmlText(capsBody, 'sessionIDVersion') || '1'
|
||
const vl = xmlText(capsBody, 'isSessionIDValidLongTerm') || 'false'
|
||
const st = xmlText(capsBody, 'isSupportSessionTag') || 'false'
|
||
const irreversible = xmlText(capsBody, 'isIrreversible') === 'true'
|
||
|
||
let digest
|
||
if (irreversible) {
|
||
digest = sha256Hex(user + salt + pass)
|
||
digest = sha256Hex(digest + challenge)
|
||
for (let i = 2; i < itr; i++) digest = sha256Hex(digest)
|
||
} else {
|
||
digest = sha256Hex(pass + challenge)
|
||
for (let i = 1; i < itr; i++) digest = sha256Hex(digest)
|
||
}
|
||
|
||
let loginXml
|
||
if (ver === '2') {
|
||
loginXml = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID><isSessionIDValidLongTerm>${vl}</isSessionIDValidLongTerm><sessionIDVersion>2</sessionIDVersion><isNeedSessionTag>${st}</isNeedSessionTag></SessionLogin>`
|
||
} else {
|
||
loginXml = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID></SessionLogin>`
|
||
}
|
||
const loginRes = await _req(
|
||
'POST',
|
||
`${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`,
|
||
loginXml,
|
||
{ 'Content-Type': 'text/plain;charset=UTF-8' },
|
||
cookieJar
|
||
)
|
||
if (loginRes.statusCode !== 200) {
|
||
throw Object.assign(new Error(`登录失败: HTTP ${loginRes.statusCode}`), {
|
||
statusCode: loginRes.statusCode,
|
||
})
|
||
}
|
||
|
||
const sessionTag = xmlText(String(loginRes.body || ''), 'sessionTag')
|
||
const token = await _getToken(httpBase, sessionTag, cookieJar)
|
||
return { token, cookieJar, sessionTag, httpBase }
|
||
}
|
||
|
||
/** 登录(带 20 分钟 session 缓存与并发锁) */
|
||
async function login(ip, httpPort, user, pass) {
|
||
const key = `${ip}:${httpPort}`
|
||
|
||
const cached = loginCache.get(key)
|
||
if (cached && Date.now() - cached.ts < LOGIN_CACHE_TTL_MS) {
|
||
try {
|
||
const token = await _getToken(cached.httpBase, cached.sessionTag, cached.cookieJar)
|
||
return { token, cookieJar: cached.cookieJar, sessionTag: cached.sessionTag, httpBase: cached.httpBase }
|
||
} catch (e) {
|
||
console.log('[hik-live] 缓存 session 取 token 失败,清除缓存重新登录:', e.message)
|
||
loginCache.delete(key)
|
||
}
|
||
}
|
||
|
||
if (loginLocks.has(key)) {
|
||
return loginLocks.get(key)
|
||
}
|
||
|
||
const promise = _doLogin(ip, httpPort, user, pass)
|
||
loginLocks.set(key, promise)
|
||
try {
|
||
const result = await promise
|
||
loginCache.set(key, {
|
||
cookieJar: result.cookieJar,
|
||
sessionTag: result.sessionTag,
|
||
httpBase: result.httpBase,
|
||
ts: Date.now(),
|
||
})
|
||
return result
|
||
} finally {
|
||
loginLocks.delete(key)
|
||
}
|
||
}
|
||
|
||
return { login }
|
||
}
|
||
|
||
/** 发送 502 兜底错误图(与 printServer 无 ffmpeg 时行为一致,触发前端公网回退逻辑) */
|
||
function sendErrorImage(res) {
|
||
res.writeHead(502, {
|
||
'Content-Type': 'image/jpeg',
|
||
'Content-Length': FALLBACK_JPEG.length,
|
||
'Access-Control-Allow-Origin': '*',
|
||
'Cache-Control': 'no-cache',
|
||
})
|
||
res.end(FALLBACK_JPEG)
|
||
}
|
||
|
||
/**
|
||
* GET /api/hikvision/live-stream —— HTTP 快照轮询模式 MJPEG
|
||
* 复刻 printServer _handleHikvisionLiveStreamHttp(仅保留 HTTP 快照分支)
|
||
*/
|
||
async function handleLiveStream(svc, res, params) {
|
||
const ip = params.get('ip')
|
||
const user = params.get('user')
|
||
const pass = params.get('pass')
|
||
const channel = parseInt(params.get('channel')) || 33
|
||
const rawStreamType = parseInt(params.get('streamType'))
|
||
const streamType = Number.isNaN(rawStreamType) ? 1 : rawStreamType
|
||
const interval = Number.isFinite(parseInt(params.get('interval')))
|
||
? Math.max(0, parseInt(params.get('interval')))
|
||
: SNAPSHOT_INTERVAL_MS
|
||
|
||
if (!ip || !user || !pass) {
|
||
sendJson(res, 400, { success: false, message: '缺少参数: ip, user, pass' })
|
||
return
|
||
}
|
||
// 海康通道号 = 100*channel + 流后缀(1=主码流/2=子码流)。
|
||
// 前端 streamType: 0/1 均按主码流(101),2 按子码流(102)——
|
||
// 直接用 100*channel+0 会得到无效通道(100),NVR 返回 503 statusCode 2。
|
||
// 与 printServer RTSP 分支的 rtspStreamType 映射保持一致。
|
||
const streamSuffix = streamType === 2 ? 2 : 1
|
||
const channelCode = 100 * channel + streamSuffix
|
||
|
||
// 端口候选回退:httpPort -> port -> 80。
|
||
// 前端 getLiveStreamUrl 透传的 port 是 NVR 端口(常为 RTSP 554),
|
||
// 而 ISAPI HTTP 服务通常在 80 端口;554 上发 HTTP 会秒拒,登录失败自动回退。
|
||
const explicitHttpPort = parseInt(params.get('httpPort'))
|
||
const portParam = parseInt(params.get('port'))
|
||
const portCandidates = []
|
||
for (const p of [explicitHttpPort, portParam, 80]) {
|
||
if (Number.isFinite(p) && p > 0 && p < 65536 && !portCandidates.includes(p)) {
|
||
portCandidates.push(p)
|
||
}
|
||
}
|
||
|
||
let closed = false
|
||
let cookieJar = {}
|
||
let sessionTag = ''
|
||
let usedHttpPort = null
|
||
let agent = null
|
||
let lastPictureErrLog = 0
|
||
|
||
const doCleanup = () => {
|
||
if (closed) return
|
||
closed = true
|
||
if (agent) {
|
||
try {
|
||
agent.destroy()
|
||
} catch {}
|
||
}
|
||
if (!res.writableEnded) {
|
||
try {
|
||
res.end()
|
||
} catch {}
|
||
}
|
||
}
|
||
|
||
res.on('close', doCleanup)
|
||
res.on('error', doCleanup)
|
||
|
||
// Step 1: 登录(候选端口逐个尝试,单端口限时 3.5s;NVR 的 RTSP 端口对 HTTP
|
||
// 请求可能挂住不响应,限时后快速回退到下一候选)
|
||
const CANDIDATE_LOGIN_TIMEOUT_MS = 3500
|
||
let loginResult = null
|
||
for (const candidate of portCandidates) {
|
||
try {
|
||
loginResult = await Promise.race([
|
||
svc.login(ip, candidate, user, pass),
|
||
new Promise((_, reject) =>
|
||
setTimeout(() => reject(new Error('登录超时')), CANDIDATE_LOGIN_TIMEOUT_MS)
|
||
),
|
||
])
|
||
usedHttpPort = candidate
|
||
break
|
||
} catch (e) {
|
||
console.log('[hik-live] 端口 %d 登录失败(%s),尝试下一候选', candidate, e.message)
|
||
}
|
||
}
|
||
if (!loginResult || !usedHttpPort) {
|
||
console.error('[hik-live] live-stream 登录失败(所有候选端口):', ip)
|
||
sendErrorImage(res)
|
||
doCleanup()
|
||
return
|
||
}
|
||
cookieJar = loginResult.cookieJar
|
||
sessionTag = loginResult.sessionTag
|
||
|
||
try {
|
||
// 连接复用:避免每帧 TCP 握手开销
|
||
agent = new http.Agent({ keepAlive: true, maxSockets: 2 })
|
||
|
||
// Step 2: 发送 MJPEG 响应头
|
||
res.writeHead(200, {
|
||
'Content-Type': 'multipart/x-mixed-replace; boundary=snapshot',
|
||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||
Pragma: 'no-cache',
|
||
Expires: '0',
|
||
Connection: 'keep-alive',
|
||
'Access-Control-Allow-Origin': '*',
|
||
})
|
||
// 关键:首帧到达前没有任何 body 写入时,Node 不会把响应头发出去,
|
||
// 必须显式 flush,否则前端 fetch 探测一直挂起(表现为本地服务未启动)。
|
||
res.flushHeaders()
|
||
|
||
const snapshotUrl = `http://${ip}:${usedHttpPort}/ISAPI/Streaming/channels/${channelCode}/picture`
|
||
|
||
// Step 3: 单路轮询(均匀节奏,避免并发乱序导致的画面跳帧)
|
||
const fetchFrame = async () => {
|
||
try {
|
||
const hdrs = sessionTag ? { SessionTag: sessionTag } : {}
|
||
const result = await _reqWithAgent('GET', snapshotUrl, null, hdrs, cookieJar, agent)
|
||
if (result.statusCode !== 200) {
|
||
// 节流日志:同一流上 picture 失败(503 Device Busy 等)每 10 秒最多一条
|
||
if (Date.now() - lastPictureErrLog > 10000) {
|
||
lastPictureErrLog = Date.now()
|
||
console.log(
|
||
'[hik-live] picture 非 200:',
|
||
result.statusCode,
|
||
result.body.toString('utf-8').replace(/\s+/g, ' ').slice(0, 220)
|
||
)
|
||
}
|
||
}
|
||
if (result.statusCode === 200 && result.body && result.body.length > 500) {
|
||
return result.body
|
||
}
|
||
if (result.statusCode === 401) {
|
||
// Session 过期,重新登录(login 内部有锁)
|
||
const relogin = await svc.login(ip, usedHttpPort, user, pass)
|
||
cookieJar = relogin.cookieJar
|
||
sessionTag = relogin.sessionTag
|
||
}
|
||
} catch (e) {
|
||
// 单次失败忽略
|
||
}
|
||
return null
|
||
}
|
||
|
||
const writeFrame = (jpeg) => {
|
||
if (!jpeg || closed || res.destroyed) return
|
||
// 背压保护:客户端消费慢(如预览窗最小化)时丢帧,避免内存持续增长
|
||
if (res.writableLength < 512 * 1024) {
|
||
res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`)
|
||
res.write(jpeg)
|
||
res.write('\r\n')
|
||
}
|
||
}
|
||
|
||
while (!closed) {
|
||
const loopStart = Date.now()
|
||
const jpeg = await fetchFrame()
|
||
writeFrame(jpeg)
|
||
if (interval > 0) {
|
||
const delay = Math.max(0, interval - (Date.now() - loopStart))
|
||
if (delay > 0) await new Promise((r) => setTimeout(r, delay))
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error('[hik-live] live-stream 启动失败:', err.message)
|
||
if (!res.headersSent) {
|
||
sendErrorImage(res)
|
||
}
|
||
doCleanup()
|
||
}
|
||
}
|
||
|
||
/** 与 fetchFrame 复用的二进制请求(复用 agent) */
|
||
function _reqWithAgent(method, url, body, headers, cookieJar, agent) {
|
||
return new Promise((resolve, reject) => {
|
||
const u = new URL(url)
|
||
const cookies = Object.entries(cookieJar || {})
|
||
.map(([k, v]) => `${k}=${v}`)
|
||
.join('; ')
|
||
const hdrs = { Accept: '*/*', 'User-Agent': 'Mozilla/5.0', ...headers }
|
||
if (cookies) hdrs['Cookie'] = cookies
|
||
const req = http.request(
|
||
{
|
||
hostname: u.hostname,
|
||
port: u.port || 80,
|
||
path: u.pathname + u.search,
|
||
method,
|
||
headers: hdrs,
|
||
timeout: REQ_TIMEOUT_MS,
|
||
agent,
|
||
},
|
||
(res) => {
|
||
const chunks = []
|
||
res.on('data', (c) => chunks.push(c))
|
||
res.on('end', () => {
|
||
const raw = Buffer.concat(chunks)
|
||
resolve({
|
||
statusCode: res.statusCode,
|
||
headers: res.headers,
|
||
body: raw, // 快照接口返回二进制 JPEG
|
||
})
|
||
})
|
||
}
|
||
)
|
||
req.on('error', reject)
|
||
req.on('timeout', () => {
|
||
req.destroy()
|
||
reject(new Error('请求超时'))
|
||
})
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
function handleRequest(svc, req, res) {
|
||
const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
|
||
const pathname = url.pathname
|
||
|
||
if (pathname === '/api/hikvision/live-stream' && req.method === 'GET') {
|
||
return handleLiveStream(svc, res, url.searchParams)
|
||
}
|
||
if (pathname === '/api/hikvision/status' && req.method === 'GET') {
|
||
return sendJson(res, 200, { success: true, source: 'wms-worker-station' })
|
||
}
|
||
if (pathname === '/api/hikvision/config' && req.method === 'GET') {
|
||
return sendJson(res, 200, { success: true, hikvision: {} })
|
||
}
|
||
return sendJson(res, 404, { success: false, message: 'Not Found' })
|
||
}
|
||
|
||
/** 探测端口是否有监听:true=被占用 / false=空闲 */
|
||
function probePort(port = PORT) {
|
||
return new Promise((resolve) => {
|
||
const sock = net.createConnection({ host: '127.0.0.1', port })
|
||
let settled = false
|
||
const finish = (result) => {
|
||
if (settled) return
|
||
settled = true
|
||
try {
|
||
sock.destroy()
|
||
} catch {}
|
||
resolve(result)
|
||
}
|
||
sock.setTimeout(1200)
|
||
sock.once('connect', () => finish(true))
|
||
sock.once('timeout', () => finish(false))
|
||
sock.once('error', () => finish(false))
|
||
})
|
||
}
|
||
|
||
let activeServer = null
|
||
|
||
/**
|
||
* 启动内置取流服务。
|
||
* 返回 { mode: 'builtin' | 'blocked' | 'error', ... }
|
||
* port 仅测试用,生产默认 17320(前端 URL 固定)。
|
||
*/
|
||
async function startHikvisionLiveServer(port = PORT) {
|
||
if (activeServer) {
|
||
return { mode: 'builtin', port }
|
||
}
|
||
|
||
const occupied = await probePort(port)
|
||
if (occupied) {
|
||
console.warn(`[hik-live] ${port} 被占用,放弃启动内置取流服务`)
|
||
return { mode: 'blocked', port }
|
||
}
|
||
|
||
return new Promise((resolve) => {
|
||
const svc = createHikvisionService()
|
||
const server = http.createServer((req, res) => handleRequest(svc, req, res))
|
||
server.on('error', (err) => {
|
||
if (err.code === 'EADDRINUSE') {
|
||
console.warn(`[hik-live] 监听 ${port} 失败(竞态占用)`)
|
||
resolve({ mode: 'blocked', port })
|
||
return
|
||
}
|
||
resolve({ mode: 'error', error: err.message })
|
||
})
|
||
server.listen(port, '127.0.0.1', () => {
|
||
activeServer = server
|
||
console.log('[hik-live] 内置海康取流服务已启动,端口:', port, '(HTTP 快照模式,~5fps,仅本机回环)')
|
||
resolve({ mode: 'builtin', port })
|
||
})
|
||
})
|
||
}
|
||
|
||
function stopHikvisionLiveServer() {
|
||
if (!activeServer) return
|
||
try {
|
||
activeServer.close()
|
||
} catch {}
|
||
activeServer = null
|
||
console.log('[hik-live] 内置取流服务已停止')
|
||
}
|
||
|
||
module.exports = { startHikvisionLiveServer, stopHikvisionLiveServer, PORT }
|