- 工作台成员扫码登入:workstation_login_records 记录谁在什么时候登入/下线了哪台工作台, 超时(团购 1h / 散单 30min)由 schedule/workstation_idle_offline 自动下线; 运单查询的 packers 取当时的登入成员 - 面单摄像头识别:workstation_cameras.is_label_camera + service/label_scan 下发本机该跑的识别配置, 设备端(桌面端 LabelScan 工作线程)按配置做面单识别并上报 - 虚拟通道 CAM-<工作台id>:工作台没接扫码枪时,面单摄像头那一路顶替扫码枪上报,records 规则按 ws_type 区分 - 桌面端:新增 LabelScanMonitor/LabelScanWorker/ScanDeviceKind 与面单预览页,扫描通道支持改名,静默窗口 5s Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
311 lines
13 KiB
JavaScript
311 lines
13 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const crypto = require('crypto');
|
||
const { Op } = require('sequelize');
|
||
const { virtualChannelIdOf, isVirtualChannelId } = require('../lib/virtual-channel');
|
||
|
||
/**
|
||
* 面单摄像头**识别配置**(下发给设备出站拉取)
|
||
*
|
||
* 现场:工作台的「面单摄像头」对着面单区,面单放进去识别到条码就开始打包,
|
||
* 识别结果按**该工作台已绑定的扫码通道**上报(这样服务端才能找到工作台快照)。
|
||
*
|
||
* 这里只做「算出这台设备该跑哪些识别任务」:
|
||
* - 只看**本主体**、启用中的工作台(**散单和团购都支持**面单摄像头);
|
||
* - 只看被标记为面单摄像头(`workstation_cameras.is_label_camera = 1`)的绑定;
|
||
* - 上报通道取「该工作台绑定、且属于**本设备**的扫码通道」(多条时取 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<object>} { 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 = [];
|
||
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}`;
|
||
|
||
// 没有扫码通道也不要紧:摄像头本身就是一条「虚拟通道」(`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: Number(camera.status) === 1 && Number(camera.enabled) === 1,
|
||
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<number>} 通知到的设备数
|
||
*/
|
||
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;
|