'use strict'; const Service = require('egg').Service; class CameraService extends Service { async list(params = {}) { const { ctx } = this; const { Op } = ctx.app.Sequelize; const warehouseId = ctx.user.store_id; const { pagination = {}, where = {} } = params; const page = Math.max(1, parseInt(pagination.page) || 1); const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); const queryWhere = { warehouse_id: warehouseId }; if (where.server_id) queryWhere.server_id = parseInt(where.server_id); if (where.custom_name) queryWhere.custom_name = { [Op.like]: `%${where.custom_name}%` }; if (where.status !== undefined && where.status !== null && where.status !== '') { queryWhere.status = parseInt(where.status); } const { count, rows } = await ctx.model.Camera.findAndCountAll({ where: queryWhere, include: [{ model: ctx.model.CameraServer, as: 'server', attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], required: false, }], order: [[ 'created_at', 'DESC' ]], offset: (page - 1) * pageSize, limit: pageSize, }); return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } }; } async detail(id) { const { ctx } = this; const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: ctx.user.store_id }, include: [{ model: ctx.model.CameraServer, as: 'server', attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], required: false, }], }); if (!record) throw new Error('摄像头不存在或无权访问'); return record; } async create(data) { const { ctx } = this; if (!data.server_id) throw new Error('所属服务器ID不能为空'); if (data.channel_id === undefined || data.channel_id === null) throw new Error('通道编号不能为空'); if (data.custom_name !== undefined && data.custom_name !== null && String(data.custom_name).trim() === '') { throw new Error('自定义名称不能为空'); } return await ctx.model.Camera.create({ warehouse_id: ctx.user.store_id, server_id: parseInt(data.server_id), channel_id: parseInt(data.channel_id), channel_name: data.channel_name || null, ip: data.ip || null, port: data.port !== undefined && data.port !== null ? parseInt(data.port) : null, model: data.model || null, serial_number: data.serial_number || null, stream_type: data.stream_type || null, username: data.username || null, password: data.password || null, custom_name: data.custom_name || null, status: data.status !== undefined ? parseInt(data.status) : 1, remark: data.remark || null, }); } async update(id, data) { const { ctx } = this; const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); if (!record) throw new Error('摄像头不存在或无权操作'); const fields = {}; if (data.server_id !== undefined) fields.server_id = parseInt(data.server_id); if (data.channel_id !== undefined) fields.channel_id = parseInt(data.channel_id); if (data.channel_name !== undefined) fields.channel_name = data.channel_name; if (data.ip !== undefined) fields.ip = data.ip; if (data.port !== undefined) fields.port = data.port !== null ? parseInt(data.port) : null; if (data.model !== undefined) fields.model = data.model; if (data.serial_number !== undefined) fields.serial_number = data.serial_number; if (data.stream_type !== undefined) fields.stream_type = data.stream_type; if (data.username !== undefined) fields.username = data.username; if (data.password !== undefined) fields.password = data.password; if (data.custom_name !== undefined) { if (data.custom_name !== null && String(data.custom_name).trim() === '') { throw new Error('自定义名称不能为空'); } fields.custom_name = data.custom_name; } if (data.status !== undefined) fields.status = parseInt(data.status); if (data.remark !== undefined) fields.remark = data.remark; if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); await record.update(fields); return record; } /** * 设置摄像头 OSD 文字叠加 * @param {Object} data - 配置选项 * @param {number} data.id - 摄像头ID * @param {string} data.text - OSD 叠加文字 * @param {number} [data.x] - X 坐标(-1 到 1,默认 -0.9) * @param {number} [data.y] - Y 坐标(-1 到 1,默认 0.8) * @return {Promise} 打印服务响应 */ async setOsd(data) { const { ctx } = this; const { id, text, x, y } = data || {}; const warehouseId = ctx.user.store_id; if (!id) throw new Error('摄像头ID不能为空'); if (!text) throw new Error('OSD叠加文字不能为空'); // 查询摄像头及关联服务器 const camera = await ctx.model.Camera.findOne({ where: { id: parseInt(id), warehouse_id: warehouseId }, include: [{ model: ctx.model.CameraServer, as: 'server', attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], required: false, }], }); if (!camera) throw new Error('摄像头不存在或无权操作'); const OsdClient = require('../../lib/osd_client'); const osdClient = new OsdClient(ctx); const result = await osdClient.setOsd({ camera, warehouseId, text, x, y, }); if (result.error) { throw new Error(`打印服务请求失败: ${result.error}`); } if (!result.response || result.response.status !== 200) { const status = result.response ? result.response.status : '无响应'; const resData = result.response && result.response.data; const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; throw new Error(`打印服务返回异常(${status}): ${msg}`); } return { camera_id: camera.id, rtsp_url: result.request.rtspUrl, osd_text: text, position: { x: result.request.x, y: result.request.y }, print_service_response: result.response, }; } /** * 查询本仓库摄像头(云台控制复用,带录像服务器认证信息兜底) * @param {number|string} id - 摄像头ID * @param {number} warehouseId - 仓库ID * @return {Promise} 摄像头记录 */ async _findCameraForControl(id, warehouseId) { const { ctx } = this; const camera = await ctx.model.Camera.findOne({ where: { id: parseInt(id), warehouse_id: warehouseId }, include: [{ model: ctx.model.CameraServer, as: 'server', attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], required: false, }], }); if (!camera) throw new Error('摄像头不存在或无权操作'); return camera; } /** * 校验打印服务响应,失败时抛出业务错误(与 setOsd 同口径) * @param {Object} result - 打印服务调用结果 * @return {Object} 原始结果 */ _assertPtzSuccess(result) { if (!result) throw new Error('打印服务无响应'); if (result.error) { throw new Error(`打印服务请求失败: ${result.error}`); } if (!result.response || result.response.status < 200 || result.response.status >= 300) { const status = result.response ? result.response.status : '无响应'; const resData = result.response && result.response.data; const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; throw new Error(`打印服务返回异常(${status}): ${msg}`); } return result; } /** * 云台方向控制(按下):按指定方向转动摄像头,需配对调用 ptzStop 停止 * @param {Object} data - 参数 * @param {number} data.id - 摄像头ID(必填) * @param {string} data.action - 云台方向(8 个位置,必填) * @param {number} [data.speed] - 云台转速(1-7,默认 4) * @return {Promise} 下发结果 */ async ptzControl(data) { const { ctx } = this; const { id, action, speed } = data || {}; const warehouseId = ctx.user.store_id; if (!id) throw new Error('摄像头ID不能为空'); const PtzClient = require('../../lib/ptz_client'); const normalizedAction = PtzClient.normalizeAction(action); const normalizedSpeed = PtzClient.normalizeSpeed(speed); const camera = await this._findCameraForControl(id, warehouseId); const ptzClient = new PtzClient(ctx); const result = await ptzClient.control({ camera, warehouseId, action: normalizedAction, speed: normalizedSpeed, }); this._assertPtzSuccess(result); return { camera_id: camera.id, rtsp_url: result.request.rtspUrl, action: normalizedAction, speed: normalizedSpeed, print_service_response: result.response, }; } /** * 云台停止(松手):停止转动,action 必须与按下时一致 * @param {Object} data - 参数 * @param {number} data.id - 摄像头ID(必填) * @param {string} data.action - 云台方向(必须与按下时一致,必填) * @return {Promise} 下发结果 */ async ptzStop(data) { const { ctx } = this; const { id, action } = data || {}; const warehouseId = ctx.user.store_id; if (!id) throw new Error('摄像头ID不能为空'); const PtzClient = require('../../lib/ptz_client'); const normalizedAction = PtzClient.normalizeAction(action); const camera = await this._findCameraForControl(id, warehouseId); const ptzClient = new PtzClient(ctx); const result = await ptzClient.stop({ camera, warehouseId, action: normalizedAction, }); this._assertPtzSuccess(result); return { camera_id: camera.id, rtsp_url: result.request.rtspUrl, action: normalizedAction, print_service_response: result.response, }; } /** * 云台预置点跳转(一次调用即可,无需 stop) * @param {Object} data - 参数 * @param {number} data.id - 摄像头ID(必填) * @param {number|string} data.presetId - 预置点编号(1-256,必填) * @return {Promise} 下发结果 */ async ptzPresetGoto(data) { const { ctx } = this; const { id, presetId } = data || {}; const warehouseId = ctx.user.store_id; if (!id) throw new Error('摄像头ID不能为空'); const PtzClient = require('../../lib/ptz_client'); const normalizedPresetId = PtzClient.normalizePresetId(presetId); const camera = await this._findCameraForControl(id, warehouseId); const ptzClient = new PtzClient(ctx); const result = await ptzClient.presetGoto({ camera, warehouseId, presetId: normalizedPresetId, }); this._assertPtzSuccess(result); return { camera_id: camera.id, rtsp_url: result.request.rtspUrl, preset_id: normalizedPresetId, print_service_response: result.response, }; } /** * 云台预置点设置:把摄像头当前机位保存为指定预置点(一次调用即可) * @param {Object} data - 参数 * @param {number} data.id - 摄像头ID(必填) * @param {number|string} data.presetId - 预置点编号(1-256,必填) * @return {Promise} 下发结果 */ async ptzPresetSet(data) { const { ctx } = this; const { id, presetId } = data || {}; const warehouseId = ctx.user.store_id; if (!id) throw new Error('摄像头ID不能为空'); const PtzClient = require('../../lib/ptz_client'); const normalizedPresetId = PtzClient.normalizePresetId(presetId); const camera = await this._findCameraForControl(id, warehouseId); const ptzClient = new PtzClient(ctx); const result = await ptzClient.presetSet({ camera, warehouseId, presetId: normalizedPresetId, }); this._assertPtzSuccess(result); return { camera_id: camera.id, rtsp_url: result.request.rtspUrl, preset_id: normalizedPresetId, print_service_response: result.response, }; } async delete(id) { const { ctx } = this; const warehouseId = ctx.user.store_id; const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: warehouseId } }); if (!record) throw new Error('摄像头不存在或无权操作'); // 检查是否被工作台绑定 const boundWorkbenches = await ctx.model.Workbench.findAll({ where: { warehouse_id: warehouseId }, attributes: [ 'id', 'name' ], }); for (const wb of boundWorkbenches) { const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : []; if (deviceIds.includes(id)) { throw new Error(`摄像头已被工作台「${wb.name}」绑定,请先解绑后再删除`); } } await record.destroy(); } } module.exports = CameraService;