'use strict'; const { Service } = require('egg'); const crypto = require('crypto'); const { Op } = require('sequelize'); const { virtualChannelIdOf, isVirtualChannelId } = require('../lib/virtual-channel'); /** * 面单摄像头**识别配置**(下发给设备出站拉取) * * 现场:工作台的「面单摄像头」对着面单区,面单放进去识别到条码就开始打包, * 识别结果按**该工作台已绑定的扫码通道**上报(这样服务端才能找到工作台快照)。 * * 这里只做「算出这台设备该跑哪些识别任务」: * - 只看**本主体**、启用中的工作台(**散单和团购都支持**面单摄像头);停用的工作台/摄像头 * 不下发,但会给一条 warning 说明原因(现场「配了面单但设备列表里没有」时看这个); * - 只看被标记为面单摄像头(`workstation_cameras.is_label_camera = 1`)的绑定; * 摄像头本身停用(`cameras.status = 0`)时不下发,改给一条 warning; * 注意**不看** `cameras.enabled`:那是导入通道时的快照,不代表现在有没有画面; * - 上报通道取「该工作台绑定、且属于**本设备**的扫码通道」(多条时取 sortNo 最小的一条); * 工作台**没接扫码枪**(没绑本机通道)时,自动给它一条虚拟通道 `CAM-<工作台id>` * (名字 `面单摄像头·<摄像头名>`,见 `lib/virtual-channel`)——摄像头可以完全替代扫码枪; * - 下发的每一项都带 `wsType`:设备端据此决定记录规则 * (散单 wsType=1 → 时间取第一次、立即上报;团购 wsType=2 → 和扫码枪一样静默 5 秒取最后一次); * - 另外下发 `channels`(本设备所有被工作台绑定的通道 + 对应 wsType,含虚拟通道), * 设备端用它决定**扫码枪**那条路的记录规则(散单也走「取第一次」); * - 设备凭据(NVR 账号密码)随配置下发,设备拿到后直接拉流; * 服务端不做缓存,接口也只在设备鉴权通过后才返回。 * * ⚠️ RTSP 路径不在这里拼:录像机的「首个数字通道号」只有设备端问得到 * (桌面端 `HikPlaybackService.LogicalChannel` 已经这样做),所以只下发 * `nvr` + `cameraChannelNo` + `streamType`,由设备端算。 */ class LabelScanService extends Service { get Workstation() { return this.app.model.Workstation; } get Nvr() { return this.app.model.Nvr; } /** * 取本设备的面单识别配置 * * @param {object} scanner 当前设备(ctx.state.scanner,已鉴权) * @return {Promise} { revision, items, warnings, scannedAt } */ async configOf(scanner) { const scannerId = Number(scanner.id); const subjectId = Number(scanner.subjectId) || 0; const workstations = await this.Workstation.findAll({ where: { subjectId, status: 1 }, attributes: [ 'id', 'code', 'name', 'wsType' ], order: [[ 'id', 'ASC' ]], }); const warnings = []; // 停用的工作台不会下发(下面只查 status=1 的),但现场很容易以为「配了面单就该出现」, // 所以单独查一遍:有面单摄像头却因为工作台停用没下发的,给一条提示。 const disabledWorkstations = (await this.Workstation.findAll({ where: { subjectId, status: { [Op.ne]: 1 } }, attributes: [ 'id', 'code', 'name', 'status' ], order: [[ 'id', 'ASC' ]], })).filter(row => Number(row.status) !== 1); if (disabledWorkstations.length) { const disabledIds = disabledWorkstations.map(row => Number(row.id)); const disabledLinks = await this.app.model.WorkstationCamera.findAll({ where: { workstationId: { [Op.in]: disabledIds }, isLabelCamera: 1 }, attributes: [ 'workstationId' ], }); const hasLabel = new Set(disabledLinks.map(link => Number(link.workstationId))); for (const row of disabledWorkstations) { if (!hasLabel.has(Number(row.id))) continue; warnings.push({ workstationId: Number(row.id), workstationName: row.name || row.code, message: '工作台已停用(启用后才会下发这一路),不会做面单识别', }); } } if (!workstations.length) { return { revision: revisionOf({ items: [], channels: [] }), items: [], channels: [], warnings, scannedAt: new Date() }; } const ids = workstations.map(row => Number(row.id)); const workstationById = new Map(workstations.map(row => [ Number(row.id), row ])); // 工作台 → 上报通道(只认本设备的通道;多条取 sortNo 最小的) const channelLinks = await this.app.model.WorkstationScanChannel.findAll({ where: { workstationId: { [Op.in]: ids }, scannerId }, attributes: [ 'id', 'workstationId', 'scannerId', 'channelId', 'channelName', 'sortNo' ], order: [[ 'workstationId', 'ASC' ], [ 'sortNo', 'ASC' ], [ 'id', 'ASC' ]], }); const channelByWorkstation = new Map(); for (const link of channelLinks) { const key = Number(link.workstationId); if (!channelByWorkstation.has(key)) channelByWorkstation.set(key, link); } // 本设备每条通道对应的工作台类型:设备端「扫码枪」那条路也按它决定记录规则 // (虚拟通道 `CAM-` 不在这里下发,等确认它确实有面单摄像头再加,见下面) const channels = []; for (const [ workstationId, link ] of channelByWorkstation) { if (isVirtualChannelId(link.channelId)) continue; const workstation = workstationById.get(workstationId); if (!workstation) continue; channels.push({ channelId: String(link.channelId), channelName: link.channelName || '', wsType: Number(workstation.wsType) === 1 ? 1 : 2, }); } const links = await this.app.model.WorkstationCamera.findAll({ where: { workstationId: { [Op.in]: ids }, isLabelCamera: 1 }, include: [{ model: this.app.model.Camera, as: 'camera', required: true, include: [{ model: this.Nvr, as: 'nvr', attributes: [ 'id', 'name', 'host', 'port', 'username' ] }], }], order: [[ 'workstationId', 'ASC' ], [ 'id', 'ASC' ]], }); if (!links.length) { return { revision: revisionOf({ items: [], channels }), items: [], channels, warnings, scannedAt: new Date() }; } const items = []; const seenWorkstations = new Set(); for (const link of links) { const workstationId = Number(link.workstationId); if (seenWorkstations.has(workstationId)) continue; // 一个工作台只保留一路(DB 也保证) seenWorkstations.add(workstationId); const workstation = workstationById.get(workstationId); const camera = link.camera; if (!workstation || !camera) continue; const cameraName = camera.name || camera.channelName || `通道${camera.channelNo}`; // ⚠️ 只看 `status`(用户自己的启用/停用)。 // // `cameras.enabled` 是**导入通道那一刻**录像机报告的「该通道已配置」,是个快照: // - 通道导入时 NVR 上还没装摄像头(或当时设备服务没起来,拿不到通道状态)→ 库里存 0; // - 之后在 NVR 上装了摄像头,预览是通的(预览只看 status),但这个字段永远不会自己变; // - 前端「拉取通道」又把已导入的通道置灰,没法靠重新导入刷新它。 // 结果就是「预览正常、设为面单摄像头却不出现在设备列表」——所以它不能当开关用。 const cameraEnabled = Number(camera.status) === 1; if (!cameraEnabled) { warnings.push({ workstationId, workstationName: workstation.name || workstation.code, message: `摄像头「${cameraName}」已停用(摄像头管理里启用后再试),不会做面单识别`, }); continue; } // 没有扫码通道也不要紧:摄像头本身就是一条「虚拟通道」(`CAM-<工作台id>`),见 ensureVirtualChannel const boundChannel = channelByWorkstation.get(workstationId); const realChannel = boundChannel && !isVirtualChannelId(boundChannel.channelId) ? boundChannel : null; const virtualChannelId = virtualChannelIdOf(workstationId); let channelId = realChannel ? String(realChannel.channelId) : virtualChannelId; let channelName = realChannel ? (realChannel.channelName || '') : `面单摄像头·${cameraName}`; const virtualChannel = !realChannel; const nvr = camera.nvr; if (!nvr) { warnings.push({ workstationId, workstationName: workstation.name || workstation.code, message: `摄像头「${cameraName}」找不到录像机`, }); continue; } const password = await this.passwordOf(nvr.id); if (!password) { warnings.push({ workstationId, workstationName: workstation.name || workstation.code, message: `录像机「${nvr.name || nvr.host}」没有保存密码,无法拉流`, }); continue; } // 纯摄像头工作台:没有扫码枪也能用,识别结果按虚拟通道上报(回放定位靠 scanner+channel 反查工作台) // 放在校验后面,免得为一条拉不了流的配置凭空建通道 if (virtualChannel) { const ensured = await this.ensureVirtualChannel(scanner, workstationId, channelName); if (ensured) { channelId = ensured.channelId; channelName = ensured.channelName; } } items.push({ workstationId, workstationCode: workstation.code || '', workstationName: workstation.name || workstation.code || '', // 1 散单(时间取第一次、立即上报)/ 2 团购(静默 5 秒、时间取最后一次,和扫码枪一样) wsType: Number(workstation.wsType) === 1 ? 1 : 2, channelId, channelName, // true = 这条通道是摄像头自己(工作台没绑扫码枪),设备端照常上报即可 virtualChannel, cameraId: Number(camera.id), cameraName, cameraChannelNo: Number(camera.channelNo) || 0, cameraEnabled, streamType: Number(link.streamType) === 1 ? 1 : 0, nvr: { id: Number(nvr.id), name: nvr.name || '', host: nvr.host, port: Number(nvr.port) || 8000, username: nvr.username || 'admin', password, }, }); } // 虚拟通道(纯摄像头工作台)也要进 channels:设备端靠它判断走「取第一次」还是「取最后一次」 for (const item of items) { if (!item.virtualChannel) continue; if (channels.some(row => row.channelId === item.channelId)) continue; channels.push({ channelId: item.channelId, channelName: item.channelName, wsType: item.wsType }); } return { revision: revisionOf({ items, channels }), items, channels, warnings, scannedAt: new Date() }; } /** * 确保「纯摄像头工作台」的虚拟通道存在(幂等)。 * * 为什么需要:扫码记录的上报结构是「中控 + 通道」,回放定位靠 `scanner+channel → 工作台` 反查快照; * 工作台没接扫码枪时没有通道,识别结果就没有落脚点。这里给它补一条**虚拟通道** * `CAM-<工作台id>`(名字 `面单摄像头·<摄像头名>`)并绑到工作台,整条链路就不用改。 * * 只在设备拉配置时顺带自愈(包括历史遗留的「设了面单但没通道」的配置)。 * * @return {Promise<{channelId:string, channelName:string}|null>} */ async ensureVirtualChannel(scanner, workstationId, channelName) { if (!scanner || !scanner.id || !workstationId) return null; const channelId = virtualChannelIdOf(workstationId); const name = channelName || '面单摄像头'; const scannerId = Number(scanner.id); try { const ScanChannel = this.app.model.ScanChannel; // 注意 `paranoid`:通道被取消面单时是**软删**,唯一键还被占着, // 所以必须用 `paranoid: false` 查出来再 restore,不能直接 findOrCreate。 let channel = await ScanChannel.findOne({ where: { scannerId, channelId }, paranoid: false }); if (channel) { if (channel.deletedAt) await ScanChannel.restore({ where: { id: channel.id } }); const fields = { lastReportAt: new Date() }; if (channel.channelName !== name) fields.channelName = name; if (Number(channel.status) !== 1) fields.status = 1; await ScanChannel.update(fields, { where: { id: channel.id }, paranoid: false }); } else { channel = await ScanChannel.create({ scannerId, subjectId: Number(scanner.subjectId) || null, channelId, channelName: name, status: 1, lastReportAt: new Date(), }); } const [ link ] = await this.app.model.WorkstationScanChannel.findOrCreate({ where: { workstationId: Number(workstationId), scannerId, channelId }, defaults: { channelName: name, sortNo: 0 }, }); if (link && link.channelName !== name) { await link.update({ channelName: name }); } return { channelId, channelName: name }; } catch (err) { // 补通道失败不能影响下发:识别照跑,只是这条记录定位不到工作台 this.ctx.logger.warn('[label-scan] 工作台 %s 的虚拟通道创建失败:%s', workstationId, err.message); return null; } } /** * 叫醒本主体的设备「面单识别配置变了,马上重拉」。 * * 设备端收到 `labelScan.refresh` 只当作**一次通知**:真正的配置仍以 * `GET /api/scanner/label-cameras` 为准(服务端不推送配置内容,避免两份真相)。 * * 为什么必须有:设备端只有一个 5 分钟的兜底轮询,现场在网页上改完面单摄像头后 * 要等好几分钟才生效;期间旧摄像头还在跑、新摄像头不启动,看起来就像「没取到新值」。 * * 推送失败只记日志:配置本身已经落库,不能因为通知失败就回滚。 * * @param {number} subjectId 主体 id * @return {Promise} 通知到的设备数 */ async notifyChanged(subjectId) { const id = Number(subjectId) || 0; if (!id) return 0; try { const scanners = await this.app.model.Scanner.findAll({ where: { subjectId: id, status: 1 }, attributes: [ 'id' ], raw: true, }); if (!scanners.length) return 0; for (const row of scanners) { // 队列有 TTL:设备离线期间任务会自己过期,不会无限堆积 await this.ctx.service.edgeTask.enqueue(Number(row.id), 'labelScan.refresh', {}); } this.ctx.logger.info('[label-scan] 已通知 %d 台设备重拉面单配置(subject %d)', scanners.length, id); return scanners.length; } catch (err) { this.ctx.logger.warn('[label-scan] 通知设备重拉面单配置失败(不影响配置本身):%s', err.message); return 0; } } /** 解密录像机密码(只给设备下发,绝不写日志) */ async passwordOf(nvrId) { const nvr = await this.Nvr.findByPk(nvrId, { attributes: { include: [ 'passwordEnc' ] } }); if (!nvr || !nvr.passwordEnc) return ''; try { return this.ctx.service.nvr.passwordOf(nvr) || ''; } catch (err) { this.ctx.logger.warn('[label-scan] 录像机 %s 密码解密失败:%s', nvrId, err.message); return ''; } } } /** * 配置指纹:内容(含密码、通道模式)一变就变,设备端据此判断要不要重建识别任务。 * 只在设备端做「本地缓存 vs 远端」比较,**不落日志**。 */ function revisionOf(payload) { const text = JSON.stringify(payload); return `sha1:${crypto.createHash('sha1').update(text).digest('hex').slice(0, 16)}`; } module.exports = LabelScanService;