424 lines
18 KiB
JavaScript
424 lines
18 KiB
JavaScript
const BaseService = require('./base');
|
||
|
||
/**
|
||
* 海康录像任务服务
|
||
* 客户端通过 WebSocket 调用:
|
||
* hikvision.fetchTasks - 拉取待录像的打包任务
|
||
* hikvision.receiveTask - 确认接收任务,更新状态为 recording
|
||
* hikvision.taskComplete - 任务完成回调,写入结果
|
||
*/
|
||
class HikvisionService extends BaseService {
|
||
/**
|
||
* 将 MySQL DATETIME(存储为 UTC)转为 ISO 8601 北京时间 (+08:00)
|
||
* @param {string} datetime - DB 时间
|
||
* @param {number} offsetMs - 额外偏移(ms),负数=提前
|
||
*/
|
||
_toISO(datetime, offsetMs = 0) {
|
||
if (!datetime) return null;
|
||
const str = String(datetime).trim();
|
||
const utc = new Date(str + 'Z');
|
||
const cst = new Date(utc.getTime() + 8 * 3600000 + offsetMs);
|
||
return cst.toISOString().replace('Z', '+08:00');
|
||
}
|
||
|
||
/**
|
||
* 拉取待录像任务
|
||
* 查询 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.end_time, t.operator_text
|
||
FROM wms_pack_task t
|
||
WHERE t.warehouse_id = ?
|
||
AND t.deleted_at IS NULL
|
||
AND t.end_time IS NOT NULL
|
||
AND t.device_ids IS NOT NULL
|
||
AND t.device_ids != '[]'
|
||
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 = [];
|
||
}
|
||
|
||
// 事务:原子化检查+插入,防止并发重复
|
||
const conn = await app.mysql.get('wms').beginTransaction();
|
||
try {
|
||
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;
|
||
|
||
// 事务内 SELECT ... FOR UPDATE 锁定检查,防止并发重复
|
||
const [existing] = await conn.query(
|
||
`SELECT id FROM wms_pack_task_video
|
||
WHERE pack_task_id = ? AND camera_id = ? AND deleted_at IS NULL
|
||
FOR UPDATE`,
|
||
[task.id, matchedCamera.id]
|
||
);
|
||
if (!existing || existing.length === 0) {
|
||
await conn.insert('wms_pack_task_video', {
|
||
pack_task_id: task.id,
|
||
camera_id: matchedCamera.id,
|
||
video_url: '',
|
||
status: 'created',
|
||
});
|
||
console.log(`[Hikvision] 创建录像记录: pack_task=${task.id}, camera=${matchedCamera.id}`);
|
||
}
|
||
|
||
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: this._toISO(task.start_time, -5000),
|
||
end_time: this._toISO(task.end_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,
|
||
},
|
||
});
|
||
}
|
||
await conn.commit();
|
||
} catch (txError) {
|
||
await conn.rollback();
|
||
throw txError;
|
||
}
|
||
}
|
||
|
||
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') {
|
||
// 取最新的录像记录 ID 精准更新,避免 forceRecord 并发覆盖
|
||
const [latestVideo] = await app.mysql.get('wms').select('wms_pack_task_video', {
|
||
where: { pack_task_id: packTaskId, deleted_at: null },
|
||
orders: [['id', 'desc']],
|
||
limit: 1,
|
||
});
|
||
if (latestVideo) {
|
||
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: { id: latestVideo.id } }
|
||
);
|
||
}
|
||
|
||
console.log(`[Hikvision] 录像完成: pack_task=${packTaskId}, url=${fileUrl}, size=${size}`);
|
||
return this.successResponse('hikvision.taskComplete',
|
||
{ packTaskId, status: 'completed' }, '录像完成');
|
||
} else {
|
||
// 录像失败 - 同样精准更新最新记录
|
||
const [latestVideo] = await app.mysql.get('wms').select('wms_pack_task_video', {
|
||
where: { pack_task_id: packTaskId, deleted_at: null },
|
||
orders: [['id', 'desc']],
|
||
limit: 1,
|
||
});
|
||
if (latestVideo) {
|
||
await app.mysql.get('wms').update('wms_pack_task_video',
|
||
{ status: 'failed', remark: errorMsg || '录像失败' },
|
||
{ where: { id: latestVideo.id } }
|
||
);
|
||
}
|
||
|
||
console.log(`[Hikvision] 录像失败: pack_task=${packTaskId}, error=${errorMsg}`);
|
||
return this.successResponse('hikvision.taskComplete',
|
||
{ packTaskId, status: 'failed', error: errorMsg }, '录像失败已记录');
|
||
}
|
||
} catch (error) {
|
||
console.error('[Hikvision] taskComplete 错误:', error);
|
||
return this.errorResponse('hikvision.taskComplete', error.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 强制录制:外部 HTTP 调用,按 pack_task_id 强制推送录制任务
|
||
* 事务内重置已有录像行,推送成功后返回
|
||
*/
|
||
async forceRecord(data) {
|
||
const { app } = this;
|
||
const { pack_task_id } = data || {};
|
||
|
||
if (!pack_task_id) {
|
||
return { status: 'fail', message: '缺少 pack_task_id' };
|
||
}
|
||
|
||
try {
|
||
// 1. 查询打包任务
|
||
const task = await app.mysql.get('wms').get('wms_pack_task', {
|
||
id: pack_task_id,
|
||
deleted_at: null,
|
||
});
|
||
|
||
if (!task) {
|
||
return { status: 'fail', message: '打包任务不存在' };
|
||
}
|
||
|
||
if (!task.end_time || !task.device_ids || task.device_ids === '[]') {
|
||
return { status: 'fail', message: '打包任务未完成或无设备信息' };
|
||
}
|
||
|
||
// 2. 查询摄像头和服务器
|
||
const cameras = await app.mysql.get('wms').select('wms_camera', {
|
||
where: { warehouse_id: task.warehouse_id, deleted_at: null, status: 1 },
|
||
});
|
||
const servers = await app.mysql.get('wms').select('wms_camera_server', {
|
||
where: { warehouse_id: task.warehouse_id, deleted_at: null, status: 1 },
|
||
});
|
||
|
||
// 3. 找到同仓库的录制电脑
|
||
const warehousePattern = `warehouse:${task.warehouse_id}:printer:*`;
|
||
const onlineKeys = [];
|
||
let cursor = '0';
|
||
do {
|
||
const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100);
|
||
cursor = nextCursor;
|
||
onlineKeys.push(...keys);
|
||
} while (cursor !== '0');
|
||
|
||
let recordingUniqueId = null;
|
||
for (const key of onlineKeys) {
|
||
const info = await app.redis.get(key);
|
||
if (!info) continue;
|
||
const parsed = JSON.parse(info);
|
||
if (parsed.is_recording === 1) {
|
||
recordingUniqueId = parsed.uniqueId;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (!recordingUniqueId) {
|
||
console.log(`[Hikvision] forceRecord 失败: 仓库 ${task.warehouse_id} 无录制电脑在线, 在线电脑: ${onlineKeys.length}台`);
|
||
return { status: 'fail', message: '该仓库无录制电脑在线' };
|
||
}
|
||
|
||
// 4. 事务:重置录像行
|
||
const deviceIds = typeof task.device_ids === 'string'
|
||
? JSON.parse(task.device_ids) : (task.device_ids || []);
|
||
|
||
const conn = await app.mysql.get('wms').beginTransaction();
|
||
try {
|
||
for (const deviceId of deviceIds) {
|
||
const matchedCamera = cameras.find(c => c.id === deviceId) || cameras[0];
|
||
if (!matchedCamera) continue;
|
||
const matchedServer = servers.find(s => s.id === matchedCamera.server_id) || servers[0];
|
||
if (!matchedServer) continue;
|
||
|
||
// 删除已有录像行,重新创建
|
||
await conn.delete('wms_pack_task_video', { pack_task_id: task.id });
|
||
await conn.insert('wms_pack_task_video', {
|
||
pack_task_id: task.id,
|
||
camera_id: matchedCamera.id,
|
||
video_url: '',
|
||
status: 'created',
|
||
});
|
||
await conn.commit();
|
||
console.log(`[Hikvision] 强制录制-重置录像行: pack_task=${task.id}`);
|
||
|
||
// 5. 推送录制任务
|
||
const payload = {
|
||
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,
|
||
start_time: this._toISO(task.start_time, -5000),
|
||
end_time: this._toISO(task.end_time),
|
||
camera: {
|
||
id: matchedCamera.id,
|
||
channel_id: matchedCamera.channel_id,
|
||
channel_name: matchedCamera.channel_name,
|
||
ip: matchedCamera.ip,
|
||
port: matchedCamera.port,
|
||
model: matchedCamera.model,
|
||
},
|
||
server: {
|
||
id: matchedServer.id,
|
||
brand: matchedServer.brand,
|
||
internal_ip: matchedServer.internal_ip,
|
||
internal_port: matchedServer.internal_port || 80,
|
||
username: matchedServer.username,
|
||
password: matchedServer.password,
|
||
},
|
||
};
|
||
|
||
const sendRes = await app.ws.sendTo(recordingUniqueId, JSON.stringify({
|
||
method: 'hikvision.receiveTask',
|
||
data: payload,
|
||
}));
|
||
|
||
if (sendRes !== 1) {
|
||
return { status: 'fail', message: '推送失败,录制电脑可能已断开' };
|
||
}
|
||
|
||
console.log(`[Hikvision] 强制录制-已推送: pack_task=${task.id}, device=${deviceId}`);
|
||
}
|
||
} catch (txError) {
|
||
await conn.rollback();
|
||
throw txError;
|
||
}
|
||
|
||
return { status: 'success', message: '强制录制任务已推送', pack_task_id: task.id };
|
||
} catch (error) {
|
||
console.error('[Hikvision] forceRecord 错误:', error);
|
||
return { status: 'fail', message: error.message };
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = HikvisionService;
|