From 7c1e449e35cea7b09b6df5f3d5ff519604a96397 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 01:39:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B5=B7=E5=BA=B7=E5=BD=95=E5=83=8F?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=9C=8D=E5=8A=A1=20-=20fetchTasks/receiveTa?= =?UTF-8?q?sk/taskComplete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/hikvision.js | 234 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 app/service/hikvision.js diff --git a/app/service/hikvision.js b/app/service/hikvision.js new file mode 100644 index 0000000..9184443 --- /dev/null +++ b/app/service/hikvision.js @@ -0,0 +1,234 @@ +const BaseService = require('./base'); + +/** + * 海康录像任务服务 + * 客户端通过 WebSocket 调用: + * hikvision.fetchTasks - 拉取待录像的打包任务 + * hikvision.receiveTask - 确认接收任务,更新状态为 recording + * hikvision.taskComplete - 任务完成回调,写入结果 + */ +class HikvisionService extends BaseService { + /** + * 拉取待录像任务 + * 查询 wms_pack_task 中 pack_mode=1 且无录像记录的任务 + * 返回任务信息 + 摄像头信息 + 服务器信息 + */ + async fetchTasks(data) { + const { app } = this; + const { print_computer_info } = this.ctx; + + if (!print_computer_info) { + return this.errorResponse('hikvision.fetchTasks', '未绑定打印电脑信息'); + } + + const warehouseId = print_computer_info.warehouse; + + try { + // 1. 查询该仓库待录像的打包任务(pack_mode=1, 状态不是已完成, 未删除) + const tasks = await app.mysql.get('wms').query( + `SELECT t.id, t.order_id, t.warehouse_id, t.workbench_id, + t.wave_no, t.waybill_code, t.device_ids, t.status AS task_status, + t.start_time, t.operator_text + FROM wms_pack_task t + WHERE t.warehouse_id = ? + AND t.pack_mode = 1 + AND t.deleted_at IS NULL + AND t.id NOT IN ( + SELECT v.pack_task_id FROM wms_pack_task_video v WHERE v.deleted_at IS NULL + ) + ORDER BY t.id DESC + LIMIT 20`, + [warehouseId] + ); + + if (!tasks || tasks.length === 0) { + return this.successResponse('hikvision.fetchTasks', [], '暂无待录像任务'); + } + + // 2. 获取该仓库的摄像头服务器信息 + const servers = await app.mysql.get('wms').select('wms_camera_server', { + where: { warehouse_id: warehouseId, deleted_at: null, status: 1 }, + }); + + // 3. 获取该仓库的摄像头列表 + const cameras = await app.mysql.get('wms').select('wms_camera', { + where: { warehouse_id: warehouseId, deleted_at: null, status: 1 }, + }); + + // 4. 组装返回数据:每个任务的每个摄像头返回一条 + const result = []; + for (const task of tasks) { + let deviceIds = []; + try { + deviceIds = typeof task.device_ids === 'string' + ? JSON.parse(task.device_ids) + : (task.device_ids || []); + } catch (e) { + deviceIds = []; + } + + for (const deviceId of deviceIds) { + // 按设备ID匹配摄像头 + const matchedCamera = cameras.find(c => c.id === deviceId) + || cameras.find(c => c.custom_name && c.custom_name.includes(`${task.workbench_id}号`)) + || cameras[0]; + + if (!matchedCamera) continue; + + const matchedServer = servers.find(s => s.id === matchedCamera.server_id) || servers[0]; + if (!matchedServer) continue; + + result.push({ + pack_task_id: task.id, + device_id: deviceId, + uniqueCode: `${task.id}_${deviceId}`, + order_id: task.order_id, + warehouse_id: task.warehouse_id, + workbench_id: task.workbench_id, + wave_no: task.wave_no, + waybill_code: task.waybill_code, + task_status: task.task_status, + start_time: task.start_time, + operator: task.operator_text, + camera: { + id: matchedCamera.id, + channel_id: matchedCamera.channel_id, + channel_name: matchedCamera.channel_name, + ip: matchedCamera.ip, + port: matchedCamera.port, + model: matchedCamera.model, + custom_name: matchedCamera.custom_name, + }, + server: { + id: matchedServer.id, + brand: matchedServer.brand, + internal_ip: matchedServer.internal_ip, + internal_port: matchedServer.internal_port || 80, + username: matchedServer.username, + password: matchedServer.password, + }, + }); + } + } + + console.log(`[Hikvision] 仓库 ${warehouseId} 返回 ${result.length} 个待录像任务`); + return this.successResponse('hikvision.fetchTasks', result, '查询成功'); + + } catch (error) { + console.error('[Hikvision] fetchTasks 错误:', error); + return this.errorResponse('hikvision.fetchTasks', error.message); + } + } + + /** + * 客户端确认接收任务 + * 创建 wms_pack_task_video 记录,状态改为 recording + */ + async receiveTask(data) { + const { app } = this; + const { taskId, uniqueCode, ok, message } = data || {}; + + if (!uniqueCode) { + return this.errorResponse('hikvision.receiveTask', '缺少 uniqueCode'); + } + + try { + // 从 uniqueCode 解析 pack_task_id(格式: {task_id}_{device_id}) + const parts = uniqueCode.split('_'); + const packTaskId = parseInt(parts[0]); + + if (!packTaskId) { + return this.errorResponse('hikvision.receiveTask', '无法解析 pack_task_id'); + } + + if (ok) { + // 任务接收成功 → 创建录像记录,状态 recording + const existingVideo = await app.mysql.get('wms').get('wms_pack_task_video', { + pack_task_id: packTaskId, + deleted_at: null, + }); + + if (!existingVideo) { + await app.mysql.get('wms').insert('wms_pack_task_video', { + pack_task_id: packTaskId, + video_url: '', + status: 'recording', + remark: message || '任务已接收', + }); + } else if (existingVideo.status === 'created') { + await app.mysql.get('wms').update('wms_pack_task_video', + { status: 'recording', remark: message || '任务已接收' }, + { where: { id: existingVideo.id } } + ); + } + + console.log(`[Hikvision] 录像开始: pack_task=${packTaskId}, taskId=${taskId}`); + return this.successResponse('hikvision.receiveTask', { packTaskId, status: 'recording' }, '录像已开始'); + } else { + // 任务接收失败 + console.log(`[Hikvision] 任务接收失败: pack_task=${packTaskId}, message=${message}`); + return this.errorResponse('hikvision.receiveTask', message || '任务接收失败'); + } + } catch (error) { + console.error('[Hikvision] receiveTask 错误:', error); + return this.errorResponse('hikvision.receiveTask', error.message); + } + } + + /** + * 客户端回调:录像任务完成 + * 成功 → 写入 video_url,状态 completed + * 失败 → 写入 remark,状态 failed + */ + async taskComplete(data) { + const { app } = this; + const { taskId, uniqueCode, status, success, output, size, duration, speed, fileUrl, error: errorMsg } = data || {}; + + if (!uniqueCode) { + return this.errorResponse('hikvision.taskComplete', '缺少 uniqueCode'); + } + + try { + const parts = uniqueCode.split('_'); + const packTaskId = parseInt(parts[0]); + + if (!packTaskId) { + return this.errorResponse('hikvision.taskComplete', '无法解析 pack_task_id'); + } + + if (success && status === 'completed') { + // 录像成功 + await app.mysql.get('wms').update('wms_pack_task_video', + { + video_url: fileUrl || output || '', + status: 'completed', + remark: `大小:${(size / 1024 / 1024).toFixed(2)}MB, 时长:${duration}s, 倍速:${speed}x`, + }, + { where: { pack_task_id: packTaskId, deleted_at: null } } + ); + + console.log(`[Hikvision] 录像完成: pack_task=${packTaskId}, url=${fileUrl}, size=${size}`); + return this.successResponse('hikvision.taskComplete', + { packTaskId, status: 'completed' }, '录像完成'); + } else { + // 录像失败 + await app.mysql.get('wms').update('wms_pack_task_video', + { + status: 'failed', + remark: errorMsg || '录像失败', + }, + { where: { pack_task_id: packTaskId, deleted_at: null } } + ); + + console.log(`[Hikvision] 录像失败: pack_task=${packTaskId}, error=${errorMsg}`); + return this.successResponse('hikvision.taskComplete', + { packTaskId, status: 'failed' }, '录像失败已记录'); + } + } catch (error) { + console.error('[Hikvision] taskComplete 错误:', error); + return this.errorResponse('hikvision.taskComplete', error.message); + } + } +} + +module.exports = HikvisionService;