feat: 支持实际摄像头视频流

This commit is contained in:
SikongJueluo 2025-07-03 17:51:12 +08:00
parent 178ac0de67
commit e84a784517
No known key found for this signature in database
4 changed files with 1323 additions and 438 deletions

View File

@ -1,8 +1,9 @@
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
/// <summary> /// <summary>
/// [TODO:description] /// 视频流控制器,支持动态配置摄像头连接
/// </summary> /// </summary>
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
@ -11,6 +12,20 @@ public class VideoStreamController : ControllerBase
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private readonly server.Services.HttpVideoStreamService _videoStreamService; private readonly server.Services.HttpVideoStreamService _videoStreamService;
/// <summary>
/// 摄像头配置请求模型
/// </summary>
public class CameraConfigRequest
{
[Required]
[RegularExpression(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ErrorMessage = "IP地址")]
public string Address { get; set; } = "";
[Required]
[Range(1, 65535, ErrorMessage = "端口必须在1-65535范围内")]
public int Port { get; set; }
}
/// <summary> /// <summary>
/// 初始化HTTP视频流控制器 /// 初始化HTTP视频流控制器
/// </summary> /// </summary>
@ -47,12 +62,14 @@ public class VideoStreamController : ControllerBase
mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream", mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream",
snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot", snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot",
connectedClients = _videoStreamService.ConnectedClientsCount, connectedClients = _videoStreamService.ConnectedClientsCount,
clientEndpoints = _videoStreamService.GetConnectedClientEndpoints() clientEndpoints = _videoStreamService.GetConnectedClientEndpoints(),
cameraStatus = _videoStreamService.GetCameraStatus()
}); });
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Error(ex, "获取 HTTP 视频流服务状态失败"); return TypedResults.InternalServerError(ex.Message); logger.Error(ex, "获取 HTTP 视频流服务状态失败");
return TypedResults.InternalServerError(ex.Message);
} }
} }
@ -77,12 +94,123 @@ public class VideoStreamController : ControllerBase
format = "MJPEG", format = "MJPEG",
htmlUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html", htmlUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html",
mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream", mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream",
snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot" snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot",
cameraAddress = _videoStreamService.CameraAddress,
cameraPort = _videoStreamService.CameraPort
}); });
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Error(ex, "获取 HTTP 视频流信息失败"); return TypedResults.InternalServerError(ex.Message); logger.Error(ex, "获取 HTTP 视频流信息失败");
return TypedResults.InternalServerError(ex.Message);
}
}
/// <summary>
/// 配置摄像头连接参数
/// </summary>
/// <param name="config">摄像头配置</param>
/// <returns>配置结果</returns>
[HttpPost("ConfigureCamera")]
[EnableCors("Users")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async Task<IResult> ConfigureCamera([FromBody] CameraConfigRequest config)
{
try
{
logger.Info("配置摄像头连接: {Address}:{Port}", config.Address, config.Port);
var success = await _videoStreamService.ConfigureCameraAsync(config.Address, config.Port);
if (success)
{
return TypedResults.Ok(new
{
success = true,
message = "摄像头配置成功",
cameraAddress = config.Address,
cameraPort = config.Port
});
}
else
{
return TypedResults.BadRequest(new
{
success = false,
message = "摄像头配置失败",
cameraAddress = config.Address,
cameraPort = config.Port
});
}
}
catch (Exception ex)
{
logger.Error(ex, "配置摄像头连接失败");
return TypedResults.InternalServerError(ex.Message);
}
}
/// <summary>
/// 获取当前摄像头配置
/// </summary>
/// <returns>摄像头配置信息</returns>
[HttpGet("CameraConfig")]
[EnableCors("Users")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public IResult GetCameraConfig()
{
try
{
logger.Info("获取摄像头配置");
var cameraStatus = _videoStreamService.GetCameraStatus();
return TypedResults.Ok(new
{
address = _videoStreamService.CameraAddress,
port = _videoStreamService.CameraPort,
isConfigured = cameraStatus.GetType().GetProperty("IsConfigured")?.GetValue(cameraStatus),
connectionString = $"{_videoStreamService.CameraAddress}:{_videoStreamService.CameraPort}"
});
}
catch (Exception ex)
{
logger.Error(ex, "获取摄像头配置失败");
return TypedResults.InternalServerError(ex.Message);
}
}
/// <summary>
/// 测试摄像头连接
/// </summary>
/// <returns>连接测试结果</returns>
[HttpPost("TestCameraConnection")]
[EnableCors("Users")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async Task<IResult> TestCameraConnection()
{
try
{
logger.Info("测试摄像头连接");
var (isSuccess, message) = await _videoStreamService.TestCameraConnectionAsync();
return TypedResults.Ok(new
{
success = isSuccess,
message = message,
cameraAddress = _videoStreamService.CameraAddress,
cameraPort = _videoStreamService.CameraPort,
timestamp = DateTime.Now
});
}
catch (Exception ex)
{
logger.Error(ex, "测试摄像头连接失败");
return TypedResults.InternalServerError(ex.Message);
} }
} }

View File

@ -1,15 +1,12 @@
using System.Net; using System.Net;
using System.Text; using System.Text;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using Peripherals.CameraClient; // 添加摄像头客户端引用 using Peripherals.CameraClient; // 添加摄像头客户端引用
namespace server.Services; namespace server.Services;
/// <summary> /// <summary>
/// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页 /// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页
/// 简化版本实现,先建立基础框架 /// 支持动态配置摄像头地址和端口
/// </summary> /// </summary>
public class HttpVideoStreamService : BackgroundService public class HttpVideoStreamService : BackgroundService
{ {
@ -22,8 +19,9 @@ public class HttpVideoStreamService : BackgroundService
// 摄像头客户端 // 摄像头客户端
private Camera? _camera; private Camera? _camera;
private readonly string _cameraAddress = "192.168.1.100"; // 根据实际FPGA地址配置 private string _cameraAddress = "192.168.1.100"; // 默认FPGA地址
private readonly int _cameraPort = 8888; // 根据实际端口配置 private int _cameraPort = 8888; // 默认端口
private readonly object _cameraLock = new object();
// 模拟 FPGA 图像数据 // 模拟 FPGA 图像数据
private int _frameCounter = 0; private int _frameCounter = 0;
@ -33,16 +31,7 @@ public class HttpVideoStreamService : BackgroundService
/// <summary> /// <summary>
/// 获取当前连接的客户端数量 /// 获取当前连接的客户端数量
/// </summary> /// </summary>
public int ConnectedClientsCount public int ConnectedClientsCount { get { return _activeClients.Count; } }
{
get
{
lock (_clientsLock)
{
return _activeClients.Count;
}
}
}
/// <summary> /// <summary>
/// 获取服务端口 /// 获取服务端口
@ -64,13 +53,141 @@ public class HttpVideoStreamService : BackgroundService
/// </summary> /// </summary>
public int FrameRate => _frameRate; public int FrameRate => _frameRate;
/// <summary>
/// 获取当前摄像头地址
/// </summary>
public string CameraAddress { get { return _cameraAddress; } }
/// <summary>
/// 获取当前摄像头端口
/// </summary>
public int CameraPort { get { return _cameraPort; } }
/// <summary> /// <summary>
/// 初始化 HttpVideoStreamService /// 初始化 HttpVideoStreamService
/// </summary> /// </summary>
public HttpVideoStreamService() public HttpVideoStreamService()
{ {
// 初始化摄像头客户端 // 延迟初始化摄像头客户端,直到配置完成
logger.Info("HttpVideoStreamService 初始化完成,默认摄像头地址: {Address}:{Port}", _cameraAddress, _cameraPort);
}
/// <summary>
/// 配置摄像头连接参数
/// </summary>
/// <param name="address">摄像头IP地址</param>
/// <param name="port">摄像头端口</param>
/// <returns>配置是否成功</returns>
public async Task<bool> ConfigureCameraAsync(string address, int port)
{
if (string.IsNullOrWhiteSpace(address))
{
logger.Error("摄像头地址不能为空");
return false;
}
if (port <= 0 || port > 65535)
{
logger.Error("摄像头端口必须在1-65535范围内");
return false;
}
try
{
await Task.Run(() =>
{
lock (_cameraLock)
{
// 如果地址和端口没有变化,直接返回成功
if (_cameraAddress == address && _cameraPort == port && _camera != null)
{
logger.Info("摄像头配置未变化,保持当前连接");
return;
}
// 关闭现有连接
if (_camera != null)
{
logger.Info("关闭现有摄像头连接");
// Camera doesn't have Dispose method, set to null
_camera = null;
}
// 更新配置
_cameraAddress = address;
_cameraPort = port;
// 创建新的摄像头客户端
_camera = new Camera(_cameraAddress, _cameraPort); _camera = new Camera(_cameraAddress, _cameraPort);
logger.Info("摄像头配置已更新: {Address}:{Port}", _cameraAddress, _cameraPort);
}
});
return true;
}
catch (Exception ex)
{
logger.Error(ex, "配置摄像头连接时发生错误");
return false;
}
}
/// <summary>
/// 测试摄像头连接
/// </summary>
/// <returns>连接测试结果</returns>
public async Task<(bool IsSuccess, string Message)> TestCameraConnectionAsync()
{
try
{
Camera? testCamera = null;
lock (_cameraLock)
{
if (_camera == null)
{
return (false, "摄像头未配置");
}
testCamera = _camera;
}
// 尝试读取一帧数据来测试连接
var result = await testCamera.ReadFrame();
if (result.IsSuccessful)
{
logger.Info("摄像头连接测试成功: {Address}:{Port}", _cameraAddress, _cameraPort);
return (true, "连接成功");
}
else
{
logger.Warn("摄像头连接测试失败: {Error}", result.Error);
return (false, result.Error.ToString());
}
}
catch (Exception ex)
{
logger.Error(ex, "摄像头连接测试出错");
return (false, ex.Message);
}
}
/// <summary>
/// 获取摄像头连接状态
/// </summary>
/// <returns>连接状态信息</returns>
public object GetCameraStatus()
{
lock (_cameraLock)
{
return new
{
Address = _cameraAddress,
Port = _cameraPort,
IsConfigured = _camera != null,
ConnectionString = $"{_cameraAddress}:{_cameraPort}"
};
}
} }
/// <summary> /// <summary>
@ -83,6 +200,10 @@ public class HttpVideoStreamService : BackgroundService
try try
{ {
logger.Info("启动 HTTP 视频流服务,端口: {Port}", _serverPort); logger.Info("启动 HTTP 视频流服务,端口: {Port}", _serverPort);
// 初始化默认摄像头连接
await ConfigureCameraAsync(_cameraAddress, _cameraPort);
// 创建 HTTP 监听器 // 创建 HTTP 监听器
_httpListener = new HttpListener(); _httpListener = new HttpListener();
_httpListener.Prefixes.Add($"http://localhost:{_serverPort}/"); _httpListener.Prefixes.Add($"http://localhost:{_serverPort}/");
@ -220,7 +341,18 @@ public class HttpVideoStreamService : BackgroundService
{ {
// 获取当前帧 // 获取当前帧
var imageData = await GetFPGAImageData(); var imageData = await GetFPGAImageData();
var jpegData = ConvertToJpeg(imageData);
// 直接使用Common.Image.ConvertRGB24ToJpeg进行转换
var jpegResult = Common.Image.ConvertRGB24ToJpeg(imageData, _frameWidth, _frameHeight, 80);
if (!jpegResult.IsSuccessful)
{
logger.Error("RGB24转JPEG失败: {Error}", jpegResult.Error);
response.StatusCode = 500;
response.Close();
return;
}
var jpegData = jpegResult.Value;
// 设置响应头 // 设置响应头
response.ContentType = "image/jpeg"; response.ContentType = "image/jpeg";
@ -338,11 +470,8 @@ public class HttpVideoStreamService : BackgroundService
// 从 FPGA 获取图像数据(模拟) // 从 FPGA 获取图像数据(模拟)
var imageData = await GetFPGAImageData(); var imageData = await GetFPGAImageData();
// 将图像数据转换为 JPEG
var jpegData = ConvertToJpeg(imageData);
// 向所有连接的客户端发送帧 // 向所有连接的客户端发送帧
await BroadcastFrameAsync(jpegData, cancellationToken); await BroadcastFrameAsync(imageData, cancellationToken);
_frameCounter++; _frameCounter++;
@ -367,7 +496,14 @@ public class HttpVideoStreamService : BackgroundService
/// </summary> /// </summary>
private async Task<byte[]> GetFPGAImageData() private async Task<byte[]> GetFPGAImageData()
{ {
if (_camera == null) Camera? currentCamera = null;
lock (_cameraLock)
{
currentCamera = _camera;
}
if (currentCamera == null)
{ {
logger.Error("摄像头客户端未初始化"); logger.Error("摄像头客户端未初始化");
return new byte[0]; return new byte[0];
@ -376,7 +512,7 @@ public class HttpVideoStreamService : BackgroundService
try try
{ {
// 从摄像头读取帧数据 // 从摄像头读取帧数据
var result = await _camera.ReadFrame(); var result = await currentCamera.ReadFrame();
if (!result.IsSuccessful) if (!result.IsSuccessful)
{ {
@ -416,18 +552,6 @@ public class HttpVideoStreamService : BackgroundService
} }
} }
private async Task<byte[]> ConvertToJpeg(byte[] rgbData)
{
var jpegResult = Common.Image.ConvertRGB24ToJpeg(rgbData, _frameWidth, _frameHeight, 80);
if (!jpegResult.IsSuccessful)
{
logger.Error("RGB24转JPEG失败: {Error}", jpegResult.Error);
return new byte[0];
}
return jpegResult.Value;
}
/// <summary> /// <summary>
/// 向所有连接的客户端广播帧数据 /// 向所有连接的客户端广播帧数据
/// </summary> /// </summary>
@ -439,8 +563,18 @@ public class HttpVideoStreamService : BackgroundService
return; return;
} }
// 直接使用Common.Image.ConvertRGB24ToJpeg进行转换
var jpegResult = Common.Image.ConvertRGB24ToJpeg(frameData, _frameWidth, _frameHeight, 80);
if (!jpegResult.IsSuccessful)
{
logger.Error("RGB24转JPEG失败: {Error}", jpegResult.Error);
return;
}
var jpegData = jpegResult.Value;
// 使用Common中的方法准备MJPEG帧数据 // 使用Common中的方法准备MJPEG帧数据
var mjpegFrameHeader = Common.Image.CreateMjpegFrameHeader(frameData.Length); var mjpegFrameHeader = Common.Image.CreateMjpegFrameHeader(jpegData.Length);
var mjpegFrameFooter = Common.Image.CreateMjpegFrameFooter(); var mjpegFrameFooter = Common.Image.CreateMjpegFrameFooter();
var clientsToRemove = new List<HttpListenerResponse>(); var clientsToRemove = new List<HttpListenerResponse>();
@ -466,7 +600,7 @@ public class HttpVideoStreamService : BackgroundService
await client.OutputStream.WriteAsync(mjpegFrameHeader, 0, mjpegFrameHeader.Length, cancellationToken); await client.OutputStream.WriteAsync(mjpegFrameHeader, 0, mjpegFrameHeader.Length, cancellationToken);
// 发送JPEG数据 // 发送JPEG数据
await client.OutputStream.WriteAsync(frameData, 0, frameData.Length, cancellationToken); await client.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
// 发送结尾换行符 // 发送结尾换行符
await client.OutputStream.WriteAsync(mjpegFrameFooter, 0, mjpegFrameFooter.Length, cancellationToken); await client.OutputStream.WriteAsync(mjpegFrameFooter, 0, mjpegFrameFooter.Length, cancellationToken);
@ -477,7 +611,7 @@ public class HttpVideoStreamService : BackgroundService
if (_frameCounter % 30 == 0) // 每秒记录一次日志 if (_frameCounter % 30 == 0) // 每秒记录一次日志
{ {
logger.Debug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节", logger.Debug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节",
client.OutputStream.GetHashCode(), _frameCounter, frameData.Length); client.OutputStream.GetHashCode(), _frameCounter, jpegData.Length);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -528,6 +662,8 @@ public class HttpVideoStreamService : BackgroundService
/// </summary> /// </summary>
public object GetServiceStatus() public object GetServiceStatus()
{ {
var cameraStatus = GetCameraStatus();
return new return new
{ {
IsRunning = _httpListener?.IsListening ?? false, IsRunning = _httpListener?.IsListening ?? false,
@ -535,7 +671,8 @@ public class HttpVideoStreamService : BackgroundService
FrameRate = _frameRate, FrameRate = _frameRate,
Resolution = $"{_frameWidth}x{_frameHeight}", Resolution = $"{_frameWidth}x{_frameHeight}",
ConnectedClients = ConnectedClientsCount, ConnectedClients = ConnectedClientsCount,
ClientEndpoints = GetConnectedClientEndpoints() ClientEndpoints = GetConnectedClientEndpoints(),
CameraStatus = cameraStatus
}; };
} }
@ -563,6 +700,12 @@ public class HttpVideoStreamService : BackgroundService
_activeClients.Clear(); _activeClients.Clear();
} }
// 关闭摄像头连接
lock (_cameraLock)
{
_camera = null;
}
await base.StopAsync(cancellationToken); await base.StopAsync(cancellationToken);
logger.Info("HTTP 视频流服务已停止"); logger.Info("HTTP 视频流服务已停止");
@ -592,6 +735,11 @@ public class HttpVideoStreamService : BackgroundService
_activeClients.Clear(); _activeClients.Clear();
} }
lock (_cameraLock)
{
_camera = null;
}
base.Dispose(); base.Dispose();
} }
} }

View File

@ -8,6 +8,306 @@
/* eslint-disable */ /* eslint-disable */
// ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming
export class VideoStreamClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : window as any;
this.baseUrl = baseUrl ?? "http://localhost:5000";
}
/**
* HTTP
* @return
*/
getStatus(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/Status";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetStatus(_response);
});
}
protected processGetStatus(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(null as any);
}
/**
* HTTP
* @return
*/
getStreamInfo(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/StreamInfo";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetStreamInfo(_response);
});
}
protected processGetStreamInfo(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(null as any);
}
/**
*
* @param config
* @return
*/
configureCamera(config: CameraConfigRequest): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/ConfigureCamera";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(config);
let options_: RequestInit = {
body: content_,
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processConfigureCamera(_response);
});
}
protected processConfigureCamera(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 400) {
return response.text().then((_responseText) => {
let result400: any = null;
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result400 = resultData400 !== undefined ? resultData400 : <any>null;
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(null as any);
}
/**
*
* @return
*/
getCameraConfig(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/CameraConfig";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetCameraConfig(_response);
});
}
protected processGetCameraConfig(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(null as any);
}
/**
*
* @return
*/
testCameraConnection(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/TestCameraConnection";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processTestCameraConnection(_response);
});
}
protected processTestCameraConnection(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(null as any);
}
/**
* HTTP
* @return
*/
testConnection(): Promise<boolean> {
let url_ = this.baseUrl + "/api/VideoStream/TestConnection";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processTestConnection(_response);
});
}
protected processTestConnection(response: Response): Promise<boolean> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<boolean>(null as any);
}
}
export class BsdlParserClient { export class BsdlParserClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }; private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string; private baseUrl: string;
@ -1542,6 +1842,55 @@ export class RemoteUpdateClient {
} }
} }
export class TutorialClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : window as any;
this.baseUrl = baseUrl ?? "http://localhost:5000";
}
/**
*
* @return
*/
getTutorials(): Promise<void> {
let url_ = this.baseUrl + "/api/Tutorial";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetTutorials(_response);
});
}
protected processGetTutorials(response: Response): Promise<void> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
return;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
return throwException("A server side error occurred.", status, _responseText, _headers);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<void>(null as any);
}
}
export class UDPClient { export class UDPClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }; private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string; private baseUrl: string;
@ -1800,15 +2149,20 @@ export class UDPClient {
} }
/** /**
* IP地址接的数据列表 * IP地址接的数据列表
* @param address (optional) IP地址 * @param address (optional) IP地址
* @param taskID (optional)
*/ */
getRecvDataArray(address: string | undefined): Promise<UDPData[]> { getRecvDataArray(address: string | undefined, taskID: number | undefined): Promise<UDPData[]> {
let url_ = this.baseUrl + "/api/UDP/GetRecvDataArray?"; let url_ = this.baseUrl + "/api/UDP/GetRecvDataArray?";
if (address === null) if (address === null)
throw new Error("The parameter 'address' cannot be null."); throw new Error("The parameter 'address' cannot be null.");
else if (address !== undefined) else if (address !== undefined)
url_ += "address=" + encodeURIComponent("" + address) + "&"; url_ += "address=" + encodeURIComponent("" + address) + "&";
if (taskID === null)
throw new Error("The parameter 'taskID' cannot be null.");
else if (taskID !== undefined)
url_ += "taskID=" + encodeURIComponent("" + taskID) + "&";
url_ = url_.replace(/[?&]$/, ""); url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = { let options_: RequestInit = {
@ -1853,55 +2207,6 @@ export class UDPClient {
} }
} }
export class TutorialClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : window as any;
this.baseUrl = baseUrl ?? "http://localhost:5000";
}
/**
*
* @return
*/
getTutorials(): Promise<void> {
let url_ = this.baseUrl + "/api/Tutorial";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetTutorials(_response);
});
}
protected processGetTutorials(response: Response): Promise<void> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
return;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
return throwException("A server side error occurred.", status, _responseText, _headers);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<void>(null as any);
}
}
export class Exception implements IException { export class Exception implements IException {
message?: string; message?: string;
innerException?: Exception | undefined; innerException?: Exception | undefined;
@ -1950,6 +2255,48 @@ export interface IException {
stackTrace?: string | undefined; stackTrace?: string | undefined;
} }
/** 摄像头配置请求模型 */
export class CameraConfigRequest implements ICameraConfigRequest {
address!: string;
port!: number;
constructor(data?: ICameraConfigRequest) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.address = _data["address"];
this.port = _data["port"];
}
}
static fromJS(data: any): CameraConfigRequest {
data = typeof data === 'object' ? data : {};
let result = new CameraConfigRequest();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["address"] = this.address;
data["port"] = this.port;
return data;
}
}
/** 摄像头配置请求模型 */
export interface ICameraConfigRequest {
address: string;
port: number;
}
export class SystemException extends Exception implements ISystemException { export class SystemException extends Exception implements ISystemException {
constructor(data?: ISystemException) { constructor(data?: ISystemException) {
@ -2091,6 +2438,8 @@ export class UDPData implements IUDPData {
address?: string; address?: string;
/** 发送来源的端口号 */ /** 发送来源的端口号 */
port?: number; port?: number;
/** 任务ID */
taskID?: number;
/** 接受到的数据 */ /** 接受到的数据 */
data?: string; data?: string;
/** 是否被读取过 */ /** 是否被读取过 */
@ -2110,6 +2459,7 @@ export class UDPData implements IUDPData {
this.dateTime = _data["dateTime"] ? new Date(_data["dateTime"].toString()) : <any>undefined; this.dateTime = _data["dateTime"] ? new Date(_data["dateTime"].toString()) : <any>undefined;
this.address = _data["address"]; this.address = _data["address"];
this.port = _data["port"]; this.port = _data["port"];
this.taskID = _data["taskID"];
this.data = _data["data"]; this.data = _data["data"];
this.hasRead = _data["hasRead"]; this.hasRead = _data["hasRead"];
} }
@ -2127,6 +2477,7 @@ export class UDPData implements IUDPData {
data["dateTime"] = this.dateTime ? this.dateTime.toISOString() : <any>undefined; data["dateTime"] = this.dateTime ? this.dateTime.toISOString() : <any>undefined;
data["address"] = this.address; data["address"] = this.address;
data["port"] = this.port; data["port"] = this.port;
data["taskID"] = this.taskID;
data["data"] = this.data; data["data"] = this.data;
data["hasRead"] = this.hasRead; data["hasRead"] = this.hasRead;
return data; return data;
@ -2141,6 +2492,8 @@ export interface IUDPData {
address?: string; address?: string;
/** 发送来源的端口号 */ /** 发送来源的端口号 */
port?: number; port?: number;
/** 任务ID */
taskID?: number;
/** 接受到的数据 */ /** 接受到的数据 */
data?: string; data?: string;
/** 是否被读取过 */ /** 是否被读取过 */
@ -2189,144 +2542,3 @@ function throwException(message: string, status: number, response: string, heade
else else
throw new ApiException(message, status, response, headers, null); throw new ApiException(message, status, response, headers, null);
} }
// VideoStreamClient - 手动添加用于HTTP视频流控制
export class VideoStreamClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : window as any;
this.baseUrl = baseUrl ?? "http://localhost:5000";
} /**
* HTTP视频流服务状态
* @return HTTP视频流服务状态信息
*/
status(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/Status";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processStatus(_response);
});
}
protected processStatus(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {};
if (response.headers && response.headers.forEach) {
response.headers.forEach((v: any, k: any) => _headers[k] = v);
}
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
throw new Error(_responseText);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
});
}
return Promise.resolve<any>(null as any);
} /**
* HTTP视频流信息
* @return HTTP视频流信息
*/
streamInfo(): Promise<any> {
let url_ = this.baseUrl + "/api/VideoStream/StreamInfo";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processStreamInfo(_response);
});
}
protected processStreamInfo(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {};
if (response.headers && response.headers.forEach) {
response.headers.forEach((v: any, k: any) => _headers[k] = v);
}
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
throw new Error(_responseText);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
});
}
return Promise.resolve<any>(null as any);
} /**
* HTTP视频流连接
* @return
*/
testConnection(): Promise<boolean> {
let url_ = this.baseUrl + "/api/VideoStream/TestConnection";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processTestConnection(_response);
});
}
protected processTestConnection(response: Response): Promise<boolean> {
const status = response.status;
let _headers: any = {};
if (response.headers && response.headers.forEach) {
response.headers.forEach((v: any, k: any) => _headers[k] = v);
}
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
return result200;
});
} else if (status === 500) {
return response.text().then((_responseText) => {
throw new Error(_responseText);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
});
}
return Promise.resolve<boolean>(false);
}
}

View File

@ -11,9 +11,18 @@
<div class="card bg-base-200 shadow-xl"> <div class="card bg-base-200 shadow-xl">
<div class="card-body"> <div class="card-body">
<h2 class="card-title text-primary"> <h2 class="card-title text-primary">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-6 h-6"
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"
/>
</svg> </svg>
控制面板 控制面板
</h2> </h2>
@ -23,8 +32,13 @@
<div class="stats shadow"> <div class="stats shadow">
<div class="stat"> <div class="stat">
<div class="stat-figure text-primary"> <div class="stat-figure text-primary">
<div class="badge" :class="statusInfo.isRunning ? 'badge-success' : 'badge-error'"> <div
{{ statusInfo.isRunning ? '运行中' : '已停止' }} class="badge"
:class="
statusInfo.isRunning ? 'badge-success' : 'badge-error'
"
>
{{ statusInfo.isRunning ? "运行中" : "已停止" }}
</div> </div>
</div> </div>
<div class="stat-title">服务状态</div> <div class="stat-title">服务状态</div>
@ -37,13 +51,24 @@
<div class="stats shadow"> <div class="stats shadow">
<div class="stat"> <div class="stat">
<div class="stat-figure text-secondary"> <div class="stat-figure text-secondary">
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-8 h-8"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
/>
</svg> </svg>
</div> </div>
<div class="stat-title">视频规格</div> <div class="stat-title">视频规格</div>
<div class="stat-value text-secondary">{{ streamInfo.frameWidth }}×{{ streamInfo.frameHeight }}</div> <div class="stat-value text-secondary">
{{ streamInfo.frameWidth }}×{{ streamInfo.frameHeight }}
</div>
<div class="stat-desc">{{ streamInfo.frameRate }} FPS</div> <div class="stat-desc">{{ streamInfo.frameRate }} FPS</div>
</div> </div>
</div> </div>
@ -52,21 +77,50 @@
<div class="stats shadow"> <div class="stats shadow">
<div class="stat"> <div class="stat">
<div class="stat-figure text-accent"> <div class="stat-figure text-accent">
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-8 h-8"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
/>
</svg> </svg>
</div> </div>
<div class="stat-title">连接数</div> <div class="stat-title">连接数</div>
<div class="stat-value text-accent">{{ statusInfo.connectedClients }}</div> <div class="stat-value text-accent">
{{ statusInfo.connectedClients }}
</div>
<div class="stat-desc"> <div class="stat-desc">
<div class="dropdown dropdown-hover"> <div class="dropdown dropdown-hover">
<div tabindex="0" role="button" class="text-xs underline cursor-help">查看客户端</div> <div
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"> tabindex="0"
<li v-for="(client, index) in statusInfo.clientEndpoints" :key="index" class="text-xs"> role="button"
class="text-xs underline cursor-help"
>
查看客户端
</div>
<ul
tabindex="0"
class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"
>
<li
v-for="(client, index) in statusInfo.clientEndpoints"
:key="index"
class="text-xs"
>
<a>{{ client }}</a> <a>{{ client }}</a>
</li> </li>
<li v-if="!statusInfo.clientEndpoints || statusInfo.clientEndpoints.length === 0"> <li
v-if="
!statusInfo.clientEndpoints ||
statusInfo.clientEndpoints.length === 0
"
>
<a class="text-xs opacity-50">无活跃连接</a> <a class="text-xs opacity-50">无活跃连接</a>
</li> </li>
</ul> </ul>
@ -76,6 +130,99 @@
</div> </div>
</div> </div>
<!-- 摄像头配置 -->
<div class="card bg-base-100 shadow-sm mt-4">
<div class="card-body">
<h3 class="card-title text-sm text-info">
<svg
class="w-5 h-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
摄像头配置
</h3>
<div class="flex flex-row justify-between items-center gap-4">
<div class="form-control">
<label class="label">
<span class="label-text">IP地址</span>
</label>
<input
type="text"
v-model="cameraConfig.address"
placeholder="例如: 192.168.1.100"
class="input input-bordered input-sm"
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text">端口号</span>
</label>
<input
type="number"
v-model="cameraConfig.port"
placeholder="例如: 8080"
class="input input-bordered input-sm"
/>
</div>
<button
class="btn btn-primary btn-sm"
@click="confirmCameraConfig"
:disabled="configuring"
>
<svg
v-if="configuring"
class="animate-spin h-4 w-4 mr-1"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
<svg
v-else
class="w-4 h-4 mr-1"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
/>
</svg>
{{ configuring ? "配置中..." : "确认" }}
</button>
</div>
</div>
</div>
<!-- 操作按钮 --> <!-- 操作按钮 -->
<div class="card-actions justify-end mt-4"> <div class="card-actions justify-end mt-4">
<button <button
@ -83,22 +230,54 @@
@click="refreshStatus" @click="refreshStatus"
:disabled="loading" :disabled="loading"
> >
<svg v-if="loading" class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24"> <svg
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> v-if="loading"
<path class="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> class="animate-spin h-4 w-4 mr-2"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg> </svg>
{{ loading ? '刷新中...' : '刷新状态' }} {{ loading ? "刷新中..." : "刷新状态" }}
</button> </button>
<button <button
class="btn btn-primary" class="btn btn-primary"
@click="testConnection" @click="testConnection"
:disabled="testing" :disabled="testing"
> >
<svg v-if="testing" class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24"> <svg
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> v-if="testing"
<path class="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> class="animate-spin h-4 w-4 mr-2"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg> </svg>
{{ testing ? '测试中...' : '测试连接' }} {{ testing ? "测试中..." : "测试连接" }}
</button> </button>
</div> </div>
</div> </div>
@ -108,16 +287,31 @@
<div class="card bg-base-200 shadow-xl"> <div class="card bg-base-200 shadow-xl">
<div class="card-body"> <div class="card-body">
<h2 class="card-title text-primary"> <h2 class="card-title text-primary">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-6 h-6"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
/>
</svg> </svg>
视频预览 视频预览
</h2> </h2>
<div class="relative bg-black rounded-lg overflow-hidden" style="aspect-ratio: 4/3;"> <div
class="relative bg-black rounded-lg overflow-hidden"
style="aspect-ratio: 4/3"
>
<!-- 视频播放器 - 使用img标签直接显示MJPEG流 --> <!-- 视频播放器 - 使用img标签直接显示MJPEG流 -->
<div v-show="isPlaying" class="w-full h-full flex items-center justify-center"> <div
v-show="isPlaying"
class="w-full h-full flex items-center justify-center"
>
<img <img
:src="currentVideoSource" :src="currentVideoSource"
alt="视频流" alt="视频流"
@ -128,12 +322,26 @@
</div> </div>
<!-- 错误信息显示 --> <!-- 错误信息显示 -->
<div v-if="hasVideoError" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70"> <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 bg-error text-white shadow-lg w-full max-w-lg">
<div class="card-body"> <div class="card-body">
<h3 class="card-title flex items-center gap-2"> <h3 class="card-title flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /> xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
/>
</svg> </svg>
视频流加载失败 视频流加载失败
</h3> </h3>
@ -144,7 +352,12 @@
<li>端口 {{ statusInfo.serverPort }} 是否可访问</li> <li>端口 {{ statusInfo.serverPort }} 是否可访问</li>
</ul> </ul>
<div class="card-actions justify-end mt-2"> <div class="card-actions justify-end mt-2">
<button class="btn btn-sm btn-outline btn-primary" @click="tryReconnect">重试连接</button> <button
class="btn btn-sm btn-outline btn-primary"
@click="tryReconnect"
>
重试连接
</button>
</div> </div>
</div> </div>
</div> </div>
@ -156,12 +369,23 @@
class="absolute inset-0 flex items-center justify-center text-white" class="absolute inset-0 flex items-center justify-center text-white"
> >
<div class="text-center"> <div class="text-center">
<svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-16 h-16 mx-auto mb-4 opacity-50"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
/>
</svg> </svg>
<p class="text-lg opacity-75">{{ videoStatus }}</p> <p class="text-lg opacity-75">{{ videoStatus }}</p>
<p class="text-sm opacity-60 mt-2">点击"播放视频流"按钮开始查看实时视频</p> <p class="text-sm opacity-60 mt-2">
点击"播放视频流"按钮开始查看实时视频
</p>
</div> </div>
</div> </div>
</div> </div>
@ -169,20 +393,49 @@
<!-- 视频控制 --> <!-- 视频控制 -->
<div class="flex justify-between items-center mt-4"> <div class="flex justify-between items-center mt-4">
<div class="text-sm text-base-content/70"> <div class="text-sm text-base-content/70">
流地址: <code class="bg-base-300 px-2 py-1 rounded">{{ streamInfo.mjpegUrl }}</code> 流地址:
<code class="bg-base-300 px-2 py-1 rounded">{{
streamInfo.mjpegUrl
}}</code>
</div> </div>
<div class="space-x-2"> <div class="space-x-2">
<div class="dropdown dropdown-hover dropdown-top dropdown-end"> <div class="dropdown dropdown-hover dropdown-top dropdown-end">
<div tabindex="0" role="button" class="btn btn-sm btn-outline btn-accent"> <div
<svg class="w-4 h-4 mr-1" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"> tabindex="0"
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /> role="button"
class="btn btn-sm btn-outline btn-accent"
>
<svg
class="w-4 h-4 mr-1"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg> </svg>
更多功能 更多功能
</div> </div>
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"> <ul
<li><a @click="openInNewTab(streamInfo.htmlUrl)">在新标签打开视频页面</a></li> tabindex="0"
class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"
>
<li>
<a @click="openInNewTab(streamInfo.htmlUrl)"
>在新标签打开视频页面</a
>
</li>
<li><a @click="takeSnapshot">获取并下载快照</a></li> <li><a @click="takeSnapshot">获取并下载快照</a></li>
<li><a @click="copyToClipboard(streamInfo.mjpegUrl)">复制MJPEG地址</a></li> <li>
<a @click="copyToClipboard(streamInfo.mjpegUrl)"
>复制MJPEG地址</a
>
</li>
</ul> </ul>
</div> </div>
<button <button
@ -190,9 +443,24 @@
@click="startStream" @click="startStream"
:disabled="isPlaying" :disabled="isPlaying"
> >
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" /> class="w-4 h-4 mr-1"
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg> </svg>
播放视频流 播放视频流
</button> </button>
@ -201,9 +469,24 @@
@click="stopStream" @click="stopStream"
:disabled="!isPlaying" :disabled="!isPlaying"
> >
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/> class="w-4 h-4 mr-1"
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"
/>
</svg> </svg>
停止视频流 停止视频流
</button> </button>
@ -216,19 +499,37 @@
<div class="card bg-base-200 shadow-xl"> <div class="card bg-base-200 shadow-xl">
<div class="card-body"> <div class="card-body">
<h2 class="card-title text-primary"> <h2 class="card-title text-primary">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-6 h-6"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/> fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg> </svg>
操作日志 操作日志
</h2> </h2>
<div class="bg-base-300 rounded-lg p-4 h-48 overflow-y-auto"> <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"> <div
<span class="text-base-content/50">[{{ formatTime(log.time) }}]</span> 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> <span :class="getLogClass(log.level)">{{ log.message }}</span>
</div> </div>
<div v-if="logs.length === 0" class="text-base-content/50 text-center py-8"> <div
v-if="logs.length === 0"
class="text-base-content/50 text-center py-8"
>
暂无日志记录 暂无日志记录
</div> </div>
</div> </div>
@ -245,103 +546,197 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue' import { ref, onMounted, onUnmounted } from "vue";
import { VideoStreamClient } from '@/APIClient' import { VideoStreamClient, CameraConfigRequest } from "@/APIClient";
// //
const loading = ref(false) const loading = ref(false);
const testing = ref(false) const testing = ref(false);
const isPlaying = ref(false) const configuring = ref(false);
const hasVideoError = ref(false) const testingCamera = ref(false);
const videoStatus = ref('点击"播放视频流"按钮开始查看实时视频') const isPlaying = ref(false);
const hasVideoError = ref(false);
const videoStatus = ref('点击"播放视频流"按钮开始查看实时视频');
// //
const statusInfo = ref({ const statusInfo = ref({
isRunning: false, isRunning: false,
serverPort: 8080, serverPort: 8080,
streamUrl: '', streamUrl: "",
mjpegUrl: '', mjpegUrl: "",
snapshotUrl: '', snapshotUrl: "",
connectedClients: 0, connectedClients: 0,
clientEndpoints: [] as string[] clientEndpoints: [] as string[],
}) });
const streamInfo = ref({ const streamInfo = ref({
frameRate: 30, frameRate: 30,
frameWidth: 640, frameWidth: 640,
frameHeight: 480, frameHeight: 480,
format: 'MJPEG', format: "MJPEG",
htmlUrl: '', htmlUrl: "",
mjpegUrl: '', mjpegUrl: "",
snapshotUrl: '' snapshotUrl: "",
}) });
const currentVideoSource = ref('') //
const logs = ref<Array<{time: Date, level: string, message: string}>>([]) const cameraConfig = ref({
address: "192.168.1.100",
port: 8080,
});
const currentVideoSource = ref("");
const logs = ref<Array<{ time: Date; level: string; message: string }>>([]);
// API // API
const videoClient = new VideoStreamClient() const videoClient = new VideoStreamClient();
// //
const addLog = (level: string, message: string) => { const addLog = (level: string, message: string) => {
logs.value.push({ logs.value.push({
time: new Date(), time: new Date(),
level, level,
message message,
}) });
// //
if (logs.value.length > 100) { if (logs.value.length > 100) {
logs.value.shift() logs.value.shift();
} }
} };
//
const loadCameraConfig = async () => {
try {
addLog("info", "正在加载摄像头配置...");
const config = await videoClient.getCameraConfig();
if (config && config.address && config.port) {
cameraConfig.value.address = config.address;
cameraConfig.value.port = config.port;
addLog("success", `摄像头配置加载成功: ${config.address}:${config.port}`);
} else {
addLog("warning", "未找到保存的摄像头配置,使用默认值");
}
} catch (error) {
addLog("error", `加载摄像头配置失败: ${error}`);
console.error("加载摄像头配置失败:", error);
}
};
//
const confirmCameraConfig = async () => {
if (!cameraConfig.value.address || !cameraConfig.value.port) {
addLog("error", "请填写完整的摄像头IP地址和端口号");
return;
}
configuring.value = true;
try {
addLog(
"info",
`正在配置摄像头: ${cameraConfig.value.address}:${cameraConfig.value.port}`,
);
const result = await videoClient.configureCamera(
CameraConfigRequest.fromJS(cameraConfig.value),
);
if (result) {
addLog("success", "摄像头配置保存成功");
//
await refreshStatus();
} else {
addLog("error", "摄像头配置保存失败");
}
} catch (error) {
addLog("error", `配置摄像头失败: ${error}`);
console.error("配置摄像头失败:", error);
} finally {
configuring.value = false;
}
};
//
const testCameraConnection = async () => {
if (!cameraConfig.value.address || !cameraConfig.value.port) {
addLog("error", "请先配置摄像头IP地址和端口号");
return;
}
testingCamera.value = true;
try {
addLog(
"info",
`正在测试摄像头连接: ${cameraConfig.value.address}:${cameraConfig.value.port}`,
);
const result = await videoClient.testCameraConnection();
if (result && result.success) {
addLog("success", "摄像头连接测试成功");
} else {
addLog("error", `摄像头连接测试失败: ${result?.message || "未知错误"}`);
}
} catch (error) {
addLog("error", `摄像头连接测试失败: ${error}`);
console.error("摄像头连接测试失败:", error);
} finally {
testingCamera.value = false;
}
};
// //
const formatTime = (time: Date) => { const formatTime = (time: Date) => {
return time.toLocaleTimeString() return time.toLocaleTimeString();
} };
// //
const getLogClass = (level: string) => { const getLogClass = (level: string) => {
switch (level) { switch (level) {
case 'error': return 'text-error' case "error":
case 'warning': return 'text-warning' return "text-error";
case 'success': return 'text-success' case "warning":
default: return 'text-base-content' return "text-warning";
case "success":
return "text-success";
default:
return "text-base-content";
} }
} };
// //
const clearLogs = () => { const clearLogs = () => {
logs.value = [] logs.value = [];
addLog('info', '日志已清空') addLog("info", "日志已清空");
} };
// //
const copyToClipboard = (text: string) => { const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text) navigator.clipboard
.writeText(text)
.then(() => { .then(() => {
addLog('success', '已复制到剪贴板'); addLog("success", "已复制到剪贴板");
}) })
.catch((err) => { .catch((err) => {
addLog('error', `复制失败: ${err}`); addLog("error", `复制失败: ${err}`);
}); });
} };
// //
const openInNewTab = (url: string) => { const openInNewTab = (url: string) => {
window.open(url, '_blank'); window.open(url, "_blank");
addLog('info', `已在新标签打开视频页面: ${url}`); addLog("info", `已在新标签打开视频页面: ${url}`);
} };
// //
const takeSnapshot = async () => { const takeSnapshot = async () => {
try { try {
addLog('info', '正在获取快照...'); addLog("info", "正在获取快照...");
// 使URL // 使URL
const snapshotUrl = streamInfo.value.snapshotUrl; const snapshotUrl = streamInfo.value.snapshotUrl;
if (!snapshotUrl) { if (!snapshotUrl) {
addLog('error', '快照URL不可用'); addLog("error", "快照URL不可用");
return; return;
} }
@ -349,138 +744,140 @@ const takeSnapshot = async () => {
const urlWithTimestamp = `${snapshotUrl}?t=${new Date().getTime()}`; const urlWithTimestamp = `${snapshotUrl}?t=${new Date().getTime()}`;
// //
const a = document.createElement('a'); const a = document.createElement("a");
a.href = urlWithTimestamp; a.href = urlWithTimestamp;
a.download = `fpga-snapshot-${new Date().toISOString().replace(/:/g, '-')}.jpg`; a.download = `fpga-snapshot-${new Date().toISOString().replace(/:/g, "-")}.jpg`;
document.body.appendChild(a); document.body.appendChild(a);
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
addLog('success', '快照已下载'); addLog("success", "快照已下载");
} catch (error) { } catch (error) {
addLog('error', `获取快照失败: ${error}`); addLog("error", `获取快照失败: ${error}`);
console.error('获取快照失败:', error); console.error("获取快照失败:", error);
} }
} };
// //
const refreshStatus = async () => { const refreshStatus = async () => {
loading.value = true loading.value = true;
try { try {
addLog('info', '正在获取服务状态...') addLog("info", "正在获取服务状态...");
const status = await videoClient.status() // 使API
statusInfo.value = status const status = await videoClient.getStatus();
statusInfo.value = status;
const info = await videoClient.streamInfo() const info = await videoClient.getStreamInfo();
streamInfo.value = info streamInfo.value = info;
addLog('success', '服务状态获取成功') addLog("success", "服务状态获取成功");
} catch (error) { } catch (error) {
addLog('error', `获取状态失败: ${error}`) addLog("error", `获取状态失败: ${error}`);
console.error('获取状态失败:', error) console.error("获取状态失败:", error);
} finally { } finally {
loading.value = false loading.value = false;
} }
} };
// //
const testConnection = async () => { const testConnection = async () => {
testing.value = true testing.value = true;
try { try {
addLog('info', '正在测试视频流连接...') addLog("info", "正在测试视频流连接...");
const result = await videoClient.testConnection() const result = await videoClient.testConnection();
if (result) { if (result) {
addLog('success', '视频流连接测试成功') addLog("success", "视频流连接测试成功");
} else { } else {
addLog('error', '视频流连接测试失败') addLog("error", "视频流连接测试失败");
} }
} catch (error) { } catch (error) {
addLog('error', `连接测试失败: ${error}`) addLog("error", `连接测试失败: ${error}`);
console.error('连接测试失败:', error) console.error("连接测试失败:", error);
} finally { } finally {
testing.value = false testing.value = false;
} }
} };
// //
const handleVideoError = () => { const handleVideoError = () => {
if (isPlaying.value) { if (isPlaying.value) {
hasVideoError.value = true hasVideoError.value = true;
addLog('error', '视频流加载失败') addLog("error", "视频流加载失败");
} }
} };
// //
const handleVideoLoad = () => { const handleVideoLoad = () => {
hasVideoError.value = false hasVideoError.value = false;
addLog('success', '视频流加载成功') addLog("success", "视频流加载成功");
} };
// //
const tryReconnect = () => { const tryReconnect = () => {
addLog('info', '尝试重新连接视频流...') addLog("info", "尝试重新连接视频流...");
hasVideoError.value = false hasVideoError.value = false;
// //
currentVideoSource.value = `${streamInfo.value.mjpegUrl}?t=${new Date().getTime()}` currentVideoSource.value = `${streamInfo.value.mjpegUrl}?t=${new Date().getTime()}`;
} };
// //
const startStream = async () => { const startStream = async () => {
try { try {
addLog('info', '正在启动视频流...') addLog("info", "正在启动视频流...");
videoStatus.value = '正在连接视频流...' videoStatus.value = "正在连接视频流...";
// //
await refreshStatus() await refreshStatus();
// //
currentVideoSource.value = streamInfo.value.mjpegUrl currentVideoSource.value = streamInfo.value.mjpegUrl;
// //
isPlaying.value = true isPlaying.value = true;
hasVideoError.value = false hasVideoError.value = false;
addLog('success', '视频流已启动') addLog("success", "视频流已启动");
} catch (error) { } catch (error) {
addLog('error', `启动视频流失败: ${error}`) addLog("error", `启动视频流失败: ${error}`);
videoStatus.value = '启动视频流失败' videoStatus.value = "启动视频流失败";
console.error('启动视频流失败:', error) console.error("启动视频流失败:", error);
} }
} };
// //
const stopStream = () => { const stopStream = () => {
try { try {
addLog('info', '正在停止视频流...') addLog("info", "正在停止视频流...");
// //
currentVideoSource.value = '' currentVideoSource.value = "";
// //
isPlaying.value = false isPlaying.value = false;
hasVideoError.value = false hasVideoError.value = false;
videoStatus.value = '点击"播放视频流"按钮开始查看实时视频' videoStatus.value = '点击"播放视频流"按钮开始查看实时视频';
addLog('success', '视频流已停止') addLog("success", "视频流已停止");
} catch (error) { } catch (error) {
addLog('error', `停止视频流失败: ${error}`) addLog("error", `停止视频流失败: ${error}`);
console.error('停止视频流失败:', error) console.error("停止视频流失败:", error);
} }
} };
// //
onMounted(async () => { onMounted(async () => {
addLog('info', 'HTTP 视频流页面已加载') addLog("info", "HTTP 视频流页面已加载");
await refreshStatus() await loadCameraConfig();
}) await refreshStatus();
});
onUnmounted(() => { onUnmounted(() => {
stopStream() stopStream();
}) });
</script> </script>
<style scoped> <style scoped>