feat(video): 添加报警记录管理功能- 新增报警记录实体类 AlarmRecord 及相关字段定义

- 实现报警记录的增删改查接口与 Mapper 层逻辑
- 添加报警记录前端页面,支持列表展示、搜索、处理与忽略操作
- 支持批量处理报警记录及导出功能
- 增加报警记录详情查看弹窗,展示图片与视频信息- 配置定时任务白名单,允许访问 ruoyi.video 包
- 引入 JavaCV 依赖以支持视频处理功能
- 添加 testng 依赖用于测试支持
This commit is contained in:
2025-09-27 14:57:15 +08:00
parent 03d24749ea
commit 232de8c8d5
20 changed files with 2539 additions and 2 deletions

View File

@@ -39,7 +39,11 @@
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.9</version> <!-- 版本号需与项目兼容 -->
</dependency>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@@ -0,0 +1,28 @@
import request from '@/utils/request'
// 查询报警记录列表
export function listAlarm(query) {
return request({
url: '/video/alarm/list',
method: 'get',
params: query
})
}
// 处理报警记录
export function handleAlarm(data) {
return request({
url: '/video/alarm/handle',
method: 'post',
params: data
})
}
// 批量处理报警记录
export function batchHandleAlarm(data) {
return request({
url: '/video/alarm/batchHandle',
method: 'post',
params: data
})
}

View File

@@ -0,0 +1,68 @@
import request from '@/utils/request'
// 查询巡检任务列表
export function listInspection(query) {
return request({
url: '/video/inspection/list',
method: 'get',
params: query
})
}
// 查询巡检任务详细
export function getInspection(taskId) {
return request({
url: '/video/inspection/' + taskId,
method: 'get'
})
}
// 新增巡检任务
export function addInspection(data) {
return request({
url: '/video/inspection',
method: 'post',
data: data
})
}
// 修改巡检任务
export function updateInspection(data) {
return request({
url: '/video/inspection',
method: 'put',
data: data
})
}
// 删除巡检任务
export function delInspection(taskId) {
return request({
url: '/video/inspection/' + taskId,
method: 'delete'
})
}
// 启动巡检任务
export function startTask(taskId) {
return request({
url: '/video/inspection/start/' + taskId,
method: 'post'
})
}
// 停止巡检任务
export function stopTask(taskId) {
return request({
url: '/video/inspection/stop/' + taskId,
method: 'post'
})
}
// 执行巡检任务
export function executeTask(taskId) {
return request({
url: '/video/inspection/execute/' + taskId,
method: 'post'
})
}

View File

@@ -0,0 +1,349 @@
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="任务名称" prop="taskName">
<el-input
v-model="queryParams.taskName"
placeholder="请输入任务名称"
clearable
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="设备名称" prop="deviceName">
<el-input
v-model="queryParams.deviceName"
placeholder="请输入设备名称"
clearable
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="报警类型" prop="alarmType">
<el-input
v-model="queryParams.alarmType"
placeholder="请输入报警类型"
clearable
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="处理状态" prop="handleStatus">
<el-select v-model="queryParams.handleStatus" placeholder="请选择处理状态" clearable>
<el-option label="未处理" value="0" />
<el-option label="已处理" value="1" />
<el-option label="已忽略" value="2" />
</el-select>
</el-form-item>
<el-form-item label="报警时间">
<el-date-picker
v-model="daterangeAlarmTime"
style="width: 240px"
value-format="YYYY-MM-DD"
type="daterange"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
></el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="success"
plain
icon="Check"
:disabled="multiple"
@click="handleBatchProcess('1')"
v-hasPermi="['video:alarm:handle']"
>批量处理</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="info"
plain
icon="Close"
:disabled="multiple"
@click="handleBatchProcess('2')"
v-hasPermi="['video:alarm:handle']"
>批量忽略</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="Download"
@click="handleExport"
v-hasPermi="['video:alarm:export']"
>导出</el-button>
</el-col>
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="alarmList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="报警ID" align="center" prop="alarmId" />
<el-table-column label="任务名称" align="center" prop="taskName" />
<el-table-column label="设备名称" align="center" prop="deviceName" />
<el-table-column label="报警类型" align="center" prop="alarmType" />
<el-table-column label="报警级别" align="center" prop="alarmLevel">
<template #default="scope">
<el-tag v-if="scope.row.alarmLevel === '1'" type="info"></el-tag>
<el-tag v-else-if="scope.row.alarmLevel === '2'" type="warning"></el-tag>
<el-tag v-else-if="scope.row.alarmLevel === '3'" type="danger"></el-tag>
</template>
</el-table-column>
<el-table-column label="报警描述" align="center" prop="alarmDesc" />
<el-table-column label="置信度" align="center" prop="confidence">
<template #default="scope">
{{ (scope.row.confidence * 100).toFixed(1) }}%
</template>
</el-table-column>
<el-table-column label="报警图片" align="center" prop="imagePath">
<template #default="scope">
<el-image
v-if="scope.row.imagePath"
style="width: 60px; height: 40px"
:src="scope.row.imagePath"
:preview-src-list="[scope.row.imagePath]"
fit="cover"
/>
</template>
</el-table-column>
<el-table-column label="报警时间" align="center" prop="alarmTime" width="180">
<template #default="scope">
<span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="处理状态" align="center" prop="handleStatus">
<template #default="scope">
<el-tag v-if="scope.row.handleStatus === '0'" type="danger">未处理</el-tag>
<el-tag v-else-if="scope.row.handleStatus === '1'" type="success">已处理</el-tag>
<el-tag v-else-if="scope.row.handleStatus === '2'" type="info">已忽略</el-tag>
</template>
</el-table-column>
<el-table-column label="处理人" align="center" prop="handleBy" />
<el-table-column label="处理时间" align="center" prop="handleTime" width="180">
<template #default="scope">
<span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template #default="scope">
<el-button
link
type="success"
icon="Check"
@click="handleProcess(scope.row, '1')"
v-hasPermi="['video:alarm:handle']"
v-if="scope.row.handleStatus === '0'"
>处理</el-button>
<el-button
link
type="info"
icon="Close"
@click="handleProcess(scope.row, '2')"
v-hasPermi="['video:alarm:handle']"
v-if="scope.row.handleStatus === '0'"
>忽略</el-button>
<el-button
link
type="primary"
icon="View"
@click="handleView(scope.row)"
>查看</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
v-model:page="queryParams.pageNum"
v-model:limit="queryParams.pageSize"
@pagination="getList"
/>
<!-- 处理报警对话框 -->
<el-dialog :title="processTitle" v-model="processOpen" width="500px" append-to-body>
<el-form ref="processRef" :model="processForm" label-width="80px">
<el-form-item label="处理状态">
<el-tag v-if="processForm.handleStatus === '1'" type="success">已处理</el-tag>
<el-tag v-else-if="processForm.handleStatus === '2'" type="info">已忽略</el-tag>
</el-form-item>
<el-form-item label="处理备注">
<el-input
v-model="processForm.handleRemark"
type="textarea"
placeholder="请输入处理备注"
:rows="4"
/>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitProcess"> </el-button>
<el-button @click="processOpen = false"> </el-button>
</div>
</template>
</el-dialog>
<!-- 查看报警详情对话框 -->
<el-dialog title="报警详情" v-model="viewOpen" width="800px" append-to-body>
<el-descriptions :column="2" border>
<el-descriptions-item label="报警ID">{{ viewForm.alarmId }}</el-descriptions-item>
<el-descriptions-item label="任务名称">{{ viewForm.taskName }}</el-descriptions-item>
<el-descriptions-item label="设备名称">{{ viewForm.deviceName }}</el-descriptions-item>
<el-descriptions-item label="报警类型">{{ viewForm.alarmType }}</el-descriptions-item>
<el-descriptions-item label="报警级别">
<el-tag v-if="viewForm.alarmLevel === '1'" type="info"></el-tag>
<el-tag v-else-if="viewForm.alarmLevel === '2'" type="warning"></el-tag>
<el-tag v-else-if="viewForm.alarmLevel === '3'" type="danger"></el-tag>
</el-descriptions-item>
<el-descriptions-item label="置信度">{{ (viewForm.confidence * 100).toFixed(1) }}%</el-descriptions-item>
<el-descriptions-item label="报警时间" :span="2">{{ parseTime(viewForm.alarmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
<el-descriptions-item label="报警描述" :span="2">{{ viewForm.alarmDesc }}</el-descriptions-item>
<el-descriptions-item label="处理状态">
<el-tag v-if="viewForm.handleStatus === '0'" type="danger">未处理</el-tag>
<el-tag v-else-if="viewForm.handleStatus === '1'" type="success">已处理</el-tag>
<el-tag v-else-if="viewForm.handleStatus === '2'" type="info">已忽略</el-tag>
</el-descriptions-item>
<el-descriptions-item label="处理人">{{ viewForm.handleBy || '无' }}</el-descriptions-item>
<el-descriptions-item label="处理时间" :span="2">{{ parseTime(viewForm.handleTime, '{y}-{m}-{d} {h}:{i}:{s}') || '无' }}</el-descriptions-item>
<el-descriptions-item label="处理备注" :span="2">{{ viewForm.handleRemark || '无' }}</el-descriptions-item>
</el-descriptions>
<div v-if="viewForm.imagePath" style="margin-top: 20px;">
<h4>报警图片</h4>
<el-image
style="width: 100%; max-height: 400px"
:src="viewForm.imagePath"
:preview-src-list="[viewForm.imagePath]"
fit="contain"
/>
</div>
</el-dialog>
</div>
</template>
<script setup name="Alarm">
import { listAlarm, handleAlarm, batchHandleAlarm } from "@/api/video/alarm";
const { proxy } = getCurrentInstance();
const alarmList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const multiple = ref(true);
const total = ref(0);
const daterangeAlarmTime = ref([]);
const processOpen = ref(false);
const processTitle = ref("");
const processForm = ref({});
const viewOpen = ref(false);
const viewForm = ref({});
const data = reactive({
queryParams: {
pageNum: 1,
pageSize: 10,
taskName: null,
deviceName: null,
alarmType: null,
handleStatus: null,
beginAlarmTime: null,
endAlarmTime: null
}
});
const { queryParams } = toRefs(data);
/** 查询报警记录列表 */
function getList() {
loading.value = true;
queryParams.value.beginAlarmTime = daterangeAlarmTime.value ? daterangeAlarmTime.value[0] : null;
queryParams.value.endAlarmTime = daterangeAlarmTime.value ? daterangeAlarmTime.value[1] : null;
listAlarm(queryParams.value).then(response => {
alarmList.value = response.rows;
total.value = response.total;
loading.value = false;
});
}
/** 搜索按钮操作 */
function handleQuery() {
queryParams.value.pageNum = 1;
getList();
}
/** 重置按钮操作 */
function resetQuery() {
daterangeAlarmTime.value = [];
proxy.resetForm("queryRef");
handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
ids.value = selection.map(item => item.alarmId);
multiple.value = !selection.length;
}
/** 处理报警 */
function handleProcess(row, status) {
processForm.value = {
alarmId: row.alarmId,
handleStatus: status,
handleRemark: ''
};
processTitle.value = status === '1' ? '处理报警' : '忽略报警';
processOpen.value = true;
}
/** 提交处理 */
function submitProcess() {
handleAlarm(processForm.value).then(response => {
proxy.$modal.msgSuccess("操作成功");
processOpen.value = false;
getList();
});
}
/** 批量处理 */
function handleBatchProcess(status) {
const alarmIds = ids.value;
const statusText = status === '1' ? '处理' : '忽略';
proxy.$modal.confirm('是否确认批量' + statusText + '选中的报警记录?').then(function() {
return batchHandleAlarm({
alarmIds: alarmIds,
handleStatus: status,
handleRemark: '批量' + statusText
});
}).then(() => {
getList();
proxy.$modal.msgSuccess("操作成功");
}).catch(() => {});
}
/** 查看详情 */
function handleView(row) {
viewForm.value = { ...row };
viewOpen.value = true;
}
/** 导出按钮操作 */
function handleExport() {
proxy.download('video/alarm/export', {
...queryParams.value
}, `alarm_${new Date().getTime()}.xlsx`)
}
onMounted(() => {
getList();
});
</script>

View File

@@ -0,0 +1,365 @@
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="任务名称" prop="taskName">
<el-input
v-model="queryParams.taskName"
placeholder="请输入任务名称"
clearable
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="设备名称" prop="deviceName">
<el-input
v-model="queryParams.deviceName"
placeholder="请输入设备名称"
clearable
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="任务状态" prop="status">
<el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
<el-option label="启用" value="0" />
<el-option label="停用" value="1" />
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="Plus"
@click="handleAdd"
v-hasPermi="['video:inspection:add']"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="Edit"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['video:inspection:edit']"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="Delete"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['video:inspection:remove']"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="Download"
@click="handleExport"
v-hasPermi="['video:inspection:export']"
>导出</el-button>
</el-col>
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="任务ID" align="center" prop="taskId" />
<el-table-column label="任务名称" align="center" prop="taskName" />
<el-table-column label="设备名称" align="center" prop="deviceName" />
<el-table-column label="Cron表达式" align="center" prop="cronExpression" />
<el-table-column label="巡检时长(秒)" align="center" prop="duration" />
<el-table-column label="任务状态" align="center" prop="status">
<template #default="scope">
<dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
</template>
</el-table-column>
<el-table-column label="启用检测" align="center" prop="enableDetection">
<template #default="scope">
<dict-tag :options="sys_normal_disable" :value="scope.row.enableDetection"/>
</template>
</el-table-column>
<el-table-column label="检测阈值" align="center" prop="threshold" />
<el-table-column label="执行次数" align="center" prop="executeCount" />
<el-table-column label="报警次数" align="center" prop="alarmCount" />
<el-table-column label="最后执行时间" align="center" prop="lastExecuteTime" width="180">
<template #default="scope">
<span>{{ parseTime(scope.row.lastExecuteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template #default="scope">
<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['video:inspection:edit']">修改</el-button>
<el-button link type="primary" icon="VideoPlay" @click="handleStart(scope.row)" v-hasPermi="['video:inspection:start']" v-if="scope.row.status === '1'">启动</el-button>
<el-button link type="warning" icon="VideoPause" @click="handleStop(scope.row)" v-hasPermi="['video:inspection:stop']" v-if="scope.row.status === '0'">停止</el-button>
<el-button link type="success" icon="CaretRight" @click="handleExecute(scope.row)" v-hasPermi="['video:inspection:execute']">执行</el-button>
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['video:inspection:remove']">删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
v-model:page="queryParams.pageNum"
v-model:limit="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改巡检任务对话框 -->
<el-dialog :title="title" v-model="open" width="500px" append-to-body>
<el-form ref="inspectionRef" :model="form" :rules="rules" label-width="80px">
<el-form-item label="任务名称" prop="taskName">
<el-input v-model="form.taskName" placeholder="请输入任务名称" />
</el-form-item>
<el-form-item label="设备" prop="deviceId">
<el-select v-model="form.deviceId" placeholder="请选择设备" style="width: 100%">
<el-option
v-for="device in deviceList"
:key="device.deviceId"
:label="device.ip"
:value="device.deviceId"
/>
</el-select>
</el-form-item>
<el-form-item label="Cron表达式" prop="cronExpression">
<el-input v-model="form.cronExpression" placeholder="请输入Cron表达式" />
<div class="el-form-item__tip">
例如0 0 8 * * ? 表示每天8点执行<br/>
0 0/30 * * * ? 表示每30分钟执行一次
</div>
</el-form-item>
<el-form-item label="巡检时长" prop="duration">
<el-input-number v-model="form.duration" :min="10" :max="3600" placeholder="巡检时长(秒)" />
</el-form-item>
<el-form-item label="任务状态" prop="status">
<el-radio-group v-model="form.status">
<el-radio label="0">启用</el-radio>
<el-radio label="1">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="启用检测" prop="enableDetection">
<el-radio-group v-model="form.enableDetection">
<el-radio label="0">启用</el-radio>
<el-radio label="1">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="检测阈值" prop="threshold">
<el-input-number v-model="form.threshold" :min="0.1" :max="1.0" :step="0.1" placeholder="检测阈值" />
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="Inspection">
import { listInspection, getInspection, delInspection, addInspection, updateInspection, startTask, stopTask, executeTask } from "@/api/video/inspection";
import { listDevice } from "@/api/video/device";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');
const inspectionList = ref([]);
const deviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const data = reactive({
form: {},
queryParams: {
pageNum: 1,
pageSize: 10,
taskName: null,
deviceName: null,
status: null
},
rules: {
taskName: [
{ required: true, message: "任务名称不能为空", trigger: "blur" }
],
deviceId: [
{ required: true, message: "设备不能为空", trigger: "change" }
],
cronExpression: [
{ required: true, message: "Cron表达式不能为空", trigger: "blur" }
],
duration: [
{ required: true, message: "巡检时长不能为空", trigger: "blur" }
],
threshold: [
{ required: true, message: "检测阈值不能为空", trigger: "blur" }
]
}
});
const { queryParams, form, rules } = toRefs(data);
/** 查询巡检任务列表 */
function getList() {
loading.value = true;
listInspection(queryParams.value).then(response => {
inspectionList.value = response.rows;
total.value = response.total;
loading.value = false;
});
}
/** 查询设备列表 */
function getDeviceList() {
listDevice({}).then(response => {
deviceList.value = response.rows;
});
}
// 取消按钮
function cancel() {
open.value = false;
reset();
}
// 表单重置
function reset() {
form.value = {
taskId: null,
taskName: null,
deviceId: null,
cronExpression: null,
duration: 300,
status: "0",
enableDetection: "0",
threshold: 0.7
};
proxy.resetForm("inspectionRef");
}
/** 搜索按钮操作 */
function handleQuery() {
queryParams.value.pageNum = 1;
getList();
}
/** 重置按钮操作 */
function resetQuery() {
proxy.resetForm("queryRef");
handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
ids.value = selection.map(item => item.taskId);
single.value = selection.length != 1;
multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
reset();
open.value = true;
title.value = "添加巡检任务";
}
/** 修改按钮操作 */
function handleUpdate(row) {
reset();
const taskId = row.taskId || ids.value;
getInspection(taskId).then(response => {
form.value = response.data;
open.value = true;
title.value = "修改巡检任务";
});
}
/** 提交按钮 */
function submitForm() {
proxy.$refs["inspectionRef"].validate(valid => {
if (valid) {
if (form.value.taskId != null) {
updateInspection(form.value).then(response => {
proxy.$modal.msgSuccess("修改成功");
open.value = false;
getList();
});
} else {
addInspection(form.value).then(response => {
proxy.$modal.msgSuccess("新增成功");
open.value = false;
getList();
});
}
}
});
}
/** 删除按钮操作 */
function handleDelete(row) {
const taskIds = row.taskId || ids.value;
proxy.$modal.confirm('是否确认删除巡检任务编号为"' + taskIds + '"的数据项?').then(function() {
return delInspection(taskIds);
}).then(() => {
getList();
proxy.$modal.msgSuccess("删除成功");
}).catch(() => {});
}
/** 启动任务 */
function handleStart(row) {
proxy.$modal.confirm('是否确认启动任务"' + row.taskName + '"').then(function() {
return startTask(row.taskId);
}).then(() => {
getList();
proxy.$modal.msgSuccess("启动成功");
}).catch(() => {});
}
/** 停止任务 */
function handleStop(row) {
proxy.$modal.confirm('是否确认停止任务"' + row.taskName + '"').then(function() {
return stopTask(row.taskId);
}).then(() => {
getList();
proxy.$modal.msgSuccess("停止成功");
}).catch(() => {});
}
/** 执行任务 */
function handleExecute(row) {
proxy.$modal.confirm('是否确认立即执行任务"' + row.taskName + '"').then(function() {
return executeTask(row.taskId);
}).then(() => {
proxy.$modal.msgSuccess("任务已提交执行");
}).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
proxy.download('video/inspection/export', {
...queryParams.value
}, `inspection_${new Date().getTime()}.xlsx`)
}
onMounted(() => {
getList();
getDeviceList();
});
</script>

View File

@@ -58,6 +58,15 @@
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-video</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.9</version> <!-- 版本号需与项目兼容 -->
</dependency>
</dependencies>

View File

@@ -163,7 +163,7 @@ public class Constants
/**
* 定时任务白名单配置(仅允许访问的包名,如其他需要可以自行添加)
*/
public static final String[] JOB_WHITELIST_STR = { "com.ruoyi.quartz.task" };
public static final String[] JOB_WHITELIST_STR = { "com.ruoyi.quartz.task" ,"com.ruoyi.video"};
/**
* 定时任务违规的字符

View File

@@ -18,6 +18,11 @@
</properties>
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.9</version> <!-- 版本号需与项目兼容 -->
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
@@ -109,6 +114,12 @@
<artifactId>ffmpeg-platform</artifactId>
<version>6.1.1-1.5.10</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,90 @@
package com.ruoyi.video.controller;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.video.domain.AlarmRecord;
import com.ruoyi.video.service.InspectionTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 报警记录Controller
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
@RestController
@RequestMapping("/video/alarm")
public class AlarmRecordController extends BaseController {
@Autowired
private InspectionTaskService inspectionTaskService;
/**
* 查询报警记录列表
*/
@PreAuthorize("@ss.hasPermi('video:alarm:list')")
@GetMapping("/list")
public TableDataInfo list(AlarmRecord alarmRecord) {
startPage();
List<AlarmRecord> list = inspectionTaskService.selectAlarmRecordList(alarmRecord);
return getDataTable(list);
}
/**
* 导出报警记录列表
*/
@PreAuthorize("@ss.hasPermi('video:alarm:export')")
@Log(title = "报警记录", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, AlarmRecord alarmRecord) {
List<AlarmRecord> list = inspectionTaskService.selectAlarmRecordList(alarmRecord);
ExcelUtil<AlarmRecord> util = new ExcelUtil<AlarmRecord>(AlarmRecord.class);
util.exportExcel(response, list, "报警记录数据");
}
/**
* 处理报警记录
*/
@PreAuthorize("@ss.hasPermi('video:alarm:handle')")
@Log(title = "处理报警记录", businessType = BusinessType.UPDATE)
@PostMapping("/handle")
public AjaxResult handle(@RequestParam Long alarmId,
@RequestParam String handleStatus,
@RequestParam(required = false) String handleRemark) {
String handleBy = SecurityUtils.getUsername();
int result = inspectionTaskService.handleAlarmRecord(alarmId, handleStatus, handleRemark, handleBy);
return toAjax(result);
}
/**
* 批量处理报警记录
*/
@PreAuthorize("@ss.hasPermi('video:alarm:handle')")
@Log(title = "批量处理报警记录", businessType = BusinessType.UPDATE)
@PostMapping("/batchHandle")
public AjaxResult batchHandle(@RequestParam Long[] alarmIds,
@RequestParam String handleStatus,
@RequestParam(required = false) String handleRemark) {
String handleBy = SecurityUtils.getUsername();
int successCount = 0;
for (Long alarmId : alarmIds) {
int result = inspectionTaskService.handleAlarmRecord(alarmId, handleStatus, handleRemark, handleBy);
if (result > 0) {
successCount++;
}
}
return success("成功处理 " + successCount + " 条记录");
}
}

View File

@@ -0,0 +1,126 @@
package com.ruoyi.video.controller;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.video.domain.InspectionTask;
import com.ruoyi.video.service.InspectionTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 巡检任务Controller
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
@RestController
@RequestMapping("/video/inspection")
public class InspectionTaskController extends BaseController {
@Autowired
private InspectionTaskService inspectionTaskService;
/**
* 查询巡检任务列表
*/
@PreAuthorize("@ss.hasPermi('video:inspection:list')")
@GetMapping("/list")
public TableDataInfo list(InspectionTask inspectionTask) {
startPage();
List<InspectionTask> list = inspectionTaskService.selectInspectionTaskList(inspectionTask);
return getDataTable(list);
}
/**
* 导出巡检任务列表
*/
@PreAuthorize("@ss.hasPermi('video:inspection:export')")
@Log(title = "巡检任务", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, InspectionTask inspectionTask) {
List<InspectionTask> list = inspectionTaskService.selectInspectionTaskList(inspectionTask);
ExcelUtil<InspectionTask> util = new ExcelUtil<InspectionTask>(InspectionTask.class);
util.exportExcel(response, list, "巡检任务数据");
}
/**
* 获取巡检任务详细信息
*/
@PreAuthorize("@ss.hasPermi('video:inspection:query')")
@GetMapping(value = "/{taskId}")
public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
return success(inspectionTaskService.selectInspectionTaskById(taskId));
}
/**
* 新增巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:add')")
@Log(title = "巡检任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody InspectionTask inspectionTask) {
return toAjax(inspectionTaskService.insertInspectionTask(inspectionTask));
}
/**
* 修改巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:edit')")
@Log(title = "巡检任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody InspectionTask inspectionTask) {
return toAjax(inspectionTaskService.updateInspectionTask(inspectionTask));
}
/**
* 删除巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:remove')")
@Log(title = "巡检任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{taskIds}")
public AjaxResult remove(@PathVariable Long[] taskIds) {
return toAjax(inspectionTaskService.deleteInspectionTaskByIds(taskIds));
}
/**
* 启动巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:start')")
@Log(title = "启动巡检任务", businessType = BusinessType.UPDATE)
@PostMapping("/start/{taskId}")
public AjaxResult start(@PathVariable Long taskId) {
boolean result = inspectionTaskService.startInspectionTask(taskId);
return result ? success("启动成功") : error("启动失败");
}
/**
* 停止巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:stop')")
@Log(title = "停止巡检任务", businessType = BusinessType.UPDATE)
@PostMapping("/stop/{taskId}")
public AjaxResult stop(@PathVariable Long taskId) {
boolean result = inspectionTaskService.stopInspectionTask(taskId);
return result ? success("停止成功") : error("停止失败");
}
/**
* 手动执行巡检任务
*/
@PreAuthorize("@ss.hasPermi('video:inspection:execute')")
@Log(title = "执行巡检任务", businessType = BusinessType.UPDATE)
@PostMapping("/execute/{taskId}")
public AjaxResult execute(@PathVariable Long taskId) {
inspectionTaskService.executeInspectionTask(taskId);
return success("任务已提交执行");
}
}

View File

@@ -0,0 +1,234 @@
package com.ruoyi.video.domain;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* 报警记录对象 v_alarm_record
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
public class AlarmRecord extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 报警记录ID */
private Long alarmId;
/** 巡检任务ID */
@Excel(name = "巡检任务ID")
private Long taskId;
/** 任务名称 */
@Excel(name = "任务名称")
private String taskName;
/** 设备ID */
@Excel(name = "设备ID")
private Long deviceId;
/** 设备名称 */
@Excel(name = "设备名称")
private String deviceName;
/** 报警类型 */
@Excel(name = "报警类型")
private String alarmType;
/** 报警级别(1=低,2=中,3=高) */
@Excel(name = "报警级别", readConverterExp = "1=低,2=中,3=高")
private String alarmLevel;
/** 报警描述 */
@Excel(name = "报警描述")
private String alarmDesc;
/** 检测置信度 */
@Excel(name = "检测置信度")
private Double confidence;
/** 报警图片路径 */
@Excel(name = "报警图片")
private String imagePath;
/** 报警视频路径 */
@Excel(name = "报警视频")
private String videoPath;
/** 报警时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "报警时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date alarmTime;
/** 处理状态(0=未处理,1=已处理,2=已忽略) */
@Excel(name = "处理状态", readConverterExp = "0=未处理,1=已处理,2=已忽略")
private String handleStatus;
/** 处理人 */
@Excel(name = "处理人")
private String handleBy;
/** 处理时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "处理时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date handleTime;
/** 处理备注 */
@Excel(name = "处理备注")
private String handleRemark;
public AlarmRecord() {}
public Long getAlarmId() {
return alarmId;
}
public void setAlarmId(Long alarmId) {
this.alarmId = alarmId;
}
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getAlarmType() {
return alarmType;
}
public void setAlarmType(String alarmType) {
this.alarmType = alarmType;
}
public String getAlarmLevel() {
return alarmLevel;
}
public void setAlarmLevel(String alarmLevel) {
this.alarmLevel = alarmLevel;
}
public String getAlarmDesc() {
return alarmDesc;
}
public void setAlarmDesc(String alarmDesc) {
this.alarmDesc = alarmDesc;
}
public Double getConfidence() {
return confidence;
}
public void setConfidence(Double confidence) {
this.confidence = confidence;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getVideoPath() {
return videoPath;
}
public void setVideoPath(String videoPath) {
this.videoPath = videoPath;
}
public Date getAlarmTime() {
return alarmTime;
}
public void setAlarmTime(Date alarmTime) {
this.alarmTime = alarmTime;
}
public String getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(String handleStatus) {
this.handleStatus = handleStatus;
}
public String getHandleBy() {
return handleBy;
}
public void setHandleBy(String handleBy) {
this.handleBy = handleBy;
}
public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public String getHandleRemark() {
return handleRemark;
}
public void setHandleRemark(String handleRemark) {
this.handleRemark = handleRemark;
}
@Override
public String toString() {
return "AlarmRecord{" +
"alarmId=" + alarmId +
", taskId=" + taskId +
", taskName='" + taskName + '\'' +
", deviceId=" + deviceId +
", deviceName='" + deviceName + '\'' +
", alarmType='" + alarmType + '\'' +
", alarmLevel='" + alarmLevel + '\'' +
", alarmDesc='" + alarmDesc + '\'' +
", confidence=" + confidence +
", imagePath='" + imagePath + '\'' +
", videoPath='" + videoPath + '\'' +
", alarmTime=" + alarmTime +
", handleStatus='" + handleStatus + '\'' +
", handleBy='" + handleBy + '\'' +
", handleTime=" + handleTime +
", handleRemark='" + handleRemark + '\'' +
'}';
}
}

View File

@@ -0,0 +1,195 @@
package com.ruoyi.video.domain;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* 巡检任务对象 v_inspection_task
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
public class InspectionTask extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 巡检任务ID */
private Long taskId;
/** 任务名称 */
@Excel(name = "任务名称")
private String taskName;
/** 设备ID */
@Excel(name = "设备ID")
private Long deviceId;
/** 设备名称 */
@Excel(name = "设备名称")
private String deviceName;
/** Cron表达式 */
@Excel(name = "Cron表达式")
private String cronExpression;
/** 巡检时长(秒) */
@Excel(name = "巡检时长")
private Integer duration;
/** 任务状态(0=启用,1=停用) */
@Excel(name = "任务状态", readConverterExp = "0=启用,1=停用")
private String status;
/** 是否启用检测(0=启用,1=停用) */
@Excel(name = "启用检测", readConverterExp = "0=启用,1=停用")
private String enableDetection;
/** 检测阈值 */
@Excel(name = "检测阈值")
private Double threshold;
/** 最后执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "最后执行时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date lastExecuteTime;
/** 下次执行时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "下次执行时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date nextExecuteTime;
/** 执行次数 */
@Excel(name = "执行次数")
private Long executeCount;
/** 报警次数 */
@Excel(name = "报警次数")
private Long alarmCount;
public InspectionTask() {}
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEnableDetection() {
return enableDetection;
}
public void setEnableDetection(String enableDetection) {
this.enableDetection = enableDetection;
}
public Double getThreshold() {
return threshold;
}
public void setThreshold(Double threshold) {
this.threshold = threshold;
}
public Date getLastExecuteTime() {
return lastExecuteTime;
}
public void setLastExecuteTime(Date lastExecuteTime) {
this.lastExecuteTime = lastExecuteTime;
}
public Date getNextExecuteTime() {
return nextExecuteTime;
}
public void setNextExecuteTime(Date nextExecuteTime) {
this.nextExecuteTime = nextExecuteTime;
}
public Long getExecuteCount() {
return executeCount;
}
public void setExecuteCount(Long executeCount) {
this.executeCount = executeCount;
}
public Long getAlarmCount() {
return alarmCount;
}
public void setAlarmCount(Long alarmCount) {
this.alarmCount = alarmCount;
}
@Override
public String toString() {
return "InspectionTask{" +
"taskId=" + taskId +
", taskName='" + taskName + '\'' +
", deviceId=" + deviceId +
", deviceName='" + deviceName + '\'' +
", cronExpression='" + cronExpression + '\'' +
", duration=" + duration +
", status='" + status + '\'' +
", enableDetection='" + enableDetection + '\'' +
", threshold=" + threshold +
", lastExecuteTime=" + lastExecuteTime +
", nextExecuteTime=" + nextExecuteTime +
", executeCount=" + executeCount +
", alarmCount=" + alarmCount +
'}';
}
}

View File

@@ -0,0 +1,87 @@
package com.ruoyi.video.mapper;
import com.ruoyi.video.domain.AlarmRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 报警记录Mapper接口
*
* @author ruoyi
* @date 2025-01-16
*/
@Mapper
public interface AlarmRecordMapper {
/**
* 查询报警记录
*
* @param alarmId 报警记录主键
* @return 报警记录
*/
public AlarmRecord selectAlarmRecordByAlarmId(Long alarmId);
/**
* 查询报警记录列表
*
* @param alarmRecord 报警记录
* @return 报警记录集合
*/
public List<AlarmRecord> selectAlarmRecordList(AlarmRecord alarmRecord);
/**
* 新增报警记录
*
* @param alarmRecord 报警记录
* @return 结果
*/
public int insertAlarmRecord(AlarmRecord alarmRecord);
/**
* 修改报警记录
*
* @param alarmRecord 报警记录
* @return 结果
*/
public int updateAlarmRecord(AlarmRecord alarmRecord);
/**
* 删除报警记录
*
* @param alarmId 报警记录主键
* @return 结果
*/
public int deleteAlarmRecordByAlarmId(Long alarmId);
/**
* 批量删除报警记录
*
* @param alarmIds 需要删除的数据主键集合
* @return 结果
*/
public int deleteAlarmRecordByAlarmIds(Long[] alarmIds);
/**
* 处理报警记录
*
* @param alarmId 报警ID
* @param handleStatus 处理状态
* @param handleRemark 处理备注
* @param handleBy 处理人
* @return 结果
*/
public int handleAlarmRecord(@Param("alarmId") Long alarmId,
@Param("handleStatus") String handleStatus,
@Param("handleRemark") String handleRemark,
@Param("handleBy") String handleBy);
/**
* 根据任务ID统计报警数量
*
* @param taskId 任务ID
* @return 报警数量
*/
public Long countAlarmByTaskId(@Param("taskId") Long taskId);
}

View File

@@ -0,0 +1,84 @@
package com.ruoyi.video.mapper;
import com.ruoyi.video.domain.InspectionTask;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 巡检任务Mapper接口
*
* @author ruoyi
* @date 2025-01-16
*/
@Mapper
public interface InspectionTaskMapper {
/**
* 查询巡检任务
*
* @param taskId 巡检任务主键
* @return 巡检任务
*/
public InspectionTask selectInspectionTaskByTaskId(Long taskId);
/**
* 查询巡检任务列表
*
* @param inspectionTask 巡检任务
* @return 巡检任务集合
*/
public List<InspectionTask> selectInspectionTaskList(InspectionTask inspectionTask);
/**
* 新增巡检任务
*
* @param inspectionTask 巡检任务
* @return 结果
*/
public int insertInspectionTask(InspectionTask inspectionTask);
/**
* 修改巡检任务
*
* @param inspectionTask 巡检任务
* @return 结果
*/
public int updateInspectionTask(InspectionTask inspectionTask);
/**
* 删除巡检任务
*
* @param taskId 巡检任务主键
* @return 结果
*/
public int deleteInspectionTaskByTaskId(Long taskId);
/**
* 批量删除巡检任务
*
* @param taskIds 需要删除的数据主键集合
* @return 结果
*/
public int deleteInspectionTaskByTaskIds(Long[] taskIds);
/**
* 查询启用状态的巡检任务列表
*
* @return 巡检任务集合
*/
public List<InspectionTask> selectEnabledInspectionTaskList();
/**
* 更新任务执行信息
*
* @param taskId 任务ID
* @param executeCount 执行次数
* @param alarmCount 报警次数
* @return 结果
*/
public int updateTaskExecuteInfo(@Param("taskId") Long taskId,
@Param("executeCount") Long executeCount,
@Param("alarmCount") Long alarmCount);
}

View File

@@ -0,0 +1,78 @@
package com.ruoyi.video.service;
import com.ruoyi.video.domain.InspectionTask;
import com.ruoyi.video.domain.AlarmRecord;
import com.ruoyi.video.domain.Detection;
import org.springframework.scheduling.annotation.Async;
import java.util.List;
/**
* 巡检任务服务接口
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
public interface InspectionTaskService {
/**
* 查询巡检任务列表
*/
List<InspectionTask> selectInspectionTaskList(InspectionTask inspectionTask);
/**
* 根据ID查询巡检任务
*/
InspectionTask selectInspectionTaskById(Long taskId);
/**
* 新增巡检任务
*/
int insertInspectionTask(InspectionTask inspectionTask);
/**
* 修改巡检任务
*/
int updateInspectionTask(InspectionTask inspectionTask);
/**
* 删除巡检任务
*/
int deleteInspectionTaskByIds(Long[] taskIds);
/**
* 启动巡检任务
*/
boolean startInspectionTask(Long taskId);
/**
* 停止巡检任务
*/
boolean stopInspectionTask(Long taskId);
/**
* 执行单次巡检任务
*/
@Async
void executeInspectionTask(Long taskId);
/**
* 处理检测结果,如果有异常则生成报警
*/
void handleDetectionResults(Long taskId, List<Detection> detections, String imagePath);
/**
* 保存报警记录
*/
void saveAlarmRecord(AlarmRecord alarmRecord);
/**
* 查询报警记录列表
*/
List<AlarmRecord> selectAlarmRecordList(AlarmRecord alarmRecord);
/**
* 处理报警记录
*/
int handleAlarmRecord(Long alarmId, String handleStatus, String handleRemark, String handleBy);
}

View File

@@ -0,0 +1,361 @@
package com.ruoyi.video.service.impl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.video.domain.*;
import com.ruoyi.video.domain.dto.CameraDto;
import com.ruoyi.video.mapper.InspectionTaskMapper;
import com.ruoyi.video.mapper.AlarmRecordMapper;
import com.ruoyi.video.service.IDeviceService;
import com.ruoyi.video.service.InspectionTaskService;
import com.ruoyi.video.thread.MediaTransferFlvByJavacv;
import com.ruoyi.video.common.ModelManager;
import com.ruoyi.video.thread.detector.YoloDetector;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.Mat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 巡检任务服务实现
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
@Slf4j
@Service
public class InspectionTaskServiceImpl implements InspectionTaskService {
@Autowired
private IDeviceService deviceService;
@Autowired
private InspectionTaskMapper inspectionTaskMapper;
@Autowired
private AlarmRecordMapper alarmRecordMapper;
// 运行状态缓存(避免重复执行)
private final Map<Long, Boolean> runningTasks = new ConcurrentHashMap<>();
private ModelManager modelManager;
// 延迟初始化,避免启动时的依赖问题
private OpenCVFrameConverter.ToMat toMat;
@Override
public List<InspectionTask> selectInspectionTaskList(InspectionTask inspectionTask) {
return inspectionTaskMapper.selectInspectionTaskList(inspectionTask);
}
@Override
public InspectionTask selectInspectionTaskById(Long taskId) {
return inspectionTaskMapper.selectInspectionTaskByTaskId(taskId);
}
@Override
public int insertInspectionTask(InspectionTask inspectionTask) {
inspectionTask.setCreateTime(DateUtils.getNowDate());
inspectionTask.setCreateBy(SecurityUtils.getUsername());
inspectionTask.setExecuteCount(0L);
inspectionTask.setAlarmCount(0L);
// 获取设备信息
Device device = deviceService.selectDeviceByDeviceId(inspectionTask.getDeviceId());
if (device != null) {
inspectionTask.setDeviceName(device.getIp());
}
return inspectionTaskMapper.insertInspectionTask(inspectionTask);
}
@Override
public int updateInspectionTask(InspectionTask inspectionTask) {
inspectionTask.setUpdateTime(DateUtils.getNowDate());
inspectionTask.setUpdateBy(SecurityUtils.getUsername());
return inspectionTaskMapper.updateInspectionTask(inspectionTask);
}
@Override
public int deleteInspectionTaskByIds(Long[] taskIds) {
for (Long taskId : taskIds) {
stopInspectionTask(taskId);
}
return inspectionTaskMapper.deleteInspectionTaskByTaskIds(taskIds);
}
@Override
public boolean startInspectionTask(Long taskId) {
InspectionTask task = inspectionTaskMapper.selectInspectionTaskByTaskId(taskId);
if (task == null) {
return false;
}
task.setStatus("0"); // 启用
task.setUpdateTime(DateUtils.getNowDate());
task.setUpdateBy(SecurityUtils.getUsername());
inspectionTaskMapper.updateInspectionTask(task);
runningTasks.put(taskId, true);
// 这里应该集成到Quartz定时任务中
log.info("启动巡检任务: {} - {}", taskId, task.getTaskName());
return true;
}
@Override
public boolean stopInspectionTask(Long taskId) {
InspectionTask task = inspectionTaskMapper.selectInspectionTaskByTaskId(taskId);
if (task == null) {
return false;
}
task.setStatus("1"); // 停用
task.setUpdateTime(DateUtils.getNowDate());
task.setUpdateBy(SecurityUtils.getUsername());
inspectionTaskMapper.updateInspectionTask(task);
runningTasks.remove(taskId);
log.info("停止巡检任务: {} - {}", taskId, task.getTaskName());
return true;
}
@Override
@Async
public void executeInspectionTask(Long taskId) {
InspectionTask task = inspectionTaskMapper.selectInspectionTaskByTaskId(taskId);
if (task == null || !"0".equals(task.getStatus())) {
return;
}
log.info("开始执行巡检任务: {} - {}", taskId, task.getTaskName());
try {
// 更新执行信息
task.setLastExecuteTime(new Date());
task.setExecuteCount(task.getExecuteCount() + 1);
// 获取设备信息
Device device = deviceService.selectDeviceByDeviceId(task.getDeviceId());
if (device == null) {
log.error("设备不存在: {}", task.getDeviceId());
return;
}
// 执行视频分析
performVideoAnalysis(task, device);
// 更新任务执行统计信息
Long alarmCount = alarmRecordMapper.countAlarmByTaskId(taskId);
inspectionTaskMapper.updateTaskExecuteInfo(taskId, task.getExecuteCount(), alarmCount);
} catch (Exception e) {
log.error("执行巡检任务失败: {} - {}", taskId, e.getMessage(), e);
}
}
/**
* 执行视频分析
*/
private void performVideoAnalysis(InspectionTask task, Device device) {
if (!"0".equals(task.getEnableDetection())) {
log.info("巡检任务未启用检测: {}", task.getTaskId());
return;
}
FFmpegFrameGrabber grabber = null;
try {
// 初始化模型管理器
if (modelManager == null) {
modelManager = new ModelManager();
URL json = getClass().getResource("/models/models.json");
if (json != null) {
modelManager.load(json);
}
}
// 创建视频抓取器
grabber = new FFmpegFrameGrabber(device.getUrl());
grabber.setOption("rtsp_transport", "tcp");
grabber.setOption("stimeout", "5000000");
grabber.start();
log.info("开始分析视频流: {}", device.getUrl());
// 分析指定时长的视频
long startTime = System.currentTimeMillis();
long duration = task.getDuration() * 1000L; // 转换为毫秒
int frameCount = 0;
List<Detection> allDetections = new ArrayList<>();
while (System.currentTimeMillis() - startTime < duration) {
Frame frame = grabber.grabImage();
if (frame == null) continue;
frameCount++;
// 每隔一定帧数进行一次检测(避免过于频繁)
if (frameCount % 25 == 0) { // 假设25fps每秒检测一次
try {
// 延迟初始化转换器
if (toMat == null) {
toMat = new OpenCVFrameConverter.ToMat();
}
Mat mat = toMat.convert(frame);
if (mat != null && !mat.empty()) {
List<Detection> detections = performDetection(mat);
allDetections.addAll(detections);
// 如果检测到异常,立即保存图片并记录报警
if (!detections.isEmpty()) {
String imagePath = saveFrameAsImage(frame, task.getTaskId());
handleDetectionResults(task.getTaskId(), detections, imagePath);
}
}
} catch (Exception e) {
log.error("帧处理失败: {}", e.getMessage());
// 如果JavaCV有问题跳过这一帧继续处理
continue;
}
}
}
log.info("巡检任务完成: {} - 分析帧数: {}, 检测结果: {}",
task.getTaskId(), frameCount, allDetections.size());
} catch (Exception e) {
log.error("视频分析失败: {}", e.getMessage(), e);
} finally {
if (grabber != null) {
try {
grabber.stop();
grabber.release();
} catch (Exception e) {
log.error("关闭视频抓取器失败", e);
}
}
}
}
/**
* 执行目标检测
*/
private List<Detection> performDetection(Mat mat) {
try {
if (modelManager != null) {
YoloDetector detector = modelManager.get("person-helmet"); // 使用人员安全帽检测
if (detector != null) {
return detector.detect(mat);
}
}
} catch (Exception e) {
log.error("目标检测失败: {}", e.getMessage(), e);
}
return Collections.emptyList();
}
/**
* 保存帧为图片
*/
private String saveFrameAsImage(Frame frame, Long taskId) {
try {
// 创建保存目录
String saveDir = "upload/alarm/" + DateUtils.dateTimeNow("yyyyMMdd");
File dir = new File(saveDir);
if (!dir.exists()) {
dir.mkdirs();
}
// 生成文件名
String fileName = "task_" + taskId + "_" + System.currentTimeMillis() + ".jpg";
String filePath = saveDir + "/" + fileName;
// 转换并保存图片
BufferedImage bufferedImage = new org.bytedeco.javacv.Java2DFrameConverter().convert(frame);
ImageIO.write(bufferedImage, "jpg", new File(filePath));
return filePath;
} catch (IOException e) {
log.error("保存图片失败: {}", e.getMessage(), e);
return null;
}
}
@Override
public void handleDetectionResults(Long taskId, List<Detection> detections, String imagePath) {
InspectionTask task = inspectionTaskMapper.selectInspectionTaskByTaskId(taskId);
if (task == null || detections.isEmpty()) {
return;
}
for (Detection detection : detections) {
// 检查置信度是否超过阈值
if (detection.conf() >= task.getThreshold()) {
// 创建报警记录
AlarmRecord alarmRecord = new AlarmRecord();
alarmRecord.setTaskId(taskId);
alarmRecord.setTaskName(task.getTaskName());
alarmRecord.setDeviceId(task.getDeviceId());
alarmRecord.setDeviceName(task.getDeviceName());
alarmRecord.setAlarmType(detection.cls());
alarmRecord.setAlarmLevel(getAlarmLevel(detection.conf()));
alarmRecord.setAlarmDesc(String.format("检测到%s置信度: %.2f",
detection.cls(), detection.conf()));
alarmRecord.setConfidence((double)detection.conf());
alarmRecord.setImagePath(imagePath);
alarmRecord.setAlarmTime(new Date());
alarmRecord.setHandleStatus("0"); // 未处理
alarmRecord.setCreateBy(SecurityUtils.getUsername());
saveAlarmRecord(alarmRecord);
log.warn("生成报警记录: 任务[{}] 检测到[{}] 置信度[{}]",
taskId, detection.cls(), detection.conf());
}
}
}
/**
* 根据置信度确定报警级别
*/
private String getAlarmLevel(float confidence) {
if (confidence >= 0.9f) {
return "3"; // 高
} else if (confidence >= 0.7f) {
return "2"; // 中
} else {
return "1"; // 低
}
}
@Override
public void saveAlarmRecord(AlarmRecord alarmRecord) {
alarmRecord.setCreateTime(DateUtils.getNowDate());
alarmRecordMapper.insertAlarmRecord(alarmRecord);
log.info("保存报警记录: {}", alarmRecord.getAlarmId());
}
@Override
public List<AlarmRecord> selectAlarmRecordList(AlarmRecord alarmRecord) {
return alarmRecordMapper.selectAlarmRecordList(alarmRecord);
}
@Override
public int handleAlarmRecord(Long alarmId, String handleStatus, String handleRemark, String handleBy) {
return alarmRecordMapper.handleAlarmRecord(alarmId, handleStatus, handleRemark, handleBy);
}
}

View File

@@ -0,0 +1,85 @@
package com.ruoyi.video.task;
import com.ruoyi.video.service.InspectionTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 巡检任务执行器
* 用于集成到若依的定时任务系统中
*
* @Author: orange
* @CreateTime: 2025-01-16
*/
@Slf4j
@Component("inspectionTaskExecutor")
public class InspectionTaskExecutor {
@Autowired
private InspectionTaskService inspectionTaskService;
/**
* 执行指定的巡检任务
* 在定时任务中调用格式: inspectionTaskExecutor.executeTask(1L)
*
* @param taskId 巡检任务ID
*/
public void executeTask(Long taskId) {
log.info("定时任务触发巡检任务执行: {}", taskId);
try {
inspectionTaskService.executeInspectionTask(taskId);
} catch (Exception e) {
log.error("定时任务执行巡检任务失败: {} - {}", taskId, e.getMessage(), e);
}
}
/**
* 执行指定的巡检任务(字符串参数版本)
* 在定时任务中调用格式: inspectionTaskExecutor.executeTaskByString('1')
*
* @param taskIdStr 巡检任务ID字符串
*/
public void executeTaskByString(String taskIdStr) {
try {
Long taskId = Long.parseLong(taskIdStr);
executeTask(taskId);
} catch (NumberFormatException e) {
log.error("巡检任务ID格式错误: {}", taskIdStr);
}
}
/**
* 批量执行多个巡检任务
* 在定时任务中调用格式: inspectionTaskExecutor.executeBatchTasks('1,2,3')
*
* @param taskIdsStr 巡检任务ID列表逗号分隔
*/
public void executeBatchTasks(String taskIdsStr) {
log.info("定时任务触发批量巡检任务执行: {}", taskIdsStr);
try {
String[] taskIdArray = taskIdsStr.split(",");
for (String taskIdStr : taskIdArray) {
Long taskId = Long.parseLong(taskIdStr.trim());
inspectionTaskService.executeInspectionTask(taskId);
}
} catch (Exception e) {
log.error("批量执行巡检任务失败: {} - {}", taskIdsStr, e.getMessage(), e);
}
}
/**
* 执行所有启用的巡检任务
* 在定时任务中调用格式: inspectionTaskExecutor.executeAllActiveTasks()
*/
public void executeAllActiveTasks() {
log.info("定时任务触发执行所有启用的巡检任务");
try {
// 这里可以查询所有启用状态的任务并执行
// 实际实现中需要查询数据库获取所有status='0'的任务
log.info("执行所有启用的巡检任务完成");
} catch (Exception e) {
log.error("执行所有启用的巡检任务失败: {}", e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.video.mapper.AlarmRecordMapper">
<resultMap type="AlarmRecord" id="AlarmRecordResult">
<result property="alarmId" column="alarm_id" />
<result property="taskId" column="task_id" />
<result property="taskName" column="task_name" />
<result property="deviceId" column="device_id" />
<result property="deviceName" column="device_name" />
<result property="alarmType" column="alarm_type" />
<result property="alarmLevel" column="alarm_level" />
<result property="alarmDesc" column="alarm_desc" />
<result property="confidence" column="confidence" />
<result property="imagePath" column="image_path" />
<result property="videoPath" column="video_path" />
<result property="alarmTime" column="alarm_time" />
<result property="handleStatus" column="handle_status" />
<result property="handleBy" column="handle_by" />
<result property="handleTime" column="handle_time" />
<result property="handleRemark" column="handle_remark" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectAlarmRecordVo">
select alarm_id, task_id, task_name, device_id, device_name, alarm_type,
alarm_level, alarm_desc, confidence, image_path, video_path, alarm_time,
handle_status, handle_by, handle_time, handle_remark,
create_by, create_time, update_by, update_time
from v_alarm_record
</sql>
<select id="selectAlarmRecordList" parameterType="AlarmRecord" resultMap="AlarmRecordResult">
<include refid="selectAlarmRecordVo"/>
<where>
<if test="taskId != null "> and task_id = #{taskId}</if>
<if test="taskName != null and taskName != ''"> and task_name like concat('%', #{taskName}, '%')</if>
<if test="deviceId != null "> and device_id = #{deviceId}</if>
<if test="deviceName != null and deviceName != ''"> and device_name like concat('%', #{deviceName}, '%')</if>
<if test="alarmType != null and alarmType != ''"> and alarm_type = #{alarmType}</if>
<if test="alarmLevel != null and alarmLevel != ''"> and alarm_level = #{alarmLevel}</if>
<if test="handleStatus != null and handleStatus != ''"> and handle_status = #{handleStatus}</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(alarm_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(alarm_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
</where>
order by alarm_time desc
</select>
<select id="selectAlarmRecordByAlarmId" parameterType="Long" resultMap="AlarmRecordResult">
<include refid="selectAlarmRecordVo"/>
where alarm_id = #{alarmId}
</select>
<select id="countAlarmByTaskId" parameterType="Long" resultType="Long">
select count(*) from v_alarm_record where task_id = #{taskId}
</select>
<insert id="insertAlarmRecord" parameterType="AlarmRecord" useGeneratedKeys="true" keyProperty="alarmId">
insert into v_alarm_record
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="taskId != null">task_id,</if>
<if test="taskName != null">task_name,</if>
<if test="deviceId != null">device_id,</if>
<if test="deviceName != null">device_name,</if>
<if test="alarmType != null and alarmType != ''">alarm_type,</if>
<if test="alarmLevel != null and alarmLevel != ''">alarm_level,</if>
<if test="alarmDesc != null">alarm_desc,</if>
<if test="confidence != null">confidence,</if>
<if test="imagePath != null">image_path,</if>
<if test="videoPath != null">video_path,</if>
<if test="alarmTime != null">alarm_time,</if>
<if test="handleStatus != null">handle_status,</if>
<if test="createBy != null">create_by,</if>
create_time
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="taskId != null">#{taskId},</if>
<if test="taskName != null">#{taskName},</if>
<if test="deviceId != null">#{deviceId},</if>
<if test="deviceName != null">#{deviceName},</if>
<if test="alarmType != null and alarmType != ''">#{alarmType},</if>
<if test="alarmLevel != null and alarmLevel != ''">#{alarmLevel},</if>
<if test="alarmDesc != null">#{alarmDesc},</if>
<if test="confidence != null">#{confidence},</if>
<if test="imagePath != null">#{imagePath},</if>
<if test="videoPath != null">#{videoPath},</if>
<if test="alarmTime != null">#{alarmTime},</if>
<if test="handleStatus != null">#{handleStatus},</if>
<if test="createBy != null">#{createBy},</if>
sysdate()
</trim>
</insert>
<update id="updateAlarmRecord" parameterType="AlarmRecord">
update v_alarm_record
<trim prefix="SET" suffixOverrides=",">
<if test="taskId != null">task_id = #{taskId},</if>
<if test="taskName != null">task_name = #{taskName},</if>
<if test="deviceId != null">device_id = #{deviceId},</if>
<if test="deviceName != null">device_name = #{deviceName},</if>
<if test="alarmType != null and alarmType != ''">alarm_type = #{alarmType},</if>
<if test="alarmLevel != null and alarmLevel != ''">alarm_level = #{alarmLevel},</if>
<if test="alarmDesc != null">alarm_desc = #{alarmDesc},</if>
<if test="confidence != null">confidence = #{confidence},</if>
<if test="imagePath != null">image_path = #{imagePath},</if>
<if test="videoPath != null">video_path = #{videoPath},</if>
<if test="alarmTime != null">alarm_time = #{alarmTime},</if>
<if test="handleStatus != null">handle_status = #{handleStatus},</if>
<if test="handleBy != null">handle_by = #{handleBy},</if>
<if test="handleTime != null">handle_time = #{handleTime},</if>
<if test="handleRemark != null">handle_remark = #{handleRemark},</if>
<if test="updateBy != null">update_by = #{updateBy},</if>
update_time = sysdate()
</trim>
where alarm_id = #{alarmId}
</update>
<update id="handleAlarmRecord">
update v_alarm_record
set handle_status = #{handleStatus},
handle_by = #{handleBy},
handle_time = sysdate(),
handle_remark = #{handleRemark},
update_time = sysdate()
where alarm_id = #{alarmId}
</update>
<delete id="deleteAlarmRecordByAlarmId" parameterType="Long">
delete from v_alarm_record where alarm_id = #{alarmId}
</delete>
<delete id="deleteAlarmRecordByAlarmIds" parameterType="String">
delete from v_alarm_record where alarm_id in
<foreach item="alarmId" collection="array" open="(" separator="," close=")">
#{alarmId}
</foreach>
</delete>
</mapper>

View File

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.video.mapper.InspectionTaskMapper">
<resultMap type="InspectionTask" id="InspectionTaskResult">
<result property="taskId" column="task_id" />
<result property="taskName" column="task_name" />
<result property="deviceId" column="device_id" />
<result property="deviceName" column="device_name" />
<result property="cronExpression" column="cron_expression" />
<result property="duration" column="duration" />
<result property="threshold" column="threshold" />
<result property="enableDetection" column="enable_detection" />
<result property="status" column="status" />
<result property="executeCount" column="execute_count" />
<result property="alarmCount" column="alarm_count" />
<result property="lastExecuteTime" column="last_execute_time" />
<result property="remark" column="remark" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectInspectionTaskVo">
select task_id, task_name, device_id, device_name, cron_expression, duration,
threshold, enable_detection, status, execute_count, alarm_count,
last_execute_time, remark, create_by, create_time, update_by, update_time
from v_inspection_task
</sql>
<select id="selectInspectionTaskList" parameterType="InspectionTask" resultMap="InspectionTaskResult">
<include refid="selectInspectionTaskVo"/>
<where>
<if test="taskName != null and taskName != ''"> and task_name like concat('%', #{taskName}, '%')</if>
<if test="deviceId != null "> and device_id = #{deviceId}</if>
<if test="deviceName != null and deviceName != ''"> and device_name like concat('%', #{deviceName}, '%')</if>
<if test="status != null and status != ''"> and status = #{status}</if>
<if test="enableDetection != null and enableDetection != ''"> and enable_detection = #{enableDetection}</if>
</where>
order by create_time desc
</select>
<select id="selectInspectionTaskByTaskId" parameterType="Long" resultMap="InspectionTaskResult">
<include refid="selectInspectionTaskVo"/>
where task_id = #{taskId}
</select>
<select id="selectEnabledInspectionTaskList" resultMap="InspectionTaskResult">
<include refid="selectInspectionTaskVo"/>
where status = '0'
order by create_time desc
</select>
<insert id="insertInspectionTask" parameterType="InspectionTask" useGeneratedKeys="true" keyProperty="taskId">
insert into v_inspection_task
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="taskName != null and taskName != ''">task_name,</if>
<if test="deviceId != null">device_id,</if>
<if test="deviceName != null">device_name,</if>
<if test="cronExpression != null and cronExpression != ''">cron_expression,</if>
<if test="duration != null">duration,</if>
<if test="threshold != null">threshold,</if>
<if test="enableDetection != null">enable_detection,</if>
<if test="status != null">status,</if>
<if test="executeCount != null">execute_count,</if>
<if test="alarmCount != null">alarm_count,</if>
<if test="lastExecuteTime != null">last_execute_time,</if>
<if test="remark != null">remark,</if>
<if test="createBy != null">create_by,</if>
create_time
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="taskName != null and taskName != ''">#{taskName},</if>
<if test="deviceId != null">#{deviceId},</if>
<if test="deviceName != null">#{deviceName},</if>
<if test="cronExpression != null and cronExpression != ''">#{cronExpression},</if>
<if test="duration != null">#{duration},</if>
<if test="threshold != null">#{threshold},</if>
<if test="enableDetection != null">#{enableDetection},</if>
<if test="status != null">#{status},</if>
<if test="executeCount != null">#{executeCount},</if>
<if test="alarmCount != null">#{alarmCount},</if>
<if test="lastExecuteTime != null">#{lastExecuteTime},</if>
<if test="remark != null">#{remark},</if>
<if test="createBy != null">#{createBy},</if>
sysdate()
</trim>
</insert>
<update id="updateInspectionTask" parameterType="InspectionTask">
update v_inspection_task
<trim prefix="SET" suffixOverrides=",">
<if test="taskName != null and taskName != ''">task_name = #{taskName},</if>
<if test="deviceId != null">device_id = #{deviceId},</if>
<if test="deviceName != null">device_name = #{deviceName},</if>
<if test="cronExpression != null and cronExpression != ''">cron_expression = #{cronExpression},</if>
<if test="duration != null">duration = #{duration},</if>
<if test="threshold != null">threshold = #{threshold},</if>
<if test="enableDetection != null">enable_detection = #{enableDetection},</if>
<if test="status != null">status = #{status},</if>
<if test="executeCount != null">execute_count = #{executeCount},</if>
<if test="alarmCount != null">alarm_count = #{alarmCount},</if>
<if test="lastExecuteTime != null">last_execute_time = #{lastExecuteTime},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null">update_by = #{updateBy},</if>
update_time = sysdate()
</trim>
where task_id = #{taskId}
</update>
<update id="updateTaskExecuteInfo">
update v_inspection_task
set execute_count = #{executeCount},
alarm_count = #{alarmCount},
last_execute_time = sysdate(),
update_time = sysdate()
where task_id = #{taskId}
</update>
<delete id="deleteInspectionTaskByTaskId" parameterType="Long">
delete from v_inspection_task where task_id = #{taskId}
</delete>
<delete id="deleteInspectionTaskByTaskIds" parameterType="String">
delete from v_inspection_task where task_id in
<foreach item="taskId" collection="array" open="(" separator="," close=")">
#{taskId}
</foreach>
</delete>
</mapper>

83
sql/inspection_system.sql Normal file
View File

@@ -0,0 +1,83 @@
-- 巡检任务表
CREATE TABLE `v_inspection_task` (
`task_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '巡检任务ID',
`task_name` varchar(100) NOT NULL COMMENT '任务名称',
`device_id` bigint(20) NOT NULL COMMENT '设备ID',
`device_name` varchar(100) DEFAULT NULL COMMENT '设备名称',
`cron_expression` varchar(100) NOT NULL COMMENT 'Cron表达式',
`duration` int(11) NOT NULL DEFAULT '300' COMMENT '巡检时长(秒)',
`status` char(1) NOT NULL DEFAULT '0' COMMENT '任务状态(0=启用,1=停用)',
`enable_detection` char(1) NOT NULL DEFAULT '0' COMMENT '是否启用检测(0=启用,1=停用)',
`threshold` decimal(3,2) NOT NULL DEFAULT '0.70' COMMENT '检测阈值',
`last_execute_time` datetime DEFAULT NULL COMMENT '最后执行时间',
`next_execute_time` datetime DEFAULT NULL COMMENT '下次执行时间',
`execute_count` bigint(20) DEFAULT '0' COMMENT '执行次数',
`alarm_count` bigint(20) DEFAULT '0' COMMENT '报警次数',
`create_by` varchar(64) DEFAULT '' COMMENT '创建者',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(64) DEFAULT '' COMMENT '更新者',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`task_id`),
KEY `idx_device_id` (`device_id`),
KEY `idx_status` (`status`),
KEY `idx_next_execute_time` (`next_execute_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='巡检任务表';
-- 报警记录表
CREATE TABLE `v_alarm_record` (
`alarm_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '报警记录ID',
`task_id` bigint(20) NOT NULL COMMENT '巡检任务ID',
`task_name` varchar(100) DEFAULT NULL COMMENT '任务名称',
`device_id` bigint(20) NOT NULL COMMENT '设备ID',
`device_name` varchar(100) DEFAULT NULL COMMENT '设备名称',
`alarm_type` varchar(50) NOT NULL COMMENT '报警类型',
`alarm_level` char(1) NOT NULL DEFAULT '1' COMMENT '报警级别(1=低,2=中,3=高)',
`alarm_desc` varchar(500) DEFAULT NULL COMMENT '报警描述',
`confidence` decimal(5,4) DEFAULT NULL COMMENT '检测置信度',
`image_path` varchar(500) DEFAULT NULL COMMENT '报警图片路径',
`video_path` varchar(500) DEFAULT NULL COMMENT '报警视频路径',
`alarm_time` datetime NOT NULL COMMENT '报警时间',
`handle_status` char(1) NOT NULL DEFAULT '0' COMMENT '处理状态(0=未处理,1=已处理,2=已忽略)',
`handle_by` varchar(64) DEFAULT NULL COMMENT '处理人',
`handle_time` datetime DEFAULT NULL COMMENT '处理时间',
`handle_remark` varchar(500) DEFAULT NULL COMMENT '处理备注',
`create_by` varchar(64) DEFAULT '' COMMENT '创建者',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(64) DEFAULT '' COMMENT '更新者',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`alarm_id`),
KEY `idx_task_id` (`task_id`),
KEY `idx_device_id` (`device_id`),
KEY `idx_alarm_time` (`alarm_time`),
KEY `idx_handle_status` (`handle_status`),
KEY `idx_alarm_level` (`alarm_level`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='报警记录表';
-- 插入测试数据
INSERT INTO `v_inspection_task` (`task_name`, `device_id`, `device_name`, `cron_expression`, `duration`, `status`, `enable_detection`, `threshold`, `create_time`) VALUES
('办公区域安全巡检', 1, '办公区摄像头', '0 0 8,12,18 * * ?', 600, '0', '0', 0.75, NOW()),
('停车场巡检任务', 2, '停车场摄像头', '0 0/30 * * * ?', 300, '0', '0', 0.70, NOW()),
('仓库区域夜间巡检', 3, '仓库摄像头', '0 0 22 * * ?', 1800, '1', '0', 0.80, NOW());
-- 菜单权限数据
INSERT INTO sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) VALUES
('视频巡检', 2000, 3, 'inspection', 'video/inspection/index', 1, 0, 'C', '0', '0', 'video:inspection:list', 'monitor', 'admin', NOW(), '', NULL, '视频巡检菜单'),
('报警记录', 2000, 4, 'alarm', 'video/alarm/index', 1, 0, 'C', '0', '0', 'video:alarm:list', 'bug', 'admin', NOW(), '', NULL, '报警记录菜单');
-- 巡检任务权限
INSERT INTO sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) VALUES
('巡检任务查询', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 1, '', '', 1, 0, 'F', '0', '0', 'video:inspection:query', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务新增', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 2, '', '', 1, 0, 'F', '0', '0', 'video:inspection:add', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务修改', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 3, '', '', 1, 0, 'F', '0', '0', 'video:inspection:edit', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务删除', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 4, '', '', 1, 0, 'F', '0', '0', 'video:inspection:remove', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务导出', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 5, '', '', 1, 0, 'F', '0', '0', 'video:inspection:export', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务启动', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 6, '', '', 1, 0, 'F', '0', '0', 'video:inspection:start', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务停止', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 7, '', '', 1, 0, 'F', '0', '0', 'video:inspection:stop', '#', 'admin', NOW(), '', NULL, ''),
('巡检任务执行', (SELECT menu_id FROM sys_menu WHERE perms = 'video:inspection:list'), 8, '', '', 1, 0, 'F', '0', '0', 'video:inspection:execute', '#', 'admin', NOW(), '', NULL, '');
-- 报警记录权限
INSERT INTO sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) VALUES
('报警记录查询', (SELECT menu_id FROM sys_menu WHERE perms = 'video:alarm:list'), 1, '', '', 1, 0, 'F', '0', '0', 'video:alarm:query', '#', 'admin', NOW(), '', NULL, ''),
('报警记录导出', (SELECT menu_id FROM sys_menu WHERE perms = 'video:alarm:list'), 2, '', '', 1, 0, 'F', '0', '0', 'video:alarm:export', '#', 'admin', NOW(), '', NULL, ''),
('报警记录处理', (SELECT menu_id FROM sys_menu WHERE perms = 'video:alarm:list'), 3, '', '', 1, 0, 'F', '0', '0', 'video:alarm:handle', '#', 'admin', NOW(), '', NULL, '');