优化宇视摄像头

This commit is contained in:
zc
2026-03-23 18:02:11 +08:00
parent 33db8595ec
commit 443ee0038b
2 changed files with 186 additions and 465 deletions

View File

@@ -0,0 +1,23 @@
import http from '@/utils/http'
const BASE_URL = '/api/ys'
/** @desc 进入称重页面 */
export function getEnterWeighPage() {
return http.get<any>(`${BASE_URL}/enter-weigh-page`)
}
/** @desc 退出称重页面 */
export function getLeaveWeighPage() {
return http.get<any>(`${BASE_URL}/leave-weigh-page`)
}
/** @desc 抓拍图片 */
export function getCaptureImage(imgName: string) {
return http.get<any>(`${BASE_URL}/capture-image?imgName=${imgName}`)
}
/** @desc 检查称重状态 */
export function getCheckStatus() {
return http.get<any>(`${BASE_URL}/status`)
}

View File

@@ -136,11 +136,11 @@
</div> </div>
<div class="form-row"> <div class="form-row">
<div class="form-item"> <div class="form-item">
<label>计算重量(g):</label> <label>标准重量(g):</label>
<a-input v-model="calculatedWeight" placeholder="-" disabled /> <a-input v-model="calculatedWeight" placeholder="-" disabled />
</div> </div>
<div class="form-item"> <div class="form-item">
<label>对应重量(g):</label> <label>称重重量(g):</label>
<a-input v-model="ahDeviceWeight" placeholder="-" disabled /> <a-input v-model="ahDeviceWeight" placeholder="-" disabled />
</div> </div>
</div> </div>
@@ -151,40 +151,24 @@
</div> </div>
</div> </div>
<!-- 这里是摄像头画面 - 替换成FLV播放器 --> <!-- 图片展示 -->
<div class="video-container large-image"> <div class="image-placeholder square-image">
<video <img
ref="cameraVideo" :src="weighingImgData.imgUrl"
autoplay alt="称重图片"
muted style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px;"
playsinline />
style="width: 100%; height: 100%; object-fit: cover;" <!-- 错误状态 -->
></video> <div v-if="weighingPageStatus === 'error'" class="video-overlay error">
<icon-close-circle-fill style="color: #ff4d4f; font-size: 24px;" />
<span>状态异常</span>
<a-button size="small" type="primary" @click="enterWeighPage">重试</a-button>
</div>
<!-- 加载状态 --> <!-- 加载状态 -->
<div v-if="cameraStatus === 'connecting'" class="video-overlay"> <div v-if="weighingPageStatus === 'entering'" class="video-overlay">
<a-spin /> <a-spin />
<span style="margin-left: 8px;">加载中...</span> <span style="margin-left: 8px;">加载中...</span>
</div> </div>
<!-- 错误状态 -->
<div v-if="cameraStatus === 'error'" class="video-overlay error">
<icon-close-circle-fill style="color: #ff4d4f; font-size: 24px;" />
<span>连接失败</span>
<a-button size="small" type="primary" @click="reconnectCamera">重试</a-button>
</div>
<!-- 未连接状态 -->
<div v-if="cameraStatus === 'disconnected'" class="video-overlay">
<icon-pause-circle-fill style="color: #999; font-size: 24px;" />
<span>未连接</span>
<a-button size="small" type="primary" @click="initCamera">连接</a-button>
</div>
<!-- 摄像头状态标识 -->
<div v-if="cameraStatus === 'connected'" class="camera-badge">
<span class="live-badge">LIVE</span>
</div>
</div> </div>
<div class="weighing-actions"> <div class="weighing-actions">
@@ -200,6 +184,10 @@
<h4>称重列表</h4> <h4>称重列表</h4>
</div> </div>
<a-table :columns="columns" :data="weighingList" bordered> <a-table :columns="columns" :data="weighingList" bordered>
<template #image="{ record }">
<a-image width="60" :src="record.image"/>
</template>
<template #action="{ record }"> <template #action="{ record }">
<a-button type="text" status="danger" @click="handleDelete(record.key)"> <a-button type="text" status="danger" @click="handleDelete(record.key)">
删除 删除
@@ -275,18 +263,17 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, onUnmounted, reactive, ref, watch, computed } from 'vue' import { nextTick, onBeforeUnmount, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { Message, Modal, Notification } from '@arco-design/web-vue' import { Message, Modal, Notification } from '@arco-design/web-vue'
import { getMaterialDetail, validateWeighing, vmSend } from '@/apis/weightManage/weightManage' import { getMaterialDetail, validateWeighing, vmSend } from '@/apis/weightManage/weightManage'
import {type WorkOrderResp, addWorkOrder} from '@/apis/workOrder/workOrder' import {type WorkOrderResp, addWorkOrder} from '@/apis/workOrder/workOrder'
import { catchPhoto } from '@/apis/material/materialInfo' import {getCaptureImage, getCheckStatus, getEnterWeighPage, getLeaveWeighPage} from "@/apis/weightManage/ys";
import router from "@/router"; import router from "@/router";
import type {TableInstanceColumns} from "@/components/GiTable/type";
defineOptions({ name: 'WeightManage' }) defineOptions({ name: 'WeightManage' })
// 动态导入flv.js
const flvjs = ref<any>(null)
// 当前步骤 // 当前步骤
const activeStep = ref(1) const activeStep = ref(1)
@@ -307,259 +294,106 @@ const imgData = reactive({
baseUrl: 'http://localhost:6609/file/001.bmp' // 基础URL baseUrl: 'http://localhost:6609/file/001.bmp' // 基础URL
}) })
const weighingImgData = reactive({
imgUrl: 'http://localhost:6609/file/ys/carousel.jpg', // 称重页面图片URL
baseUrl: 'http://localhost:6609/file/ys/carousel.jpg' // 基础URL
})
// 比对结果 // 比对结果
const compareMatchResult = ref('') const compareMatchResult = ref('')
// 摄像头状态
const cameraStatus = ref<'connected' | 'connecting' | 'disconnected' | 'error'>('disconnected')
// 视频元素引用
const cameraVideo = ref<HTMLVideoElement | null>(null)
// 物料编码输入框引用 // 物料编码输入框引用
const materialCodeInput = ref<any>(null) const materialCodeInput = ref<any>(null)
// FLV播放器实例 // 称重页面状态
let player: any = null const weighingPageStatus = ref<'idle' | 'entering' | 'entered' | 'error'>('idle')
const reconnectCount = ref(1) // 检查状态定时器
const maxReconnectAttempts = 3
const reconnectTimer = ref<any>(null)
// 直接写死FLV流地址根据你的实际地址修改
const FLV_URL = 'http://192.168.2.87:8866/live?url=rtsp://admin:admin%40123@192.168.2.59:554/media/video1' // 摄像头的FLV地址
// 加载flv.js
const loadFlvJs = async () => {
if (typeof window !== 'undefined') {
const module = await import('flv.js')
flvjs.value = module.default
}
}
// 初始化摄像头
const initCamera = () => {
if (!cameraVideo.value || !flvjs.value) {
return
}
// 检查浏览器支持
if (!flvjs.value.isSupported()) {
Message.error('当前浏览器不支持FLV播放')
cameraStatus.value = 'error'
return
}
cameraStatus.value = 'connecting'
// 清除之前的重连定时器
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value)
reconnectTimer.value = null
}
try {
// 销毁旧的播放器
if (player) {
player.destroy()
player = null
}
// 创建新的播放器
player = flvjs.value.createPlayer({
type: 'flv',
url: FLV_URL,
isLive: true,
hasAudio: false,
hasVideo: true,
enableStashBuffer: false,
stashInitialSize: 128,
enableWorker: true,
autoCleanupSourceBuffer: true,
})
// 绑定视频元素
player.attachMediaElement(cameraVideo.value)
// 加载并播放
player.load()
player.play().then(() => {
cameraStatus.value = 'connected'
reconnectCount.value = 1 // 连接成功,重置重连计数
}).catch((error: any) => {
cameraStatus.value = 'error'
Message.error('摄像头播放失败,正在重连')
// 触发自动重连
handleReconnect()
return
})
// 监听各种事件
player.on(flvjs.value.Events.ERROR, (err: any) => {
cameraStatus.value = 'error'
// 触发自动重连
handleReconnect()
})
player.on(flvjs.value.Events.STALLED, () => {
// 可以在这里处理卡顿,但不立即重连
})
player.on(flvjs.value.Events.RECOVERED_EARLY, () => {
if (cameraStatus.value !== 'connected') {
cameraStatus.value = 'connected'
}
})
} catch (error) {
cameraStatus.value = 'error'
handleReconnect()
}
}
// 处理自动重连
const handleReconnect = () => {
// 只有当前在称重页面才重连
if (activeStep.value !== 2) return
// 检查重连次数
if (reconnectCount.value >= maxReconnectAttempts) {
return
}
// 增加重连计数
reconnectCount.value++
// 计算重连延迟(指数退避)
const delay = Math.min(1000 * 2 ** (reconnectCount.value - 1), 30000)
// 清除旧的定时器
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value)
}
// 设置新的重连定时器
reconnectTimer.value = setTimeout(() => {
initCamera()
}, delay)
}
// 重新连接摄像头(手动)
const reconnectCamera = () => {
reconnectCount.value = 1 // 手动重连时重置计数
initCamera()
}
// 添加一个定时检查状态的函数
const checkCameraStatus = () => {
if (!player || !cameraVideo.value) return
try {
// 检查播放器状态
if (player.isPlaying && !player.isPlaying()) {
if (cameraStatus.value === 'connected') {
cameraStatus.value = 'error'
handleReconnect()
}
}
} catch (error) {
}
}
// 启动状态检查定时器
let statusCheckTimer: any = null let statusCheckTimer: any = null
// 监听步骤变化
// watch(activeStep, (newVal) => {
// if (newVal === 2) {
// // 进入称重登记页面,启动摄像头
// reconnectCount.value = 1 // 重置重连计数
// nextTick(() => {
// initCamera()
// })
//
// // 启动状态检查每30秒检查一次
// statusCheckTimer = setInterval(checkCameraStatus, 30000)
// } else {
// // 离开称重登记页面,停止摄像头和定时器
// stopCamera()
// if (statusCheckTimer) {
// clearInterval(statusCheckTimer)
// statusCheckTimer = null
// }
// if (reconnectTimer.value) {
// clearTimeout(reconnectTimer.value)
// reconnectTimer.value = null
// }
// reconnectCount.value = 1
// }
// })
// 组件卸载时清理所有定时器
onBeforeUnmount(() => {
stopCamera()
if (statusCheckTimer) {
clearInterval(statusCheckTimer)
statusCheckTimer = null
}
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value)
reconnectTimer.value = null
}
})
// 重新连接摄像头
// const reconnectCamera = () => {
// if (player) {
// player.unload()
// player.detachMediaElement()
// player.destroy()
// player = null
// }
// setTimeout(() => initCamera(), 1000)
// }
// 停止摄像头
const stopCamera = () => {
if (player) {
player.pause()
player.unload()
player.detachMediaElement()
player.destroy()
player = null
cameraStatus.value = 'disconnected'
}
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value)
reconnectTimer.value = null
}
reconnectCount.value = 1
}
// 监听步骤变化
watch(activeStep, (newVal) => {
if (newVal === 2) {
// 进入称重登记页面,启动摄像头
nextTick(() => {
initCamera()
})
} else {
// 离开相关页面,停止摄像头
stopCamera()
}
})
// 图片刷新定时器 // 图片刷新定时器
let imageRefreshTimer: any = null let imageRefreshTimer: any = null
// 组件挂载时 // 进入称重页面
onMounted(async () => { const enterWeighPage = async () => {
await loadFlvJs() weighingPageStatus.value = 'entering'
try {
const res = await getEnterWeighPage();
if (res.code === '0') {
weighingPageStatus.value = 'entered'
// 启动状态检查
startStatusCheck()
} else {
weighingPageStatus.value = 'error'
Message.error(res.msg)
}
} catch (error) {
weighingPageStatus.value = 'error'
Message.error("摄像头连接失败")
}
}
// 离开称重页面
const leaveWeighPage = async () => {
try {
await getLeaveWeighPage();
} catch (error) {
console.error('离开称重页面失败:', error)
}
// 停止状态检查
stopStatusCheck()
weighingPageStatus.value = 'idle'
}
// 手动抓图
const captureImage = async (imgName) => {
try {
const response = await getCaptureImage(imgName);
if (response.code === '0') {
return response.data
}
return null
} catch (error) {
console.error('抓图失败:', error)
return null
}
}
// 检查状态
const checkStatus = async () => {
try {
const response = await getCheckStatus();
if (response.code !== '0') {
weighingPageStatus.value = 'error'
}
} catch (error) {
weighingPageStatus.value = 'error'
}
}
// 启动状态检查
const startStatusCheck = () => {
// 每30秒检查一次状态
statusCheckTimer = setInterval(checkStatus, 30000)
}
// 停止状态检查
const stopStatusCheck = () => {
if (statusCheckTimer) {
clearInterval(statusCheckTimer)
statusCheckTimer = null
}
}
// 组件挂载时
onMounted(() => {
// 启动图片自动刷新,每秒更新一次 // 启动图片自动刷新,每秒更新一次
imageRefreshTimer = setInterval(() => { imageRefreshTimer = setInterval(() => {
// 添加时间戳参数,避免浏览器缓存 // 添加时间戳参数,避免浏览器缓存
imgData.imgUrl = `${imgData.baseUrl}?t=${Date.now()}` imgData.imgUrl = `${imgData.baseUrl}?t=${Date.now()}`
}, 1000) weighingImgData.imgUrl = `${weighingImgData.baseUrl}?t=${Date.now()}`
}, 1500)
// 页面加载后自动聚焦到物料编码输入框 // 页面加载后自动聚焦到物料编码输入框
nextTick(() => { nextTick(() => {
@@ -567,16 +401,34 @@ onMounted(async () => {
materialCodeInput.value.focus() materialCodeInput.value.focus()
} }
}) })
// 监听步骤变化
watch(activeStep, (newVal) => {
if (newVal === 2) {
// 进入称重登记页面
nextTick(() => {
enterWeighPage()
})
} else {
// 离开称重页面
leaveWeighPage()
}
})
}) })
// 组件卸载时 // 组件卸载时
onBeforeUnmount(() => { onBeforeUnmount(() => {
stopCamera()
// 清除图片刷新定时器 // 清除图片刷新定时器
if (imageRefreshTimer) { if (imageRefreshTimer) {
clearInterval(imageRefreshTimer) clearInterval(imageRefreshTimer)
imageRefreshTimer = null imageRefreshTimer = null
} }
// 停止状态检查
stopStatusCheck()
// 离开称重页面
if (activeStep.value === 2) {
leaveWeighPage()
}
}) })
const workOrderResp = ref<WorkOrderResp>({ const workOrderResp = ref<WorkOrderResp>({
@@ -615,57 +467,14 @@ const weighingList = ref([
]) ])
// 称重表格列 // 称重表格列
const columns = [ const columns = ref<TableInstanceColumns[]>([
{ { title: '序号', dataIndex: 'weightTime', key: 'weightTime',},
title: '称重次数', { title: '数量', dataIndex: 'quantity', key: 'quantity', className: 'green-bg',},
dataIndex: 'weightTime', { title: '称重重量(g)', dataIndex: 'weight', key: 'weight', className: 'green-bg',},
key: 'weightTime', { title: '标准重量(g)', dataIndex: 'calculatedWeight', key: 'calculatedWeight',},
}, { title: '抓图', dataIndex: 'image', key: 'image',slotName: 'image',},
{ { title: '操作', dataIndex: 'action', key: 'action', slotName: 'action',},
title: '数量',
dataIndex: 'quantity',
key: 'quantity',
className: 'green-bg',
},
{
title: '重量(g)',
dataIndex: 'weight',
key: 'weight',
className: 'green-bg',
},
{
title: '计算重量(g)',
dataIndex: 'calculatedWeight',
key: 'calculatedWeight',
className: 'green-bg',
},
{
title: '抓拍图片',
dataIndex: 'image',
key: 'image',
className: 'green-bg',
// 使用自定义渲染
render: ({ record }) => {
if (record.image && record.image !== '未抓拍') {
return h('div', { class: 'image-preview' }, [
h('img', {
src: record.image,
alt: '抓拍图片',
style: 'width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;',
onClick: () => previewImage(record.image),
}),
]) ])
}
return h('span', record.image || '-')
},
},
{
title: '操作',
dataIndex: 'action',
key: 'action',
slotName: 'action',
},
]
// 防抖函数 // 防抖函数
const debounce = <T extends (...args: any[]) => any>(func: T, delay: number): ((...args: Parameters<T>) => void) => { const debounce = <T extends (...args: any[]) => any>(func: T, delay: number): ((...args: Parameters<T>) => void) => {
@@ -969,89 +778,18 @@ const handleConfirm = async () => {
calculatedWeight.value = '' calculatedWeight.value = ''
weighingCount.value = weighingList.value.length + 1 weighingCount.value = weighingList.value.length + 1
// 异步执行抓拍,不阻塞主流程 // 调用手动抓图接口
if (cameraVideo.value && cameraStatus.value === 'connected') { const imageUrl = await captureImage(newItem.key + '_' + newItem.materialId);
// 立即执行异步抓拍
capturePhoto().then((captureUrl) => {
// 找到刚刚添加的项更新图片URL
const addedItem = weighingList.value.find((item) => item.key === newItem.key) const addedItem = weighingList.value.find((item) => item.key === newItem.key)
if (addedItem) { if (addedItem) {
addedItem.image = captureUrl || '抓失败' addedItem.image = imageUrl || '抓失败'
// 触发视图更新 // 触发视图更新
weighingList.value = [...weighingList.value] weighingList.value = [...weighingList.value]
} }
Message.success('图片抓拍成功')
}).catch((error) => {
})
} else {
// 摄像头未连接,直接显示未抓拍
const addedItem = weighingList.value.find((item) => item.key === newItem.key)
if (addedItem) {
addedItem.image = '未抓拍'
weighingList.value = [...weighingList.value]
}
}
Message.success('添加成功') Message.success('添加成功')
} }
// 抓拍功能 - 内部方法,不暴露按钮
const capturePhoto = (): Promise<string> => {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
const video = cameraVideo.value
if (!video) {
reject(new Error('视频未初始化'))
return
}
// 创建canvas抓取当前帧
const canvas = document.createElement('canvas')
canvas.width = video.videoWidth || 640
canvas.height = video.videoHeight || 480
const ctx = canvas.getContext('2d')
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
// 转换为Blob
const blob = await new Promise<Blob>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.9)
})
// 创建FormData
const formData = new FormData()
formData.append('file', blob, `capture_${Date.now()}.jpg`)
// 调用后端接口
const response = await catchPhoto(formData)
if (response.msg !== 'ok') {
return
}
const imageUrl = await response.data
resolve(imageUrl)
} catch (error) {
reject(error)
}
})
}
// 图片预览函数
const previewImage = (url: string) => {
// 使用Arco Design的图片预览组件
Modal.info({
title: '图片预览',
content: () => h('div', { style: 'text-align: center;' }, [
h('img', {
src: url,
style: 'max-width: 100%; max-height: 500px; object-fit: contain;',
}),
]),
okText: '关闭',
hideCancel: true,
width: 'auto',
})
}
// 处理重置 // 处理重置
const handleReset = () => { const handleReset = () => {
@@ -1262,69 +1000,7 @@ onUnmounted(() => {
font-weight: bold; font-weight: bold;
} }
/* 视频容器 - 替换原来的image-placeholder */
.video-container {
position: relative;
width: 100%;
height: 240px;
background: #000;
border-radius: 4px;
overflow: hidden;
margin: 20px 0;
}
.video-container video {
width: 100%;
height: 100%;
object-fit: cover;
}
.video-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #fff;
gap: 10px;
}
.video-overlay.error {
background: rgba(255, 77, 79, 0.2);
}
.camera-badge {
position: absolute;
top: 10px;
right: 10px;
z-index: 10;
}
.live-badge {
background: #ff4d4f;
color: white;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.7; }
100% { opacity: 1; }
}
.large-image {
width: 100%;
height: 240px;
}
.input-placeholder { .input-placeholder {
width: 100%; width: 100%;
@@ -1401,6 +1077,7 @@ onUnmounted(() => {
/* 图片占位符 */ /* 图片占位符 */
.image-placeholder { .image-placeholder {
position: relative;
width: 100%; width: 100%;
height: 150px; height: 150px;
background-color: #e8e8e8; background-color: #e8e8e8;
@@ -1409,6 +1086,27 @@ onUnmounted(() => {
justify-content: center; justify-content: center;
margin-bottom: 20px; margin-bottom: 20px;
border-radius: 4px; border-radius: 4px;
overflow: hidden;
}
/* 视频覆盖层样式(用于错误和加载状态) */
.video-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #fff;
gap: 10px;
}
.video-overlay.error {
background: rgba(255, 77, 79, 0.2);
} }
/* 正方形图片 */ /* 正方形图片 */