add: 完善HDMI输入前后端,现在无法关闭

This commit is contained in:
alivender 2025-08-04 16:35:42 +08:00
parent e86cd5464e
commit a331494fde
5 changed files with 769 additions and 27 deletions

View File

@ -16,7 +16,7 @@ public class HttpHdmiVideoStreamService : BackgroundService
{ {
private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private HttpListener? _httpListener; private HttpListener? _httpListener;
private readonly int _serverPort = 6666; private readonly int _serverPort = 4322;
private readonly ConcurrentDictionary<string, HdmiIn> _hdmiInDict = new(); private readonly ConcurrentDictionary<string, HdmiIn> _hdmiInDict = new();
private bool _isEnabled = true; private bool _isEnabled = true;
@ -39,7 +39,9 @@ public class HttpHdmiVideoStreamService : BackgroundService
HttpListenerContext? context = null; HttpListenerContext? context = null;
try try
{ {
logger.Debug("Waiting for HTTP request...");
context = await _httpListener.GetContextAsync(); context = await _httpListener.GetContextAsync();
logger.Debug($"Received request: {context.Request.Url?.AbsolutePath}");
} }
catch (ObjectDisposedException) catch (ObjectDisposedException)
{ {
@ -71,12 +73,46 @@ public class HttpHdmiVideoStreamService : BackgroundService
{ {
logger.Info("Stopping HDMI Video Stream Service..."); logger.Info("Stopping HDMI Video Stream Service...");
_isEnabled = false; _isEnabled = false;
// 禁用所有活跃的HDMI传输
var disableTasks = new List<Task>();
foreach (var hdmiIn in _hdmiInDict.Values)
{
disableTasks.Add(DisableHdmiTransmissionAsync(hdmiIn));
}
// 等待所有禁用操作完成
await Task.WhenAll(disableTasks);
// 清空字典
_hdmiInDict.Clear();
_httpListener?.Close(); // 立即关闭监听器,唤醒阻塞 _httpListener?.Close(); // 立即关闭监听器,唤醒阻塞
await base.StopAsync(cancellationToken); await base.StopAsync(cancellationToken);
} }
private async Task DisableHdmiTransmissionAsync(HdmiIn hdmiIn)
{
try
{
var disableResult = await hdmiIn.EnableTrans(false);
if (disableResult.IsSuccessful)
{
logger.Info("Successfully disabled HDMI transmission");
}
else
{
logger.Error($"Failed to disable HDMI transmission: {disableResult.Error}");
}
}
catch (Exception ex)
{
logger.Error(ex, "Exception occurred while disabling HDMI transmission");
}
}
// 获取/创建 HdmiIn 实例 // 获取/创建 HdmiIn 实例
private HdmiIn? GetOrCreateHdmiIn(string boardId) private async Task<HdmiIn?> GetOrCreateHdmiInAsync(string boardId)
{ {
if (_hdmiInDict.TryGetValue(boardId, out var hdmiIn)) if (_hdmiInDict.TryGetValue(boardId, out var hdmiIn))
return hdmiIn; return hdmiIn;
@ -98,6 +134,24 @@ public class HttpHdmiVideoStreamService : BackgroundService
var board = boardRet.Value.Value; var board = boardRet.Value.Value;
hdmiIn = new HdmiIn(board.IpAddr, board.Port, 0); // taskID 可根据实际需求调整 hdmiIn = new HdmiIn(board.IpAddr, board.Port, 0); // taskID 可根据实际需求调整
// 启用HDMI传输
try
{
var enableResult = await hdmiIn.EnableTrans(true);
if (!enableResult.IsSuccessful)
{
logger.Error($"Failed to enable HDMI transmission for board {boardId}: {enableResult.Error}");
return null;
}
logger.Info($"Successfully enabled HDMI transmission for board {boardId}");
}
catch (Exception ex)
{
logger.Error(ex, $"Exception occurred while enabling HDMI transmission for board {boardId}");
return null;
}
_hdmiInDict[boardId] = hdmiIn; _hdmiInDict[boardId] = hdmiIn;
return hdmiIn; return hdmiIn;
} }
@ -112,7 +166,7 @@ public class HttpHdmiVideoStreamService : BackgroundService
return; return;
} }
var hdmiIn = GetOrCreateHdmiIn(boardId); var hdmiIn = await GetOrCreateHdmiInAsync(boardId);
if (hdmiIn == null) if (hdmiIn == null)
{ {
await SendErrorAsync(context.Response, "Invalid boardId or board not available"); await SendErrorAsync(context.Response, "Invalid boardId or board not available");
@ -139,37 +193,206 @@ public class HttpHdmiVideoStreamService : BackgroundService
private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, HdmiIn hdmiIn, CancellationToken cancellationToken) private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, HdmiIn hdmiIn, CancellationToken cancellationToken)
{ {
try
{
logger.Debug("处理HDMI快照请求");
const int frameWidth = 960; // HDMI输入分辨率
const int frameHeight = 540;
// 从HDMI读取RGB565数据
var frameResult = await hdmiIn.ReadFrame(); var frameResult = await hdmiIn.ReadFrame();
if (frameResult.IsSuccessful) if (!frameResult.IsSuccessful || frameResult.Value == null)
{
response.ContentType = "image/jpeg";
await response.OutputStream.WriteAsync(frameResult.Value, 0, frameResult.Value.Length, cancellationToken);
}
else
{ {
logger.Error("HDMI快照获取失败");
response.StatusCode = 500; response.StatusCode = 500;
await response.OutputStream.WriteAsync(System.Text.Encoding.UTF8.GetBytes("Failed to get snapshot")); var errorBytes = System.Text.Encoding.UTF8.GetBytes("Failed to get HDMI snapshot");
} await response.OutputStream.WriteAsync(errorBytes, 0, errorBytes.Length, cancellationToken);
response.Close(); response.Close();
return;
}
var rgb565Data = frameResult.Value;
// 验证数据长度
var expectedLength = frameWidth * frameHeight * 2;
if (rgb565Data.Length != expectedLength)
{
logger.Warn("HDMI快照数据长度不匹配期望: {Expected}, 实际: {Actual}",
expectedLength, rgb565Data.Length);
}
// 将RGB565转换为RGB24
var rgb24Result = Common.Image.ConvertRGB565ToRGB24(rgb565Data, frameWidth, frameHeight, isLittleEndian: false);
if (!rgb24Result.IsSuccessful)
{
logger.Error("HDMI快照RGB565转RGB24失败: {Error}", rgb24Result.Error);
response.StatusCode = 500;
var errorBytes = System.Text.Encoding.UTF8.GetBytes("Failed to process HDMI snapshot");
await response.OutputStream.WriteAsync(errorBytes, 0, errorBytes.Length, cancellationToken);
response.Close();
return;
}
// 将RGB24转换为JPEG
var jpegResult = Common.Image.ConvertRGB24ToJpeg(rgb24Result.Value, frameWidth, frameHeight, 80);
if (!jpegResult.IsSuccessful)
{
logger.Error("HDMI快照RGB24转JPEG失败: {Error}", jpegResult.Error);
response.StatusCode = 500;
var errorBytes = System.Text.Encoding.UTF8.GetBytes("Failed to encode HDMI snapshot");
await response.OutputStream.WriteAsync(errorBytes, 0, errorBytes.Length, cancellationToken);
response.Close();
return;
}
var jpegData = jpegResult.Value;
// 设置响应头参考Camera版本
response.ContentType = "image/jpeg";
response.ContentLength64 = jpegData.Length;
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
await response.OutputStream.FlushAsync(cancellationToken);
logger.Debug("已发送HDMI快照图像大小{Size} 字节", jpegData.Length);
}
catch (Exception ex)
{
logger.Error(ex, "处理HDMI快照请求时出错");
response.StatusCode = 500;
}
finally
{
response.Close();
}
} }
private async Task HandleMjpegStreamAsync(HttpListenerResponse response, HdmiIn hdmiIn, CancellationToken cancellationToken) private async Task HandleMjpegStreamAsync(HttpListenerResponse response, HdmiIn hdmiIn, CancellationToken cancellationToken)
{ {
response.ContentType = "multipart/x-mixed-replace; boundary=--frame"; try
{
// 设置MJPEG流的响应头参考Camera版本
response.ContentType = "multipart/x-mixed-replace; boundary=--boundary";
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
response.Headers.Add("Pragma", "no-cache");
response.Headers.Add("Expires", "0");
logger.Debug("开始HDMI MJPEG流传输");
int frameCounter = 0;
const int frameWidth = 960; // HDMI输入分辨率
const int frameHeight = 540;
while (!cancellationToken.IsCancellationRequested && _isEnabled) while (!cancellationToken.IsCancellationRequested && _isEnabled)
{ {
var frameResult = await hdmiIn.ReadFrame(); try
if (frameResult.IsSuccessful)
{ {
var header = $"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {frameResult.Value.Length}\r\n\r\n"; var frameStartTime = DateTime.UtcNow;
await response.OutputStream.WriteAsync(System.Text.Encoding.ASCII.GetBytes(header));
await response.OutputStream.WriteAsync(frameResult.Value, 0, frameResult.Value.Length, cancellationToken); // 从HDMI读取RGB565数据
await response.OutputStream.WriteAsync(System.Text.Encoding.ASCII.GetBytes("\r\n")); var readStartTime = DateTime.UtcNow;
var frameResult = await hdmiIn.ReadFrame();
var readEndTime = DateTime.UtcNow;
var readTime = (readEndTime - readStartTime).TotalMilliseconds;
if (!frameResult.IsSuccessful || frameResult.Value == null)
{
logger.Warn("HDMI帧读取失败或为空");
continue;
} }
await Task.Delay(33, cancellationToken); // ~30fps
var rgb565Data = frameResult.Value;
// 验证数据长度是否正确 (RGB565为每像素2字节)
var expectedLength = frameWidth * frameHeight * 2;
if (rgb565Data.Length != expectedLength)
{
logger.Warn("HDMI数据长度不匹配期望: {Expected}, 实际: {Actual}",
expectedLength, rgb565Data.Length);
} }
// 将RGB565转换为RGB24参考Camera版本的处理
var convertStartTime = DateTime.UtcNow;
var rgb24Result = Common.Image.ConvertRGB565ToRGB24(rgb565Data, frameWidth, frameHeight, isLittleEndian: false);
var convertEndTime = DateTime.UtcNow;
var convertTime = (convertEndTime - convertStartTime).TotalMilliseconds;
if (!rgb24Result.IsSuccessful)
{
logger.Error("HDMI RGB565转RGB24失败: {Error}", rgb24Result.Error);
continue;
}
// 将RGB24转换为JPEG参考Camera版本的处理
var jpegStartTime = DateTime.UtcNow;
var jpegResult = Common.Image.ConvertRGB24ToJpeg(rgb24Result.Value, frameWidth, frameHeight, 80);
var jpegEndTime = DateTime.UtcNow;
var jpegTime = (jpegEndTime - jpegStartTime).TotalMilliseconds;
if (!jpegResult.IsSuccessful)
{
logger.Error("HDMI RGB24转JPEG失败: {Error}", jpegResult.Error);
continue;
}
var jpegData = jpegResult.Value;
// 发送MJPEG帧使用Camera版本的格式
var mjpegFrameHeader = Common.Image.CreateMjpegFrameHeader(jpegData.Length);
var mjpegFrameFooter = Common.Image.CreateMjpegFrameFooter();
await response.OutputStream.WriteAsync(mjpegFrameHeader, 0, mjpegFrameHeader.Length, cancellationToken);
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
await response.OutputStream.WriteAsync(mjpegFrameFooter, 0, mjpegFrameFooter.Length, cancellationToken);
await response.OutputStream.FlushAsync(cancellationToken);
frameCounter++;
var totalTime = (DateTime.UtcNow - frameStartTime).TotalMilliseconds;
// 性能统计日志每30帧记录一次
if (frameCounter % 30 == 0)
{
logger.Debug("HDMI帧 {FrameNumber} 性能统计 - 读取: {ReadTime:F1}ms, RGB转换: {ConvertTime:F1}ms, JPEG转换: {JpegTime:F1}ms, 总计: {TotalTime:F1}ms, JPEG大小: {JpegSize} 字节",
frameCounter, readTime, convertTime, jpegTime, totalTime, jpegData.Length);
}
}
catch (Exception ex)
{
logger.Error(ex, "处理HDMI帧时发生错误");
}
}
}
catch (Exception ex)
{
logger.Error(ex, "HDMI MJPEG流处理异常");
}
finally
{
try
{
// 停止传输时禁用HDMI传输
await hdmiIn.EnableTrans(false);
logger.Info("已禁用HDMI传输");
}
catch (Exception ex)
{
logger.Error(ex, "禁用HDMI传输时出错");
}
try
{
response.Close(); response.Close();
} }
catch
{
// 忽略关闭时的错误
}
logger.Debug("HDMI MJPEG流连接已关闭");
}
}
private async Task SendVideoHtmlPageAsync(HttpListenerResponse response, string boardId) private async Task SendVideoHtmlPageAsync(HttpListenerResponse response, string boardId)
{ {
@ -200,6 +423,10 @@ public class HttpHdmiVideoStreamService : BackgroundService
response.Close(); response.Close();
} }
/// <summary>
/// 获取所有可用的HDMI视频流终端点
/// </summary>
/// <returns>返回所有可用的HDMI视频流终端点列表</returns>
public List<HdmiVideoStreamEndpoint>? GetAllVideoEndpoints() public List<HdmiVideoStreamEndpoint>? GetAllVideoEndpoints()
{ {
var db = new Database.AppDataConnection(); var db = new Database.AppDataConnection();
@ -221,6 +448,11 @@ public class HttpHdmiVideoStreamService : BackgroundService
return endpoints; return endpoints;
} }
/// <summary>
/// 获取指定板卡ID的HDMI视频流终端点
/// </summary>
/// <param name="boardId">板卡ID</param>
/// <returns>返回指定板卡的HDMI视频流终端点</returns>
public HdmiVideoStreamEndpoint GetVideoEndpoint(string boardId) public HdmiVideoStreamEndpoint GetVideoEndpoint(string boardId)
{ {
return new HdmiVideoStreamEndpoint return new HdmiVideoStreamEndpoint

View File

@ -465,7 +465,8 @@ public class UDPClientPool
CommandID = Convert.ToByte(taskID), CommandID = Convert.ToByte(taskID),
IsWrite = false, IsWrite = false,
BurstLength = (byte)(currentSegmentSize - 1), BurstLength = (byte)(currentSegmentSize - 1),
Address = devAddr + (uint)(i * max4BytesPerRead) Address = (burstType == BurstType.ExtendBurst)?(devAddr + (uint)(i * max4BytesPerRead)):(devAddr),
// Address = devAddr + (uint)(i * max4BytesPerRead),
}; };
pkgList.Add(new SendAddrPackage(opts)); pkgList.Add(new SendAddrPackage(opts));
} }

View File

@ -15,6 +15,7 @@ import {
DebuggerClient, DebuggerClient,
ExamClient, ExamClient,
ResourceClient, ResourceClient,
HdmiVideoStreamClient,
} from "@/APIClient"; } from "@/APIClient";
import router from "@/router"; import router from "@/router";
import { HubConnectionBuilder } from "@microsoft/signalr"; import { HubConnectionBuilder } from "@microsoft/signalr";
@ -38,7 +39,8 @@ type SupportedClient =
| OscilloscopeApiClient | OscilloscopeApiClient
| DebuggerClient | DebuggerClient
| ExamClient | ExamClient
| ResourceClient; | ResourceClient
| HdmiVideoStreamClient;
export class AuthManager { export class AuthManager {
// 存储token到localStorage // 存储token到localStorage
@ -205,6 +207,10 @@ export class AuthManager {
return AuthManager.createAuthenticatedClient(ResourceClient); return AuthManager.createAuthenticatedClient(ResourceClient);
} }
public static createAuthenticatedHdmiVideoStreamClient(): HdmiVideoStreamClient {
return AuthManager.createAuthenticatedClient(HdmiVideoStreamClient);
}
public static createAuthenticatedJtagHubConnection() { public static createAuthenticatedJtagHubConnection() {
const token = this.getToken(); const token = this.getToken();
if (isNull(token)) { if (isNull(token)) {

View File

@ -31,8 +31,8 @@
:checked="checkID === 3" :checked="checkID === 3"
@change="handleTabChange" @change="handleTabChange"
/> />
<SquareActivityIcon class="icon" /> <Monitor class="icon" />
示波器 HDMI视频流
</label> </label>
<label class="tab"> <label class="tab">
<input <input
@ -42,8 +42,8 @@
:checked="checkID === 4" :checked="checkID === 4"
@change="handleTabChange" @change="handleTabChange"
/> />
<Binary class="icon" /> <SquareActivityIcon class="icon" />
逻辑分析仪 示波器
</label> </label>
<label class="tab"> <label class="tab">
<input <input
@ -53,6 +53,17 @@
:checked="checkID === 5" :checked="checkID === 5"
@change="handleTabChange" @change="handleTabChange"
/> />
<Binary class="icon" />
逻辑分析仪
</label>
<label class="tab">
<input
type="radio"
name="function-bar"
id="6"
:checked="checkID === 6"
@change="handleTabChange"
/>
<Hand class="icon" /> <Hand class="icon" />
嵌入式逻辑分析仪 嵌入式逻辑分析仪
</label> </label>
@ -73,12 +84,15 @@
<VideoStreamView /> <VideoStreamView />
</div> </div>
<div v-else-if="checkID === 3" class="h-full overflow-y-auto"> <div v-else-if="checkID === 3" class="h-full overflow-y-auto">
<OscilloscopeView /> <HdmiVideoStreamView />
</div> </div>
<div v-else-if="checkID === 4" class="h-full overflow-y-auto"> <div v-else-if="checkID === 4" class="h-full overflow-y-auto">
<LogicAnalyzerView /> <OscilloscopeView />
</div> </div>
<div v-else-if="checkID === 5" class="h-full overflow-y-auto"> <div v-else-if="checkID === 5" class="h-full overflow-y-auto">
<LogicAnalyzerView />
</div>
<div v-else-if="checkID === 6" class="h-full overflow-y-auto">
<Debugger /> <Debugger />
</div> </div>
</div> </div>
@ -94,9 +108,11 @@ import {
MinimizeIcon, MinimizeIcon,
Binary, Binary,
Hand, Hand,
Monitor,
} from "lucide-vue-next"; } from "lucide-vue-next";
import { useLocalStorage } from "@vueuse/core"; import { useLocalStorage } from "@vueuse/core";
import VideoStreamView from "@/views/Project/VideoStream.vue"; import VideoStreamView from "@/views/Project/VideoStream.vue";
import HdmiVideoStreamView from "@/views/Project/HdmiVideoStream.vue";
import OscilloscopeView from "@/views/Project/Oscilloscope.vue"; import OscilloscopeView from "@/views/Project/Oscilloscope.vue";
import LogicAnalyzerView from "@/views/Project/LogicAnalyzer.vue"; import LogicAnalyzerView from "@/views/Project/LogicAnalyzer.vue";
import { isNull, toNumber } from "lodash"; import { isNull, toNumber } from "lodash";

View File

@ -0,0 +1,487 @@
<template>
<div class="bg-base-100 flex flex-col gap-7">
<!-- 控制面板 -->
<div class="card bg-base-200 shadow-xl mx-5">
<div class="card-body">
<h2 class="card-title text-primary">
<Settings class="w-6 h-6" />
HDMI视频流控制面板
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<!-- 板卡信息 -->
<div class="stats shadow">
<div class="stat bg-base-100">
<div class="stat-figure text-primary">
<div class="badge" :class="endpoint ? 'badge-success' : 'badge-warning'">
{{ endpoint ? "已连接" : "未配置" }}
</div>
</div>
<div class="stat-title">板卡状态</div>
<div class="stat-value text-primary">HDMI</div>
<div class="stat-desc">{{ endpoint ? `板卡: ${endpoint.boardId.substring(0, 8)}...` : "请先连接板卡" }}</div>
</div>
</div>
<!-- 连接状态 -->
<div class="stats shadow">
<div class="stat bg-base-100">
<div class="stat-figure text-secondary">
<Video class="w-8 h-8" />
</div>
<div class="stat-title">视频状态</div>
<div class="stat-value text-secondary">
{{ isPlaying ? "播放中" : "未播放" }}
</div>
<div class="stat-desc">{{ videoStatus }}</div>
</div>
</div>
</div>
<!-- 操作按钮 -->
<div class="card-actions justify-end mt-4">
<button class="btn btn-outline btn-primary" @click="refreshEndpoint" :disabled="loading">
<RefreshCw v-if="loading" class="animate-spin h-4 w-4 mr-2" />
<RefreshCw v-else class="h-4 w-4 mr-2" />
{{ loading ? "刷新中..." : "刷新连接" }}
</button>
<button class="btn btn-primary" @click="testConnection" :disabled="testing || !endpoint">
<RefreshCw v-if="testing" class="animate-spin h-4 w-4 mr-2" />
<TestTube v-else class="h-4 w-4 mr-2" />
{{ testing ? "测试中..." : "测试连接" }}
</button>
</div>
</div>
</div>
<!-- 视频预览区域 -->
<div class="card bg-base-200 shadow-xl mx-5">
<div class="card-body">
<h2 class="card-title text-primary">
<Video class="w-6 h-6" />
HDMI视频预览
</h2>
<div class="relative bg-black rounded-lg overflow-hidden cursor-pointer" :class="[
{ 'cursor-not-allowed': !isPlaying || hasVideoError || !endpoint }
]" style="aspect-ratio: 16/9" @click="handleVideoClick">
<!-- 视频播放器 - 使用img标签直接显示MJPEG流 -->
<div v-show="isPlaying && endpoint" class="w-full h-full flex items-center justify-center">
<img :src="currentVideoSource" alt="HDMI视频流" class="max-w-full max-h-full object-contain"
@error="handleVideoError" @load="handleVideoLoad" />
</div>
<!-- 错误信息显示 -->
<div v-if="hasVideoError" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70">
<div class="card bg-error text-white shadow-lg w-full max-w-lg">
<div class="card-body">
<h3 class="card-title flex items-center gap-2">
<AlertTriangle class="h-6 w-6" />
HDMI视频流加载失败
</h3>
<p>无法连接到HDMI视频服务器请检查以下内容</p>
<ul class="list-disc list-inside">
<li>HDMI输入设备是否已连接</li>
<li>板卡是否正常工作</li>
<li>网络连接是否正常</li>
<li>HDMI视频流服务是否已启动</li>
</ul>
<div class="card-actions justify-end mt-2">
<button class="btn btn-sm btn-outline btn-primary" @click="tryReconnect">
重试连接
</button>
</div>
</div>
</div>
</div>
<!-- 占位符 -->
<div v-show="(!isPlaying && !hasVideoError) || !endpoint"
class="absolute inset-0 flex items-center justify-center text-white">
<div class="text-center">
<Video class="w-16 h-16 mx-auto mb-4 opacity-50" />
<p class="text-lg opacity-75">{{ videoStatus }}</p>
<p class="text-sm opacity-60 mt-2">
{{ endpoint ? '点击"播放HDMI视频流"按钮开始查看实时视频' : '请先刷新连接以获取板卡信息' }}
</p>
</div>
</div>
</div>
<!-- 视频控制 -->
<div class="flex justify-between items-center mt-4" v-if="endpoint">
<div class="text-sm text-base-content/70">
MJPEG地址:
<code class="bg-base-300 px-2 py-1 rounded text-xs">{{
endpoint.mjpegUrl
}}</code>
</div>
<div class="space-x-2">
<div class="dropdown dropdown-hover dropdown-top dropdown-end">
<div tabindex="0" role="button" class="btn btn-sm btn-outline btn-accent">
<MoreHorizontal class="w-4 h-4 mr-1" />
更多功能
</div>
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52">
<li>
<a @click="openInNewTab(endpoint.videoUrl)">
<ExternalLink class="w-4 h-4" />
在新标签打开视频页面
</a>
</li>
<li>
<a @click="takeSnapshot">
<Camera class="w-4 h-4" />
获取并下载快照
</a>
</li>
<li>
<a @click="copyToClipboard(endpoint.mjpegUrl)">
<Copy class="w-4 h-4" />
复制MJPEG地址
</a>
</li>
</ul>
</div>
<button class="btn btn-success btn-sm" @click="startStream" :disabled="isPlaying || !endpoint">
<Play class="w-4 h-4 mr-1" />
播放HDMI视频流
</button>
<button class="btn btn-error btn-sm" @click="stopStream" :disabled="!isPlaying">
<Square class="w-4 h-4 mr-1" />
停止视频流
</button>
</div>
</div>
</div>
</div>
<!-- 日志区域 -->
<div class="card bg-base-200 shadow-xl mx-5">
<div class="card-body">
<h2 class="card-title text-primary">
<FileText class="w-6 h-6" />
操作日志
</h2>
<div class="bg-base-300 rounded-lg p-4 h-48 overflow-y-auto">
<div v-for="(log, index) in logs" :key="index" class="text-sm font-mono mb-1">
<span class="text-base-content/50">[{{ formatTime(log.time) }}]</span>
<span :class="getLogClass(log.level)">{{ log.message }}</span>
</div>
<div v-if="logs.length === 0" class="text-base-content/50 text-center py-8">
暂无日志记录
</div>
</div>
<div class="card-actions justify-end mt-2">
<button class="btn btn-outline btn-sm" @click="clearLogs">
清空日志
</button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import {
Settings,
Video,
RefreshCw,
TestTube,
Play,
Square,
ExternalLink,
Camera,
Copy,
FileText,
AlertTriangle,
MoreHorizontal,
} from "lucide-vue-next";
import { HdmiVideoStreamClient, type HdmiVideoStreamEndpoint } from "@/APIClient";
import { AuthManager } from "@/utils/AuthManager";
import { useAlertStore } from "@/components/Alert";
// Alert
const alert = useAlertStore();
//
const loading = ref(false);
const testing = ref(false);
const isPlaying = ref(false);
const hasVideoError = ref(false);
const videoStatus = ref('未连接');
// HDMI
const endpoint = ref<HdmiVideoStreamEndpoint | null>(null);
const currentVideoSource = ref('');
//
interface LogEntry {
time: Date;
level: 'info' | 'success' | 'warning' | 'error';
message: string;
}
const logs = ref<LogEntry[]>([]);
//
function addLog(level: LogEntry['level'], message: string) {
logs.value.unshift({
time: new Date(),
level,
message
});
// 100
if (logs.value.length > 100) {
logs.value = logs.value.slice(0, 100);
}
}
//
function formatTime(date: Date): string {
return date.toLocaleTimeString();
}
//
function getLogClass(level: LogEntry['level']): string {
switch (level) {
case 'success':
return 'text-success';
case 'warning':
return 'text-warning';
case 'error':
return 'text-error';
default:
return 'text-base-content';
}
}
//
function clearLogs() {
logs.value = [];
addLog('info', '日志已清空');
}
// HDMI
async function refreshEndpoint() {
loading.value = true;
try {
addLog('info', '正在获取HDMI视频流端点...');
const client = AuthManager.createAuthenticatedHdmiVideoStreamClient();
const result = await client.getMyEndpoint();
if (result) {
endpoint.value = result;
videoStatus.value = '已连接板卡,可以播放视频流';
addLog('success', `成功获取HDMI视频流端点板卡ID: ${result.boardId.substring(0, 8)}...`);
alert?.success('HDMI视频流连接成功');
} else {
endpoint.value = null;
videoStatus.value = '无法获取板卡信息';
addLog('error', '未找到绑定的板卡或板卡未配置HDMI输入');
alert?.error('未找到绑定的板卡');
}
} catch (error) {
console.error('获取HDMI视频流端点失败:', error);
endpoint.value = null;
videoStatus.value = '连接失败';
addLog('error', `获取HDMI视频流端点失败: ${error}`);
alert?.error('获取HDMI视频流信息失败');
} finally {
loading.value = false;
}
}
//
async function testConnection() {
if (!endpoint.value) {
alert?.warn('请先刷新连接获取板卡信息');
return;
}
testing.value = true;
try {
addLog('info', '正在测试HDMI视频流连接...');
//
const response = await fetch(endpoint.value.snapshotUrl, {
method: 'GET',
headers: {
'Cache-Control': 'no-cache'
}
});
if (response.ok) {
addLog('success', 'HDMI视频流连接测试成功');
alert?.success('HDMI连接测试成功');
videoStatus.value = '连接正常,可以播放视频流';
} else {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
} catch (error) {
console.error('HDMI视频流连接测试失败:', error);
addLog('error', `连接测试失败: ${error}`);
alert?.error('HDMI连接测试失败');
videoStatus.value = '连接测试失败';
} finally {
testing.value = false;
}
}
//
function startStream() {
if (!endpoint.value) {
alert?.warn('请先刷新连接获取板卡信息');
return;
}
try {
//
const timestamp = new Date().getTime();
currentVideoSource.value = `${endpoint.value.mjpegUrl}&t=${timestamp}`;
isPlaying.value = true;
hasVideoError.value = false;
videoStatus.value = '正在加载视频流...';
addLog('info', '开始播放HDMI视频流');
alert?.success('开始播放HDMI视频流');
} catch (error) {
console.error('启动HDMI视频流失败:', error);
addLog('error', `启动视频流失败: ${error}`);
alert?.error('启动HDMI视频流失败');
}
}
//
function stopStream() {
isPlaying.value = false;
currentVideoSource.value = '';
videoStatus.value = '已停止播放';
addLog('info', '停止播放HDMI视频流');
alert?.info('已停止播放HDMI视频流');
}
//
function handleVideoError() {
hasVideoError.value = true;
videoStatus.value = '视频流加载失败';
addLog('error', 'HDMI视频流加载失败');
}
//
function handleVideoLoad() {
hasVideoError.value = false;
videoStatus.value = '视频流播放中';
addLog('success', 'HDMI视频流加载成功');
}
//
function handleVideoClick() {
if (!isPlaying.value || hasVideoError.value || !endpoint.value) {
return;
}
//
addLog('info', '视频画面被点击');
}
//
function tryReconnect() {
hasVideoError.value = false;
if (endpoint.value) {
startStream();
}
}
//
function openInNewTab(url: string) {
window.open(url, '_blank');
addLog('info', '在新标签页打开HDMI视频页面');
}
//
async function takeSnapshot() {
if (!endpoint.value) {
alert?.warn('请先刷新连接获取板卡信息');
return;
}
try {
addLog('info', '正在获取HDMI视频快照...');
const response = await fetch(endpoint.value.snapshotUrl, {
method: 'GET',
headers: {
'Cache-Control': 'no-cache'
}
});
if (response.ok) {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `hdmi_snapshot_${new Date().toISOString().replace(/:/g, '-')}.jpg`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
addLog('success', '快照下载成功');
alert?.success('HDMI快照下载成功');
} else {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
} catch (error) {
console.error('获取HDMI快照失败:', error);
addLog('error', `获取快照失败: ${error}`);
alert?.error('获取HDMI快照失败');
}
}
//
async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
addLog('success', '地址已复制到剪贴板');
alert?.success('地址已复制到剪贴板');
} catch (error) {
console.error('复制到剪贴板失败:', error);
addLog('error', '复制到剪贴板失败');
alert?.error('复制到剪贴板失败');
}
}
//
onMounted(() => {
addLog('info', 'HDMI视频流界面已初始化');
refreshEndpoint();
});
//
onUnmounted(() => {
stopStream();
});
</script>
<style scoped>
/* 对焦动画效果 */
@keyframes focus-pulse {
0%, 100% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
}
50% {
box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
}
}
.focus-animation {
animation: focus-pulse 1s ease-out;
}
</style>